Raushan Raushan - 1 year ago 151
Java Question

Pdf in Landscape using pdfBox

Currently I am working with PDFBox of Apache to generate pdf. It is working perfectly fine in portrait mode but then my requirement is that 1st two page should be in landscape mode and afterwards all other pages in portrait.

So can anyone please help me on how to create pdf in landscape and achieve this functionality??

Note:I cannot switch from PDFBox to other libraries

Answer Source

There are two strategies:

1) assign a landscape mediabox (this is for A4):

float POINTS_PER_INCH = 72;
float POINTS_PER_MM = 1 / (10 * 2.54f) * POINTS_PER_INCH;
new PDPage(new PDRectangle(297 * POINTS_PER_MM, 210 * POINTS_PER_MM));

2) assign a portrait mediabox, rotate the page and rotate the CTM, as shown in the official example:

PDPage page = new PDPage(PDRectangle.A4);
PDRectangle pageSize = page.getMediaBox();
float pageWidth = pageSize.getWidth();
PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false);
// add the rotation using the current transformation matrix
// including a translation of pageWidth to use the lower left corner as 0,0 reference
contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download