Combining pdfs with itext - landscape pages render

2019-05-31 19:09发布

问题:

I'm maintaining a legacy application that uses itext to combine multiple landscape and portrait pdfs. This process is working fine when combining pdfs produced by the same application, with other pdfs it renders landscape as portait and cuts off content.

Question: Are there properties in the structure of the pdf that can cause such difference in rendering?

Thanks!

回答1:

The behavior you're describing only occurs if you follow bad examples. It doesn't occur when you follow the official documentation.

Although you didn't provide any source code, I'm pretty sure that you use a PdfWriter instance and that you add existing pages to the direct content of this instance using the addTemplate() method. This is (as I have pointed out many times to people who don't read the documentation) wrong.

You need to replace the merging process and use PdfCopy or PdfSmartCopy to concatenate PDF documents. Take a look at the MergeForms (merging forms) and FillFlattenMerge2 (introducing PdfSmartCopy so that the resulting file size remains low) examples for inspiration. If your application is really old, you may not find the addDocument() method.

In that case, you need to use old examples, such as the Concatenate example:

Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
document.open();
PdfReader reader;
int n;
for (int i = 0; i < files.length; i++) {
    reader = new PdfReader(files[i]);
    n = reader.getNumberOfPages();
    for (int page = 0; page < n; ) {
        copy.addPage(copy.getImportedPage(reader, ++page));
    }
    copy.freeReader(reader);
    reader.close();
}
document.close();


标签: java itext