java服务端生成echarts图片,并将图片保存至服务器
- echarts
- 时间:2023-05-23 12:44
- 2610人已阅读
🔔🔔好消息!好消息!🔔🔔
有需要的朋友👉:微信号
前言:
最近公司有这样一个需求,对公司的统计数据使用图表进行展示,并且支持word导出,word文档中需要包含
思路分析:
首先看到图表,第一步就想到echarts或highcharts,但是我们一般使用前面2个图表软件默认需要使用html,运行在浏览器中,如果我们需要将统计图表通过word 导出,首先需要将图片生成并写入到word中,那么我们现在的第一步就变成了,使用java生成echarts图表并保存。既然echart需要运行在浏览器端,而且我们服务端又没有浏览器,那么我们可以通过使用无界面的浏览器来解决问题,既然总体思路确定了,那么我们就想到了无界面浏览器phantomjs.
phantomjs是什么
PhantomJS是一个基于webkit的JavaScript API。它使用QtWebKit作为它核心浏览器的功能,使用webkit来编译解释执行JavaScript代码。任何你可以在基于webkit浏览器做的事情,它都能做到。它不仅是个隐形的浏览器,提供了诸如CSS选择器、支持Web标准、DOM操作、JSON、HTML5、Canvas、SVG等,同时也提供了处理文件I/O的操作,从而使你可以向操作系统读写文件等。PhantomJS的用处可谓非常广泛,诸如网络监测、网页截屏、无需浏览器的 Web 测试、页面访问自动化等。
PhantomJS官方地址:http://phantomjs.org/。
PhantomJS官方API:http://phantomjs.org/api/。
PhantomJS官方示例:http://phantomjs.org/examples/。
PhantomJS GitHub:https://github.com/ariya/phantomjs/
1 phantomjs的安装
我们从phantomjs官网下载后,解压放入不要放入带有中文的目录中(中国程序员永远的痛),
并加入到环境变量path中,方便程序调用。
配置环境变量:
2 下载相关脚本
2.1 echarts.min.js
这个脚本可以从echarts官网下载
https://echarts.apache.org/zh/index.html
2.2 jquery.js
这个脚本可以通过jquery官网下载
https://jquery.com/
2.3 echarts-convert.js
此脚本很重要,内容如下:负责将echarts的抓换,内容如下:
(function() { var system = require('system'); var fs = require('fs'); var config = { // define the location of js files JQUERY : 'jquery-1.9.1.min.js', ECHARTS3 : 'echarts/echarts-all4.js', //ECHARTS3 : 'echarts.min_4.js', // default container width and height DEFAULT_WIDTH : '1000', DEFAULT_HEIGHT : '600' }, parseParams, render; 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; } } }; var base64Pad = '='; var toBinaryTable = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 ]; base64ToString = function(data) { //console.log("data = "+data); var result = ''; var leftbits = 0; // number of bits decoded, but yet to be appended var leftdata = 0; // bits decoded, but yet to be appended // Convert one by one. for (var i = 0; i < data.length; i++) { var c = toBinaryTable[data.charCodeAt(i) & 0x7f]; //console.log("i = "+c); var padding = (data.charCodeAt(i) == base64Pad.charCodeAt(0)); // Skip illegal characters and whitespace if (c == -1) continue; // Collect data into leftdata, update bitcount leftdata = (leftdata << 6) | c; leftbits += 6; // If we have 8 or more bits, append 8 bits to the result if (leftbits >= 8) { leftbits -= 8; // Append if not padding. if (!padding) result += String.fromCharCode((leftdata >> leftbits) & 0xff); leftdata &= (1 << leftbits) - 1; } } console.log(result); // if (leftbits) // throw Components.Exception('Corrupted base64 string'); return result; }; getParams = 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') { key = 'path'; try { var vals = system.args[i + 1]; console.log("vals = "+vals); map[key] = vals; } catch (e) { console.log('Error: cannot find file, ' + system.args[i + 1]); phantom.exit(); } } else { map[key]= system.args[i + 1]; } } } return map; }; parseParams = function() { var map = {}; var data= getParams(); var dataPath=data.path; console.log("+++++dataPath++++++++") console.log("dataPath-----"+dataPath) var fs = require('fs'); var str = fs.read(dataPath); map['options']=str; map['outfile']=data.outfile; return map; }; render = function(params) { var page = require('webpage').create(), createChart; page.onConsoleMessage = function(msg) { console.log(msg); }; page.onAlert = function(msg) { console.log(msg); }; createChart = function(inputOption, width, height) { 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(document.getElementById("container")); myChart.setOption(options); // load images loadImages(); }; // parse the params page.open("about:blank", function(status) { // inject the dependency js page.injectJs(config.JQUERY); page.injectJs(config.ECHARTS3); var width = pick(params.width, config.DEFAULT_WIDTH); var height = pick(params.height, config.DEFAULT_HEIGHT); // create the chart page.evaluate(createChart, params.options, width, height); // 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); }());
注意(大写加粗,这3个文件需要放在同一目录(也可以改路径)):
3 代码实现
package com; import java.io.*; import java.util.UUID; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2018</p> * <p>Company: http://www.ubisys.com.cn/</p> * * @Auther: cw * @Date: 2020/1/21 17:35 */ public class T { private static final String JSpath = "D:\\phantomjs-2.1.1-windows\\echarts-convert\\echarts-convert.js"; public static void main(String[] args) { String options = "{\"title\":{\"text\":\"销售图\",\"subtext\":\"销售统计\",\"x\":\"CENTER\"},\"toolbox\": {\"feature\": {\"saveAsImage\": {\"show\": true,}}},\"tooltip\": {\"show\": true},\"legend\": {\"data\":[\"直接访问\",\"邮件营销\",\"联盟广告\",\"视频广告\",\"搜索引擎\"]}, \"series\":[{\"name\":\"访问来源\",\"type\":\"pie\",\"radius\": '55%',\"center\": ['50%', '60%'],\"data\":[{\"value\":335, \"name\":\"直接访问\"},{\"value\":310, \"name\":\"邮件营销\"},{\"value\":234, \"name\":\"联盟广告\"},{\"value\":135, \"name\":\"视频广告\"},{\"value\":1548, \"name\":\"搜索引擎\"}]}]}"; String picPath = generateEChart(options); } /* * 主程序 */ public static String generateEChart(String options) { String dataPath = writeFile(options); String fileName = UUID.randomUUID().toString() + ".png"; String path = "D:/" + 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) { } input.close(); } catch (IOException e) { e.printStackTrace(); } finally { } return path; } /* * * options生成文件存储 */ public static String writeFile(String options) { String dataPath = "D:\\" + UUID.randomUUID().toString().substring(0, 8) + ".json"; try { /* option写入文本文件 用于执行命令*/ 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(options); out.flush(); // 把缓存区内容压入文件 out.close(); // 最后关闭文件 } catch (IOException e) { e.printStackTrace(); } return dataPath; } }
后语:示例中echarts的options,是使用写死的json串,现实中我们的options可能从数据库动态生成的,在此给大家推荐一个使用java生成echarts的开源库,如果有需要请大家自行参阅。
码云地址:https://gitee.com/free/ECharts
文中的源码和相关软件我会传到github,上,如果大家需要欢迎下载。(github又抽风连不上去了)
git@github.com:shao139772/genertorEchartsPhoto.git