【发布时间】:2015-11-29 22:21:36
【问题描述】:
我正在制作一个简单的 WinForms 应用程序,我希望允许用户从 RichTextBox 打印文本。
然后我关注了MSDN link.. 它适用于真正的打印机(真正的我是指我可以触摸的打印机:))
但是如果我想使用某种 PDF 打印机怎么办? 那么我必须说它在只打印一页 时有效。 每一个下一页都被打印在第一页上,这意味着文本被套印了。 这很明显,但我能做些什么来强制 PDF 打印机创建一个新页面?
这是我的代码:
private PrintDocument docToPrint;
private string stringToPrint;
public mainForm()
{
InitializeComponent();
CenterToScreen();
this.docToPrint = new PrintDocument();
(...)
}
private void tsBtnPrint_Click(object sender, EventArgs e)
{
PrintDialog myPrintDialog = new PrintDialog();
myPrintDialog.AllowCurrentPage = true;
myPrintDialog.AllowSelection = true;
myPrintDialog.AllowSomePages = true;
myPrintDialog.Document = docToPrint;
if(myPrintDialog.ShowDialog()==DialogResult.OK)
{
StringReader reader = new StringReader(this.richTextBox.Text);
stringToPrint = reader.ReadToEnd();
this.docToPrint.PrintPage += new PrintPageEventHandler(this.docToPrintCustom);
this.docToPrint.Print();
}
}
private void docToPrintCustom(object sender, PrintPageEventArgs e)
{
Font PrintFont = this.richTextBox.Font;
SolidBrush PrintBrush = new SolidBrush(Color.Black);
int LinesPerPage = 0;
int charactersOnPage = 0;
e.Graphics.MeasureString(stringToPrint, PrintFont, e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out LinesPerPage);
e.Graphics.DrawString(stringToPrint, PrintFont, PrintBrush, e.MarginBounds, StringFormat.GenericTypographic);
stringToPrint = stringToPrint.Substring(charactersOnPage);
MessageBox.Show(stringToPrint.Length.ToString());
e.HasMorePages = (stringToPrint.Length > 0);
PrintBrush.Dispose();
}
我应该怎么做才能以正确的方式打印每一页?
【问题讨论】:
-
您能否检查一下您是否只在代码中设置了一次
PrintPage事件?如果您多次设置它可能会发生这种情况(如果您的代码基于 MSDN 示例,那么构造函数中的“(...)”可能会有另一个分配)。 -
嗨 :) 是的,我只设置了一次 PrintPage 事件,如代码所示。 (...) 中没有其他赋值。
-
很奇怪。它适用于某些 PDF 打印机,其中一些不适用。我不知道有什么我可以做的。
-
只执行一次:
this.docToPrint.PrintPage += new PrintPageEventHandler设置打印处理程序。每次单击按钮时都会添加它,因此每次单击按钮时您的代码都会运行多次。您不需要那个 StringReader,只需stringToPrint = this.richTextBox.Text;学习使用调试器并逐步检查代码以查看发生了什么的美好一天。 MessageBox 是穷人的调试器——停止使用它。 -
@LarsTech 谢谢你的好建议,我真的很感激:)
标签: c# .net winforms printing richtextbox