我已经尝试了以下代码。它工作得很好,但只适用于有限的情况,比如文本是用一条指令添加的。如果文本被添加到多个指令中,如何执行此操作。有人能帮我解决这个问题吗?
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");```
发布于 2021-10-21 10:57:51
您可以使用pdfSweep (iText 7 add-on)来删除或编辑文档中的信息。有关更多信息,请参阅https://itextpdf.com/en/products/itext-7/pdf-redaction-pdfsweep
使用PdfSweep从Java文档中删除“文本将被替换”的代码如下所示:
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);
}
https://stackoverflow.com/questions/69527470
复制相似问题