Java将XChart另存为PDF

时间:2017-05-21 15:14:16

标签: java graph charts

使用XChart我可以制作漂亮的图表。当我制作图表时,我可以右键单击它,并选择“#34;另存为"过来。然后,我可以通过点击来将指定格式的图像保存到指定的目录。

我怎样才能编写为我自动化的Java代码?也就是说,我有一个创建大约五十个图形的应用程序,并且我不想在每次运行应用程序时都必须手动保存它所属的每个图形。

以下是我制作图表的方式:

private void makeLineChart(int[][] data, String title) {
    MyLineChart c = new MyLineChart(data, title);
    XYChart chart = c.getChart();
    new SwingWrapper<XYChart>(chart).displayChart();
    // save as pdf...?
}

2 个答案:

答案 0 :(得分:2)

xchart的示例代码有解决方案。每次启动应用程序时,BitmapEncoder都可以执行此操作。BitmapEncoder.saveBitmap(chart, "./Sample_Chart", BitmapFormat.PNG);

public class Example1 {

public static void main(String[] args) throws Exception {
 double[] yData = new double[] { 2.0, 1.0, 0.0 };
// Create Chart
XYChart chart = new XYChart(500, 400);
chart.setTitle("Sample Chart");
chart.setXAxisTitle("X");
chart.setXAxisTitle("Y");
XYSeries series = chart.addSeries("y(x)", null, yData);
series.setMarker(SeriesMarkers.CIRCLE);

BitmapEncoder.saveBitmap(chart, "./Sample_Chart", BitmapFormat.PNG);
BitmapEncoder.saveBitmap(chart, "./Sample_Chart", BitmapFormat.JPG);
BitmapEncoder.saveJPGWithQuality(chart, "./Sample_Chart_With_Quality.jpg", 0.95f);
BitmapEncoder.saveBitmap(chart, "./Sample_Chart", BitmapFormat.BMP);
BitmapEncoder.saveBitmap(chart, "./Sample_Chart", BitmapFormat.GIF);

BitmapEncoder.saveBitmapWithDPI(chart, "./Sample_Chart_300_DPI", BitmapFormat.PNG, 300);
BitmapEncoder.saveBitmapWithDPI(chart, "./Sample_Chart_300_DPI", BitmapFormat.JPG, 300);
BitmapEncoder.saveBitmapWithDPI(chart, "./Sample_Chart_300_DPI", BitmapFormat.GIF, 300);

VectorGraphicsEncoder.saveVectorGraphic(chart, "./Sample_Chart", VectorGraphicsFormat.EPS);
VectorGraphicsEncoder.saveVectorGraphic(chart, "./Sample_Chart", VectorGraphicsFormat.PDF);
VectorGraphicsEncoder.saveVectorGraphic(chart, "./Sample_Chart", VectorGraphicsFormat.SVG);

} }

答案 1 :(得分:0)

类似于 dawnfyly's answer,但更具体地针对 OP 的问题,并且仅将输出写入 PDF。

可以使用 VectorGraphicsEncoder 编写 PDF,如标题 "Save Chart as Bitmap" 下的示例所示。

在这里,我已将示例精简为仅提供相关信息:

package com.example;

import java.io.IOException;

import org.knowm.xchart.VectorGraphicsEncoder;
import org.knowm.xchart.VectorGraphicsEncoder.VectorGraphicsFormat;
import org.knowm.xchart.XYChart;
import org.knowm.xchart.XYSeries;
import org.knowm.xchart.style.markers.SeriesMarkers;

public class TryXchartToPdf extends XchartBase {
    /**
     * Creates a simple Chart and saves it as a PDF file.
     * @throws IOException
     */

    public static void main(String[] args) throws IOException {

        double[] yData = new double[] { 2.0, 1.0, 0.0 };

        // Create Chart
        XYChart chart = new XYChart(500, 400);
        chart.setTitle("Sample Chart");
        chart.setXAxisTitle("X");
        chart.setXAxisTitle("Y");
        XYSeries series = chart.addSeries("y(x)", null, yData);
        series.setMarker(SeriesMarkers.CIRCLE);

        VectorGraphicsEncoder.saveVectorGraphic(chart, "./Sample_Chart", VectorGraphicsFormat.PDF);

    }
}