欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

poi报表开发1-PhantomJS工具安装

程序员文章站 2022-04-30 20:36:02
...

1.概要

PhantomJS是一个*面的,可脚本编程的WebKit浏览器引擎,可以在后台模拟浏览器的工具。可选装Linux版本和Windows版本。

主要用来在后台生成echarts图表的图片,供报表使用。

2.Linux下安装

https://phantomjs.org/download.html,选择版本Linux 64-bit,获得压缩包phantomjs-2.1.1-linux-x86_64.tar.bz2。

解压命令:

tar xjf phantomjs-2.1.1-linux-x86_64.tar.bz2

 poi报表开发1-PhantomJS工具安装

修改解压的目录名为phantomjs(有点号后续会有报错,故去掉):

poi报表开发1-PhantomJS工具安装

设置环境变量,并使得配置文件生效,命令:

export PATH=${PATH}:/home/tams/software/phantomjs/bin
source /etc/profile

poi报表开发1-PhantomJS工具安装

测试执行例子中的js,命令:

phantomjs /home/tams/software/phantomjs/examples/hello.js

poi报表开发1-PhantomJS工具安装

输出“Hello, world!”表示安装成功。

 

3.Windows下安装

https://phantomjs.org/download.html,选择版本Windows,获得压缩包phantomjs-2.1.1-windows.zip。解压:

poi报表开发1-PhantomJS工具安装

添加环境变量:

poi报表开发1-PhantomJS工具安装

测试命令:

phantomjs D:\it\work\software\phantomjs-2.1.1-windows\examples\hello.js

poi报表开发1-PhantomJS工具安装

输出“Hello, world!”表示安装成功。

4.添加echarts-js文件

三个js文件echarts.min.js、jquery-3.2.1.min.js和echarts-convert.js必须都放在同一目录下。这里我暂且都放在phantomjs的bin目录下。

 

poi报表开发1-PhantomJS工具安装

echarts.min.js、jquery-3.2.1.min.js可从官网下载。echarts-convert.js为开发的js,且生成图片的高宽在其中配置:

poi报表开发1-PhantomJS工具安装

echarts-convert.js源码如下(参考文章:java 实现后台生成echarts 图片(PhantomJS浏览器引擎(window系统与linux系统)))

(function () {
var system = require('system');
var fs = require('fs');
var config = {
    // define the location of js files
    JQUERY: 'jquery-3.2.1.min.js',
    //ESL: 'esl.js',
    ECHARTS: 'echarts.min.js',
    // default container width and height
    DEFAULT_WIDTH: '700',
    DEFAULT_HEIGHT: '300'
}, 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);
}());

【END】

 

 

相关标签: 报表