有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java替换PDF文件中的黑色

我正在尝试替换PDF文件中的黑色(0,0,0)颜色(它不是带有名称的专色,它是正常的填充色),但我还找不到方法,有人能帮我吗

附上PDF文件:https://gofile.io/d/AB1Bil


共 (1) 个答案

  1. # 1 楼答案

    利用this answer中的^{},您可以替换在页面内容流中选择黑色RGB颜色的指令,如下所示:

    float[] replacementColor = new float[] {.1f, .7f, .6f};
    
    PDDocument document = ...;
    for (PDPage page : document.getDocumentCatalog().getPages()) {
        PdfContentStreamEditor identity = new PdfContentStreamEditor(document, page) {
            @Override
            protected void write(ContentStreamWriter contentStreamWriter, Operator operator, List<COSBase> operands) throws IOException {
                String operatorString = operator.getName();
    
                if (RGB_FILL_COLOR_OPERATORS.contains(operatorString))
                {
                    if (operands.size() == 3) {
                        if (isApproximately(operands.get(0), 0) &&
                                isApproximately(operands.get(1), 0) &&
                                isApproximately(operands.get(2), 0)) {
                            for (int i = 0; i < replacementColor.length; i++) {
                                operands.set(i, new COSFloat(replacementColor[i]));
                            }
                        }
                    }
                }
    
                super.write(contentStreamWriter, operator, operands);
            }
    
            boolean isApproximately(COSBase number, float compare) {
                return (number instanceof COSNumber) && Math.abs(((COSNumber)number).floatValue() - compare) < 1e-4;
            }
    
            final List<String> RGB_FILL_COLOR_OPERATORS = Arrays.asList("rg", "sc", "scn");
        };
        identity.processPage(page);
    }
    document.save("gridShapesModified-RGBBlackReplaced.pdf");
    

    EditPageContent测试testReplaceRGBBlackGridShapesModified

    当然,对于您的示例PDF,可以简单地获取内容流,并用.1 .7 .6 rg替换0 0 0 rg,以获得相同的效果。不过,总的来说,情况可能更复杂,所以我建议采用这种方法

    不过要小心:

    • 内容流编辑器仅处理即时页面内容流。但是颜色也可以在XObject中设置和使用,也可以在XObject中使用图案。所以严格地说,我们必须深入到页面资源中的XObject和模式
    • 我盲目地对待所有三个参数scscn操作,就像它们设置RGB颜色一样。事实上,它们也可以指实验室颜色,也可以指模式、分离、设备和基于ICC的颜色。严格地说,我们应该在这里测试当前的非笔划色彩空间
    • 我完全忽略了在其他内容上添加的内容(具有有趣的混合模式)可能会导致显示的颜色与当前填充颜色不同