Java-PDFbox:为带标签的PDF中的线条和下划线创建构件标签

2022-04-25 00:00:00 pdf java pdfbox tagged-pdf

我正在从标记的pdf创建辅助功能PDF。它显示";路径对象未标记&q;错误。PDF有线条和带下划线的文本。因此,我正在尝试为未添加标签的行项目添加";artiture";标记。我可以从PDFGraphicsStreamEngine获得这些行。有人能帮我这个忙吗?

PDF页面 PAC3错误

解决方案

您可以使用PdfContentStreamEditor中的PdfContentStreamEditor类根据需要编辑页面内容流,方法如下:

PDDocument document = ...;
for (PDPage page : document.getDocumentCatalog().getPages()) {
    PdfContentStreamEditor markEditor = new PdfContentStreamEditor(document, page) {
        int markedContentDepth = 0;

        @Override
        public void beginMarkedContentSequence(COSName tag, COSDictionary properties) {
            if (inArtifact) {
                System.err.println("Structural error in content stream: Path not properly closed by path painting instruction.");
            }
            markedContentDepth++;
            super.beginMarkedContentSequence(tag, properties);
        }

        @Override
        public void endMarkedContentSequence() {
            markedContentDepth--;
            super.endMarkedContentSequence();
        }

        boolean inArtifact = false;

        @Override
        protected void write(ContentStreamWriter contentStreamWriter, Operator operator, List<COSBase> operands) throws IOException {
            String operatorString = operator.getName();

            boolean unmarked = markedContentDepth == 0;
            boolean inArtifactBefore = inArtifact;

            if (unmarked && (!inArtifactBefore) && PATH_CONSTRUCTION.contains(operatorString)) {
                super.write(contentStreamWriter, Operator.getOperator("BMC"), Collections.singletonList(COSName.ARTIFACT));
                inArtifact = true;
            }

            super.write(contentStreamWriter, operator, operands);

            if (unmarked && inArtifactBefore && PATH_PAINTING.contains(operatorString)) {
                super.write(contentStreamWriter, Operator.getOperator("EMC"), Collections.emptyList());
                inArtifact = false;
            }
        }

        final List<String> PATH_CONSTRUCTION = Arrays.asList("m", "l", "c", "v", "y", "h", "re");
        final List<String> PATH_PAINTING = Arrays.asList("s", "S", "f", "F", "f*", "B", "B*", "b", "b*", "n");
    };
    markEditor.processPage(page);
}
document.save(...);

(EditMarkedContent测试testMarkUnmarkedPathsAsArtifactsTradeSimple1)

beginMarkedContentSequenceendMarkedContentSequence覆盖跟踪当前标记的内容嵌套深度,特别是是否标记了当前内容。

对于尚未标记的指令,write覆盖会将未标记的路径构建和绘制指令序列包含在/Artifact BMC ... EMC中。

请注意,此代码仅考虑页面内容流中的内容,它不会下降为表单XObject、模式等。

此外,如果内容流有错误(例如,在没有绘制的情况下构建路径),此代码可能会添加额外的错误(例如,不平衡的标记内容开始和结束)。

相关文章