简体   繁体   English

如何在Java中设置打印页面的大小?

[英]How do I set the size of a printed page in java?

I have written a program that uses the Java print API to print pages from a printer. 我编写了一个程序,该程序使用Java打印API从打印机打印页面。 I believe I have put in code to set the page size to letter, but it still prints on whatever size is default for the printer. 我相信我已经在代码中将页面大小设置为字母,但是它仍然可以使用打印机默认的大小进行打印。 Here is my printPage() method: 这是我的printPage()方法:

public void printPage() {
    getTot();
    PrinterJob job = PrinterJob.getPrinterJob();
    PageFormat pf = job.defaultPage();
    Paper paper = pf.getPaper();
    paper.setSize(8.5 * 72, 11 * 72);
    paper.setImageableArea(0.5 * 72, 0.0 * 72, 7.5 * 72, 10.5 * 72);
    pf.setPaper(paper);
    job.setPrintable(this);
    boolean ok = job.printDialog();
    if (ok) {
        if (cov)
            try {
                for (j = 0; j < printPaths.size(); j++)
                    job.print();
                cov = false;
            } catch (PrinterException ex) {
                System.out.println(ex.getMessage());
            }
        if (summ)
            try {
                job.print();
                summ = false;
            } catch (PrinterException ex) {
                System.out.println(ex.getMessage());
            }
    }

}

What am I doing wrong? 我究竟做错了什么?

Can you try adding this piece of code and rerun : 您可以尝试添加以下代码并重新运行:

Book book = new Book();//java.awt.print.Book
book.append(this, pf);
job.setPageable(book);

instead of 代替

job.setPrintable(this);

Book didn't work for me with my multiple pages example (the result was the printing of only the first page), but it gave me another idea. 在我的多页示例中,Book不适用于我(结果是仅打印第一页),但这给了我另一个主意。 Instead of : 代替 :

Book book = new Book();//java.awt.print.Book
book.append(this, pf);
job.setPageable(book);

I tried another overloaded method and it worked for all pages: 我尝试了另一种重载方法,它适用于所有页面:

PageFormat pf = job.defaultPage();
pf.setPaper(paper);
job.setPrintable(this, pf);

If you want custom paper size, you need to forward it to print method as an argument (which Java will do for you but you must pass it to setPrintable method). 如果您想要自定义纸张尺寸,则需要将其作为参数转发到打印方法(Java将为您做这件事,但您必须将其传递给setPrintable方法)。 Changing PaperFormat after method starts to execute will have an effect only on the second and further pages or not have any effect at all. 在方法开始执行后更改PaperFormat将仅对第二页及以后的页产生影响,或者根本不起作用。

Anyway, thanks to you both. 无论如何,谢谢你们俩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM