IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> java + jfreechart + itextpdf创建折线图饼图并导出为pdf -> 正文阅读

[JavaScript知识库]java + jfreechart + itextpdf创建折线图饼图并导出为pdf

一、添加需要的maven依赖

<!--用于生成pdf-->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.9</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<!--用于jfreechart生成图片  -->
<dependency>
    <groupId>org.jfree</groupId>
    <artifactId>jfreechart</artifactId>
    <version>1.5.0</version>
</dependency>

二、工具类生成pdf

import com.alibaba.fastjson.JSONArray;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.manager.util.echarts.dto.VehicleIndex;
import com.manager.util.echarts.dto.VehicleIndex1;
import com.manager.util.echarts.dto.VehicleIndex2;
import com.manager.util.echarts.dto.VehicleIndex3;
import org.apache.commons.lang3.ObjectUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author yanjj
 * @ClassName CreateTable
 * @date 2022/7/12
 */
public class CreateEchartsPdfUtils {

    public static void createTable(ByteArrayOutputStream outputStream, List<VehicleIndex> tableContentList, List<VehicleIndex> tableContentList2, Map<String,Map<String, BigDecimal>> linePort, List<VehicleIndex> tableContentList3, Map<String, BigDecimal> piePort,List<VehicleIndex> tableContentList4) throws DocumentException, IOException {
        // 创建一个文档(默认大小A4,边距36, 36, 36, 36)
        Document document = new Document();
        // 设置文档大小
        document.setPageSize(PageSize.A4);
        // 设置边距,单位都是像素,换算大约1厘米=28.33像素
        document.setMargins(50, 50, 50, 50);
        // 创建writer,通过writer将文档写入磁盘
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        //标题
        String title = "XXXX投资基金周度报告";
        //设置标题时间
        String createHeadTime = "报告截止日期:2022-07-08";
        // 打开文档,只有打开后才能往里面加东西
        document.open();
        // 设置作者
        document.addAuthor("XX");
        // 设置创建者
        document.addCreator("XX");
        // 设置主题
        document.addSubject(title);
        // 设置标题
        document.addTitle(title);
        // 设置标题
        Paragraph paragraphHead1 = createHead1(title);
        document.add(paragraphHead1);
        // 设置标题时间
        Paragraph paragraphHeadTime = createHeadTime(createHeadTime);
        document.add(paragraphHeadTime);
        //产品净值表格
        buildProductNetValue(document,tableContentList);
        //收益率指标
        buildYield(document,tableContentList2);
        //净值走势折线图
        JFreeChartUtils.createLinePortImage(document,"净值走势", linePort, "日期", "净值");
        //风险指标
        buildRiskIndicator(document,tableContentList3);
        //创建饼状图
        JFreeChartUtils.createPiePortImage(document,"组合配置", piePort);
        //产品信息
        buildProductDetail(document,tableContentList4);
        // 关闭文档,才能输出
        document.close();
        writer.close();
    }

    /**
     * 根据传入的参数生成PDF文档使用的字体
     *
     * @param fontSize  字体大小
     * @param fontMode  字体正常、加粗、下划线等
     * @param fontColor 字体颜色
     * @return 返回生成的字体
     */
    private static Font createFont(int fontSize, int fontMode, BaseColor fontColor) throws DocumentException, IOException {
        BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        return new Font(bfChinese, fontSize, fontMode, fontColor);
    }

    /**
     * 设置一级标题
     *
     * @param title 标题内容
     * @return 标题段落
     */
    private static Paragraph createHead1(String title) throws DocumentException, IOException {
        Font font = createFont(22, Font.BOLD, BaseColor.BLACK);
        Paragraph paragraph = new Paragraph(title, font);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        return paragraph;
    }

    /**
     * 设置标题下的时间字段
     *
     * @param time 时间
     * @return 时间的段落
     */
    private static Paragraph createHeadTime(String time) throws DocumentException, IOException {
        Font font = createFont(14, Font.BOLD, BaseColor.BLACK);
        Paragraph paragraph = new Paragraph(time, font);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        return paragraph;
    }

