Skip to main content
Skip table of contents

Why does the function to concatenate / merge PDFs cause issues in some cases?

The code usually works great! But once in a while, it's rotating some of the pages by 90 degrees. Anyone ever have this happen?


I'm using the following code to merge PDFs together using iText:


public static void concatenatePdfs(ListFile> listOfPdfFiles, File outputFile)
    throws DocumentException, IOException {
    Document document = new Document();
    FileOutputStream outputStream = new FileOutputStream(outputFile);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    for (File inFile : listOfPdfFiles) {
        PdfReader reader = new PdfReader(inFile.getAbsolutePath());
        for (int i = 1; i  reader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = writer.getImportedPage(reader, i);
            cb.addTemplate(page, 0, 0);
        }
    }
    document.close();
}
This usually works great! But once in a while, it's rotating some of the pages by 90 degrees. Anyone ever have this happen?


Posted on StackOverflow on Apr 14, 2014 by Nicholas DiPiazza

There are errors once in a while because you are using the wrong method to concatenate documents. You should not use PdfWriter to concatenate (or merge) PDF documents. That is wrong because:

  • 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 was done using PdfCopy in iText 5. In iText 7 we create a new PdfDocument and use the copyPagesTo() method, like this:

PdfWriter writer = new PdfWriter(toFile);
writer.setSmartMode(isSmartModeOn);
PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.initializeOutlines();
PdfDocument addedDoc = new PdfDocument(new PdfReader(fromFile));
addedDoc.copyPagesTo(1, addedDoc.getNumberOfPages(), pdfDoc);
addedDoc.close();
pdfDoc.close();

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

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.