• PrintDocument 打印多页文本,PDF打印


    在开始编码之前先了解PrintDocument的几个方法,如下:

     打印文本的基本逻辑如下

         PrintDocument pdDocument = new PrintDocument();
         pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
    
    private void OnPrintPage(object sender, PrintPageEventArgs e)
            {
                int leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4);  //左边距
                int topMargin = Convert.ToInt32(e.MarginBounds.Top * 2 / 3);    //顶边距
                while (linesPrinted < lines.Length)
                {
                    e.Graphics.DrawString("你好", new Font("黑体", 10), Brushes.Black, leftMargin, topMargin);
                 }
            }

    如果需要打印的文本比较长,使用上述打印方式就会出现文字内容不全的问题,此时需要能够打印多页的功能

    大致思路是将文本按照一个分隔符将文本分割成数组在OnPrintPage方法中给每一行计算一个高度,判断高度是否超出文档页高度,如果超出则设置新一页

                PrintDocument pdDocument = new PrintDocument();//声明一个文档
                private string[] lines;//存储文本数组
    private int linesPrinted;//记录行数 pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint); pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage); /// <summary> /// 得到打印內容 /// 每个打印任务只调用OnBeginPrint()一次。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void pdDocument_BeginPrint(object sender, PrintEventArgs e) { lines = this.richTextBox1.Text.Split(new string[1] { " " }, StringSplitOptions.None); } /// <summary> /// 绘制多个打印界面 /// printDocument的PrintPage事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnPrintPage(object sender, PrintPageEventArgs e) { int leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4);  //左边距 int topMargin = Convert.ToInt32(e.MarginBounds.Top * 2 / 3);    //顶边距 while (linesPrinted < lines.Length) { e.Graphics.DrawString(lines[linesPrinted++], new Font("黑体", 10), Brushes.Black, leftMargin, topMargin); topMargin += 25;//行高为55,可调整 //页面累加的高度大于页面高度。根据自己需要,可以适当调整 if (topMargin >= e.PageBounds.Height - 60) { //如果大于设定的高 e.HasMorePages = true; /* * PrintPageEventArgs类的HaeMorePages属性为True时,通知控件器,必须再次調用OnPrintPage()方法,打印一个页面。 * PrintLoopI()有一个用於每个要打印的页面的序例。如果HasMorePages是False,PrintLoop()就会停止。 */ return; } } linesPrinted = 0; //绘制完成后,关闭多页打印功能 e.HasMorePages = false; }
     e.Graphics.DrawString(lines[linesPrinted++], new Font("黑体", 10), Brushes.Black, leftMargin, topMargin);
    方法有多个重载,如果需要指定保留文本格式,则使用

     public void DrawString(string s, Font font, Brush brush, float x, float y, StringFormat format)

    默认文本格式(文本的原有格式)

     public void DrawString(string s, Font font, Brush brush, float x, float y)

    打印效果,下图为缩略图有4页文档被输出成PDF

    //声明一个文档
  • 相关阅读:
    「字符串算法」第4章 字典树课堂过关
    「字符串算法」第3章 KMP 算法课堂过关
    「字符串算法」第2章 Hash 和 Hash 表课堂过关
    「基础算法」第5章 广度搜索课堂过关
    「基础算法」第3章 二分算法课堂过关
    「基础算法」第1章 递推算法强化训练
    「基础算法」第1章 递推算法课堂过关
    YbtOJ:冲刺 NOIP2020 模拟赛 Day10
    【模板】轻重链剖分
    LINUX-磁盘空间
  • 原文地址:https://www.cnblogs.com/houzf/p/13524457.html
Copyright © 2020-2023  润新知