Search code examples
c#printingprintdocument

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


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)


Solution

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