    /**
     * 设置一级标题
     *
     * @param title 标题内容
     * @return 标题段落
     */
    public static Paragraph createHead2(String title) throws DocumentException, IOException {
        Font font = createFont(12, Font.BOLD, BaseColor.BLACK);
        Paragraph paragraph = new Paragraph(title, font);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        return paragraph;
    }

    /**
     * 根据传入的标题名称:批量设置标题值
     *
     * @param table        创建的表格对象
     * @param tableHeadStr 每个标题值按顺序来
     */
    private static void createTableHead(PdfPTable table, String[] tableHeadStr) throws DocumentException, IOException {
        if (ObjectUtils.isEmpty(tableHeadStr)) {
            return;
        }
        //获取设置表格标题的字体
        Font font = createFont(10, Font.NORMAL, BaseColor.BLACK);
        for (String tableHead : tableHeadStr) {
            PdfPCell cell = new PdfPCell(new Phrase(tableHead, font));
            cell.setBackgroundColor(new BaseColor(221, 221, 221));
            cell.setMinimumHeight(20);
            cell.setUseAscender(true);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }
    }

    /**
     * 创建表格内容
     *
     * @param table            表格对象
     * @param tableContentList 表格内容对象
     */
    private static void createTableContent(PdfPTable table, List<VehicleIndex> tableContentList) throws DocumentException, IOException {
        if (ObjectUtils.isEmpty(tableContentList)) {
            return;
        }
        //判断类型是VehicleIndex2还是VehicleIndex
        VehicleIndex index = tableContentList.get(0);
        if (index instanceof VehicleIndex2){
            List<VehicleIndex2> vehicleIndex2s = JSONArray.parseArray(JSONArray.toJSONString(tableContentList), VehicleIndex2.class);
            for (VehicleIndex2 vehicleIndex : vehicleIndex2s) {
                //获取设置表格内容的字体与内容
                table.addCell(createTableContent(vehicleIndex.getIndexName()));
                table.addCell(createTableContent(vehicleIndex.getIndexValue()));
                table.addCell(createTableContent(vehicleIndex.getChainValue()));
            }
        }else if (index instanceof VehicleIndex3){
            List<VehicleIndex3> vehicleIndex3s = JSONArray.parseArray(JSONArray.toJSONString(tableContentList), VehicleIndex3.class);
            for (VehicleIndex3 vehicleIndex : vehicleIndex3s) {
                //获取设置表格内容的字体与内容
                table.addCell(createTableContent(vehicleIndex.getIndexName()));
                table.addCell(createTableContent(vehicleIndex.getIndexValue()));
            }
        } else {
            List<VehicleIndex1> vehicleIndex1s = JSONArray.parseArray(JSONArray.toJSONString(tableContentList), VehicleIndex1.class);
            for (VehicleIndex1 vehicleIndex : vehicleIndex1s) {
                //获取设置表格内容的字体与内容
                table.addCell(createTableContent(vehicleIndex.getIndexValue()));
                table.addCell(createTableContent(vehicleIndex.getChainValue()));
            }
        }

    }

    /**
     * 设置表格内容
     *
     * @param title 标题内容
     * @return 表格标题内容
     */
    private static PdfPCell createTableContent(String title) throws DocumentException, IOException {
        Font font = createFont(10, Font.NORMAL, BaseColor.BLACK);
        PdfPCell cell = new PdfPCell(new Phrase(title, font));
        cell.setMinimumHeight(20);
        cell.setUseAscender(true);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        return cell;
    }

    /**
     * 创建产品净值表格
     * @param document
     * @param tableContentList
     * @throws DocumentException
     * @throws IOException
     */
    public static void buildProductNetValue(Document document,List<VehicleIndex> tableContentList) throws DocumentException, IOException {
        //二级标题
        String title = "产品净值";
        Paragraph paragraphHead = createHead2(title);
        //设置段落前后间距
        paragraphHead.setSpacingAfter(10);
        paragraphHead.setSpacingBefore(10);
        document.add(paragraphHead);
        //创建表格(2列的表格)
        PdfPTable table = new PdfPTable(2);
        table.setTotalWidth(PageSize.A4.getWidth() - 100);
        table.setLockedWidth(true);
        // 创建头
        String[] tableHeadStr = {"单位净值", "累计净值"};
        createTableHead(table, tableHeadStr);
        // 添加表格内容
        createTableContent(table, tableContentList);
        document.add(table);
    }

