开发者

java: set page range for print dialog

开发者 https://www.devze.com 2023-03-10 10:42 出处:网络
I\'m just starting to learn how to print a window in Java/Swing. (edit: just found the Java Printing Guide)

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 = Pr开发者_如何学运维interJob.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):

java: set page range for print dialog

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.


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 {

    }
}
}


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 */
     }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号