How to rotate a page while creating a PDF document?

Category: 
Tags: page sizepage rotationpage eventslandscapeportraitseascapeinverted portraitiText 5

I want to produce a PDF with pages in landscape. While I can set the size of the page to landscape using document.setPageSize(PageSize.LETTER.rotate());, it this doesn't achieve what I want. The content is still oriented left->right while I would like it to be bottom->top.

This is what I get

This is what I want

I have been able to achieve the desired output by opening the PDF after it has been created and rotating it using iText, but I would like a solution that lets me rotate it immediately with iText after adding content to it.

Posted on StackOverflow on Jan 29, 2013 by Natan Villaescusa

Excellent question. If I was able to upvote it twice, I would!

You can achieve what you want with a PdfPageEvent:

public class RotateEvent extends PdfPageEventHelper {
    public void onStartPage(PdfWriter writer, Document document) {
        writer.addPageDictEntry(PdfName.ROTATE, PdfPage.SEASCAPE);
    }
}

You should use this RotateEvent right after you've defined the writer:

PdfWriter writer = PdfWriter.getInstance(document, os);
writer.setPageEvent(new RotateEvent());

Note that I used SEASCAPE to get the orientation shown in your image.

All the possible values for the rotation are:

  • PdfPage.PORTRAIT
  • PdfPage.LANDSCAPE
  • PdfPage.INVERTEDPORTRAIT
  • PdfPage.SEASCAPE

That worked! I found that I didn't need to create the RotateEvent though, I just used writer.addPageDictEntry(PdfName.ROTATE, PdfPage.SEASCAPE); immediately after creating the PdfWriter since I am always creating a single page.

You're right, that works too, but each time the extra entry of the page dictionary was "used", it's gone. In your case, that doesn't matter because you're only creating one page!