Search code examples
c#itext

How to make multisheet page in iTextSharp?


I have single page document made with iTextSharp (A4 size in portrait orientation). Now I copy first page, paste it as second - there are two same pages. In Acrobat Reader there is option to print multiple sheets per page - so I can print those 2 pages on 1 in landscape orientation.

How to achieve the same effect, using only iTextSharp?


Solution

  • Please read the tutorial on how to use iText 7, more specifically Chapter 6: Reusing existing PDF documents

    In that chapter, you'll find an example called TheGoldenGateBridge_N_up:

    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    PdfDocument sourcePdf = new PdfDocument(new PdfReader(SRC));
    //Original page
    PdfPage origPage = sourcePdf.getPage(1);
    Rectangle orig = origPage.getPageSize();
    PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
    //N-up page
    PageSize nUpPageSize = PageSize.A4.rotate();
    PdfPage page = pdf.addNewPage(nUpPageSize);
    PdfCanvas canvas = new PdfCanvas(page);
    //Scale page
    AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
        nUpPageSize.getWidth() / orig.getWidth() / 2f,
        nUpPageSize.getHeight() / orig.getHeight() / 2f);
    canvas.concatMatrix(transformationMatrix);
    //Add pages to N-up page
    canvas.addXObject(pageCopy, 0, orig.getHeight());
    canvas.addXObject(pageCopy, orig.getWidth(), orig.getHeight());
    canvas.addXObject(pageCopy, 0, 0);
    canvas.addXObject(pageCopy, orig.getWidth(), 0);
    // close the documents
    pdf.close();
    sourcePdf.close();
    

    In this example, we add 4 pages of an existing PDF to one page. The principle is called N-upping in which you replace N by a power of 2. In the example, we do 4-upping; you want 2-upping. Changing the 4-up example into a 2-up example is only a matter of applying some simple Math.

    You will also benefit from reading this FAQ entry: How to convert an A4 size PDF to a PDF booklet? If you are still using an old version of iText, you can read the iText 5 version of the FAQ entry.