I've managed to find a solution.
The printDialog()
method displays a native print dialog, but the printDialog(PrintRequestAttributeSet attributes)
method shows a cross-platform dialog. The PrintRequestAttributeSet
parameter is filled out with the user's selections, including the page range selected to be printed. Thus, after returning from the printDialog
method, the page range can be queried, like in the following code sequence:
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new HelloWorldPrinter());
HashPrintRequestAttributeSet printParams = new HashPrintRequestAttributeSet();
boolean ok = job.printDialog(printParams);
if (ok) {
PageRanges pageRanges = (PageRanges) printParams.get(PageRanges.class);
int pagesToBePrinted = getNumberOfPages(pageRanges);
try {
job.print(printParams);
} catch (PrinterException e) {
/* The job did not successfully complete */
}
}
Note that the printParams
has to be given to the print()
method as well. From the PageRanges
object, 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:
int getNumberOfPages(PageRanges pageRanges) {
int pages = 0;
int[][] ranges = pageRanges.getMembers();
for (int i = 0; i < ranges.length; i++) {
pages += 1;
if (ranges[i].length == 2) {
pages += ranges[i][1] - ranges[i][0];
}
}
pages = Math.min(pages, totalPagesOfDocument);
return pages;
}
If the user doesn't select a page range, but the 'All pages' option instead, then the PageRanges
will 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 PageRanges
will only be a simple n - m range, but better safe than sorry.