首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何删除/替换pdf中的特定文本,如果要替换的文本是使用多个连续的指令绘制的?

如何删除/替换pdf中的特定文本,如果要替换的文本是使用多个连续的指令绘制的?
EN

Stack Overflow用户
提问于 2021-10-11 14:00:42
回答 1查看 121关注 0票数 0

我已经尝试了以下代码。它工作得很好,但只适用于有限的情况,比如文本是用一条指令添加的。如果文本被添加到多个指令中,如何执行此操作。有人能帮我解决这个问题吗?

代码语言:javascript
运行
复制
for (PDPage page : document.getDocumentCatalog().getPages()) {
    PdfContentStreamEditor editor = new PdfContentStreamEditor(document, page) {
        final StringBuilder recentChars = new StringBuilder();
        @Override
        protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, Vector displacement)
                throws IOException {
            String string = font.toUnicode(code);
            if (string != null)
                recentChars.append(string);

            super.showGlyph(textRenderingMatrix, font, code, displacement);
        }

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

            if (TEXT_SHOWING_OPERATORS.contains(operatorString) && "Text which is to be replace".equals(recentText))
            {
                return;
            }

            super.write(contentStreamWriter, operator, operands);
        }

        final List<String> TEXT_SHOWING_OPERATORS = Arrays.asList("Tj", "'", "\"", "TJ");
    };
    editor.processPage(page);
}
document.save("watermark-RemoveByText.pdf");```
EN

回答 1

Stack Overflow用户

发布于 2021-10-21 10:57:51

您可以使用pdfSweep (iText 7 add-on)来删除或编辑文档中的信息。有关更多信息,请参阅https://itextpdf.com/en/products/itext-7/pdf-redaction-pdfsweep

使用PdfSweep从Java文档中删除“文本将被替换”的代码如下所示:

代码语言:javascript
运行
复制
try (PdfDocument pdf = new PdfDocument(new PdfReader("Path to source file"), new PdfWriter("Path to out file"))) {
    ICleanupStrategy cleanupStrategy = new RegexBasedCleanupStrategy("Text which is to be replace")
        .setRedactionColor(ColorConstants.WHITE);
    PdfCleaner.autoSweepCleanUp(pdf, cleanupStrategy);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69527470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档