Copy PDF with Annotations using iText

前端 未结 1 1545
说谎
说谎 2020-12-11 19:56

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:

相关标签:
1条回答
  • 2020-12-11 21:03

    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:

    • MergeForms
    • MergeForms2

    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.

    0 讨论(0)
提交回复
热议问题