java: set page range for print dialog
Asked Answered
S

2

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.

Sunflower answered 2/6, 2011 at 15:14 Comment(3)
I think the "nt" in the end of "Print" but for some reason your icon is overlapping it.Musgrave
It's not my icon, it's the standard Java icon.Sunflower
@Abdullah -- OH! I just did a Print from another application and there is no icon there.Sunflower
G
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 {

    }
}
}
Girlie answered 2/6, 2011 at 15:32 Comment(3)
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.Sunflower
book.append(Printable) requires a PageFormat, which cannot be null, so I'm back to square one.Sunflower
edited my code fragment, there is a default option for page format - "job.defaultPage()"Girlie
E
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 */
     }
}
Economizer answered 7/8, 2017 at 21:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.