How to rotate a page while creating a PDF document?

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.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!

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now