使用phantomjs生成echarts图片

1. 安装phantomjs依赖

# 下载依赖
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
或者
wget https://npm.taobao.org/mirrors/phantomjs/phantomjs-2.1.1-linux-x86_64.tar.bz2

# 解压安装
yum install bzip2
#解压并把解压出来的文件移到/usr/local/src目录下
tar -jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2
mv ./phantomjs-2.1.1-linux-x86_64 /usr/local/src/phantomjs

# 安装依赖
yum -y install fontconfig

# 配置环境变量或创建软链接
vim /etc/profile
#末尾加入
export PATH=$PATH:/usr/local/src/phantomjs/bin
#刷新配置文件
source /etc/profile

--或者直接创建软链接--
ln -s /usr/local/src/phantomjs/bin/phantomjs /usr/bin

# 通过版本号显示说明phantomjs安装成功了
phantomjs -v
或
phantomjs --version

2. 生成图片

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

/**
 * @Auther: cxh
 * @Date: 2023/5/26
 */
@Slf4j
public class EchartsUtils {




    /**
     * 导出echarts 图片,需要安装phantomjs
     *
     * @param options  echarts 配置的json
     * @param fileName 导出的图片名,不带后缀
     * @return 图片文件名
     */
    public static String generateEChart(String options, String path, String fileName) {
        String dataPath = writeFile(options, path, fileName);
        StringBuilder builder = new StringBuilder();
        BufferedReader input = null;
        String line = "";
        try {
            File file = new File(path);     //文件路径
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            // 创建文件
            String cmd = "phantomjs " + path + "js/echarts-convert.js" + " -infile " + dataPath + " -width " + 1100 + " -height " + 700;//生成命令行
            Process process = Runtime.getRuntime().exec(cmd);
            input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = input.readLine()) != null) {
                if (line.startsWith("data:image/png;base64,")) {
                    builder.append(line);
                    break;
                }
            }
        } catch (IOException e) {
            log.error("Failed to create Echarts  message:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            IoUtil.close(input);
        }
        return convertBase64ForPng(builder.toString(), path + "images/", fileName);
    }

    /**
     * 写入数据
     *
     * @param options  写入文件的数据
     * @param fileName 文件名,不带后缀
     * @return 文件名
     */
    public static String writeFile(String options, String path, String fileName) {
        path += "json/";
        /* option写入文本文件 用于执行命令*/
        BufferedWriter out = null;
        String fullFileName = path + fileName + ".json";
        try {
            File writeName = new File(fullFileName);
            if (!writeName.exists()) {
                File dir = new File(writeName.getParent());
                dir.mkdirs();
                writeName.createNewFile(); //
            }
            out = new BufferedWriter(new FileWriter(writeName));
            out.write(options);
            out.flush(); // 把缓存区内容压入文件
        } catch (IOException e) {
            log.error("Failed to write json file message:{}", e.getMessage());
            throw new RuntimeException(e);
        } finally {
            IoUtil.close(out);
        }
        return fullFileName;
    }

    /**
     * Base64 转 Png
     *
     * @param base        数据源
     * @param outFileName 输出的文件名称
     * @param outFilePath 输出的文件路径
     * @return
     */
    private static String convertBase64ForPng(String base, String outFilePath, String outFileName) {
        if (StrUtil.isBlank(base)) {
            return null;
        }
        Base64.Decoder decoder = Base64.getDecoder();
        String baseValue = base.replaceAll(" ", "+");//前台在用Ajax传base64值的时候会把base64中的+换成空格,所以需要替换回来。
        byte[] b = decoder.decode(baseValue.replace("data:image/png;base64,", ""));//去除base64中无用的部分
        File file1 = new File(outFilePath);
        //判断文件路径下的文件夹是否存在,不存在则创建
        if (!file1.exists() && !file1.isDirectory()) {
            file1.mkdirs();
        }
        OutputStream out = null;
        String filePath = outFilePath + outFileName + ".png";
        try {
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            File file = new File(outFilePath + outFileName + ".png");
            // 如果要返回file文件这边return就可以了,存到临时文件中
            out = Files.newOutputStream(Paths.get(file.getPath()));
            out.write(b);
            out.flush();
            return filePath;
        } catch (IOException e) {
            log.error("Failed to convert Base64 to Png  message:{}", e.getMessage());
            throw new RuntimeException(e);
        } finally {
            IoUtil.close(out);
        }
    }
    
}

3. 依赖js

生成echarts图片需要依赖3个js文件
echarts.min.js jquery-3.5.1.min.js echarts-convert.js
其中 echarts.min.js jquery-3.5.1.min.js 可以直接在对应官网下载

echarts-convert.js 如下

(function () {
    var system = require('system');
    var fs = require('fs');
    var config = {
        // define the location of js files
        JQUERY: 'jquery-3.5.1.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].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.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);
            console.log(base64);
            // define the clip-rectangle
            console.log('\nbase64 complete');
            // 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();
    }

// render the image
    render(params);
}());
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容