function that can use iText to concatenate / merge pdfs together – causing some issues

There are errors once in a while because you are using the wrong method to concatenate documents. Please read chapter 6 of my book and you’ll notice that using PdfWriter to concatenate (or merge) PDF documents is wrong:

  • You completely ignore the page size of the pages in the original document (you assume they are all of size A4),
  • You ignore page boundaries such as the crop box (if present),
  • You ignore the rotation value stored in the page dictionary,
  • You throw away all interactivity that is present in the original document, and so on.

Concatenating PDFs is done using PdfCopy, see for instance the FillFlattenMerge2 example:

Document document = new Document();
PdfCopy copy = new PdfSmartCopy(document, new FileOutputStream(dest));
document.open();
PdfReader reader;
String line = br.readLine();
// loop over readers
    // add the PDF to PdfCopy
    reader = new PdfReader(baos.toByteArray());
    copy.addDocument(reader);
    reader.close();
// end loop
document.close();

There are other examples in the book.

Leave a Comment