How to merge documents correctly?

Tags: merge documentsconcatenateiText 7

I would like to add a link to an existing pdf that jumps to a coordinate on another page.

I have the following problem when printing the PDF file after merge, the PDF documents get cut off. Sometimes this happens because the documents aren't 8.5 x 11 whereas the page size might be 11 x 17.

Is there some way to detect the page size and then use that same page size for those documents? Or, if not, is it possible to have it fit to page? This is my code:

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
        BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
while (iteratorPDFReader.hasNext()) {
    PdfReader pdfReader = iteratorPDFReader.next();
    while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
        Rectangle r = pdfReader.getPageSize(
            pdfReader.getPageN(pageOfCurrentReaderPDF + 1));
        if(r.getWidth()==792.0 && r.getHeight()==612.0)
            document.setPageSize(PageSize.A4.rotate());
        else
            document.setPageSize(PageSize.A4);
        document.newPage();
        pageOfCurrentReaderPDF++;
        currentPageNumber++;
        page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
        cb.addTemplate(page, 0, 0);
        cb.beginText();
        cb.setFontAndSize(bf, 9);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
            + currentPageNumber + " of " + totalPages, 520, 5, 0);
        cb.endText();
    }
    pageOfCurrentReaderPDF = 0;
}
document.close();
Concatenated PDFs

Posted on StackOverflow on Feb 12, 2014 by Sumit Vaidya

Using PdfWriter to merge documents is a bad idea. This has been explained on StackOverflow many times! See for instance Why does the function to concatenate / merge PDFs cause issues in some cases?

Merging documents is done using copyPagesTo() method in iText 7.

If you need an example, see for instance the FillFlattenMerge2 example:

PdfWriter writer = new PdfWriter(dest);
writer.setSmartMode(true);
PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.initializeOutlines();
ByteArrayOutputStream baos;
PdfReader reader;
PdfDocument pdfInnerDoc;
BufferedReader br = new BufferedReader(new FileReader(data));
String line = br.readLine();
// loop over readers
    // create a PDF in memory
    baos = new ByteArrayOutputStream();
    reader = new PdfReader(src);
    pdfInnerDoc = new PdfDocument(reader, new PdfWriter(baos));
    form = PdfAcroForm.getAcroForm(pdfInnerDoc, true);
    //fill and flatten form...
    //add the PDF using copyPagesTo
    pdfInnerDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
    pdfInnerDoc.copyPagesTo(1, pdfInnerDoc.getNumberOfPages(), pdfDoc, new PdfPageFormCopier());
    pdfInnerDoc.close();
// end loop
pdfDoc.close();

In your case, you also need to add page numbers, you can do this in a second go, as is done in the StampPageXofY example:

PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
Document doc = new Document(pdfDoc);
int n = pdfDoc.getNumberOfPages();
for (int i = 1; i <= n; i++) {
    doc.showTextAligned(new Paragraph(String.format("page %s of %s", i, n)),
            559, 806, i, TextAlignment.RIGHT, VerticalAlignment.TOP, 0);
}
doc.close();

Or you can add them while merging, as is done in the MergeWithToc example.

I strongly advise against using PdfWriter to merge documents! This is typically not what you want. You're only making it harder on yourself if you insist on using that class. I don't understand why so many people use the wrong approach to merge documents. I blame the unofficial documentation for the popularity of this wrong approach.

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