我们是否可以创建新的自定义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。所以In newTokens list包含所有现有的COSBase对象,所以我想操作一些标记COSBase对象,如果我保存了新文档,那么它应该被标记,而不需要处理任何解码、编码、字体和图像处理。
首先,这个想法会奏效吗?如果是,那么帮助我一些代码来创建自定义COSBase对象。我对java非常陌生。
发布于 2019-06-06 21:58:24
根据您的文档格式,您可以插入标记的内容。
//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
https://stackoverflow.com/questions/56231681
复制相似问题