java - 使用 iText Java 向 PDF 目录添加新条目

标签 java dictionary pdf itext catalog

我正在尝试向新 PDF 文档中的 PDF 目录 对象添加新条目。为此,我使用库 iText Java,新条目是一对,其键为“/MyVar”,值为一个数字。代码结束执行没有问题,文件已创建,但如果我转到目录,条目不在那里。

我当前的代码:

package iTextExamples;

import java.io.FileNotFoundException;

import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.Document;

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        String path = "C:\\Path\\PDF1.pdf";
        
        PdfWriter pdfWriter = new PdfWriter(path);
        
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        
        pdfDocument.addNewPage();
        
        int dia = 14;
        
        PdfNumber value = new PdfNumber(dia);
        
        PdfObject obj;
        
        obj = value;
        
        PdfName key = new PdfName("/MyVar");
        
        PdfCatalog cat = pdfDocument.getCatalog();
        
        cat.put(key, value);        

        Document document = new Document(pdfDocument);
        
        document.close();
    }

}

如果您知道可能出了什么问题并与我们分享,我将不胜感激。

最佳答案

The code ends the execution with no problem and the file is created but if I go to the Catalog the entry is not there.

恰恰相反,我刚刚测试了你的代码,看到入口在那里:

1 0 obj
<</#2fMyVar 14/Pages 2 0 R/Type/Catalog>> 

如果你期望/MyVar而不是/#2fMyVar,你应该替换

PdfName key = new PdfName("/MyVar");

通过

PdfName key = new PdfName("MyVar");

因为 PdfName 构造函数不希望 PDF 名称指示符 / 成为其参数的一部分。

关于java - 使用 iText Java 向 PDF 目录添加新条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67093875/

相关文章:

java - 对整数进行排序但保留索引以恢复其顺序

java - 如何以某种格式打印出HashMap的内容?

python - 如何使用 Python 将多个标签变量转换为 tkinter 中的字典?

excel - 编写字典 VBA 脚本 - 区分重复项

tomcat - Itext 5.5 将 RTL 语言(阿拉伯语)的 HTML 转换为 PDF 不适用于 tomcat

c# - iTextSharp ShowTextAligned anchor

java - Gradle 脱离 Bash for 循环

java - JUnit 测试返回 null 和 false

java - 检查 GPS 和蓝牙是否已激活时出现问题

java - 如何在 WebView Android Studio 中打开本地 pdf 文件