栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

SpringBoot纯后台生成Echarts图片(三)

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot纯后台生成Echarts图片(三)

SpringBoot纯后台生成Echarts图片(一)

SpringBoot纯后台生成Echarts图片(二)

一、项目工程结构

二.项目依赖说明

项目的pom.xml配置,属性配置 见第一篇

三.项目代码说明

(1)echarts-pojo模块(数据模型)

package com.lhf.springboot.echarts.pojo;

import lombok.Data;


@Data
public class PieData {

    private String[] types;
    private String[] datas;
    private String title;

}

(2)controler模块(API接口)

package com.lhf.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lhf.springboot.common.JsonResult;
import com.lhf.springboot.echarts.pojo.BarData;
import com.lhf.springboot.echarts.pojo.LinesData;
import com.lhf.springboot.echarts.pojo.PieData;
import com.lhf.springboot.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.FastDateFormat;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.*;
import java.util.List;


@Api(value = "Freemarker模板生成Echarts图表Api接口", tags = "模板生成图表Api-1")
@RequestMapping("/template")
@RestController
public class EchartsTemplateController {

    private final static Logger logger = Logger.getLogger(EchartsController.class);

    @Value("${img-url}")
    private String imgUrl;

    @Value("${img-url-path}")
    private String imgUrlPath;

    @Value("${request-url}")
    private String requestUrl;

    private static final String path = FreemarkerUtil.class.getClassLoader().getResource("").getPath();
    private String temPath = path + "templates";

    
    @ApiOperation("模板生成饼图, html文件格式")
    @RequestMapping(value = "/pie", method = RequestMethod.POST)
    public JsonResult createPieFtl(@RequestBody PieData pieData) {
        String title = pieData.getTitle();
        String[] types = pieData.getTypes();
        String[] datas = pieData.getDatas();

        if (title == null || types == null || datas == null) {
            return new JsonResult(-1, "参数异常");
        }

        if(types.length != datas.length){
            return new JsonResult(-1, "数据不对应");
        }


        //组装参数
        Double data = null;
        Double sum = 0.0;

        DecimalFormat df = new DecimalFormat(".00");

        List stringList = new ArrayList<>();
        String bfb = null;
        String typeParam = null;
        List> listMap = new ArrayList<>();

        for(int i = 0;i mapStr = new HashMap<>();
            mapStr.put("name", typeParam);
            mapStr.put("value", datas[i]);

            listMap.add(mapStr);

        }

        System.out.println(stringList);
        System.out.println(listMap);

        try {
            //组装参数
            HashMap pieDatas = new HashMap<>();
            pieDatas.put("title", title);
            //pieDatas.put("types", JSON.toJSonString(types));
            pieDatas.put("types", JSON.toJSonString(stringList));
            pieDatas.put("datas", JSON.toJSonString(listMap));
            String option = FreemarkerUtil.generateString("pieOption1.ftl", temPath, pieDatas);
            System.out.println("option = " + option);

            Map pieOption = new HashMap<>();
            pieOption.put("option", option);
            String htmlPie = FreemarkerUtil.generateString("pieOption.ftl", temPath, pieOption);
            System.out.println("htmlPie = " + htmlPie);

            //写入html
            String nowStr = FastDateFormat.getInstance("yyyyMMddHHmmss").format(new Date());
            String imageName = "pie"+nowStr;
            File htmlFile = new File(imgUrl+imageName+".html");
            if(!htmlFile.exists()){
                htmlFile.createNewFile();
            }
            byte bytes[] = new byte[1024];
            bytes = htmlPie.getBytes();
            int b = bytes.length;  //字节长度
            FileOutputStream fos = new FileOutputStream(htmlFile);
            fos.write(bytes, 0, b);
            fos.write(bytes);
            fos.close();

        } catch (Exception e) {
            logger.error("发生了异常," + e.getMessage());
            return new JsonResult(-1, "Fail");
        }
        return new JsonResult(1, "SUCCESS");
    }

