运行效果:
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace Print
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private int intCurrentRowIndex = ; public void InitPrintDocument(PrintDocument printDocument)
{
printDocument.DocumentName = "PrintDocument事例!"; foreach (PaperSize ps in printDocument.PrinterSettings.PaperSizes)
{
if (ps.PaperName == "A4")
{
printDocument.DefaultPageSettings.PaperSize = ps;
break;
}
} printDocument.BeginPrint += printDocument_BeginPrint; printDocument.EndPrint += printDocument_EndPrint; printDocument.PrintPage += printDocument_PrintPage;
} void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
int x = ;
int y = ; for (int i = intCurrentRowIndex; i < this.textBox1.Lines.Length; i++)
{
e.Graphics.DrawString(this.textBox1.Lines[i], this.textBox1.Font, Brushes.Black, x, y);
intCurrentRowIndex++; y = this.textBox1.Font.Height + ; if (y > e.PageBounds.Height)
{
e.HasMorePages = true;
break;
}
}
} void printDocument_EndPrint(object sender, PrintEventArgs e)
{
this.label2.Text = "打印完成!";
} void printDocument_BeginPrint(object sender, PrintEventArgs e)
{
intCurrentRowIndex = ;
this.label2.Text = "开始打印!";
Application.DoEvents();
} private void Form1_Load(object sender, EventArgs e)
{
InitPrintDocument(this.printDocument1);
} private void btn_Print_Click(object sender, EventArgs e)
{
this.printDocument1.Print();
} private void btn_Cancle_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
完成。