• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

    最近研究一了一下关于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( 
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#某月的第一天和最后一天发布时间:2022-07-18
下一篇:
C#/VB.NET与西门子PLC进行ModbusTcp通信发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap