C#教程之打印和打印预览

    最近研究一了一下关于PDF打印和打印预览的功能,在此小小的总结记录一下学习过程。

实现打印和打印预览的方法,一般要实现如下的菜单项:打印、打印预览、页面设置、

PrintDocument类

  PrintDocument组件是用于完成打印的类,其常用的属性、方法事件如下:

属性DocumentName:字符串类型,记录打印文档时显示的文档名(例如,在打印状态对话框或打印机队列中显示),即用户填写生成pdf文件名时的默认值为DocumentName
方法Print:开始文档的打印。
事件BeginPrint:在调用Print方法后,在打印文档的第一页之前发生。
事件PrintPage:需要打印新的一页时发生。
事件EndPrint:在文档的最后一页打印后发生。

若要打印,首先创建PrintDocument组建的对象,然后使用页面上设置对话框PageSetupDialog设置页面打印方式,这些设置作为打印页的默认设置、使用打印对话框PrintDialog设置对文档进行打印的打印机的参数。在打开两个对话框前,首先设置对话框的属性Document为指定的PrintDocument类对象,修改的设置将保存到PrintDocument组件对象中。

第三步是调用PrintDocument.Print方法来实际打印文档,调用该方法后,引发下列事件:BeginPrint、PrintPage、EndPrint。其中每打印一页都引发PrintPage事件,打印多页,要多次引发PrintPage事件。完成一次打印,可以引发一个或多个PrintPage事件。

        /// <summary>
        /// 打印纸设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_PageSet_Click(object sender, EventArgs e)
        {
            PageSetupDialog pageSetupDialog = new PageSetupDialog();
            pageSetupDialog.Document = printDocument;
            pageSetupDialog.ShowDialog();
        }
        /// <summary>
        /// 打印机设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_PrintSet_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            printDialog.Document = printDocument;
            printDialog.ShowDialog();
        }
        /// <summary>
        /// 预览功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_PrintView_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog {Document = printDocument};
            lineReader = new StreamReader(@"f:\新建文本文档.txt");
            try
            { // 脚本学堂 www.jbxue.com
                printPreviewDialog.ShowDialog();
            }
            catch (Exception excep)
            {
                MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 打印功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_Print_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog {Document = printDocument};
            lineReader = new StreamReader(@"f:\新建文本文档.txt");
            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    printDocument.Print();
                }
                catch (Exception excep)
                {
                    MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    printDocument.PrintController.OnEndPrint(printDocument, new PrintEventArgs());
                }
            }
        }

程序员应为这3个事件编写事件处理函数。BeginPrint事件处理函数进行打印初始化,一般设置在打印时所有页的相同属性或共用的资源,例如所有页共同使用的字体、建立要打印的文件流等。PrintPage事件处理函数负责打印一页数据。EndPrint事件处理函数进行打印善后工作。这些处理函数的第2个参数System.Drawing.Printing.PrintEventArgs e提供了一些附加信息,主要有:
l e.Cancel:布尔变量,设置为true,将取消这次打印作业。
l e.Graphics:所使用的打印机的设备环境,参见第五章。
l e.HasMorePages:布尔变量。PrintPage事件处理函数打印一页后,仍有数据未打印,退出事件处理函数前设置HasMorePages=true,退出PrintPage事件处理函数后,将再次引发PrintPage事件,打印下一页。
l e.MarginBounds:打印区域的大小,是Rectangle结构,元素包括左上角坐标:Left和Top,宽和高:Width和Height。单位为1/100英寸。
l e.MarginBounds:打印纸的大小,是Rectangle结构。单位为1/100英寸。
l e.PageSettings:PageSettings类对象,包含用对话框PageSetupDialog设置的页面打印方式的全部信息。可用帮助查看PageSettings类的属性。

