Is there a better way to get the page count from a PrintDocument than this?

此生再无相见时 提交于 2019-12-09 03:05:49

问题


This is the best I've come up with:

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;
}

Is there a better way to do this? (This is actually quite slow)


回答1:


So the final solution would be:

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



回答2:


Declare the PrintController as a Printing.PreviewPrintController.

This way, you're only printing to memory, not to a file.

I use this in a VB.NET project, and it works perfectly!




回答3:


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

There is a PrintDocument.QueryPageSettings Event that could be handled. If handled, it is called before each PrintDocument.PrintPage event. So you can put a counter there to count the pages. This way you could avoid a two pass (one pass to print the doc to file for counting the pages and second pass for the actual job printing).

The URL above has some example code for a counter also.

Hope this helps



来源:https://stackoverflow.com/questions/3137207/is-there-a-better-way-to-get-the-page-count-from-a-printdocument-than-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!