gpt4 book ai didi

c# - Windows 窗体 700 多页打印问题

转载 作者:行者123 更新时间:2023-11-30 18:30:26 25 4
gpt4 key购买 nike

我有一些自定义 Windows 窗体,动态加载每个窗体并使用 System.Drawing.Printing.PrintDocument 打印窗体控件值。

我的问题是,我有 700 多页要打印,如果打印超过 300 页,我就会遇到内存不足的问题,如何使用 System.Drawing.Printing

最佳答案

PrintDocument 具有OnBeginPrint(),您可以在您的继承类中重写它(或处理为订阅它的事件)。它传递的参数可以告诉您此打印是用于预览还是实际打印(实际上有 3 个值:PrintToFilePrintToPreviewPrintToPrinter) .你可以这样区分打印的目的。此外,您唯一需要知道的是,当您预览您的文档时,您的OnPrintPage() 将被连续调用 700 次,从而在内存中构建整个文档;当您实际打印文档到打印机时,在调用OnPrintPage() 之后,它不会在内存中保留所有以前的页面。这就是为什么要打印任何文档,您实际上需要内存来仅存储其最占内存的页面。

因此您只需要在预览时绘制简化的页面内容,并在实际打印时才绘制完整的页面。

下一个示例说明了我的方法:

class PrintDocument1 : PrintDocument
{
int currentPage;
bool isPreview;

protected override void OnBeginPrint(PrintEventArgs e)
{
currentPage = 0;
isPreview = e.PrintAction == PrintAction.PrintToPreview;
}

protected override void OnPrintPage(PrintPageEventArgs e)
{
currentPage++;

if (isPreview)
{
// simplified page drawing

e.Graphics.FillRectangle(Brushes.BurlyWood, e.MarginBounds);
e.Graphics.DrawString("Page #" + currentPage, SystemFonts.CaptionFont, Brushes.Black, e.MarginBounds.Location);
}
else
{
// full page drawing

Bitmap[] bmaps = new Bitmap[] {
SystemIcons.Application.ToBitmap(),
SystemIcons.Information.ToBitmap(),
SystemIcons.Question.ToBitmap(),
SystemIcons.Warning.ToBitmap(),
SystemIcons.Shield.ToBitmap(),
SystemIcons.Error.ToBitmap()
};

Point p = e.MarginBounds.Location;
for (int i = 0; p.Y < e.MarginBounds.Bottom; i++, p.Y += 40)
{
e.Graphics.DrawString("Some text goes here, line " + (i + 1), SystemFonts.CaptionFont, Brushes.Black, p);
e.Graphics.DrawLine(Pens.CadetBlue, e.MarginBounds.Left, p.Y, e.MarginBounds.Right, p.Y);
for (int j = 0; j < bmaps.Length; j++)
e.Graphics.DrawImage(bmaps[j], p.X + 200 + j * 40, p.Y);
}
}

e.HasMorePages = currentPage < 700; // a lot of pages to draw
}
}

// above class can be previewed and printed next way:
// PrintPreviewDialog d = new PrintPreviewDialog();
// d.Document = new PrintDocument1();
// d.ShowDialog();

关于c# - Windows 窗体 700 多页打印问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21529191/

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