如何使用PDFBox在带标签PDF中添加Annot标签及注释
问题描述
我有一份符合PDF-UA规范的带标签PDF,结构示意图:带标签PDF
我需要添加如下注释:
<?xml version="1.0" encoding="UTF-8"?> <xfdf xmlns="http://ns.adobe.com/xfdf/"> <annots> <text color="#FFC333" date="D:20240425000000" flags="print,nozoom,norotate" opacity="0.600000" page="0" rect="43.086,707.79,63.086,732.79" title="ABC"> <contents-richtext> <body xmlns="http://www.w3.org/1999/xhtml"> <p dir="ltr">Sample comment</p> </body> </contents-richtext> <popup flags="nozoom,norotate" open="yes" page="0" rect="595.0,507.78998,790.0,632.79"/> </text> </annots> </xfdf>
需要将注释嵌套在
标签下的
我已经成功将XFDF XML导入PDF,代码如下:
PDDocument document = PDDocument.load(new File("tagged.pdf")); FDFDocument fdfDoc = FDFDocument.loadXFDF(new File("annotation.xfdf")); List<FDFAnnotation> fdfAnnots = fdfDoc.getCatalog().getFDF().getAnnotations(); List<PDAnnotation> pageAnnotations = new ArrayList<>(); for (int i=0; i < fdfAnnots.size(); i++) { FDFAnnotation fdfannot = fdfAnnots.get(i); PDAnnotation pdfannot = PDAnnotation.createAnnotation(fdfannot.getCOSObject()); pdfannot.constructAppearances(); pageAnnotations.add(pdfannot); } document.getPage(0).setAnnotations(pageAnnotations); document.save(new File("tagged_with_annotation.pdf"));
但veraPDF检查器提示:
除Widget、PrinterMark或Link子类型外的注释必须嵌套在Annot标签内
PDF无障碍检查工具(PAC tool)提示:
注释未嵌套在"Annot"结构元素内
这符合预期,因为我还没为导入的注释设置Annot标签并指定位置。
另外,我已经能获取
标签对象:
PDDocumentCatalog pdDocumentCatalog = document.getDocumentCatalog(); PDStructureTreeRoot pdStructureTreeRoot = pdDocumentCatalog.getStructureTreeRoot(); COSArray aDocument = (COSArray)(pdStructureTreeRoot.getK().getCOSObject()); COSObject oDocument = (COSObject) aDocument.get(0); COSArray aPart = (COSArray)oDocument.getItem(COSName.K).getCOSObject(); COSObject oPart = (COSObject) aPart.get(0); COSArray aSect = (COSArray)oPart.getItem(COSName.K).getCOSObject(); COSObject oSect = (COSObject) aSect.get(0); COSArray aP = (COSArray)oSect.getItem(COSName.K).getCOSObject(); COSObject oP= (COSObject) aP.get(0);
但我不知道如何编辑PDF中现有的标签树。
问题:如何使用PDFBox将注释添加到PDF现有的标签树中,并嵌套在Annot标签内?
更新内容
- 更新1:示例PDF和XFDF文件可获取(原外部链接已移除)
- 更新2:已修正
tagged_with_annotation_acrobat.pdf文件,补充了缺失的Annotation标签 - 更新3:如需选择最后一个
标签,将:
COSArray aP = oSect.getCOSArray(COSName.K);
修改为:
COSArray aH1P = oSect.getCOSArray(COSName.K); COSDictionary oP = (COSDictionary) aH1P.getObject(1); COSArray aP = oP.getCOSArray(COSName.K);
若要在最后一个
标签内直接添加注释(无需外层
标签),可使用以下代码:
// 添加注释元素 COSDictionary anDict = new COSDictionary(); anDict.setItem(COSName.S, COSName.ANNOT); anDict.setItem(COSName.P, oP); anDict.setItem(COSName.PG, page); PDObjectReference objRef = new PDObjectReference(); anDict.setItem(COSName.K, objRef); objRef.setReferencedObject(page.getAnnotations().get(0)); aP.add(anDict);
内容的提问来源于stack exchange,提问作者Alexander Dyuzhev
相关产品推荐
相关产品推荐

