You need to enable JavaScript to run this app. 能否使用PDFBox按指定位置实现真实PDF区域脱敏并保留原有属性?
优惠活动
大模型
产品
解决方案
定价
更多

能否使用PDFBox按指定位置实现真实PDF区域脱敏并保留原有属性?

PDF区域脱敏实现需求与现有方案说明

场景背景

当前已有的实现方案为遍历PDF页面,在目标位置绘制黑色矩形做视觉遮盖,目前已持有全部待遮盖区域对应的PDRectangle列表,可实现视觉层面隐藏指定文本的效果。

现存问题

  • 黑色矩形下方的文本仍可被其他工具复制、检索或提取,并未实现真正的内容脱敏;此前曾通过将PDF栅格化转换为单图层图像文档的方式解决该问题,但该方案并非合规的真实脱敏,仅为临时规避手段
  • 最终生成的PDF为纯图像文档,完全丢失原生PDF的检索、复制等核心属性,且整体处理流程效率较低

目标诉求

希望依托已持有的精准区域坐标,使用PDFBox实现真正的区域脱敏操作:对指定矩形区域做涂黑遮盖的同时,彻底清除区域内的底层可读内容,全程保留PDF的原生属性,确保已脱敏区域无法被任何方式读取。
已知悉PDFBox旧版本ReplaceText功能存在缺陷,但本次因持有精准的目标区域坐标,可实现待处理范围的精准擦除;同时也欢迎其他免费开源类库的可行方案建议。

技术环境

  • PDFBox 2.0.21
  • Java 11.0.6+10(AdoptOpenJDK)
  • MacOS Catalina 10.15.4(16gb内存 x86_64架构)

现有实现代码

黑色矩形绘制方法

private void draw(PDPage page, PDRectangle hitPdRectangle) throws IOException {
    PDPageContentStream content = new PDPageContentStream(pdDocument, page,
        PDPageContentStream.AppendMode.APPEND, false, false);
    content.setNonStrokingColor(0f);
    
    content.addRect(hitPdRectangle.getLowerLeftX(), 
        hitPdRectangle.getLowerLeftY() - 0.5f, 
        hitPdRectangle.getUpperRightX() - hitPdRectangle.getLowerLeftX(), 
        hitPdRectangle.getUpperRightY() - hitPdRectangle.getLowerLeftY());
    
    content.fill();
    content.close();
}

栅格化生成图像版PDF方法

private PDDocument createNewRedactedPdf() throws IOException {
    PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
    PDDocument redactedDocument = new PDDocument();

    for (int pageIndex = 0; pageIndex < pdDocument.getNumberOfPages(); pageIndex++) {
        BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, 200);

        String formatName = "jpg";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, formatName, baos);

        byte[] bimg = baos.toByteArray();

        PDPage page = pdDocument.getPage(pageIndex);
        float pageWidth = page.getMediaBox().getWidth();
        float pageHeight = page.getMediaBox().getHeight();

        PDPage pageDraw = new PDPage(new PDRectangle(pageWidth, pageHeight));
        redactedDocument.addPage(pageDraw);
        String imgSuffixName = pageIndex + "." + formatName;
        PDImageXObject img = PDImageXObject.createFromByteArray(redactedDocument, bimg,
            pdDocument.getDocument().getDocumentID() + imgSuffixName);

        try (PDPageContentStream contentStream
                 = new PDPageContentStream(redactedDocument, pageDraw, PDPageContentStream.AppendMode.OVERWRITE, false)) {
            contentStream.drawImage(img, 0, 0, pageWidth, pageHeight);
        }
    }
    return redactedDocument;
}

内容的提问来源于stack exchange,提问作者Thales Valias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.17 14:24:04