迁移至iText 7:如何添加通用PdfObject至PDF且不显示在文档中
Got it, let's port that iText 5 functionality over to iText 7 smoothly! The core goal is adding an indirect PDF object to your document without linking it to any visible content (so it stays hidden in the PDF's structure but still exists). Here's how to do it properly:
Full Working Code
import com.itextpdf.kernel.pdf.*; import java.io.FileOutputStream; import java.io.IOException; public class AddHiddenPdfObject { public static void main(String[] args) throws IOException { // Initialize reader for the source PDF PdfReader reader = new PdfReader(args[0]); // Initialize writer for the output PDF PdfWriter writer = new PdfWriter(args[0] + "-itext7.pdf"); // Create the main PdfDocument instance to handle modifications PdfDocument pdfDoc = new PdfDocument(reader, writer); // Build your custom PDF objects just like in iText 5 PdfLiteral helloLiteral = new PdfLiteral("HelloWorld"); PdfArray customArray = new PdfArray(); customArray.add(helloLiteral); // Add the array as an indirect object to the document—this keeps it hidden // since we don't link it to any pages, annotations, or visible elements pdfDoc.addNewObject(customArray); // Close the document to auto-handle resource cleanup for reader/writer pdfDoc.close(); } }
Key Differences & Explanations
- Core Class Shift: iText 7 uses
PdfDocumentas the central class for all PDF operations, replacing the iText 5 combo ofPdfReader+PdfStamper. This simplifies resource management a lot. - Hidden Object Addition: The
addNewObject()method is what does the magic here. It registers yourPdfArray(or any validPdfObject) as an indirect object in the PDF, but doesn't associate it with any visible parts of the document (like page dictionaries, the outline tree, etc.). This matches exactly what your iText 5 code was doing. - Auto Resource Cleanup: Unlike iText 5 where you had to manually close streams, readers, and stampers, calling
pdfDoc.close()takes care of all that for you—no more forgetting to close a stream and leaving file locks!
This code will produce a PDF with your hidden PdfArray containing the "HelloWorld" literal, just like your iText 5 implementation did.
内容的提问来源于stack exchange,提问作者Ben Ingle
相关产品推荐
相关产品推荐

