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

相关推荐
我要学编程(ಥ_ಥ)6 分钟前
一文详解“二叉树中的深搜“在算法中的应用
java·数据结构·算法·leetcode·深度优先
music0ant9 分钟前
Idea 添加tomcat 并发布到tomcat
java·tomcat·intellij-idea
计算机徐师兄38 分钟前
Java基于SSM框架的无中介租房系统小程序【附源码、文档】
java·微信小程序·小程序·无中介租房系统小程序·java无中介租房系统小程序·无中介租房微信小程序
源码哥_博纳软云39 分钟前
JAVA智慧养老养老护理帮忙代办陪诊陪护小程序APP源码
java·开发语言·微信小程序·小程序·微信公众平台
忒可君2 小时前
C# winform 报错:类型“System.Int32”的对象无法转换为类型“System.Int16”。
java·开发语言
斌斌_____2 小时前
Spring Boot 配置文件的加载顺序
java·spring boot·后端
路在脚下@2 小时前
Spring如何处理循环依赖
java·后端·spring
一个不秃头的 程序员2 小时前
代码加入SFTP JAVA ---(小白篇3)
java·python·github
丁总学Java3 小时前
--spring.profiles.active=prod
java·spring
上等猿3 小时前
集合stream
java