注意:本例打印或预览RichTextBox中的内容,增加变量:StringReader streamToPrint=null。如果打印或预览文件,改为:StreamReader streamToPrint,

    接下来用winform的例子具体实现一个小功能:

   首先我们要生成的pdf 文件中的数据来源有:从其他文本中获得,用户将现有的数据按照某只格式输出为pdf文件

   首先介绍一下,读取txt文件中的内容,生成pdf文件的具体代码:

 PrintDocument printDocument;
        StreamReader lineReader = null;
        public Form1()
        {
            InitializeComponent();
            // 这里的printDocument对象可以通过将PrintDocument控件拖放到窗体上来实现,注意要设置该控件的PrintPage事件。
            printDocument=new PrintDocument();
            printDocument.DocumentName = "张海伦测试";
            printDocument.PrintPage += new PrintPageEventHandler (this.printDocument_PrintPage);
        }

        /// <summary>
        /// 打印内容页面布局
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            var g = e.Graphics; //获得绘图对象
            float linesPerPage = 0; //页面的行号
            float yPosition = 0; //绘制字符串的纵向位置
            var count = 0; //行计数器
            float leftMargin = e.MarginBounds.Left; //左边距
            float topMargin = e.MarginBounds.Top; //上边距
            string line = null;
            System.Drawing.Font printFont = this.textBox.Font; //当前的打印字体
            BaseFont baseFont = BaseFont.CreateFont("f:\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var myBrush = new SolidBrush(Color.Black); //刷子
            linesPerPage = e.MarginBounds.Height / printFont.GetHeight(g); //每页可打印的行数
            //逐行的循环打印一页
            while (count < linesPerPage && ((line = lineReader.ReadLine()) != null))
            {
                yPosition = topMargin + (count * printFont.GetHeight(g));
                g.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
                count++;           
            }        
        
        }
        
        /// <summary>
        /// 打印纸设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_PageSet_Click(object sender, EventArgs e)
        {
            PageSetupDialog pageSetupDialog = new PageSetupDialog();
            pageSetupDialog.Document = printDocument;
            pageSetupDialog.ShowDialog();
        }
        /// <summary>
        /// 打印机设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_PrintSet_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            printDialog.Document = printDocument;
            printDialog.ShowDialog();
        }
        /// <summary>
        /// 预览功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_PrintView_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog {Document = printDocument};
            lineReader = new StreamReader(@"f:\新建文本文档.txt");
            try
            { // 脚本学堂 www.jbxue.com
                printPreviewDialog.ShowDialog();
            }
            catch (Exception excep)
            {
                MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 打印功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_Print_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog {Document = printDocument};
            lineReader = new StreamReader(@"f:\新建文本文档.txt");
            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    printDocument.Print();
                }
                catch (Exception excep)
                {
                    MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    printDocument.PrintController.OnEndPrint(printDocument, new PrintEventArgs());
                }
            }
        }
View Code

  其次,根据现有数据数据某种文本样式的pdf文件具体代码如下:

  ///GetPrintSw方法用来构造打印文本,内部StringBuilder.AppendLine在Drawstring时单独占有一行。
        public StringBuilder GetPrintSW()
        {
            StringBuilder sb = new StringBuilder();
            string tou = "测试管理公司名称";
            string address = "河南洛阳";
            string saleID = "2010930233330";    //单号        
            string item = "项目";
            decimal price = 25.00M;
            int count = 5;
            decimal total = 0.00M;
            decimal fukuan = 500.00M;
            sb.AppendLine(" " + tou + " \n");
            sb.AppendLine("--------------------------------------");
            sb.AppendLine("日期:" + DateTime.Now.ToShortDateString() + " " + "单号:" + saleID);
            sb.AppendLine("-----------------------------------------");
            sb.AppendLine("项目" + "      " + "数量" + "    " + "单价" + "    " + "小计");
            for (int i = 0; i < count; i++)
            {
                decimal xiaoji = (i + 1) * price;
                sb.AppendLine(item + (i + 1) + "      " + (i + 1) + "     " + price + "    " + xiaoji);
                total += xiaoji;
            }
            sb.AppendLine("-----------------------------------------");
            sb.AppendLine("数量:" + count + "  合计: " + total);
            sb.AppendLine("付款:" + fukuan);
            sb.AppendLine("现金找零:" + (fukuan - total));
            sb.AppendLine("-----------------------------------------");
            sb.AppendLine("地址:" + address + "");
            sb.AppendLine("电话:123456789 123456789");
            sb.AppendLine("谢谢惠顾欢迎下次光临 ");
            sb.AppendLine("-----------------------------------------");
            return sb;

        }
View Code

最后我们在软件中,经常使用的是将现有的某条记录生成一个pdf文件表格,里面有用户从数据库中获取的值。具体代码如下:

private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            Font titleFont = new Font("宋体", 9, FontStyle.Bold);//标题字体            
            Font font = new Font("宋体", 9, FontStyle.Regular);//正文文字            
            Brush brush = new SolidBrush(Color.Black);//画刷            
            Pen pen = new Pen(Color.Black);           //线条颜色            
            Point po = new Point(10, 10);
            try
            {
                e.Graphics.DrawString(GetPrintSW().ToString(), titleFont, brush, po);   //DrawString方式进行打印。  
                int length = 500;
                int height = 500;
                Graphics g = e.Graphics;//利用该图片对象生成“画板”
                Pen p = new Pen(Color.Red, 1);//定义了一个红色,宽度为的画笔
                g.Clear(Color.White); //设置黑色背景
                //一排数据
                g.DrawRectangle(p, 100, 100, 80, 20);//在画板上画矩形,起始坐标为(10,10),宽为80,高为20
                g.DrawRectangle(p, 180, 100, 80, 20);//在画板上画矩形,起始坐标为(90,10),宽为80,高为20
                g.DrawRectangle(p, 260, 100, 80, 20);//
                g.DrawRectangle(p, 340, 100, 80, 20);//
                g.DrawString("目标", font, brush, 12, 12);//
                g.DrawString("完成数", font, brush, 92, 12);
                g.DrawString("完成率", font, brush, 172, 12);//进行绘制文字。起始坐标为(172, 12)
                g.DrawString("效率", font, brush, 252, 12);//关键的一步,进行绘制文字。

                g.DrawRectangle(p, 10, 30, 80, 20);
                g.DrawRectangle(p, 90, 30, 80, 20);
                g.DrawRectangle(p, 170, 30, 80, 20);
                g.DrawRectangle(p, 250, 30, 80, 20);
                g.DrawString("800", font, brush, 12, 32);
                g.DrawString("500", font, brush, 92, 32);//关键的一步,进行绘制文字。
                g.DrawString("60%", font, brush, 172, 32);//关键的一步,进行绘制文字。
                g.DrawString("50%", font, brush, 252, 32);//关键的一步,进行绘制文字。

                g.DrawRectangle(p, 10, 50, 80, 20);
                g.DrawRectangle(p, 90, 50, 80, 20);
                g.DrawRectangle(p, 170, 50, 160, 20);//在画板上画矩形,起始坐标为(170,10),宽为160,高为20
                g.DrawString("总查数", font, brush, 12, 52);
                g.DrawString("不良数", font, brush, 92, 52);
                g.DrawString("合格率", font, brush, 222, 52);

                g.Dispose();//释放掉该资源
            }

            catch (Exception ex)
            {

                MessageBox.Show(this, "打印出错!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

        }
View Code

效果图如:

上面这3个例子,均是在winform中实现的,最后一个功能的实现比较复杂,不是很好,

 下面是俩个wpf实现打印的例子,

  简单的一个具体代码有:

  1  public MainWindow()
  2         {
  3             InitializeComponent();
  4         }
  5         /// <summary>
  6         /// 我得第一个Pdf程序
  7         /// </summary>
  8         private void CreatePdf()
  9         {
 10             string fileName = string.Empty;
 11             Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
 12             dlg.FileName = "我的第一个PDF";
 13             dlg.DefaultExt = ".pdf";
 14             dlg.Filter = "Text documents (.pdf)|*.pdf";
 15             Nullable<bool> result = dlg.ShowDialog();
 16             if (result == true)
 17             {
 18                 fileName = dlg.FileName;
 19                 Document document = new Document();                
 20                 PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
 21                 document.Open();
 22                 iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph("Hello World");
 23                 document.Add(paragraph);
 24                 document.Close();             
 25             }//end if          
 26         }
 27         /// <summary>
 28         /// 设置页面大小、作者、标题等相关信息设置
 29         /// </summary>
 30         private void CreatePdfSetInfo()
 31         {
 32             string fileName = string.Empty;
 33             Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
 34             dlg.FileName = "我的第一个PDF";
 35             dlg.DefaultExt = ".pdf";
 36             dlg.Filter = "Text documents (.pdf)|*.pdf";
 37             Nullable<bool> result = dlg.ShowDialog();
 38             if (result == true)
 39             {
 40                 fileName = dlg.FileName;
 41                 //设置页面大小
 42                 iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f);
 43                 pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE);
 44                 //设置边界
 45                 Document document = new Document(pageSize, 36f, 72f, 108f, 180f);
 46                 PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
 47                 // 添加文档信息
 48                 document.AddTitle("PDFInfo");
 49                 document.AddSubject("Demo of PDFInfo");
 50                 document.AddKeywords("Info, PDF, Demo");
 51                 document.AddCreator("SetPdfInfoDemo");
 52                 document.AddAuthor("焦涛");
 53                 document.Open();
 54                 // 添加文档内容
 55                 for (int i = 0; i < 5; i++)
 56                 {
 57                     document.Add(new iTextSharp.text.Paragraph("Hello World! Hello People! " +"Hello Sky! Hello Sun! Hello Moon! Hello Stars!"));
 58                 }              
 59                 document.Close();
 60             }//end if
 61         }
 62         /// <summary>
 63         /// 创建多个Pdf新页
 64         /// </summary>
 65         private void CreateNewPdfPage()
 66         {
 67             string fileName = string.Empty;
 68             Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
 69             dlg.FileName = "创建多个Pdf新页";//生成的pdf文件名
 70             dlg.DefaultExt = ".pdf";//pdf的默认后缀名
 71             dlg.Filter = "Text documents (.pdf)|*.pdf";
 72             Nullable<bool> result = dlg.ShowDialog();
 73             if (result == true)
 74             {
 75                 fileName = dlg.FileName;
 76                 Document document = new Document(PageSize.NOTE);            
 77                 PdfWriter writer= PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));                
 78                 document.Open();
 79                 // 第一页
 80                 document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
 81                 document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
 82                 document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
 83                 document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));             
 84                 // 添加新页面
 85                 document.NewPage();
 86                 // 第二页
 87                 // 添加第二页内容
 88                 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
 89                 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
 90                 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
 91                 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
 92                 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
 93                 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));          
 94                 // 添加新页面
 95                 document.NewPage();
 96                 // 第三页
 97                 // 添加新内容
 98                 document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
 99                 document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
