c# 分页打印多行文本

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zanfeng/article/details/54988594
直接上代码了。 
[code=csharp]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;


namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            text = this.textBox1.Text;
            PrintDocument pd = new PrintDocument();
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            pd.BeginPrint += new PrintEventHandler(pd_BeginPrint); 
             
            using (System.Windows.Forms.PrintPreviewDialog dlg = new PrintPreviewDialog())
            {
                dlg.Document = pd;
                dlg.WindowState = FormWindowState.Maximized;
                dlg.AllowTransparency = true;
                dlg.AutoScaleMode = AutoScaleMode.Dpi; 
                dlg.ShowDialog(); 
            }
        }


        void pd_BeginPrint(object sender, PrintEventArgs e)
        {
            sf = Size.Empty;
            top = 0;
        }
        string text = string.Empty;
        int top = 0;
        Size sf = Size.Empty;


        void pd_PrintPage(object sender, PrintPageEventArgs e)
        { 
            if (sf == Size.Empty)
            {
                sf =Size.Round ( e.Graphics.MeasureString(text, Font, e.MarginBounds.Width));
            }
            e.Graphics.SetClip(e.MarginBounds);
            e.Graphics.DrawString(text, this.Font, Brushes.Black, new Rectangle(e.MarginBounds.Location.X,
                e.MarginBounds.Location.Y + top * -1, sf.Width, sf.Height));
            //e.Graphics.DrawString(text, this.Font, Brushes.Black, new PointF(0, top * -1));
            if (top + e.MarginBounds.Height < sf.Height)
            {
                top = top + e.MarginBounds.Height;
                e.HasMorePages = true;
            } 
        }
    }
}


[/code]






没有测试上百页的,估计是有问题。

展开阅读全文

没有更多推荐了,返回首页