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

SaintWacko picture SaintWacko · Nov 29, 2011 · Viewed 16.9k times · Source

I have written a program that uses the Java print API to print pages from a printer. 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:

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?

Answer

mprabhat picture mprabhat · Nov 29, 2011

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);