100                 document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
101                 document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
102                 // 重新开始页面计数
103                 document.ResetPageCount();
104                 // 新建一页
105                 document.NewPage();
106                 // 第四页
107                 // 添加第四页内容
108                 document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
109                 document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
110                 document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
111                 document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
112                 document.Close();
113             }//end if
114         }
115         /// <summary>
116         /// 生成图片pdf页(pdf中插入图片)
117         /// </summary>
118         public void ImageDirect()
119         {
120             string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image\1.jpg"; //临时文件路径
121             string fileName = string.Empty;
122             Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
123             dlg.FileName = "我的第一个PDF";
124             dlg.DefaultExt = ".pdf";
125             dlg.Filter = "Text documents (.pdf)|*.pdf";
126             Nullable<bool> result = dlg.ShowDialog();
127             if (result == true)
128             {
129                 fileName = dlg.FileName;
130                 Document document = new Document();
131                 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
132                 document.Open();
133                 iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
134                 img.SetAbsolutePosition((PageSize.POSTCARD.Width - img.ScaledWidth) / 2, (PageSize.POSTCARD.Height - img.ScaledHeight) / 2);
135                 writer.DirectContent.AddImage(img);
136                 iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph("Foobar Film Festival", new iTextSharp.text.Font(Font.FontFamily.HELVETICA, 22f));
137                 p.Alignment = Element.ALIGN_CENTER;
138                 document.Add(p);
139                 document.Close();
140             }//end if
141         }
142         private void ReadPdf()
143         {
144             Console.WriteLine("读取PDF文档");
145             try
146             {
147                 // 创建一个PdfReader对象
148                 PdfReader reader = new PdfReader(@"D:\我的第一个PDF.pdf");
149                 // 获得文档页数
150                 int n = reader.NumberOfPages;
151                 // 获得第一页的大小
152                 iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
153                 float width = psize.Width;
154                 float height = psize.Height;
155                 // 创建一个文档变量
156                 Document document = new Document(psize, 50, 50, 50, 50);
157                 // 创建该文档
158                 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"d:\Read.pdf", FileMode.Create));
159                 // 打开文档
160                 document.Open();
161                 // 添加内容
162                 PdfContentByte cb = writer.DirectContent;
163                 int i = 0;
164                 int p = 0;
165                 Console.WriteLine("一共有 " + n + " 页.");
166                 while (i < n)
167                 {
168                     document.NewPage();
169                     p++;
170                     i++;
171                     PdfImportedPage page1 = writer.GetImportedPage(reader, i);
172                     cb.AddTemplate(page1, .5f, 0, 0, .5f, 0, height / 2);
173                     Console.WriteLine("处理第 " + i + "");
174                     if (i < n)
175                     {
176                         i++;
177                         PdfImportedPage page2 = writer.GetImportedPage(reader, i);
178                         cb.AddTemplate(page2, .5f, 0, 0, .5f, width / 2, height / 2);
179                         Console.WriteLine("处理第 " + i + "");
180                     }
181                     if (i < n)
182                     {
183                         i++;
184                         PdfImportedPage page3 = writer.GetImportedPage(reader, i);
185                         cb.AddTemplate(page3, .5f, 0, 0, .5f, 0, 0);
186                         Console.WriteLine("处理第 " + i + "");
187                     }
188                     if (i < n)
189                     {
190                         i++;
191                         PdfImportedPage page4 = writer.GetImportedPage(reader, i);
192                         cb.AddTemplate(page4, .5f, 0, 0, .5f, width / 2, 0);
193                         Console.WriteLine("处理第 " + i + "");
194                     }
195                     cb.SetRGBColorStroke(255, 0, 0);
196                     cb.MoveTo(0, height / 2);
197                     cb.LineTo(width, height / 2);
198                     cb.Stroke();
199                     cb.MoveTo(width / 2, height);
200                     cb.LineTo(width / 2, 0);
201                     cb.Stroke();
202                     BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
203                     cb.BeginText();
204                     cb.SetFontAndSize(bf, 14);
205                     cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 4) + (n % 4 > 0 ? 1 : 0)), width / 2, 40, 0);
206                     cb.EndText();
207                 }
208                 // 关闭文档
209                 document.Close();
210             }
211             catch (Exception de)
212             {
213                 Console.Error.WriteLine(de.Message);
214                 Console.Error.WriteLine(de.StackTrace);
215             }
216         }
217         
218         /// <summary>
219         /// 创建表格
220         /// </summary>
221         public void CreateFirstTable()
222         {
223             string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image\1.pm"; //临时文件路径
224             string fileName = string.Empty;
225             Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
226             dlg.FileName = "我的第一个PDF";
227             dlg.DefaultExt = ".pdf";
228             dlg.Filter = "Text documents (.pdf)|*.pdf";
229             Nullable<bool> result = dlg.ShowDialog();
230             BaseFont baseFont = BaseFont.CreateFont("D:\\STSONG.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
231             iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 9);
232             if (result == true)
233             {
234                 fileName = dlg.FileName;
235                 Document document = new Document();
236                 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
237                 document.Open();
238 
239                 iTextSharp.text.Paragraph p;
240                 p = new iTextSharp.text.Paragraph("中华人民共和国海关出口货物打单", font);
241                 p.Alignment = Element.ALIGN_CENTER;//设置标题居中
242                 p.SpacingAfter = 12;//设置段落行 通过设置Paragraph的SpacingBefore和SpacingAfter属性调整Paragraph对象与之间或之后段落的间距
243                 p.SpacingBefore = 1;
244                 document.Add(p);//添加段落
245 
246                 p = new iTextSharp.text.Paragraph(GetBlank(5)+"预录入编号:" +"编号代码"+GetBlank(15)+"海关编号:"+GetBlank(5),font);
247                 //p.IndentationLeft = 20;
248                 //p.IndentationLeft = 20;
249                 //p.IndentationRight = 20;
250                 //p.FirstLineIndent = 20;
251                 //IndentationLeft属性设置左侧缩进。
252                 //IndentationRight属性设置右侧缩进。
253                 p.SpacingAfter = 12;
254                 document.Add(p);//添加段落
255 
256 
257                 PdfPTable table = new PdfPTable(10);//几列
258                 
259                 PdfPCell cell;
260                 cell=new PdfPCell(new Phrase("收发货人"+GetBlank(5)+"具体值"));
261                 cell.Colspan = 4;
262                 
263                 table.AddCell(cell);
264                 
265                 cell = new PdfPCell(new Phrase("出关口岸"+GetBlank(10)+"具体值"));
266                 cell.Rowspan = 2;
267                 table.AddCell(cell);
268                 cell = new PdfPCell(new Phrase("出口日期" + GetBlank(10) + "具体值"));
269                 cell.Rowspan = 2;
270                 table.AddCell(cell);
271                 cell = new PdfPCell(new Phrase("申报日期" + GetBlank(10) + "具体值"));
272                 cell.Rowspan = 2;
273                 table.AddCell(cell);
274 
275 
276                 cell = new PdfPCell(new Phrase("收发货人" + GetBlank(5) + "具体值"));
277                 cell.Colspan = 4;
278                 table.AddCell(cell);
279 
280                 cell = new PdfPCell(new Phrase("出关口岸" + GetBlank(10) + "具体值"));
281                 cell.Rowspan = 2;
282                 table.AddCell(cell);
283                 cell = new PdfPCell(new Phrase("出口日期" + GetBlank(10) + "具体值"));
284                 cell.Rowspan = 2;
285                 table.AddCell(cell);
286                 cell = new PdfPCell(new Phrase("申报日期" + GetBlank(10) + "具体值"));
287                 cell.Rowspan = 2;
288                 table.AddCell(cell);
289 
290 
291                 //table.AddCell("row 1; cell 1");
292                 //table.AddCell("row 1; cell 2");
293                 //table.AddCell("row 2; cell 1");
294                 //table.AddCell("row 2; cell 2");
295                 document.Add(table);
296                 document.Close();
297             }//end if
298         }
299         /// <summary>
300         /// 获得空格
301         /// </summary>
302         /// <param name="num"></param>
303         /// <returns></returns>
304         private static string GetBlank(int num)
305         {
306             StringBuilder blank = new StringBuilder();
307             for (int i = 0; i < num; i++)
308             {
309                 blank.Append(" ");
310             }
311             return blank.ToString();
312         }
313 
314         private void button1_Click(object sender, RoutedEventArgs e)
315         {
316             //CreatePdf();      
317             //CreatePdfPageSize();
318             CreateNewPdfPage();
319         }
320         private void button2_Click(object sender, RoutedEventArgs e)
321         {
322             CreateFirstTable();
323         }
324 
325         private void button3_Click(object sender, RoutedEventArgs e)
326         {
327             ImageDirect();
328         }
329 
330         private void button4_Click(object sender, RoutedEventArgs e)
331         {
332             ReadPdf();
333         } 
View Code

