private void printReceipt()
{
printDialog.Document = printDocument;
DialogResult result = printDialog.ShowDialog();
if (result != DialogResult.OK) return;
try
{
sPrint = new StreamReader(
new MemoryStream(
Encoding.ASCII.GetBytes(richTextBoxResult.Text)));
printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
printDocument.Print();
}
catch (Exception e)
{
MessageBox.Show("Failed to print \n" + e.Message);
}
finally
{
if (sPrint != null)
sPrint.Close();
}
}
void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
// No of lines that fit on to the page
float linesPerPage = e.MarginBounds.Height / richTextBoxResult.Font.GetHeight(e.Graphics);
float fontHeight = richTextBoxResult.Font.GetHeight(e.Graphics);
for (int count = 0; count < linesPerPage && !sPrint.EndOfStream; count++)
{
e.Graphics.DrawString(sPrint.ReadLine(),
richTextBoxResult.Font,
Brushes.Black,
e.MarginBounds.Left,
e.MarginBounds.Top + (count * fontHeight),
new StringFormat());
}
e.HasMorePages = !sPrint.EndOfStream;
}
我的问题:-
- 我需要在打印时正确调整所有文本框内容。 (较长的单行未打印,而是跳到页面之外)
- 是否有可能在打印菜单下启用打印范围选项? (在输出 GUI 上,假设我有可以放在多个页面上的文本内容)
请帮忙。 谢谢。
最佳答案
至于打印时你的字符串越界,使用Graphics.DrawString就像您现在所做的那样,但使用不同的参数。 Graphics.DrawString 有一组不同的参数,可让您定义字符串必须适合的矩形的高度和宽度。如果你给它适当的宽度,当同一行的最后一个单词不适合并开始换行时,字符串将被“中断”。
像这样:
e.Graphics.DrawString(sPrint.ReadLine(),
richTextBoxResult.Font,
Brushes.Black,
new RectangleF(x, y, p.DefaultPageSettings.PrintableArea.Width, p.DefaultPageSettings.PrintableArea.Height));
注意上面的代码,硬编码页面的限制可能不是一个好主意,但你明白了。
关于你的第二个问题,如果我理解正确的话:你想测量你的字符串在什么时候不适合你的页面(垂直)?您可以使用 Graphics.MeasureString为了那个原因。我一直在为同样的事情苦苦挣扎,我发现这是性能更高的选项之一。
关于C# 打印问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16775405/