forked from rototor/pdfbox-graphics2d
/
RGBtoCMYKColorMapper.java
63 lines (56 loc) · 2.23 KB
/
RGBtoCMYKColorMapper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package de.rototor.pdfbox.graphics2d;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDICCBased;
import java.awt.*;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.io.IOException;
import java.io.OutputStream;
/**
* Usage:
*
* <pre>
* PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(this.doc, (int) (width), (int) (height));
* PdfBoxGraphics2DColorMapper colorMapper = new RGBtoCMYKColorMapper(icc_profile);
* pdfBoxGraphics2D.setColorMapper(colorMapper);
* </pre>
*
* Where ICC_Profile is an instance of java.awt.color.ICC_Profile that supports
* a CMYK colorspace. For testing purposes, we're using ISOcoated_v2_300_bas.icc
* which ships with PDFBox.
*/
public class RGBtoCMYKColorMapper extends PdfBoxGraphics2DColorMapper {
private final ICC_ColorSpace icc_colorspace;
private final PDICCBased pdProfile;
public RGBtoCMYKColorMapper(ICC_Profile icc_profile, PDDocument document) throws IOException
{
this.icc_colorspace = new ICC_ColorSpace(icc_profile);
this.pdProfile = new PDICCBased(document);
OutputStream outputStream = pdProfile.getPDStream().createOutputStream(COSName.FLATE_DECODE);
outputStream.write(icc_profile.getData());
outputStream.close();
pdProfile.getPDStream().getCOSObject().setInt(COSName.N, 4);
pdProfile.getPDStream().getCOSObject().setItem(COSName.ALTERNATE, COSName.DEVICECMYK);
}
public PDColor mapColor(PDPageContentStream contentStream, Color rgbColor) {
int r = rgbColor.getRed();
int g = rgbColor.getGreen();
int b = rgbColor.getBlue();
int[] rgbInts = { r, g, b };
float[] rgbFoats = rgbIntToFloat(rgbInts);
float[] cmykFloats = icc_colorspace.fromRGB(rgbFoats);
return new PDColor(cmykFloats, pdProfile);
}
private static float[] rgbIntToFloat(int[] rgbInts)
{
// the input ints are in the range 0 to 255
// the output floats need to be in the range 0.0 to 1.0
float red = (float) rgbInts[0] / 255.0F;
float green = (float) rgbInts[1] / 255.0F;
float blue = (float) rgbInts[2] / 255.0F;
return new float[] { red, green, blue };
}
}