gpt4 book ai didi

c# - 如何在 C# 中将长字符串打印到多个页面

转载 作者:行者123 更新时间:2023-11-30 23:11:05 24 4
gpt4 key购买 nike

我正在尝试使用下面的代码打印一个很长的字符串,但它只在一页中打印了整个文本。有什么简单的方法可以正确打印吗?

string text="the text has like 1000 words";

System.Drawing.Printing.PrintDocument p = new System.Drawing.Printing.PrintDocument();

p.PrintPage += delegate (object sender1, System.Drawing.Printing.PrintPageEventArgs e1)
{
e1.Graphics.DrawString(text, new System.Drawing.Font("Times New Roman", 12), new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.RectangleF(50, 50, p.DefaultPageSettings.PrintableArea.Width - 50, p.DefaultPageSettings.PrintableArea.Height - 50));

};
try
{
p.Print();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}

我试着用 this article 来解决它但是该方法卡在了某个我不知道如何修复的循环中。

最佳答案

您必须记住,只要告诉它还有更多页面,PrintDocument 就会引发事件PrintPage。您的任务是跟踪打印的内容、接下来需要打印的内容以及是否需要另一页。

有几种方法可以做到这一点。在这种情况下,我选择获取您的 text 的内容,检查它有多少适合当前页面,DrawString 那一点,然后更新我的处理字符串,称为 remainingtext 以便能够重复下一页。完成后,通过将 PrintEvent 参数实例的 HasMorepages 设置为 true 或 false 来决定是否需要下一页。

代码如下:

PrintDocument p = new PrintDocument();

var font = new Font("Times New Roman", 12);
var margins = p.DefaultPageSettings.Margins;
var layoutArea = new RectangleF(
margins.Left,
margins.Top,
p.DefaultPageSettings.PrintableArea.Width - (margins.Left + margins.Right ),
p.DefaultPageSettings.PrintableArea.Height - (margins.Top + margins.Bottom));
var layoutSize = layoutArea.Size;
layoutSize.Height = layoutSize.Height - font.GetHeight(); // keep lastline visible
var brush = new SolidBrush(Color.Black);

// what still needs to be printed
var remainingText = text;

p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
{
int charsFitted, linesFilled;

// measure how many characters will fit of the remaining text
var realsize = e1.Graphics.MeasureString(
remainingText,
font,
layoutSize,
StringFormat.GenericDefault,
out charsFitted, // this will return what we need
out linesFilled);

// take from the remainingText what we're going to print on this page
var fitsOnPage = remainingText.Substring(0, charsFitted);
// keep what is not printed on this page
remainingText = remainingText.Substring(charsFitted).Trim();

// print what fits on the page
e1.Graphics.DrawString(
fitsOnPage,
font,
brush,
layoutArea);

// if there is still text left, tell the PrintDocument it needs to call
// PrintPage again.
e1.HasMorePages = remainingText.Length > 0;
};
p.Print();

当我连接 PrintPreviewControl 时,结果如下:

shows the printpage in action

关于c# - 如何在 C# 中将长字符串打印到多个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44979794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com