    /**
     * 收益率指标表格
     * @param document
     * @param tableContentList
     * @throws DocumentException
     * @throws IOException
     */
    public static void buildYield(Document document,List<VehicleIndex> tableContentList) throws DocumentException, IOException {
        //二级标题
        String title = "收益率指标";
        Paragraph paragraphHead = createHead2(title);
        //设置段落前后间距
        paragraphHead.setSpacingAfter(10);
        paragraphHead.setSpacingBefore(10);
        document.add(paragraphHead);
        //创建表格(3列的表格)
        PdfPTable table = new PdfPTable(3);
        table.setTotalWidth(PageSize.A4.getWidth() - 100);
        table.setLockedWidth(true);
        // 创建头
        String[] tableHeadStr2 = {"", "本产品", "沪深300"};
        createTableHead(table, tableHeadStr2);
        createTableContent(table, tableContentList);
        document.add(table);
    }


    /**
     * 风险指标
     * @param document
     * @param tableContentList
     * @throws DocumentException
     * @throws IOException
     */
    public static void buildRiskIndicator(Document document,List<VehicleIndex> tableContentList) throws DocumentException, IOException {
        //二级标题
        String title = "风险指标";
        Paragraph paragraphHead = createHead2(title);
        //设置段落前后间距
        paragraphHead.setSpacingAfter(10);
        paragraphHead.setSpacingBefore(10);
        document.add(paragraphHead);
        //创建表格(3列的表格)
        PdfPTable table = new PdfPTable(2);
        table.setTotalWidth(PageSize.A4.getWidth() - 100);
        table.setLockedWidth(true);
        createTableContent(table, tableContentList);
        document.add(table);
    }

    /**
     * 产品信息
     * @param document
     * @param tableContentList
     * @throws DocumentException
     * @throws IOException
     */
    public static void buildProductDetail(Document document,List<VehicleIndex> tableContentList) throws DocumentException, IOException {
        //二级标题
        String title = "产品信息";
        Paragraph paragraphHead5 = createHead2(title);
        //设置段落前后间距
        paragraphHead5.setSpacingAfter(10);
        paragraphHead5.setSpacingBefore(10);
        document.add(paragraphHead5);
        PdfPTable table = new PdfPTable(2);
        table.setTotalWidth(PageSize.A4.getWidth() - 100);
        table.setLockedWidth(true);
        createTableContent(table, tableContentList);
        document.add(table);
    }
}

三、生成折线图饼图工具类

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Map;

/**
 * @author yanjj
 * @ClassName JFreeChartUtils
 * @date 2022/7/12
 */
public class JFreeChartUtils {

    private static final String NO_DATA_MSG = "暂无数据";
    private static final Font FONT = new Font("STSongStd-Light", Font.BOLD, 12);
    public static Color[] CHART_COLORS = {
            new Color(146, 29, 34),
            new Color(126, 126, 126),
            new Color(31, 129, 188),
            new Color(92, 92, 97),
            new Color(144, 237, 125),
            new Color(255, 188, 117),
            new Color(153, 158, 255),
            new Color(255, 117, 153),
            new Color(253, 236, 109),
            new Color(128, 133, 232),
            new Color(158, 90, 102),
            new Color(255, 204, 102)};

    static {
        setChartTheme();
    }

