使用
PdfWriter类合并文档违反了 官方 文档中的所有建议,尽管有一些 非正式的
示例可能会诱使您编写不良代码。我希望您了解,我发现这些不好的例子比您更讨厌。
请看本书第6章中的表6.1
。它为您提供了显示何时使用哪个类的概述。在这种情况下,您应该使用
PdfCopy:
String[] files = { Movielinks1.RESULT, MovieHistory.RESULT };// step 1document document = new document();// step 2PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));// step 3document.open();// step 4PdfReader reader;int n;// loop over the documents you want to concatenatefor (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 5document.close();如果您使用的是iText的最新版本,则甚至可以使用此
adddocument()方法,而无需遍历所有页面。如果涉及表格,则还需要特别小心。有许多示例在Sandbox中展示了新功能(从本书编写之后开始)。



