【问题标题】:How to generate a JFreeChart with only CMYK Colors如何生成只有 CMYK 颜色的 JFreeChart
【发布时间】:2012-09-27 12:09:36
【问题描述】:

如何生成只有 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>   

【问题讨论】:

    标签: java itext jfreechart


    【解决方案1】:

    您可以通过调用 plot.setDrawingSupplier() 并提供您喜欢的颜色来更改绘图将用于不同数据集的颜色(如果有帮助,您可以使用 ChartColor 类)。它是一个接口,因此您可以自己制作,也可以使用 DefaultDrawingSupplier 并且它是多参数构造函数以使其更简单。然后是 setOutlinePaint、setBackgroundPaint 和 setNoDataPaint,以防万一。这应该涵盖大多数东西,除了我相信已经是灰色的刻度线等。

    【讨论】:

      猜你喜欢
      • 2011-07-11
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 2013-06-24
      相关资源
      最近更新 更多