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

Jonathan Mitchem picture Jonathan Mitchem · Jun 29, 2010 · Viewed 9.3k times · Source

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)

Answer

TzOk picture TzOk · Jul 12, 2012

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