Return to Snippet

Revision: 66315
at April 16, 2014 21:14 by johansonkatherine


Initial Code
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());
	}
   }

Initial URL
http://www.aspose.com/docs/display/pdfjava/Changing+Color+space+of+a+PDF+document

Initial Description
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])

Initial Title
Java code for Changing Color Space of PDF Document

Initial Tags
text, files, color, update

Initial Language
Java