【问题标题】:Is there a better way to get the page count from a PrintDocument than this?有没有比这更好的方法来从 PrintDocument 获取页数?
【发布时间】:2011-03-09 09:49:24
【问题描述】:

这是我想出的最好的:

public static int GetPageCount( PrintDocument printDocument )
{
    printDocument.PrinterSettings.PrintFileName = Path.GetTempFileName();
    printDocument.PrinterSettings.PrintToFile = true;

    int count = 0;

    printDocument.PrintController = new StandardPrintController();
    printDocument.PrintPage += (sender, e) => count++;

    printDocument.Print();

    File.Delete( printDocument.PrinterSettings.PrintFileName );

    return count;
}

有没有更好的方法来做到这一点? (这实际上很慢)

【问题讨论】:

  • 与 PrintDocument 本身无关。您将需要通过行数和将使用的边距以及每页所需的行数等来了解要打印的文件的页数。

标签: c# printing printdocument


【解决方案1】:

所以最终的解决方案是:

public static int GetPageCount(PrintDocument printDocument)
{
    int count = 0;
    printDocument.PrintController = new PreviewPrintController();
    printDocument.PrintPage += (sender, e) => count++;
    printDocument.Print();
    return count;
}

【讨论】:

  • 我建议备份 PrintController 并将其恢复到完成假打印后的状态。没有这个,当我想做真正的打印时,我的就不会打印了。所以它在开始时是“PrintController pcBackup = printDocument.PrintController”,在返回计数值之前是“printDocument.PrintController = pcBackup”。
  • 如何构建printDocument
【解决方案2】:

将 PrintController 声明为 Printing.PreviewPrintController

这样,您只打印到内存,而不是文件。

我在一个 VB.NET 项目中使用它,效果很好!

【讨论】:

    【解决方案3】:

    检查 - http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.querypagesettings.aspx

    有一个可以处理的 PrintDocument.QueryPageSettings 事件。如果已处理,则在每个 PrintDocument.PrintPage 事件之前调用它。所以你可以在那里放一个计数器来计算页面。这样您就可以避免两次通过(一次通过打印文档到文件以计算页数,第二次通过实际作业打印)。

    上面的 URL 也有一些计数器的示例代码。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 2010-11-11
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多