8

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)

Jonathan Mitchem
  • 953
  • 3
  • 13
  • 18
  • Not with PrintDocument itself. You will need to know the amount of page of the file you want to print via the amount of line and the margin you will use and the amount of line you want per page, etc. – Wildhorn Aug 27 '10 at 18:30

3 Answers3

5

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;
}
TzOk
  • 66
  • 1
  • 3
  • 1
    I'd suggest backing up the PrintController and restoring it back to how it was after you've done the fake print. Without this, mine wouldn't print when I wanted to do the real print. So it'd be "PrintController pcBackup = printDocument.PrintController" at the beginning and "printDocument.PrintController = pcBackup" just before returning the count value. – joshhendo Jan 31 '14 at 02:17
  • How you construct the `printDocument` ? – huMpty duMpty Jul 09 '14 at 12:36
1

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!

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
0

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

Nitin Unni
  • 358
  • 1
  • 6