首页 前端知识 JAVA后端使用echarts生成折线表格转成图片保存在本地

JAVA后端使用echarts生成折线表格转成图片保存在本地

2024-02-28 11:02:30 前端知识 前端哥 772 633 我要收藏

效果图:

准备工作:

由于echarts是前端的包,后端需要用到依赖工具。

工具下载:

链接:https://pan.baidu.com/s/1NX9pf77SlEtU_QdKMn3_Ow
提取码:wli7

解压后我是直接放在D盘根目录下,echarts-convert.js:

 

PhantomJS工具(执行命令工具,需要配置环境变量)

官方文档:http://phantomjs.org/headless-testing.html

 配置环境变量:

 

具体代码:

        <!--导出echarts图片-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <dependency>
            <groupId>com.github.abel533</groupId>
            <artifactId>ECharts</artifactId>
            <version>2.2.6</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
package com.chen.test;

import com.chen.entity.MetricsMonitor;
import com.chen.entity.PmsMetricsMonitorIndexVO;
import com.github.abel533.echarts.Grid;
import com.github.abel533.echarts.Label;
import com.github.abel533.echarts.Legend;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.Title;
import com.github.abel533.echarts.axis.Axis;
import com.github.abel533.echarts.axis.AxisLabel;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.AxisType;
import com.github.abel533.echarts.code.LineType;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Position;
import com.github.abel533.echarts.code.SeriesType;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.X;
import com.github.abel533.echarts.series.Line;
import com.google.gson.Gson;
import lombok.SneakyThrows;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: Chen
 * @Date: 2023/4/18 10:44
 * @Desc:
 */
public class LeetCodeTest {

    private static final String JSpath = "D:\\echarts-convert\\echarts-convert1.js";

    @SneakyThrows
    public static void main(String[] args) {
        MetricsMonitor metricsMonitor = new MetricsMonitor();
        PmsMetricsMonitorIndexVO vo = new PmsMetricsMonitorIndexVO();
        vo.setTechDeliDura(new BigDecimal(345));
        metricsMonitor.setTargetValue(vo);
        List<PmsMetricsMonitorIndexVO> monitorIndexVOList = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //造数据
        for (int i = 1; i < 12; i++) {
            PmsMetricsMonitorIndexVO monitorIndexVO = new PmsMetricsMonitorIndexVO();
            monitorIndexVO.setCurrentTimeStr(format.format(new Date()));
            if (i%2 == 0) {
                monitorIndexVO.setTechDeliDura(new BigDecimal((192.5 - i)));
            } else {
                monitorIndexVO.setTechDeliDura(new BigDecimal((92.9 + i)));
            }
            if (i==9) {
                monitorIndexVO.setTechDeliDura(new BigDecimal(55));
            }
            if (i==10 || i==11) {
                monitorIndexVO.setTechDeliDura(new BigDecimal(367));
            }
            monitorIndexVOList.add(monitorIndexVO);
        }
        metricsMonitor.setMetricsMonitorList(monitorIndexVOList);
        Option option = getTechDeliDuraOption(metricsMonitor);
        Map<String,Object> resultMap=new HashMap<>();

        String path = generateEChart(new Gson().toJson(option), resultMap);

        // 构建HTTP POST请求,发送ECharts配置项和echarts.min.js文件
        HttpPost httpPost = new HttpPost("https://www.echartsjs.com/api/echarts/export");

        // 发送HTTP请求并获取响应
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        // 将响应内容保存为PNG图像文件
        OutputStream outputStream = new FileOutputStream("chart.png");
        entity.writeTo(outputStream);
        outputStream.close();
    }

