如何仅使用 CMYK 颜色生成 JFreeChart?
我必须调用所有的.setPaint(new CmykColor(...))
还是有更优雅的方式?即使我不知道所有可能的.setPaint(...)
方法。
为了重现这个问题,我写了一个小单元测试。它生成一个图表,最后将其添加到仅允许 CMYK 的 PDF/x。
如果否,则测试变为绿色com.lowagie.text.pdf.PdfXConformanceException
:不允许使用颜色空间 RGB。抛出异常。
public class TestChart
{
public static final int WIDTH = 500;
public static final int HEIGHT = 400;
private JFreeChart chart;
@Before
public void createChart()
{
final DefaultPieDataset dataSet = new DefaultPieDataset();
dataSet.setValue("United States", 4.54);
dataSet.setValue("Brazil", 2.83);
this.chart = ChartFactory.createPieChart("World Population by countries", dataSet, true, true, false);
// ChartUtilities.saveChartAsPNG(new File("test.png"), chart, width, height);
}
@Test
public void shouldAddChartToPdfX() throws FileNotFoundException, DocumentException
{
final Document document = new Document();
document.addTitle("Test PDF/x");
final PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("test.pdf"));
pdfWriter.setPDFXConformance(PdfWriter.PDFX1A2001);
document.open();
final PdfContentByte directContent = pdfWriter.getDirectContent();
final PdfTemplate pdfTemplate = directContent.createTemplate(TestChart.WIDTH, TestChart.HEIGHT);
final Graphics2D graphics2d = pdfTemplate.createGraphics(TestChart.WIDTH, TestChart.HEIGHT);
final Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, TestChart.WIDTH, TestChart.HEIGHT);
this.chart.draw(graphics2d, rectangle2d);
graphics2d.dispose();
directContent.addTemplate(pdfTemplate, 0, 0);
document.close();
}
}
要执行此操作,您需要此 Maven 依赖项:
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.14</version>
</dependency>