zoukankan      html  css  js  c++  java
  • 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());
                    }
                }
            }
    

      其次,根据现有数据数据某种文本样式的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 + " 
    ");
                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;
    
            }
    

      最后我们在软件中,经常使用的是将现有的某条记录生成一个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);
    
                }
    
            }
    

      

    效果图如:

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

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

      简单的一个具体代码有:

    public MainWindow()
            {
                InitializeComponent();
            }
            /// <summary>
            /// 我得第一个Pdf程序
            /// </summary>
            private void CreatePdf()
            {
                string fileName = string.Empty;
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = "我的第一个PDF";
                dlg.DefaultExt = ".pdf";
                dlg.Filter = "Text documents (.pdf)|*.pdf";
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    fileName = dlg.FileName;
                    Document document = new Document();                
                    PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
                    document.Open();
                    iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph("Hello World");
                    document.Add(paragraph);
                    document.Close();             
                }//end if          
            }
            /// <summary>
            /// 设置页面大小、作者、标题等相关信息设置
            /// </summary>
            private void CreatePdfSetInfo()
            {
                string fileName = string.Empty;
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = "我的第一个PDF";
                dlg.DefaultExt = ".pdf";
                dlg.Filter = "Text documents (.pdf)|*.pdf";
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    fileName = dlg.FileName;
                    //设置页面大小
                    iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f);
                    pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE);
                    //设置边界
                    Document document = new Document(pageSize, 36f, 72f, 108f, 180f);
                    PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
                    // 添加文档信息
                    document.AddTitle("PDFInfo");
                    document.AddSubject("Demo of PDFInfo");
                    document.AddKeywords("Info, PDF, Demo");
                    document.AddCreator("SetPdfInfoDemo");
                    document.AddAuthor("焦涛");
                    document.Open();
                    // 添加文档内容
                    for (int i = 0; i < 5; i++)
                    {
                        document.Add(new iTextSharp.text.Paragraph("Hello World! Hello People! " +"Hello Sky! Hello Sun! Hello Moon! Hello Stars!"));
                    }              
                    document.Close();
                }//end if
            }
            /// <summary>
            /// 创建多个Pdf新页
            /// </summary>
            private void CreateNewPdfPage()
            {
                string fileName = string.Empty;
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = "创建多个Pdf新页";//生成的pdf文件名
                dlg.DefaultExt = ".pdf";//pdf的默认后缀名
                dlg.Filter = "Text documents (.pdf)|*.pdf";
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    fileName = dlg.FileName;
                    Document document = new Document(PageSize.NOTE);            
                    PdfWriter writer= PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));                
                    document.Open();
                    // 第一页
                    document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                    document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                    document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                    document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));             
                    // 添加新页面
                    document.NewPage();
                    // 第二页
                    // 添加第二页内容
                    document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                    document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                    document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                    document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                    document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                    document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));          
                    // 添加新页面
                    document.NewPage();
                    // 第三页
                    // 添加新内容
                    document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                    document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                    document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                    document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                    // 重新开始页面计数
                    document.ResetPageCount();
                    // 新建一页
                    document.NewPage();
                    // 第四页
                    // 添加第四页内容
                    document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                    document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                    document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                    document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                    document.Close();
                }//end if
            }
            /// <summary>
            /// 生成图片pdf页(pdf中插入图片)
            /// </summary>
            public void ImageDirect()
            {
                string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image1.jpg"; //临时文件路径
                string fileName = string.Empty;
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = "我的第一个PDF";
                dlg.DefaultExt = ".pdf";
                dlg.Filter = "Text documents (.pdf)|*.pdf";
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    fileName = dlg.FileName;
                    Document document = new Document();
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
                    document.Open();
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
                    img.SetAbsolutePosition((PageSize.POSTCARD.Width - img.ScaledWidth) / 2, (PageSize.POSTCARD.Height - img.ScaledHeight) / 2);
                    writer.DirectContent.AddImage(img);
                    iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph("Foobar Film Festival", new iTextSharp.text.Font(Font.FontFamily.HELVETICA, 22f));
                    p.Alignment = Element.ALIGN_CENTER;
                    document.Add(p);
                    document.Close();
                }//end if
            }
            private void ReadPdf()
            {
                Console.WriteLine("读取PDF文档");
                try
                {
                    // 创建一个PdfReader对象
                    PdfReader reader = new PdfReader(@"D:我的第一个PDF.pdf");
                    // 获得文档页数
                    int n = reader.NumberOfPages;
                    // 获得第一页的大小
                    iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
                    float width = psize.Width;
                    float height = psize.Height;
                    // 创建一个文档变量
                    Document document = new Document(psize, 50, 50, 50, 50);
                    // 创建该文档
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"d:Read.pdf", FileMode.Create));
                    // 打开文档
                    document.Open();
                    // 添加内容
                    PdfContentByte cb = writer.DirectContent;
                    int i = 0;
                    int p = 0;
                    Console.WriteLine("一共有 " + n + " 页.");
                    while (i < n)
                    {
                        document.NewPage();
                        p++;
                        i++;
                        PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                        cb.AddTemplate(page1, .5f, 0, 0, .5f, 0, height / 2);
                        Console.WriteLine("处理第 " + i + " 页");
                        if (i < n)
                        {
                            i++;
                            PdfImportedPage page2 = writer.GetImportedPage(reader, i);
                            cb.AddTemplate(page2, .5f, 0, 0, .5f, width / 2, height / 2);
                            Console.WriteLine("处理第 " + i + " 页");
                        }
                        if (i < n)
                        {
                            i++;
                            PdfImportedPage page3 = writer.GetImportedPage(reader, i);
                            cb.AddTemplate(page3, .5f, 0, 0, .5f, 0, 0);
                            Console.WriteLine("处理第 " + i + " 页");
                        }
                        if (i < n)
                        {
                            i++;
                            PdfImportedPage page4 = writer.GetImportedPage(reader, i);
                            cb.AddTemplate(page4, .5f, 0, 0, .5f, width / 2, 0);
                            Console.WriteLine("处理第 " + i + " 页");
                        }
                        cb.SetRGBColorStroke(255, 0, 0);
                        cb.MoveTo(0, height / 2);
                        cb.LineTo(width, height / 2);
                        cb.Stroke();
                        cb.MoveTo(width / 2, height);
                        cb.LineTo(width / 2, 0);
                        cb.Stroke();
                        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                        cb.BeginText();
                        cb.SetFontAndSize(bf, 14);
                        cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 4) + (n % 4 > 0 ? 1 : 0)), width / 2, 40, 0);
                        cb.EndText();
                    }
                    // 关闭文档
                    document.Close();
                }
                catch (Exception de)
                {
                    Console.Error.WriteLine(de.Message);
                    Console.Error.WriteLine(de.StackTrace);
                }
            }
            
            /// <summary>
            /// 创建表格
            /// </summary>
            public void CreateFirstTable()
            {
                string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image1.pm"; //临时文件路径
                string fileName = string.Empty;
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = "我的第一个PDF";
                dlg.DefaultExt = ".pdf";
                dlg.Filter = "Text documents (.pdf)|*.pdf";
                Nullable<bool> result = dlg.ShowDialog();
                BaseFont baseFont = BaseFont.CreateFont("D:\STSONG.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 9);
                if (result == true)
                {
                    fileName = dlg.FileName;
                    Document document = new Document();
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
                    document.Open();
    
                    iTextSharp.text.Paragraph p;
                    p = new iTextSharp.text.Paragraph("中华人民共和国海关出口货物打单", font);
                    p.Alignment = Element.ALIGN_CENTER;//设置标题居中
                    p.SpacingAfter = 12;//设置段落行 通过设置Paragraph的SpacingBefore和SpacingAfter属性调整Paragraph对象与之间或之后段落的间距
                    p.SpacingBefore = 1;
                    document.Add(p);//添加段落
    
                    p = new iTextSharp.text.Paragraph(GetBlank(5)+"预录入编号:" +"编号代码"+GetBlank(15)+"海关编号:"+GetBlank(5),font);
                    //p.IndentationLeft = 20;
                    //p.IndentationLeft = 20;
                    //p.IndentationRight = 20;
                    //p.FirstLineIndent = 20;
                    //IndentationLeft属性设置左侧缩进。
                    //IndentationRight属性设置右侧缩进。
                    p.SpacingAfter = 12;
                    document.Add(p);//添加段落
    
    
                    PdfPTable table = new PdfPTable(10);//几列
                    
                    PdfPCell cell;
                    cell=new PdfPCell(new Phrase("收发货人"+GetBlank(5)+"具体值"));
                    cell.Colspan = 4;
                    
                    table.AddCell(cell);
                    
                    cell = new PdfPCell(new Phrase("出关口岸"+GetBlank(10)+"具体值"));
                    cell.Rowspan = 2;
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase("出口日期" + GetBlank(10) + "具体值"));
                    cell.Rowspan = 2;
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase("申报日期" + GetBlank(10) + "具体值"));
                    cell.Rowspan = 2;
                    table.AddCell(cell);
    
    
                    cell = new PdfPCell(new Phrase("收发货人" + GetBlank(5) + "具体值"));
                    cell.Colspan = 4;
                    table.AddCell(cell);
    
                    cell = new PdfPCell(new Phrase("出关口岸" + GetBlank(10) + "具体值"));
                    cell.Rowspan = 2;
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase("出口日期" + GetBlank(10) + "具体值"));
                    cell.Rowspan = 2;
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase("申报日期" + GetBlank(10) + "具体值"));
                    cell.Rowspan = 2;
                    table.AddCell(cell);
    
    
                    //table.AddCell("row 1; cell 1");
                    //table.AddCell("row 1; cell 2");
                    //table.AddCell("row 2; cell 1");
                    //table.AddCell("row 2; cell 2");
                    document.Add(table);
                    document.Close();
                }//end if
            }
            /// <summary>
            /// 获得空格
            /// </summary>
            /// <param name="num"></param>
            /// <returns></returns>
            private static string GetBlank(int num)
            {
                StringBuilder blank = new StringBuilder();
                for (int i = 0; i < num; i++)
                {
                    blank.Append(" ");
                }
                return blank.ToString();
            }
    
            private void button1_Click(object sender, RoutedEventArgs e)
            {
                //CreatePdf();      
                //CreatePdfPageSize();
                CreateNewPdfPage();
            }
            private void button2_Click(object sender, RoutedEventArgs e)
            {
                CreateFirstTable();
            }
    
            private void button3_Click(object sender, RoutedEventArgs e)
            {
                ImageDirect();
            }
    
            private void button4_Click(object sender, RoutedEventArgs e)
            {
                ReadPdf();
            }
    

      在这里用到了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第三个例子样的功能。

  • 相关阅读:
    Java核心技术(初阶)知识点复习——[2]面向对象思想
    Java核心技术(初阶)知识点复习——[1]Java的类结构和main函数
    printStream与printWriter
    java反射的初步探索
    JDKJREJVM的关系
    树链剖分模板
    树状数组模板2
    树状数组模板1
    树状数组+欧拉降幂
    线段树模板二
  • 原文地址:https://www.cnblogs.com/jiangyunfeng/p/11666668.html
Copyright © 2011-2022 走看看