接着我上一篇文章去写,Java EasyWord导出word文档。上一篇文章中图片是固定的(图片路径固定),实际中可能需要根据数据做一些统计图出来,并和文档一起导出(只要我们知道生成的图片路径就可以动态的导出了)。就是相当于,把前端Echarts生成的图片直接在后端生成。
准备工作
- 下载并解压PhantomJs,这是官网地址 https://phantomjs.org/download.html,有两个包,Windows和Linux。我展示使用的版本是phantomjs-2.1.1。
- jquery-xxx.min.js,任意版本都可以,我使用的是jquery-3.6.0.min.js
- echarts.min.js。下载地址:https://echarts.baidu.com/download.html
- echarts-convert.js
(function () { var system = require('system'); var fs = require('fs'); var config = { // define the location of js files JQUERY: 'jquery-3.6.0.min.js', ECHARTS: 'echarts.min.js', // default container width and height DEFAULT_WIDTH: '600', DEFAULT_HEIGHT: '700' }, parseParams, render, pick, usage; // 提示:命令格式 usage = function () { console.log("\n" + "Usage: phantomjs echarts-convert.js -infile URL -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; 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("The images load error"); } } 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].getAt