使用phantomjs生成echarts图片

2023年 7月 25日 55.2k 0

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  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 = $("").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);
}());

相关文章

服务器端口转发,带你了解服务器端口转发
服务器开放端口,服务器开放端口的步骤
产品推荐:7月受欢迎AI容器镜像来了,有Qwen系列大模型镜像
如何使用 WinGet 下载 Microsoft Store 应用
百度搜索:蓝易云 – 熟悉ubuntu apt-get命令详解
百度搜索:蓝易云 – 域名解析成功但ping不通解决方案

发布评论