1
votes

I have a Printable class named myPrintableObject and print method is over-ridden in following manner:

public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException
      {
        if(pageIndex<5)
          {
           pf.setOrientation(PageFormat.LANDSCAPE);
           g.drawString("HELLO FRIEND",100,180);
           return PAGE_EXISTS;
          }
        else
          {return NO_SUCH_PAGE;}

     }

I wanted to print multiple pages in landscape orientation in same document. It is printing except the first page. It is always getting printed in portrait orientation.

How can I fix this?

1
You should override the method PageFormat getPageFormat(int pageIndex) of Pageable interfaceStanislavL
will you please explain in details ???? @ StanislavLARNAB2012

1 Answers

1
votes

Here you are:

    PrinterJob job = PrinterJob.getPrinterJob();
    PageFormat pf = job.defaultPage();
    pf.setOrientation(PageFormat.LANDSCAPE);
    job.setPrintable(myPrintableObject, pf);

Working example:

public class MyPrintable implements Printable {

    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        if (pageIndex < 5) {
            graphics.drawString("HELLO FRIEND", 100, 180);
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }

    public static void main(String[] args) {
        PrinterJob job = PrinterJob.getPrinterJob();
        PageFormat pf = job.defaultPage();
        pf.setOrientation(PageFormat.LANDSCAPE);
        job.setPrintable(new MyPrintable(), pf);

        boolean ok = job.printDialog();
        if (ok) {
            try {
                job.print();
            } catch (PrinterException ex) {
                /* The job did not successfully complete */
            }
        }
    }
}