    public static String generateEChart(String options, Map<String,Object> resultMap) {
        //获取时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmss");
        String nowDate = sdf.format(new Date());
        String dataPath = writeFile(options);
        String fileName= String.format("%s库位移动量趋势图.png", nowDate);
        String path = "D:/temp/Echart/" + fileName;
        try {
            File file = new File(path);     //文件路径(路径+文件名)
            if (!file.exists()) {   //文件不存在则创建文件,先创建目录
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            String cmd = "phantomjs " + JSpath + " -infile " + dataPath + " -outfile " + path;
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = input.readLine()) != null) {
                System.out.println("line++++++++++++++++++++"+line);
            }
            input.close();

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            return path;
        }
    }

    public static String writeFile(String options) {
        String dataPath="D:\\chartData\\data" + UUID.randomUUID().toString().substring(0, 8) +".json";
        try {
            File writename = new File(dataPath); // 相对路径,如果没有则要建立一个新的output.txt文件
            if (!writename.exists()) {   //文件不存在则创建文件,先创建目录
                File dir = new File(writename.getParent());
                dir.mkdirs();
                writename.createNewFile(); // 创建新文件
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(options); // \r\n即为换行
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 最后记得关闭文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataPath;
    }

    public static Option getTechDeliDuraOption(MetricsMonitor metricsMonitor) {
        List<PmsMetricsMonitorIndexVO> metricsMonitorList = metricsMonitor.getMetricsMonitorList();
        Option optionTechDeliDura = new Option();

        // 设置标题
        Title title = new Title();
        title.setText("平均技术交付时长趋势图(自然日)");
        title.setTextAlign(X.left);
        optionTechDeliDura.setTitle(title);

        // 设置提示框
        /*Tooltip tooltip = new Tooltip();
        tooltip.setTrigger(Trigger.axis);
        optionTechDeliDura.setTooltip(tooltip);*/
        optionTechDeliDura.tooltip().trigger(Trigger.axis);
        // 设置图例
        Legend legend = new Legend();
        List<Object> legendData = new ArrayList<>();
        legendData.add("平均技术交付时长");
        legendData.add("目标值");
        legend.setData(legendData);
        legend.setOrient(Orient.vertical);
        optionTechDeliDura.setLegend(legend);

        // 设置网格
        Grid grid = new Grid();
        grid.setWidth(800);
        grid.setHeight(450);
        optionTechDeliDura.setGrid(grid);

        // 设置x轴
        CategoryAxis xAxis = new CategoryAxis();
        xAxis.setType(AxisType.category);
        xAxis.setBoundaryGap(false);
        List<Object> xAxisData = new ArrayList<>();
        for (PmsMetricsMonitorIndexVO monitorIndexVO : metricsMonitorList) {
            xAxisData.add(monitorIndexVO.getCurrentTimeStr());
        }
        xAxis.setData(xAxisData);
        AxisLabel axisLabel = new AxisLabel();
        axisLabel.setRotate(45);
        xAxis.setAxisLabel(axisLabel);
        List<Axis> axisListX = new ArrayList<>();
        axisListX.add(xAxis);
        optionTechDeliDura.setxAxis(axisListX);

        // 设置y轴
        ValueAxis yAxis = new ValueAxis();
        yAxis.setType(AxisType.value);
        List<Axis> axisListY = new ArrayList<>();
        axisListY.add(yAxis);
        optionTechDeliDura.setyAxis(axisListY);


        Label lineLabel = new Label();
        lineLabel.setShow(true);
        lineLabel.setPosition(Position.top);
        // 设置平均技术交付时长的线条
        Line lineTechDeliDura = new Line();
        List<Object> techDeliDuraData = new ArrayList<>();
        for (PmsMetricsMonitorIndexVO monitorIndexVO : metricsMonitorList) {
            if (monitorIndexVO.getTechDeliDura() != null) {
                lineTechDeliDura.setType(SeriesType.line);
                lineTechDeliDura.setName("平均技术交付时长");
                techDeliDuraData.add(monitorIndexVO.getTechDeliDura());
            } else {
                techDeliDuraData.add("-");
            }
        }
        lineTechDeliDura.setData(techDeliDuraData);
        lineTechDeliDura.itemStyle().normal().label(lineLabel);
        lineTechDeliDura.setShowAllSymbol(true);
        optionTechDeliDura.series(lineTechDeliDura);

        // 设置目标值的线条
        Line targetLine = new Line();
        List<Object> targetLineData = new ArrayList<>();
        for (PmsMetricsMonitorIndexVO monitorIndexVO : metricsMonitorList) {
            targetLine.setType(SeriesType.line);
            targetLine.setName("目标值");
            targetLineData.add(metricsMonitor.getTargetValue().getTechDeliDura());
        }
        targetLine.setData(targetLineData);
        targetLine.itemStyle().normal().lineStyle().width(4).type(LineType.dotted);
        lineTechDeliDura.setShowAllSymbol(true);
        optionTechDeliDura.series(targetLine);

        return optionTechDeliDura;
    }
}

生成的文件:

chartData

temp 

 

转载请注明出处或者链接地址:https://www.qianduange.cn//article/2889.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!