问题
I need to print an image. When I set orientation like
printRequestAttributeSet.add(OrientationRequested.LANDSCAPE);
all works fine.
But when I set orientation inside print()
method of Printable
:
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex >= images.size())
return Printable.NO_SUCH_PAGE;
image = images.get(pageIndex);
// if image width>height --> Landscape, else --> Protrait
if (image.getWidth(null) > image.getHeight(null))
pageFormat.setOrientation(PageFormat.LANDSCAPE);
else
pageFormat.setOrientation(PageFormat.PORTRAIT);
graphics2D = (Graphics2D) graphics;
graphics.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
return PAGE_EXISTS;
};
it doesn't work with first page. i.e. it prints all pages in Landscape mode except 1-st page.
回答1:
You can not change the orientation when your already trying to print the page.
If you need to provide a number of pages with different orientations, you will want to look at the Book and Pageable interfaces, see Printing in Java for examples.
The only other solution you have is to rotate the image in Printable
, which is troublesome at best.
ps - Printing is fun...when it works ;)
回答2:
Place pf.setOrientation(PageFormat.LANDSCAPE)
before calling printJob
ex.
if(pay_type.getSelectedItem().equals("EMI"))
{
EMI();
}
else{
validation();
}
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable((Printable) this);
boolean ok = job.printDialog();
if (ok) {
try {
//here set page oriatetion
job.print();
} catch (PrinterException ex) {
/* The job did not successfully complete */
}
}
来源:https://stackoverflow.com/questions/12192656/setting-landscape-orientation-when-printing