by
426 17

Java code for Changing Color Space of PDF Document

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])
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/47395/Java-code-for-Changing-Color-Space-of-PD?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
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 System.out.println(oper.toString()); double[] rgbFloatArray = new double[] { Double.valueOf(oper.getParameters().get(0).toString()), Double.valueOf(oper.getParameters().get(1).toString()), Double.valueOf(oper.getParameters().get(2).toString()), }; 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])); } else throw new java.lang.Throwable("Unsupported command"); } catch (Throwable e) { e.printStackTrace(); } } doc.save(myDir + "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) { System.out.println(oper.toString()); } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus