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

标签 c# winforms

我有一些自定义 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/

相关文章:

c# - Winforms中如何获取被点击的ListView单元格?

winforms - 使用c#在执行之前解析sql脚本

c# - 如何在字符串格式 c# 中添加 {

c# - Xamarin Forms - 如何获取设备的当前国家/地区

c# - MVVM 绑定(bind)搜索栏到 Observablecollection 错误

c# - 如何将 .Net 框架先决条件添加到设置安装

.net - 与字体相关的控制定位

c# - 以编程方式安排/创建 Skype for Business session

c# - 如何加快此 LINQ 查询的速度?

c# - 将 C# 表单序列化为 XML