且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用iText合并不同宽度的pdf文档

更新时间:2023-12-05 16:36:34

使用 PdfWriter 类合并文档违背官方文档中给出的所有建议,尽管有非官方的示例可能会诱使您编写错误的代码。我希望你明白我发现这些不好的例子比你更烦人。

Using the PdfWriter class to merge documents goes against all the recommendations given in the official documentation, though there are unofficial examples that may have lured you into writing bad code. I hope that you understand that I find these bad examples even more annoying than you do.

请看一下我书的第6章。它为您提供了一个概述,显示何时使用哪个类。在这种情况下,你应该使用 PdfCopy

Please take a look at Table 6.1 in chapter 6 of my book. It gives you an overview showing when to use which class. In this case, you should use PdfCopy:

String[] files = { MovieLinks1.RESULT, MovieHistory.RESULT };
// step 1
Document document = new Document();
// step 2
PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
// step 3
document.open();
// step 4
PdfReader reader;
int n;
// loop over the documents you want to concatenate
for (int i = 0; i < files.length; i++) {
    reader = new PdfReader(files[i]);
    // loop over the pages in that document
    n = reader.getNumberOfPages();
    for (int page = 0; page < n; ) {
        copy.addPage(copy.getImportedPage(reader, ++page));
    }
    copy.freeReader(reader);
    reader.close();
}
// step 5
document.close();

如果您使用的是最近版本的iText,您甚至可以使用 addDocument()方法,在这种情况下,您不需要遍历所有页面。如果涉及表格,您还需要特别小心。有几个例子在 Sandbox 中展示了新功能(可追溯到本书编写之后)。

If you are using a recent version of iText, you can even use the addDocument() method in which case you don't need to loop over all the pages. You also need to take special care if forms are involved. There are several examples demonstrating the new functionality (dating from after the book was written) in the Sandbox.