9

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.

Dani
  • 1,825
  • 2
  • 15
  • 29
Jason S
  • 184,598
  • 164
  • 608
  • 970

2 Answers2

4

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 {

    }
}
}
t_barbz
  • 747
  • 2
  • 13
  • 21
  • Hmm. Not so easy. Although `Pageable` allows you to return the # of pages, it also requires you to come up with a PageFormat document and I don't know how to do that. – Jason S Jun 02 '11 at 15:36
  • book.append(Printable) requires a PageFormat, which cannot be null, so I'm back to square one. – Jason S Jun 02 '11 at 15:41
  • edited my code fragment, there is a default option for page format - "job.defaultPage()" – t_barbz Jun 02 '11 at 15:49
2

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 */
     }
}
Dani
  • 1,825
  • 2
  • 15
  • 29