You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移至iText 7:如何添加通用PdfObject至PDF且不显示在文档中

Solution for Adding Hidden PdfObject in iText 7

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 PdfDocument as the central class for all PDF operations, replacing the iText 5 combo of PdfReader + PdfStamper. This simplifies resource management a lot.
  • Hidden Object Addition: The addNewObject() method is what does the magic here. It registers your PdfArray (or any valid PdfObject) 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:00:57