I'm trying to replace the black (0,0,0) color in a PDF file (it's not a spot color with name, it's normal fill color) but I could not find a way to do that yet, could anyone please help me with this?
Attached the PDF file: https://gofile.io/d/AB1Bil
Making use of the PdfContentStreamEditor
from this answer, you can replace the instructions selecting a black'ish RGB color in the page content streams like this:
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 test testReplaceRGBBlackGridShapesModified
)
Of course, for your example PDF one could have simply taken the content stream and replaced 0 0 0 rg
by .1 .7 .6 rg
for the same effect. In general, though, the situation can be more complicated, so I propose this approach.
Beware, though:
sc
and scn
operation as if they set RGB colors. In truth they can also refer to Lab colors and (for scn
) to Pattern, Separation, DeviceN and ICCBased colors. Strictly speaking on should test the current non-stroking colorspace here.