This is the basic printing program example from the Sun tutorial:
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new HelloWorldPrinter());
boolean doPrint = job.printDialog();
if (doPrint) {
try {
job.print();
} catch (PrinterException e) {
/* The job did not successfully complete */
}
}
When the user is shown the print dialog (on the second line), he can choose to print only a range of pages from the document. Can I somehow get the number of pages that are to be printed? For example, if I have a 25 page document, but the user chooses to print the range 4-10, then only 7 pages will be printed. Is there someway to access that information?
I need this in order to show a progress bar which increases with each page printed, but for that I need to know the total number of pages that are going to be printed.
So how can I get that number?
I’ve managed to find a solution.
The
printDialog()method displays a native print dialog, but theprintDialog(PrintRequestAttributeSet attributes)method shows a cross-platform dialog. ThePrintRequestAttributeSetparameter is filled out with the user’s selections, including the page range selected to be printed. Thus, after returning from theprintDialogmethod, the page range can be queried, like in the following code sequence:Note that the
printParamshas to be given to theprint()method as well. From thePageRangesobject, the page ranges can be obtained in array format, i.e. an array of 1-length arrays meaning a single page each or 2-length arrays meaning contiguous ranges of pages. See the javadoc for more details. To calculate the total number of pages is straightforward:If the user doesn’t select a page range, but the ‘All pages’ option instead, then the
PageRangeswill contain the range (1, Integer.MAX_VALUE). So I say that if the computed value exceeds the number of pages of the document, then the number of pages to be printed is the total number of the document’s pages (which I hope you know from somewhere).The algorithm is perhaps overkill, as probably the
PageRangeswill only be a simple n – m range, but better safe than sorry.