How to convert an existing A4 PDF document to an A3 booklet?

Tags: bookletmerge documentspage sizeiText 7

I want to convert an existing A4 PDF document into an A3 PDF using Java. Since I am new to the iText API, I wonder if anyone can guide me how to do this. A sample would be appreciated. Note: the output PDF should be an A3 booklet format.

Posted on StackOverflow on Dec 1, 2015 by Rajasekhar-b-1989

Please take a look at the MakeA3Booklet example. In this example, we take an existing PDF document with 299 A4 pages (primes.pdf) and we convert it to a 150-page A3 booklet (a3_booklet.pdf):

public void manipulatePdf(String src, String dest) throws IOException {
    PdfDocument srcDoc = new PdfDocument(new PdfReader(src));
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    pdfDoc.setDefaultPageSize(new PageSize(PageSize.A3).rotate());
    PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
    float a4_width = PageSize.A4.getWidth();
    int n = srcDoc.getNumberOfPages();
    int p = 0;
    PdfFormXObject page;
    while (p++ < n) {
        page = srcDoc.getPage(p).copyAsFormXObject(pdfDoc);
        if (p % 2 == 1) {
            canvas.addXObject(page, 0, 0);
        } else {
            canvas.addXObject(page, a4_width, 0);
            canvas = new PdfCanvas(pdfDoc.addNewPage());
        }
    }
    pdfDoc.close();
    srcDoc.close();
}

We create a PdfDocument object with PageSize.A3 as parameter, but as PageSize.A3 is in portrait, we rotate it so that we get the page size in landscape. We need the width of the A4 page (which is half of the width of the A3 page in landscape format) and we loop over all the pages in the existing document.

If we encounter an odd page, we add it at position (x = 0; y = 0). If we encounter an even page, we add it at position (x = a4_width; y = 0) and we create a new page.

You'll find more complex examples in the answer to the question “How to convert an A4 size PDF to a PDF booklet?”

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