c# 分页打印多行文本

来源:互联网 发布:妖姬葵 知乎 编辑:程序博客网 时间:2024/06/01 03:58
直接上代码了。 
[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]






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

0 0
原创粉丝点击