[英]Replace black color in PDF file
我正在嘗試替換 PDF 文件中的黑色(0,0,0)顏色(它不是帶名稱的專色,它是正常的填充顏色)但我還沒有找到辦法做到這一點,誰能幫忙我用這個?
附上PDF文件: https://gofile.io/d/AB1Bil
使用此答案中的PdfContentStreamEditor
,您可以替換在頁面內容流中選擇黑色 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 ,可以簡單地獲取內容 stream 並將0 0 0 rg
替換為.1.7.6 rg
以獲得相同的效果。 但總的來說,情況可能會更復雜,所以我提出了這種方法。
但請注意:
sc
和scn
操作都一味地對待,就好像它們設置了 RGB colors。 事實上,他們也可以參考 Lab colors 和(對於scn
)Pattern, Separation, DeviceN 和 ICCBased colors。 嚴格來說應該在這里測試當前的非描邊色彩空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.