c#打印一个Windows窗体应用程序
本文关键字:一个 Windows 窗体 应用程序 打印 | 更新日期: 2023-09-27 18:17:19
我发现这段代码打印
// The PrintDialog will print the document
// by handling the document's PrintPage event.
private void document_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
// Insert code to render the page here.
// This code will be called when the control is drawn.
// The following code will render a simple
// message on the printed document.
string text = "In document_PrintPage method.";
System.Drawing.Font printFont = new System.Drawing.Font
("Arial", 35, System.Drawing.FontStyle.Regular);
// Draw the content.
e.Graphics.DrawString(text, printFont,
System.Drawing.Brushes.Black, 10, 10);
}
// Declare the PrintDocument object.
private System.Drawing.Printing.PrintDocument docToPrint =
new System.Drawing.Printing.PrintDocument();
private void printButton_Click(object sender, EventArgs e)
{
PrintDialog PrintDialog1 = new PrintDialog();
// Allow the user to choose the page range he or she would
// like to print.
PrintDialog1.AllowSomePages = true;
// Show the help button.
PrintDialog1.ShowHelp = true;
// Set the Document property to the PrintDocument for
// which the PrintPage Event has been handled. To display the
// dialog, either this property or the PrinterSettings property
// must be set
PrintDialog1.Document = docToPrint;
DialogResult result = PrintDialog1.ShowDialog();
// If the result is OK then print the document.
if (result == DialogResult.OK)
{
docToPrint.Print();
}
}
我执行它,打印的结果是一个empty page
,我的问题是我在哪里可以把数据打印?以及如何将打印的数据作为行,每一行都有标签和值。
将PrintDocument创建为私有成员:
// Declare the PrintDocument object.
private System.Drawing.Printing.PrintDocument docToPrint =
new System.Drawing.Printing.PrintDocument();
但是这使得很难在正确的时刻附加事件处理程序。我建议使用构造函数:
// Declare the PrintDocument object.
private System.Drawing.Printing.PrintDocument docToPrint;
//= new System.Drawing.Printing.PrintDocument();
public Form1() // the Form ctor
{
InitializeComponents();
docToPrint = new System.Drawing.Printing.PrintDocument();
docToPrint.PrintPage += document_PrintPage; // the missing piece
}