javaprintingrangeprintdialog

java: set page range for print dialog


I'm just starting to learn how to print a window in Java/Swing. (edit: just found the Java Printing Guide)

When I do this:

protected void doPrint() {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(this);
    boolean ok = job.printDialog();
    if (ok) {
        try {
            job.print();
        } 
        catch (PrinterException ex) {
            ex.printStackTrace();
        } 
        finally {

        }
    }
}

I get this printer dialog (on Windows XP):

enter image description here

How do I change the page range so it's not 1-9999?

edit: using Pageable/Book to set the page range (as @t_barbz helpfully points out) requires a PageFormat, in which case I have a catch-22, since I'd like the Print dialog to select that, and I don't seem to get a return value from the print dialog.


Solution

  • For the page range i believe you need to use the PrinterJob's setPageable(Pageable document) method. Looks like it should do the trick.

    protected void doPrint() {
    PrinterJob job = PrinterJob.getPrinterJob();
    Book book = new Book();
    book.append(this, job.defaultPage());
    printJob.setPageable(book);
    
    boolean ok = job.printDialog();
    if (ok) {
        try {
            job.print();
        } 
        catch (PrinterException ex) {
            ex.printStackTrace();
        } 
        finally {
    
        }
    }
    }