使用pdfbox创建新的自定义COSBase对象?

时间:2019-05-21 05:35:25

标签: java accessibility pdfbox tagging

我们可以创建一个新的自定义PDFOperator(例如PDFOperator {BDC})和COSBase对象(例如COSName {P} COSName {Prop1}(再次,Prop1将引用一个obj))吗?并将它们添加到pdf的根结构中吗?

我已经从现有的pdf文档中阅读了一些解析器标记列表。我想标记pdf。在该过程中,我将首先使用新创建的COSBase对象操作令牌列表。最后,我将它们添加到根树结构中。因此,在这里如何创建COSBase对象。我正在使用代码从pdf中提取令牌是

old_document = PDDocument.load(new File(inputPdfFile));
List<Object> newTokens = new ArrayList<>();
for (PDPage page : old_document.getPages()) 
{
    PDFStreamParser parser = new PDFStreamParser(page);
    parser.parse();
    List<Object> tokens = parser.getTokens();
    for (Object token : tokens) {
        System.out.println(token);
        if (token instanceof Operator) {
            Operator op = (Operator) token;     
        }
}
newTokens.add(token);
}

PDStream newContents = new PDStream(document);
document.addPage(page);
OutputStream out = newContents.createOutputStream(COSName.FLATE_DECODE);
ContentStreamWriter writer = new ContentStreamWriter(out);
writer.writeTokens(newTokens);
out.close();
page.setContents(newContents);
document.save(outputPdfFile);
document.close();

以上代码将创建一个包含所有格式和图像的新pdf文件。 因此,在newTokens列表中包含所有现有的COSBase对象,因此我想使用一些标记COSBase对象进行操作,如果我保存了新文档,则应该对其进行标记而无需进行任何解码,编码,字体和图像处理。

首先,这个想法行得通吗?如果是,那么请帮助我编写一些代码来创建自定义COSBase对象。我对Java很陌生。

1 个答案:

答案 0 :(得分:0)

根据您的文档格式,您可以插入标记的内容。

//Below code is to add   "/p <<MCID 0>> /BDC"

newTokens.add(COSName.getPDFName("P"));
currentMarkedContentDictionary = new COSDictionary();
currentMarkedContentDictionary.setInt(COSName.MCID, mcid);
mcid++;
newTokens.add(currentMarkedContentDictionary);
newTokens.add(Operator.getOperator("BDC"));

// After adding mcid you have to append your existing tokens TJ , TD, Td, T* ....
newTokens.add(existing_token);
// Closed EMC
newTokens.add(Operator.getOperator("EMC"));
//Adding marked content to the root tree structure.
structureElement = new PDStructureElement(StandardStructureTypes.P, currentSection);
structureElement.setPage(page);
PDMarkedContent markedContent = new PDMarkedContent(COSName.P, currentMarkedContentDictionary);
structureElement.appendKid(markedContent);
currentSection.appendKid(structureElement);

感谢@Tilman Hausherr