java JFreeChart 绘制各种图形 并使用itextPdf生成PDF导出

一、引入maven

xml 复制代码
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>
<dependency>
    <groupId>org.jfree</groupId>
    <artifactId>jfreechart</artifactId>
    <version>1.5.4</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

二、使用

java 复制代码
package com.jiayou.peis.common.core.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.FileUtils;
import org.jfree.chart.ChartUtils;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import java.io.*;


public class Test {

    public static void main(String[] args) throws IOException {
        PdfWriter writer = null;
        OutputStream outputStream = null;
        Document doc = null;
        try {
            doc = new Document(PageSize.A4);
            doc.setMargins(55, 46, 27, 20);

            File f = new File("C:\\Users\\Administrator\\Desktop\\新建文件夹\\9.pdf");
            if (!f.getParentFile().exists()) {
                FileUtils.forceMkdir(f.getParentFile());
            }
            outputStream = new FileOutputStream(f);
            writer = PdfWriter.getInstance(doc, outputStream);

            doc.open();


            //线图
            ByteArrayOutputStream lineBos = new ByteArrayOutputStream();
            ChartUtils.writeChartAsJPEG(lineBos, ChartUtil.lineChart("线图","r","d",getLineDataset()), 850, 440);
            Image lineImage = Image.getInstance(lineBos.toByteArray());
            lineImage.scalePercent(60);
            doc.add(lineImage);

            //饼图
            ByteArrayOutputStream pieBos = new ByteArrayOutputStream();
            ChartUtils.writeChartAsJPEG(pieBos, ChartUtil.pieChart("饼图",getPieDataset()), 850, 440);
            Image pieImage = Image.getInstance(pieBos.toByteArray());
            pieImage.scalePercent(60);
            doc.add(pieImage);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            doc.close();
            writer.close();
            outputStream.close();

        }
    }

    private static DefaultPieDataset getPieDataset() {
        DefaultPieDataset dataset=new DefaultPieDataset();
        dataset.setValue("硕士",1);
        dataset.setValue("专科",2);
        dataset.setValue("本科",3);
        dataset.setValue("高中",3);
        return dataset;
    }

    private static DefaultCategoryDataset getLineDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(15, "schools", "1970");
        dataset.addValue(30, "schools", "1980");
        dataset.addValue(60, "schools", "1990");
        dataset.addValue(120, "schools", "2000");
        dataset.addValue(240, "schools", "2010");
        dataset.addValue(300, "schools", "2020");
        dataset.addValue(320, "schools", "2022");
        return dataset;
    }
}

三、工具类

