Java code for Changing Color Space of PDF Document


/ Published in: Java

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 this code and paste it in your HTML
  1. Document doc = new Document(myDir + "input_color.pdf");
  2. OperatorCollection contents = doc.getPages().get_Item(1).getContents();
  3. System.out.println("Values of RGB color operators in the pdf document");
  4. for (int j = 1; j <= contents.size(); j++)
  5. {
  6. Operator oper = contents.get_Item(j);
  7. if (oper instanceof Operator.SetRGBColor || oper instanceof Operator.SetRGBColorStroke)
  8. try {
  9. //Converting RGB to CMYK color
  10. System.out.println(oper.toString());
  11.  
  12. double[] rgbFloatArray = new double[]
  13. {
  14. Double.valueOf(oper.getParameters().get(0).toString()),
  15. Double.valueOf(oper.getParameters().get(1).toString()),
  16. Double.valueOf(oper.getParameters().get(2).toString()),
  17. };
  18. double[] cmyk = new double[4];
  19. if (oper instanceof Operator.SetRGBColor)
  20. {
  21. ((Operator.SetRGBColor)oper).getCMYKColor(rgbFloatArray, cmyk);
  22. contents.set_Item(j, new Operator.SetCMYKColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3]));
  23. }
  24. else if (oper instanceof Operator.SetRGBColorStroke)
  25. {
  26. ((Operator.SetRGBColorStroke)oper).getCMYKColor(rgbFloatArray, cmyk);
  27. contents.set_Item(j, new Operator.SetCMYKColorStroke(cmyk[0], cmyk[1], cmyk[2], cmyk[3]));
  28. }
  29. else
  30. throw new java.lang.Throwable("Unsupported command");
  31.  
  32. } catch (Throwable e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. doc.save(myDir + "input_colorout.pdf");
  37.  
  38. //Testing the result
  39. System.out.println("Values of converted CMYK color operators in the result pdf document");
  40. doc = new Document(myDir + "input_colorout.pdf");
  41. contents = doc.getPages().get_Item(1).getContents();
  42. for (int j = 1; j <= contents.size(); j++)
  43. {
  44. Operator oper = contents.get_Item(j);
  45. if (oper instanceof Operator.SetCMYKColor || oper instanceof Operator.SetCMYKColorStroke)
  46. {
  47. System.out.println(oper.toString());
  48. }
  49. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.