We need to import existing multiple PDFs into a single new PDF. Part of codes work similar to the sample codes in section 6.2.1 of iText in Action 2nd edition:
Being the author of the book you refer to, I'd like to point out that the examples in the book are somewhat outdated. The book will advise you to use PdfCopyFields
to merge forms, but that class is deprecated in recent versions of iText.
Please take a look at the new examples:
In other words: forms can now be copied/merged using the PdfCopy
class, but it is imported to tell PdfCopy
that the fields need to be merged as is done in the following code snippet:
public void createPdf(String filename) throws IOException, DocumentException {
PdfReader[] readers = {
new PdfReader(getFile1()),
new PdfReader(getFile2())
};
createPdf(filename, readers);
}
public void createPdf(String filename, PdfReader[] readers)
throws IOException, DocumentException {
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream(filename));
copy.setMergeFields();
document.open();
for (PdfReader reader : readers) {
copy.addDocument(reader);
}
document.close();
for (PdfReader reader : readers) {
reader.close();
}
}
The setMergeFields()
method is the method you need to remember.