    /**
     * 中文主题样式 解决乱码
     */
    public static void setChartTheme() {
        // 设置中文主题样式 解决乱码
        StandardChartTheme chartTheme = new StandardChartTheme("CN");
        // 设置标题字体
        chartTheme.setExtraLargeFont(FONT);
        // 设置图例的字体
        chartTheme.setRegularFont(FONT);
        // 设置轴向的字体
        chartTheme.setLargeFont(FONT);
        chartTheme.setSmallFont(FONT);
        chartTheme.setTitlePaint(new Color(51, 51, 51));
        chartTheme.setSubtitlePaint(new Color(85, 85, 85));
        // 设置标注
        chartTheme.setLegendBackgroundPaint(Color.WHITE);
        chartTheme.setLegendItemPaint(Color.BLACK);
        chartTheme.setChartBackgroundPaint(Color.WHITE);
        // 绘制颜色绘制颜色.轮廓供应商
        // paintSequence,outlinePaintSequence,strokeSequence,outlineStrokeSequence,shapeSequence

        Paint[] OUTLINE_PAINT_SEQUENCE = new Paint[]{Color.WHITE};
        // 绘制器颜色源
        DefaultDrawingSupplier drawingSupplier = new DefaultDrawingSupplier(CHART_COLORS, CHART_COLORS, OUTLINE_PAINT_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
        chartTheme.setDrawingSupplier(drawingSupplier);
        // 绘制区域
        chartTheme.setPlotBackgroundPaint(Color.WHITE);
        // 绘制区域外边框
        chartTheme.setPlotOutlinePaint(Color.WHITE);
        // 链接标签颜色
        chartTheme.setLabelLinkPaint(new Color(8, 55, 114));
        chartTheme.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE);

        chartTheme.setAxisOffset(new RectangleInsets(5, 12, 5, 12));
        // X坐标轴垂直网格颜色
        chartTheme.setDomainGridlinePaint(new Color(192, 208, 224));
        // Y坐标轴水平网格颜色
        chartTheme.setRangeGridlinePaint(new Color(192, 192, 192));

        chartTheme.setBaselinePaint(Color.WHITE);
        chartTheme.setCrosshairPaint(Color.BLUE);
        // 坐标轴标题文字颜色
        chartTheme.setAxisLabelPaint(new Color(51, 51, 51));
        // 刻度数字
        chartTheme.setTickLabelPaint(new Color(67, 67, 72));
        // 设置柱状图渲染
        chartTheme.setBarPainter(new StandardBarPainter());
        // XYBar 渲染
        chartTheme.setXYBarPainter(new StandardXYBarPainter());

        chartTheme.setItemLabelPaint(Color.black);
        chartTheme.setThermometerPaint(Color.white);

        ChartFactory.setChartTheme(chartTheme);
    }

