How to create a document with unequal page sizes?

I want to create a PDF file that has unequal page sizes. I have these two rectangles:

Rectangle one = new Rectangle(70,140); Rectangle two = new Rectangle(700,400);

I am creating the PDF like this:


Document document = new Document();
PdfWriter writer=  PdfWriter.getInstance(
    document, new FileOutputStream(("MYpdf.pdf")));
when I create the document, I have the option to specify the page size, but I want different page sizes for different pages in my PDF. Is that possible? E.g. the first page will have rectangle one as the page size, and the second page will have rectangle two as the page size.

Posted on StackOverflow on Apr 16, 2014 by Harvey Slash

I've created an UnequalPages example for you that shows how it works:

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
Rectangle one = new Rectangle(70,140);
Rectangle two = new Rectangle(700,400);
document.setMargins(2, 2, 2, 2);;
Paragraph p = new Paragraph("Hi");
document.setMargins(20, 20, 20, 20);

It is important to change the page size (and margins) before the page is initialized. The first page is initialized when you open() the document, all following pages are initialized when a newPage() occurs. A new page can be triggered explicitly (using the newPage() method in your code) or implicitly (by iText, when a page was full and a new page is needed).

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