Search code examples
javaitext

iText Generate PDF with landscape and portrait pages


I have a problem with a generation of PDF document. For example I need to generate 3 pages:

  • First page (PORTRAIT) with portrait text
  • Second page (LANDSCAPE) with portrait text
  • Third page (PORTRAIT) with portrait text

I set after creating the first page:

document.setPageSize(PageSize.A4.rotate());

and It seems to be working. When I create the third page I set this code for the second time but the document is still in landscape mode. This is my code:

    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    document.open();
    document.newPage();
    document.add(new Paragraph("Hello 1"));

    document.setPageSize(PageSize.A4.rotate());
    document.newPage();
    document.add(new Paragraph("Hello 2"));

    document.setPageSize(PageSize.A4.rotate());
    document.newPage();
    document.add(new Paragraph("Hello 3"));

    document.close();

I would like to have something like this:

enter image description here

Any suggestion?


Solution

  • You set PageSize.A4.rotate() as page size both right before creating page 2 and page 3 respectively. Thus, those two pages both are landscape.

    As the most recently set document page size value is used for creating a new page, the result is the same if you don't set it at all before creating page 3, only before creating page 2.

    If you don't want the third page in landscape, therefore, you explicitly have to set the page size value back to the portrait value PageSize.A4 before creating page 3:

    document.setPageSize(PageSize.A4);
    document.newPage();
    document.add(new Paragraph("Hello 3"));