    @ApiOperation("模板生成饼图")
    @RequestMapping(value = "/pieImg", method = RequestMethod.POST)
    public JsonResult createPieFtlImage(@RequestBody PieData pieData) {
        String title = pieData.getTitle();
        String[] types = pieData.getTypes();
        String[] datas = pieData.getDatas();

        if (title == null || types == null || datas == null) {
            return new JsonResult(-1, "参数异常");
        }

        if(types.length != datas.length){
            return new JsonResult(-1, "数据不对应");
        }


        //组装参数
        Double data = null;
        Double sum = 0.0;

        DecimalFormat df = new DecimalFormat(".00");

        List stringList = new ArrayList<>();
        String bfb = null;
        String typeParam = null;
        List> listMap = new ArrayList<>();

        for(int i = 0;i mapStr = new HashMap<>();
            mapStr.put("name", typeParam);
            mapStr.put("value", datas[i]);

            listMap.add(mapStr);

        }

        System.out.println(stringList);
        System.out.println(listMap);

        String oldFilePath = null;
        String newFilePath = null;

        try {
            //组装参数
            HashMap pieDatas = new HashMap<>();
            pieDatas.put("title", title);
            //pieDatas.put("types", JSON.toJSonString(types));
            pieDatas.put("types", JSON.toJSonString(stringList));
            pieDatas.put("datas", JSON.toJSonString(listMap));
            String option = FreemarkerUtil.generateString("pieOption1.ftl", temPath, pieDatas);
            System.out.println("option = " + option);

            long nowStr = Calendar.getInstance().getTimeInMillis();
            String imageName = "pie"+nowStr+ RandomUtils.getRandomString(4)+".png";

            Map opt = (Map) JSONObject.parse(option);
            PhantomJS js = new PhantomJS();
            js.setOpt(opt);
            js.setReqMethod("echarts");
            js.setFile(imgUrlPath+imageName);
            PhantomJSUtil.phantomJS(requestUrl, JSON.parseObject(JSON.toJSonString(js)));

            oldFilePath = imgUrlPath+imageName;
            newFilePath = imgUrlPath+"new"+imageName;

            logger.info("oldFilePath = " + oldFilePath);
            logger.info("newFilePath = " + newFilePath);

            String logoText = "霜花似雪";

            //添加水印
            ImageUtil.markImageByText(logoText, oldFilePath, newFilePath, -15, new Color(190,190,190), "png");

        } catch (Exception e) {
            logger.error("发生了异常," + e.getMessage());
            return new JsonResult(-1, "Fail");
        }
        return new JsonResult(1, "SUCCESS");
    }

}

三、插件环境配置说明

插件环境说明见第一篇文章

其他重要说明:

生成饼图的命令:

D:>cd D:softpackechartsphantomjs-2.1.1-windowsbin

D:softpackechartsphantomjs-2.1.1-windowsbin>phantomjs D:softpackechartsphantomjs-2.1.1-windowsbinecharts-util.js -s -p 6668
                             或者phantomjs D:softpackechartsphantomjs-2.1.1-windowsbinecharts-util-one.js -s -p 6668

关键文件说明:

echarts-util.js: 此文件用于生成状图、折线图、饼图, 只限于普通的option(option中没有js方法的)               

echarts-util-one.js: 此文件用于生成状图、折线图、饼图,生成的柱状图具有颜色渐变的效果,option中含有js方法,实例可以参考bar.txt文件    

echarts-util.js代码:

phantom.outputEncoding = "gbk";// 为防止输出中文时出现乱码,可设置输出编码格式,写在最顶部
var params = require('system');// 获取系统参数
    var server = require('webserver').create(); // 服务端
    var port = params.args[3];// 端口,与启动命令有关,不一定是3
    var listen = server.listen(port, function(request, response) {// 监听端口
    var args = serverGetArgs(request);// 得到网络请求参数
    args.response = response;
    methodDis(args);
});
var jslib = {
    jquery : phantom.libraryPath + '/lib/jquery-3.2.1.min.js',
    echarts : phantom.libraryPath + '/lib/echarts.min.js',
    china : phantom.libraryPath + '/lib/china.js',
};

function methodDis(args) {
    if (args.reqMethod == "table") {
    table(args);
    } else if (args.reqMethod == "echarts") {
    echarts(args);
    }
    if (args.exit == "true") {
    writeResponse(args.response, {
    error_no : 0
    });
    phantom.exit();
    }
}
function table(args) {
    var page = require('webpage').create();// 打开页面
    // 设置分辨率
    page.viewportSize = {
    width : 1000,
    height : 1200
    };
    // 打开页面
    page.open(args.url || 'http://127.0.0.1:8080/hello', function(status) {
    if (status == "fail") {
    writeResponse(args.response, {
    error_no : -1
    });
    return;
    }
    page.injectJs(jslib.jquery);
    var tableheight = page.evaluate(function() {
    return $('body').height() + 20;
    });
    // 定义剪切范围
    page.clipRect = {
    top : 0,
    left : 0,
    width : 1000,
    height : tableheight
    };
    // var base64 = 'data:image/png;base64,' + page.renderbase64('png');
    page.render(args.file);// 将整个page保存为文件,可以是png,jpg, gif,pdf
    page.close();
    writeResponse(args.response, {
    error_no : 0
    });
    });
    page.onError = function(msg, trace) {
    writeResponse(args.response, {
    error_no : -1,
    error_info : trace
    });
    };
}
function echarts(args) {
    var page = require('webpage').create(); // 客户端
    page.open("about:blank", function(status) {// 空白页
    page.injectJs(jslib.jquery);
    page.injectJs(jslib.echarts);
    page.injectJs(jslib.china);
    var pageBody = page.evaluate(function(args) {
    // 动态加载js,获取options数据
    $('






(2)生成饼图,图片格式,效果图如下

不带水印:

带水印:

更多关于Echarts图表的使用请读者自行研究,如果遇到问题,欢迎与我交流。需要代码的话,也可以找我!

喜欢的话,请点个赞,感谢你的支持!


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/234164.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号