关于java后台生成echarts图片问题总结

关于后台生成图片,首先考虑的就是如何加载js,在无浏览器模式下。抱着这个疑问百度结果

----phantomjs-----

phantomjs可以在无浏览器模式下加载js,且可以通过java代码运行cmd命令执行

了解到phantomjs之后,就是安装且借助echartsconvert来在无浏览器模式下生成图片附代码:

import com.joyintech.tams.invest.risk.stresstestmanage.marketriskstresstestview.dto.ReportGlobalConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.*;


@Service
public class EchartsService {
    private Logger logger = LoggerFactory.getLogger(EchartsService.class);

    /**
     * 创建echarts图表文件(图片)
     *
     * @param options 图表数据
     * @param echartsFilePathName 图表文件全路径和名称
     * @return 图表文件
     */
    public File buildEChartFile(String options, String echartsFilePathName) {
        // 生成echarts图片工具存放路径
        //String echartsPicExportPath  = CacheUtil.getSysParam(ReportGlobalConstant.POI_ECHARTS_PIC_EXPORT_PATH);
        String echartsPicExportPath="E:\\workSpace\\phantomjs-2.1.1-windows\\bin\\";
        if (StringUtils.isEmpty(echartsPicExportPath)) {
            logger.error("未配置poi导出报表之生成echarts图片工具存放路径:" + ReportGlobalConstant.POI_ECHARTS_PIC_EXPORT_PATH);
            return null;
        }

        String jsonData = buildEChartOptionsFile(options,echartsFilePathName);
        String echartsPicture = echartsFilePathName + ".png";

        File file = new File(echartsPicture); // 文件路径
        if (!file.exists()) {
            File dir = new File(file.getParent());
            dir.mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 创建phantomjs命令(必须用全路径)
        String phantomjsCmd = echartsPicExportPath + "phantomjs "
                + echartsPicExportPath+"echartsconvert\\"  + "echarts-convert.js" + " -infile " + jsonData + " -outfile " + echartsPicture;
        Process process = null;
        logger.debug("即将执行phantomjs命令:" + phantomjsCmd);
        try {
            // 执行phantomjs命令,生成echarts图片
            process = Runtime.getRuntime().exec(phantomjsCmd);
        } catch (IOException e) {
            logger.error("执行的phantomjs命令:" + phantomjsCmd);
            logger.error("执行phantomjs命令异常,请检查phantomjs工具是否安装成功和phantomjs命令语句!");
            e.printStackTrace();
        } finally {
            if (process != null) {
                try {
                    process.waitFor();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                process.destroy();
            }
        }
        // 删除临时json文件
        File jsondata = new File(jsonData);
        if (jsondata != null && jsondata.exists())
            jsondata.delete();
        logger.debug("已创建图表:" + file.getPath());
        return file;
    }

    /**
     * 生成options存储json文件
     * @param echartsFileTmp
     * @param option 图表数据
     * @return 文件
     */
    private String buildEChartOptionsFile(String option, String echartsFileTmp) {
        // Echarts临时json文件
        String dataPath = echartsFileTmp + ".json";
        try {
            File writename = new File(dataPath);
            if (!writename.exists()) {
                File dir = new File(writename.getParent());
                dir.mkdirs();
                writename.createNewFile();
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(option);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataPath;
    }
}

注意:这边安装phantomjs时候和echartsconver有一个路径问题,同时还有在网上找的echartsconver有很多不对且有些要积分贴一下我安装时候路径,和echarts-conver.js需要者自取

(function () {
var system = require('system');
var fs = require('fs');
var config = {
    // define the location of js files
    //这样写要求这三个js在同一个文件夹下
    JQUERY: 'jquery-3.2.1.min.js',
    //ESL: 'esl.js',
    ECHARTS: 'echarts.min.js',
    // default container width and height
    DEFAULT_WIDTH: '400',
    DEFAULT_HEIGHT: '600'
}, parseParams, render, pick, usage;

usage = function () {
    console.log("\nUsage: phantomjs echarts-convert.js -options options -outfile filename -width width -height height"
        + "OR"
        + "Usage: phantomjs echarts-convert.js -infile URL -outfile filename -width width -height height\n");
};

pick = function () {
    var args = arguments, i, arg, length = args.length;
    for (i = 0; i < length; i += 1) {
        arg = args[i];
        if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') {
            return arg;
        }
    }
};

parseParams = function () {
    var map = {}, i, key;
    if (system.args.length < 2) {
        usage();
        phantom.exit();
    }
    for (i = 0; i < system.args.length; i += 1) {
        if (system.args[i].charAt(0) === '-') {
            key = system.args[i].substr(1, i.length);
            if (key === 'infile') {
                // get string from file
                // force translate the key from infile to options.
                key = 'options';
                try {
                    map[key] = fs.read(system.args[i + 1]).replace(/^\s+/, '');
                } catch (e) {
                    console.log('Error: cannot find file, ' + system.args[i + 1]);
                    phantom.exit();
                }
            } else {
                map[key] = system.args[i + 1].replace(/^\s+/, '');
            }
        }
    }
    return map;
};

render = function (params) {
    var page = require('webpage').create(), createChart;

    var bodyMale = config.SVG_MALE;
    page.onConsoleMessage = function (msg) {
        console.log(msg);
    };

    page.onAlert = function (msg) {
        console.log(msg);
    };

    createChart = function (inputOption, width, height,config) {
        var counter = 0;
        function decrementImgCounter() {
            counter -= 1;
            if (counter < 1) {
                console.log(messages.imagesLoaded);
            }
        }

        function loadScript(varStr, codeStr) {
            var script = $('<script>').attr('type', 'text/javascript');
            script.html('var ' + varStr + ' = ' + codeStr);
            document.getElementsByTagName("head")[0].appendChild(script[0]);
            if (window[varStr] !== undefined) {
                console.log('Echarts.' + varStr + ' has been parsed');
            }
        }

        function loadImages() {
            var images = $('image'), i, img;
            if (images.length > 0) {
                counter = images.length;
                for (i = 0; i < images.length; i += 1) {
                    img = new Image();
                    img.onload = img.onerror = decrementImgCounter;
                    img.src = images[i].getAttribute('href');
                }
            } else {
                console.log('The images have been loaded');
            }
        }
        // load opitons
        if (inputOption != 'undefined') {
            // parse the options
            loadScript('options', inputOption);
            // disable the animation
            options.animation = false;
        }

        // we render the image, so we need set background to white.
        $(document.body).css('backgroundColor', 'white');
        var container = $("<div>").appendTo(document.body);
        container.attr('id', 'container');
        container.css({
            width: width,
            height: height
        });
        // render the chart
        var myChart = echarts.init(container[0]);
        myChart.setOption(options);
        // load images
        loadImages();
        return myChart.getDataURL();
    };

    // parse the params
    page.open("about:blank", function (status) {
        // inject the dependency js
        page.injectJs(config.ESL);
        page.injectJs(config.JQUERY);
        page.injectJs(config.ECHARTS);


        var width = pick(params.width, config.DEFAULT_WIDTH);
        var height = pick(params.height, config.DEFAULT_HEIGHT);

        // create the chart
        var base64 = page.evaluate(createChart, params.options, width, height,config);
        fs.write("base64.txt",base64);
        // define the clip-rectangle
        page.clipRect = {
            top: 0,
            left: 0,
            width: width,

            height: height
        };
        // render the image
        page.render(params.outfile);
        console.log('render complete:' + params.outfile);
        // exit
        phantom.exit();
    });
};
// get the args
var params = parseParams();

// validate the params
if (params.options === undefined || params.options.length === 0) {
    console.log("ERROR: No options or infile found.");
    usage();
    phantom.exit();
}
// set the default out file
if (params.outfile === undefined) {
    var tmpDir = fs.workingDirectory + '/tmp';
    // exists tmpDir and is it writable?
    if (!fs.exists(tmpDir)) {
        try {
            fs.makeDirectory(tmpDir);
        } catch (e) {
            console.log('ERROR: Cannot make tmp directory');
        }
    }
    params.outfile = tmpDir + "/" + new Date().getTime() + ".png";
}

// render the image
render(params);
}());

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值