itextxmlworker

how to rotate pages into landscape and page content should be in portrait iTextpdf


I'm trying to create a PDF document with more than 2 pages in portrait and others in landscape, I found that both page and text rotates to landscape I need to prevent page content rotation. am using following code

 Document document = new Document(PageSize.A4, 36, 36, 36, 72);
    PdfWriter writer = PdfWriter.getInstance(document, new 
    FileOutputStream(outPutDirectory + indexID + ".pdf"));
    writer.setPageEvent(new Orientation(orientation));
    document.open();
    XMLWorkerHelper.getInstance().parseXHtml(writer,document, new ByteArrayInputStream(parserXHtml(page.getPageContent()).getBytes()))
    document.close();

my expected result should be like this

expected result.pdf


Solution

  • Instead of using a page event, you have to change the page size.

    For instance:

    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document, new 
    FileOutputStream(outPutDirectory + indexID + ".pdf"));
    document.open();
    // Add some content in portrait
    document.setPageSize(PageSize.A4.rotate());
    document.newPage();
    // Add some content in landscape
    document.close();
    

    Be aware of the fact that the page size only changes on the next page. The order of setPageSize() and newPage() is important.