How to create a document with unequal page sizes?

Tags: page sizemarginsiText 7

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 in iText 7:

PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
Rectangle one = new Rectangle(70,140);
Rectangle two = new Rectangle(700,400);
Document document = new Document(pdf, new PageSize(one));
document.setMargins(2, 2, 2, 2);
Paragraph p = new Paragraph("Hi");
document.add(p);
document.add(new AreaBreak(new PageSize(two)));
document.setMargins(20, 20, 20, 20);
document.add(p);
document.close();

It is a good way to add margins immediately after adding new page, in this case all elements which will be added after will be displayed correctly.

A new page can be triggered explicitly (using the AreaBreak class in your code) or implicitly (by iText, when a page was full and a new page is needed).

Click this link if you want to see how to answer this question in iText 5.