    /**
     * 设置折线图样式
     * @param plot 折线图对象
     * @param isShowDataLabels 是否显示数据标题
     * @param isShapesVisible 是否显示数据点
     */
    public static void setLineRender(CategoryPlot plot, boolean isShowDataLabels, boolean isShapesVisible) {
        plot.setNoDataMessage(NO_DATA_MSG);
        plot.setInsets(new RectangleInsets(10, 10, 0, 10), false);
        LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
        renderer.setDefaultStroke(new BasicStroke(1.5F));
        if (isShowDataLabels) {
            renderer.setDefaultItemLabelsVisible(true);
            renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator(StandardCategoryItemLabelGenerator.DEFAULT_LABEL_FORMAT_STRING,
                    NumberFormat.getInstance()));
            renderer.setDefaultPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BOTTOM_CENTER));
        }
        // 数据点绘制形状
        renderer.setDefaultShapesVisible(isShapesVisible);
        setXAixs(plot);
        setYAixs(plot);
    }

    /**
     * 设置类别图表(CategoryPlot) X坐标轴线条颜色和样式
     * @param plot 类别图表对象
     */
    public static void setXAixs(CategoryPlot plot) {
        Color lineColor = new Color(51, 51, 51);
        plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
        // X坐标轴颜色
        plot.getDomainAxis().setAxisLinePaint(lineColor);
        // X坐标轴标记|竖线颜色
        plot.getDomainAxis().setTickMarkPaint(lineColor);
        plot.getDomainAxis().setTickLabelFont(new Font("STSongStd-Light",Font.BOLD,12));
    }

    /**
     * 设置类别图表(CategoryPlot) Y坐标轴线条颜色和样式 同时防止数据无法显示
     * @param plot 类别图表对象
     */
    public static void setYAixs(CategoryPlot plot) {
        Color axisColor = new Color(51, 51, 51);
        Color tickColor = new Color(219, 218, 218);
        ValueAxis axis = plot.getRangeAxis();
        // Y坐标轴颜色
        axis.setAxisLinePaint(axisColor);
        // Y坐标轴标记|竖线颜色
        axis.setTickMarkPaint(tickColor);
        // false隐藏Y刻度
        axis.setAxisLineVisible(true);
        axis.setTickMarksVisible(true);
        // Y轴网格线条
        plot.setRangeGridlinePaint(new Color(229, 229, 229));
        plot.setRangeGridlineStroke(new BasicStroke(1));
        // 设置顶部Y坐标轴间距,防止数据无法显示
        plot.getRangeAxis().setUpperMargin(0.1);
        // 设置底部Y坐标轴间距
        plot.getRangeAxis().setLowerMargin(0.1);
        plot.getRangeAxis().setTickLabelFont(new Font("STSongStd-Light",Font.BOLD,12));
    }


    /**
     * 生成折线图并返回Image数组
     *
     * @param title 标题
     * @param datas 数据
     * @param xName X轴
     * @param yName Y轴
     * @return 生成的折线图byte数组
     */
    public static void createLinePortImage(Document document, String title, Map<String,Map<String, BigDecimal>> datas, String xName, String yName) throws DocumentException, IOException {
        //二级标题
        Paragraph paragraphHead = CreateEchartsPdfUtils.createHead2(title);
        //设置段落前后间距
        paragraphHead.setSpacingAfter(5);
        paragraphHead.setSpacingBefore(5);
        document.add(paragraphHead);
        try {
            //种类数据集
            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            //遍历map
            for (Map.Entry<String,Map<String, BigDecimal>> entry : datas.entrySet()) {
                String key = entry.getKey();
                Map<String, BigDecimal> value = entry.getValue();
                for (Map.Entry<String, BigDecimal> decimalEntry : value.entrySet()) {
                    dataset.setValue(decimalEntry.getValue(),
                            key,
                            decimalEntry.getKey());
                }
            }
            //创建2D折线图,折线图分水平显示和垂直显示两种
            //legend:是否显示图例(对于简单的柱状图必须是false)
            //tooltips:是否生成工具
            //urls:是否生成URL链接
            JFreeChart chart = ChartFactory.createLineChart("", xName, yName, dataset,
                    PlotOrientation.VERTICAL,
                    true,
                    true,
                    true);
            //得到绘图区
            setLineRender((CategoryPlot) chart.getPlot(), true, true);
            ByteArrayOutputStream bas = new ByteArrayOutputStream();
            ChartUtils.writeChartAsJPEG(bas, 1.0f, chart, 800, 500, null);
            com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(bas.toByteArray());
            image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER);
            image.scaleAbsolute(500, 300);
            document.add(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 生成饼图,并返回byte数组
     *
     * @param title 标题
     * @param datas 数据
     * @return 返回生成的byte数组
     */
    public static void createPiePortImage(Document document,String title, Map<String, BigDecimal> datas) throws DocumentException, IOException {
        //二级标题
        Paragraph paragraphHead = CreateEchartsPdfUtils.createHead2(title);
        //设置段落前后间距
        paragraphHead.setSpacingAfter(5);
        paragraphHead.setSpacingBefore(5);
        document.add(paragraphHead);
        try {
            // 如果不使用Font,中文将显示不出来
            DefaultPieDataset pds = new DefaultPieDataset();
            //遍历map
            for (Map.Entry<String, BigDecimal> entry : datas.entrySet()) {
                pds.setValue(entry.getKey(),
                        entry.getValue());
            }
            /**
             * 生成一个饼图的图表
             * 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接
             */
            JFreeChart chart = ChartFactory.createPieChart("", pds, true, true, true);
            setPieRender(chart.getPlot());
            ByteArrayOutputStream bas = new ByteArrayOutputStream();
            ChartUtils.writeChartAsJPEG(bas, 1.0f, chart, 800, 500, null);
            com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(bas.toByteArray());
            image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER);
            image.scaleAbsolute(500, 300);
            document.add(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置饼状图渲染
     * @param plot 饼图对象
     */
    public static void setPieRender(Plot plot) {

        plot.setNoDataMessage(NO_DATA_MSG);
        plot.setInsets(new RectangleInsets(10, 10, 5, 10));
        PiePlot piePlot = (PiePlot) plot;
        piePlot.setInsets(new RectangleInsets(0, 0, 0, 0));
        // 圆形
        piePlot.setCircular(true);
        piePlot.setLabelGap(0.01);
        piePlot.setInteriorGap(0.05D);
        // 图例形状
        piePlot.setLegendItemShape(new Rectangle(10, 10));
        piePlot.setIgnoreNullValues(true);
        // 去掉背景色
        piePlot.setLabelBackgroundPaint(null);
        // 去掉阴影
        piePlot.setLabelShadowPaint(null);
        // 去掉边框
        piePlot.setLabelOutlinePaint(null);
        piePlot.setShadowPaint(null);
        // 0:category 1:value:2 :percentage
        // 显示标签数据
        piePlot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{2}"));
    }

}

四、测试数据

import com.itextpdf.text.DocumentException;
import com.manager.util.echarts.dto.VehicleIndex;
import com.manager.util.echarts.dto.VehicleIndex1;
import com.manager.util.echarts.dto.VehicleIndex2;
import com.manager.util.echarts.dto.VehicleIndex3;
import org.apache.commons.io.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yanjj
 * @ClassName test
 * @date 2022/7/12
 */
public class test {

    public static void main(String[] args) throws DocumentException, IOException {
        ArrayList<VehicleIndex> tableContentList = new ArrayList<>(10);
        VehicleIndex1 vehicleIndex = new VehicleIndex1();
        vehicleIndex.setIndexValue("1.2950");
        vehicleIndex.setChainValue("1.9350");
        tableContentList.add(vehicleIndex);

        ArrayList<VehicleIndex> tableContentList2 = new ArrayList<>(10);
        VehicleIndex2 vehicle = new VehicleIndex2();
        vehicle.setIndexName("周增长率");
        vehicle.setIndexValue("-1.82%");
        vehicle.setChainValue("-0.85%");
        tableContentList2.add(vehicle);
        VehicleIndex2 vehicle2 = new VehicleIndex2();
        vehicle2.setIndexName("月增长率");
        vehicle2.setIndexValue("-2.19%");
        vehicle2.setChainValue("-1.25%");
        tableContentList2.add(vehicle2);
        VehicleIndex2 vehicle3 = new VehicleIndex2();
        vehicle3.setIndexName("今年以来增长率");
        vehicle3.setIndexValue("-11.12%");
        vehicle3.setChainValue("-10.36%");
        tableContentList2.add(vehicle3);
        VehicleIndex2 vehicle4 = new VehicleIndex2();
        vehicle4.setIndexName("自成立以来增长率");
        vehicle4.setIndexValue("115.57%");
        vehicle4.setChainValue("115.57%");
        tableContentList2.add(vehicle4);

        ArrayList<VehicleIndex> tableContentList3 = new ArrayList<>(10);
        VehicleIndex3 index = new VehicleIndex3();
        index.setIndexName("夏普比率");
        index.setIndexValue("0.93");
        tableContentList3.add(index);
        VehicleIndex3 index2 = new VehicleIndex3();
        index2.setIndexName("索提诺比率");
        index2.setIndexValue("0.96");
        tableContentList3.add(index2);
        VehicleIndex3 index3 = new VehicleIndex3();
        index3.setIndexName("年化波动率");
        index3.setIndexValue("16.87%");
        tableContentList3.add(index3);
        VehicleIndex3 index4 = new VehicleIndex3();
        index4.setIndexName("近3年最大回撤");
        index4.setIndexValue("28.29%");
        tableContentList3.add(index4);
        VehicleIndex3 index5 = new VehicleIndex3();
        index5.setIndexName("年化收益率");
        index5.setIndexValue("13.91%");
        tableContentList3.add(index5);

        ArrayList<VehicleIndex> tableContentList4 = new ArrayList<>(10);
        VehicleIndex3 vehicleIndex1 = new VehicleIndex3();
        vehicleIndex1.setIndexName("管理人");
        vehicleIndex1.setIndexValue("观富(北京)资产管理有限公司");
        tableContentList4.add(vehicleIndex1);
        VehicleIndex3 vehicleIndex2 = new VehicleIndex3();
        vehicleIndex2.setIndexName("托管人");
        vehicleIndex2.setIndexValue("兴业证券");
        tableContentList4.add(vehicleIndex2);
        VehicleIndex3 vehicleIndex3 = new VehicleIndex3();
        vehicleIndex3.setIndexName("成立日期");
        vehicleIndex3.setIndexValue("2017-06-13");
        tableContentList4.add(vehicleIndex3);
        VehicleIndex3 vehicleIndex4 = new VehicleIndex3();
        vehicleIndex4.setIndexName("开放日");
        vehicleIndex4.setIndexValue("每月15日,连续2日开放");
        tableContentList4.add(vehicleIndex4);
        VehicleIndex3 vehicleIndex5 = new VehicleIndex3();
        vehicleIndex5.setIndexName("申购费");
        vehicleIndex5.setIndexValue("0%");
        tableContentList4.add(vehicleIndex5);
        VehicleIndex3 vehicleIndex6 = new VehicleIndex3();
        vehicleIndex6.setIndexName("赎回费");
        vehicleIndex6.setIndexValue("持有不足1年(360个自然日)1%");
        tableContentList4.add(vehicleIndex6);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CreateEchartsPdfUtils.createTable(outputStream,tableContentList,tableContentList2,createLinePort(), tableContentList3,createPiePort(),tableContentList4);
        FileUtils.copyInputStreamToFile(new ByteArrayInputStream(outputStream.toByteArray()),new File("D:\\折线图/demo.pdf"));
    }

    /**
     * 折线图数据
     * @return
     */
    private static Map<String,Map<String, BigDecimal>> createLinePort(){
        Map<String,Map<String, BigDecimal>> resultmap = new HashMap<>(16);
        Map<String, BigDecimal> map = new HashMap<>(16);
        map.put("2021-06-22",  new BigDecimal("3.1"));
        map.put("2021-06-25",  new BigDecimal("5.1"));
        map.put("2021-06-30",  new BigDecimal("7.1"));
        map.put("2021-07-22",  new BigDecimal("10.1"));
        map.put("2021-07-23",  new BigDecimal("4.2"));
        map.put("2021-07-24",  new BigDecimal("12.8"));
        map.put("2021-07-25",  new BigDecimal("18.91"));
        map.put("2021-07-26",  new BigDecimal("20.3"));
        map.put("2021-07-27",  new BigDecimal("30.1"));
        resultmap.put("本产品",map);
        Map<String, BigDecimal> map2 = new HashMap<>(16);
        map2.put("2021-06-22",  new BigDecimal("4.1"));
        map2.put("2021-06-25",  new BigDecimal("7.1"));
        map2.put("2021-06-30",  new BigDecimal("2.1"));
        map2.put("2021-07-22",  new BigDecimal("10.1"));
        map2.put("2021-07-23",  new BigDecimal("14.2"));
        map2.put("2021-07-24",  new BigDecimal("17.8"));
        map2.put("2021-07-25",  new BigDecimal("12.91"));
        map2.put("2021-07-26",  new BigDecimal("27.3"));
        map2.put("2021-07-27",  new BigDecimal("37.1"));
        resultmap.put("沪深线",map2);
        return resultmap;
    }

    /**
     * 饼图数据
     * @return
     */
    private static Map<String, BigDecimal> createPiePort(){
        Map<String, BigDecimal> map = new HashMap<>(16);
        map.put("其他",  new BigDecimal("26.72"));
        map.put("固定收益",  new BigDecimal("0"));
        map.put("权益类",  new BigDecimal("73.28"));
        return map;
    }
}

五、使用到的dto

public class VehicleIndex {

}
@Data
public class VehicleIndex1 extends VehicleIndex{

    private String indexValue;

    private String chainValue;
}
@Data
public class VehicleIndex2 extends VehicleIndex1{

    private String indexName;

}
@Data
public class VehicleIndex3 extends VehicleIndex{

    private String indexName;

    private String indexValue;
}

六、成品

参考:

https://blog.csdn.net/weixin_43618209/article/details/119216777

https://blog.51cto.com/u_15363394/3841748

https://www.pudn.com/news/62a93d88a11cf7345f9dd670.html

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2022-07-17 16:13:50  更:2022-07-17 16:16:31 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年1日历 -2025/1/11 12:32:24-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码