1.引入maven依赖
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
2.java代码示例
package com.github.xiaoymin.knife4j.spring.util;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ChartToPDF {
public static void main(String[] args) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(1, "Category 1", "Value 1");
dataset.addValue(2, "Category 1", "Value 2");
dataset.addValue(3, "Category 2", "Value 1");
dataset.addValue(4, "Category 2", "Value 2");
JFreeChart chart = ChartFactory.createBarChart("Bar Chart", "Category", "Value", dataset);
try {
ChartUtils.saveChartAsPNG(new File("barchart.png"), chart, 400, 300);
} catch (IOException e) {
e.printStackTrace();
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream("barchart.pdf"));
document.open();
com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance("barchart.png");
document.add(image);
document.close();
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
}
3.实现效果