iText 7.0.2 Java合并PdfDocument列表为单PDF的问题求助
How to Merge Filled Form PDFs (iText 7.0.2 Java)
Let's break down why your previous attempts failed and fix this step by step:
- First attempt error: You tried copying pages from
PdfDocumentinstances that were still attached to aPdfWriter(they were in an active "writing" state). iText blocks copying indirect objects from a document that’s still being written to. - Second attempt error: Every
PdfPageis tightly bound to its parentPdfDocument—you can’t directly move or add a page from one document to another without proper copying logic. - Third attempt issue: When you re-read the PDFs without first finalizing the filled forms, the form data wasn’t persisted correctly, leading to lost content.
The Core Fix: Store Completed PDF Byte Arrays, Not Open PdfDocument Instances
The root problem is you’re storing open, write-bound PdfDocument objects. Instead, you need to fully finalize each filled PDF (close the document, capture its byte content) and store those byte arrays. Then use PdfMerger to combine them properly.
Step 1: Modify Form Filling to Store Byte Arrays
ArrayList<byte[]> pdfBytesList = new ArrayList<>(); while (rs.next()) { URL fullPath = context.getResource("/formulare/kontrollbogen.pdf"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PdfWriter writer = new PdfWriter(bos); PdfReader reader = new PdfReader(fullPath.getFile()); PdfDocument doc = new PdfDocument(reader, writer); // Fill your form fields PdfAcroForm form = PdfAcroForm.getAcroForm(doc, true); String firma = rs.getString("firma"); if (firma != null && !firma.isEmpty()) { form.getField("firma").setValue(firma); } // Add other form field population logic here... // Critical: Close the document to finalize all content doc.close(); // Store the completed PDF as a byte array pdfBytesList.add(bos.toByteArray()); }
Step 2: Merge Byte Arrays with PdfMerger
ByteArrayOutputStream mergedBos = new ByteArrayOutputStream(); PdfWriter mergedWriter = new PdfWriter(mergedBos); PdfDocument mergedDoc = new PdfDocument(mergedWriter); PdfMerger merger = new PdfMerger(mergedDoc); for (byte[] pdfBytes : pdfBytesList) { // Create a reader from the stored byte array PdfReader reader = new PdfReader(new ByteArrayInputStream(pdfBytes)); PdfDocument tempDoc = new PdfDocument(reader); // Merge all pages from the temp document into the merged one merger.merge(tempDoc, 1, tempDoc.getNumberOfPages()); tempDoc.close(); } // Finalize the merged document mergedDoc.close(); // mergedBos now contains your complete merged PDF with all form data intact
Why This Works
- Closing each filled
PdfDocumentensures all form data and PDF structure is properly written to theByteArrayOutputStream. - Storing byte arrays means you’re working with complete, finalized PDFs—not open, stateful document instances.
PdfMergerhandles page copying and indirect object management correctly, avoiding the errors you ran into earlier.
内容的提问来源于stack exchange,提问作者Dennis Weinmann
相关产品推荐
相关产品推荐

