改变PDF文档颜色空间的Java代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了改变PDF文档颜色空间的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])
  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. }

以上是关于改变PDF文档颜色空间的Java代码的主要内容,如果未能解决你的问题,请参考以下文章

Java itext为pdf 文件添加水印核心功能代码片段

怎么改变PDF文件天蓝色的背景呢?

在wps中如何改变编号颜色?

在java中如何设定面板的背景颜色

怎提取pdf中的图片? java代码! 望高手解决!谢

java 编程 背景颜色的改变