我正在尝试向新 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/