Java code for Changing Color Space of PDF Document

Date Submitted Wed. Apr. 16th, 2014 11:17 AM
Revision 1 of 1
Helper johansonkatherine
Tags bookmarks | conversion | jpeg | pdf | to | XML
Comments 0 comments
This code shows how java developers can change color space of PDF document from RGB color to CMYK and vice versa by using Aspose.PDF for Java Library. The following methods have been implemented in the Operator class for changing colors. Use it to change some specific RGB/CMYK colors to CMYK/RGB color space, keeping the remaining PDF document as it is.

• com.aspose.pdf.Operator.SetRGBColorStroke.getCMYKColor(new double[3], new double[4])
• com.aspose.pdf.Operator.SetRGBColor.getCMYKColor(new double[3], new double[4])
• com.aspose.pdf.Operator.SetCMYKColorStroke.getRGBColor(new double[4], new double[3])
• com.aspose.pdf.Operator.SetCMYKColor.getRGBColor(new double[4], new double[3])

Document doc = new Document(myDir + "input_color.pdf");
OperatorCollection contents = doc.getPages().get_Item(1).getContents();
System.out.println("Values of RGB color operators in the pdf document");
for (int j = 1; j <= contents.size(); j++)
        Operator oper = contents.get_Item(j);
        if (oper instanceof Operator.SetRGBColor || oper instanceof Operator.SetRGBColorStroke)
        try {
            //Converting RGB to CMYK color

            double[] rgbFloatArray = new double[]
            double[] cmyk = new double[4];
            if (oper instanceof Operator.SetRGBColor)
                ((Operator.SetRGBColor)oper).getCMYKColor(rgbFloatArray, cmyk);
                contents.set_Item(j, new Operator.SetCMYKColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3]));
                else if (oper instanceof Operator.SetRGBColorStroke)
                    ((Operator.SetRGBColorStroke)oper).getCMYKColor(rgbFloatArray, cmyk);
                   contents.set_Item(j, new Operator.SetCMYKColorStroke(cmyk[0], cmyk[1], cmyk[2], cmyk[3]));
throw new java.lang.Throwable("Unsupported command");

        } catch (Throwable e) {
                        } + "input_colorout.pdf");

//Testing the result
System.out.println("Values of converted CMYK color operators in the result pdf document");
doc = new Document(myDir + "input_colorout.pdf");
contents = doc.getPages().get_Item(1).getContents();
for (int j = 1; j <= contents.size(); j++)
        Operator oper = contents.get_Item(j);
        if (oper instanceof Operator.SetCMYKColor || oper instanceof Operator.SetCMYKColorStroke)


Katherine Johanson


There are currently no comments for this snippet.


Votes Down