You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@pdfbox.apache.org by Ivan Ridao Freitas <in...@ivanrf.com> on 2016/05/14 00:09:05 UTC

Printing and saving with PageFormat

I finished my PDF design and now I'm testing printing.

I found that using PrinterJob.print(PrintRequestAttributeSet) with 
attributes like orientation has no effect. For example, passing an 
OrientationRequested.REVERSE_LANDSCAPE generates the same output as 
printing with OrientationRequested.LANDSCAPE.

Then, I saw in your examples that you use a Book as a way to set a 
custom PageFormat. I managed to dynamically set different page sizes, 
margins and orientations with this method.

The thing is that the same dynamic design that I make (PDDocument) can 
be printed or saved to a PDF. So, I need to take the PageFormat into 
account when building the PDDocument. There are two approaches:
  - apply margins and orientation to the PDDocument -> print without 
margins, the file will have margins/rotations
  - only set imageable area to the PDDocument -> print using PageFormat, 
the file won't have margins

I choose the second one, and define the page as:

PageFormat pageFormat = ...;
float pageWidth = (float) pageFormat.getImageableWidth();
float pageHeight = (float) pageFormat.getImageableHeight();
PDPage page = new PDPage(new PDRectangle(pageWidth, pageHeight));

With that code, I handle page size, margin and orientation directly on 
the PDPage. Then, I print with:

PageFormat pageFormat = ...;
pageFormat = job.validatePage(pageFormat);
Book book = new Book();
book.append(new PDFPrintable(document), pageFormat, 
document.getNumberOfPages());
job.setPageable(book);
job.print();

Is this the best way to deal with what I want? is there a better approach?
Would it be useful for the lib to allow PDRectangle to take a PageFormat 
as parameter?

Ivan