在这里用到了iTextSharp ,需要先先下载dll文件,然后引用,总结一下其中常用的用法和属性之类的知识点,

PdfWriter的setInitialLeading操作用于设置行间距
Font font = new Font(Font.FontFamily.COURIER, 12, Font.BOLD, BaseColor.WHITE);
设置缩进
iTextSharp中,Paragraph有三个属性可以设置缩进:
//设置Paragraph对象的缩进
contentPara1.IndentationLeft = 20;
contentPara1.IndentationRight = 20;
contentPara1.FirstLineIndent = 20;
IndentationLeft属性设置左侧缩进。
IndentationRight属性设置右侧缩进。
FirstLineIndent属性设置首行左侧缩进。
三个值都可设为正负值。
设置对齐方式
设置Alignment属性可以调整Paragraph对象中文字的对齐方式。如:
//设置Paragraph对象的对齐方式为两端对齐
contentPara1.Alignment = Element.ALIGN_JUSTIFIED;
默认情况使用左对齐。
Paragraph之间的间距
iTextSharp中,通过设置Paragraph的SpacingBefore和SpacingAfter属性调整Paragraph对象与之间或之后段落的间距。例如:
//设置Paragraph对象与后面Paragraph对象之间的间距
contentPara1.SpacingAfter = 36;
文字分行问题
iText默认的规则是尽可能多的将完整单词放在同一行内。iText当遇到空格或连字符才会分行,可以通过重新定义分隔符(split character)来改变这种规则。
 
分隔符(the split character)
使用nonbreaking space character,(char)160代替普通空格(char)32放入两个单词中间从而避免iText将它们放到不同行中。

最好的是自己设计界面和功能当做模板使用,绑定数据实现如winform第三个例子样的功能。

 

posted @ 2016-07-03 15:38  ZHLBKY  阅读(4462)  评论(0编辑  收藏  举报