java 复制代码
package com.jiayou.peis.common.core.pdf;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import java.awt.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class ChartUtil {
    private static final Color[] BAR_COLORS = new Color[]{new Color(79, 129, 189), new Color(192, 80, 77), new Color(155, 187, 89),};

    public static final Color[] LINE_COLORS = new Color[]{new Color(237, 123, 46), new Color(90, 154, 213), new Color(164, 164, 164),};

    private static final Color[] PIE_COLORS = new Color[]{new Color(75, 172, 198), new Color(128, 100, 162), new Color(155, 187, 89), new Color(192, 80, 77), new Color(79, 129, 189), new Color(44, 77, 117), new Color(247, 150, 70), new Color(165, 165, 165),};


    static StandardChartTheme initChartTheme() {
        StandardChartTheme currentTheme = new StandardChartTheme("JFree");
        // 横轴纵轴标题文字大小
        currentTheme.setLargeFont(new java.awt.Font("宋体", java.awt.Font.BOLD, 15));
        // 横轴纵轴数值文字大小
        currentTheme.setRegularFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 13));
        currentTheme.setExtraLargeFont(new java.awt.Font("宋体", java.awt.Font.BOLD, 20));
        // 背景颜色
        currentTheme.setPlotBackgroundPaint(new Color(255, 255, 204, 0));
        // 边框线条
        currentTheme.setPlotOutlinePaint(new Color(0, 0, 0, 0));
        // 网格线条
        currentTheme.setRangeGridlinePaint(new Color(78, 74, 74));
        return currentTheme;
    }

    /**
     * 线图
     *
     * @param title             标题
     * @param categoryAxisLabel 分类标签
     * @param valueAxisLabel    数值标签
     * @param dataset           数据集
     * @return org.jfree.chart.JFreeChart
     * @author Hou_fx
     * @date 2021.8.4 10:39
     */
    public static JFreeChart lineChart(String title, String categoryAxisLabel, String valueAxisLabel, DefaultCategoryDataset dataset) {
        ChartFactory.setChartTheme(initChartTheme());

        JFreeChart chart = ChartFactory.createLineChart(title,// 图标题
                categoryAxisLabel,// x轴标题
                valueAxisLabel,// y轴标题
                dataset,//数据集
                PlotOrientation.VERTICAL,//图表方向
                true, true, false);

        CategoryPlot plot = chart.getCategoryPlot();
        LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
        // 折现点显示数值
        renderer.setDefaultItemLabelsVisible(true);
        renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        // 更改线条颜色
        for (int i = 0; i < dataset.getRowKeys().size(); i++) {
            renderer.setSeriesPaint(i, LINE_COLORS[i]);
        }
        return chart;
    }


    /**
     * 柱状图
     *
     * @param title
     * @param categoryAxisLabel
     * @param valueAxisLabel
     * @param dataset           数据集
     * @return org.jfree.chart.JFreeChart
     * @author Hou_fx
     * @date 2021.8.4 14:03
     */
    public static JFreeChart barChart(String title, String categoryAxisLabel, String valueAxisLabel, DefaultCategoryDataset dataset) {
        ChartFactory.setChartTheme(initChartTheme());

        JFreeChart chart = ChartFactory.createBarChart(title, categoryAxisLabel, valueAxisLabel, dataset, PlotOrientation.VERTICAL, true, true, false);

        CategoryPlot plot = chart.getCategoryPlot();
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        // 纯色显示
        renderer.setBarPainter(new StandardBarPainter());
        // 柱子上显示小数字
        renderer.setDefaultItemLabelsVisible(true);
        renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        // 设置柱子间隔
        renderer.setItemMargin(0.0);
        // 设置柱子颜色
        for (int i = 0; i < dataset.getRowKeys().size(); i++) {
            renderer.setSeriesPaint(i, BAR_COLORS[i]);
        }
        return chart;
    }

    /**
     * 饼图
     *
     * @param title
     * @param dataset
     * @return org.jfree.chart.JFreeChart
     * @author Hou_fx
     * @date 2021.8.4 14:04
     */
    public static JFreeChart pieChart(String title, DefaultPieDataset dataset) {
        ChartFactory.setChartTheme(initChartTheme());

        JFreeChart chart = ChartFactory.createPieChart(title, dataset, true, true, false);
        PiePlot plot = (PiePlot) chart.getPlot();
        // 设置扇区颜色
        for (int i = 0; i < dataset.getKeys().size(); i++) {
            plot.setSectionPaint(dataset.getKey(i), PIE_COLORS[i]);
        }
        // 设置扇区的线条颜色
        plot.setDefaultSectionOutlinePaint(new Color(255, 255, 255));
        // 设置扇区的线条大小
        plot.setDefaultSectionOutlineStroke(new BasicStroke(3));
        // 设置标签颜色
        plot.setLabelLinkPaint(new Color(255, 255, 255, 0));
        // 设置标签背景色
        plot.setLabelBackgroundPaint(new Color(255, 255, 255, 0));
        // 设置标签线条颜色
        plot.setLabelOutlinePaint(new Color(255, 255, 255, 0));
        // 设置标签阴影颜色
        plot.setLabelShadowPaint(new Color(255, 255, 255, 0));
        // 设置饼图阴影颜色
        plot.setShadowPaint(new Color(255, 255, 255, 0));
        // 添加标签数字百分比显示
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator(("{0}{2}"), NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
        return chart;
    }
}

参考:
https://blog.csdn.net/hfy1237/article/details/126693786
https://blog.csdn.net/qq_39149275/article/details/119381389

相关推荐
百事老饼干15 分钟前
Java[面试题]-真实面试
java·开发语言·面试
customer0822 分钟前
【开源免费】基于SpringBoot+Vue.JS医院管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·开源·intellij-idea
2402_8575893632 分钟前
SpringBoot框架:作业管理技术新解
java·spring boot·后端
HBryce2436 分钟前
缓存-基础概念
java·缓存
一只爱打拳的程序猿1 小时前
【Spring】更加简单的将对象存入Spring中并使用
java·后端·spring
杨荧1 小时前
【JAVA毕业设计】基于Vue和SpringBoot的服装商城系统学科竞赛管理系统
java·开发语言·vue.js·spring boot·spring cloud·java-ee·kafka
minDuck1 小时前
ruoyi-vue集成tianai-captcha验证码
java·前端·vue.js
为将者,自当识天晓地。1 小时前
c++多线程
java·开发语言
daqinzl1 小时前
java获取机器ip、mac
java·mac·ip