Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 770
Jason S Avatar asked Jun 02 '11 15:06

Jason S


2 Answers

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 {

    }
}
}
like image 81
t_barbz Avatar answered Nov 16 '22 23:11

t_barbz


Finally here is a simple code:

PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
PrintRequestAttributeSet printAttribute = new HashPrintRequestAttributeSet();
printAttribute.add(new PageRanges(1, 100));        
boolean ok = job.printDialog(printAttribute);
if (ok) {
     try {
          job.print();
     } catch (PrinterException ex) {
      /* The job did not successfully complete */
     }
}
like image 24
Dani Avatar answered Nov 17 '22 01:11

Dani