nodejs搭配phantomjs highcharts后台生成图表

简单分享一下,后台使用nodejs结合highcharts、phantomjs生成报表图片的方法。这主要应用在日报邮件。

主要参考以下资料:

关键是使用phantomjs模拟浏览器环境,这个是一个绿色的程序,无需安装。win7和64bit linux上亲测ok。

然后,大概我们需要部署一个类似这样的环境(代码地址 https://github.com/kenkozheng/HTML5_research/tree/master/NodeJS-Highcharts ):


phantomjs是linux版,phantomjs.exe就是windows版。

那么在windows下,我们可以写:

var process = require("child_process");
process.exec('phantomjs.exe ./highcharts/highcharts-convert.js -infile options1.json -outfile chart1.png -constr Chart', {cwd: './'}, function (err, stdout, stderr) {
    console.log(err, stdout, stderr);
});

options1.json就是我们配置的数据。
需要注意的是,到了linux下,需要改为exec(‘./phantomjs …. 。 当然,熟悉linux的同学都可以忽略我说的废话了。

当然,为了更方便使用,稍稍修改一下highcharts-convert.js,增加一个input参数,直接传入数据,而不需要读文件。

为了避免空格引号什么的问题,这里encode一下。

          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 === 'callback' || key === 'dataoptions' || key === 'globaloptions' || key === 'customcode') {
                         // get string from file
                         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 if(key === 'input'){
                    map['infile'] = decodeURIComponent(system.args[i + 1]);     //这里是修改的部分
                } else {
                    map[key] = system.args[i + 1];
                }
               }
          }

 

修改后就可以这么玩了:

var process = require("child_process");
var data = {
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0,
            135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]
};
process.exec('phantomjs.exe ./highcharts/highcharts-convert.js -input ' + encodeURIComponent(JSON.stringify(data)) + ' -outfile chart1.png -constr Chart', {cwd: './'}, function (err, stdout, stderr) {
    console.log(err, stdout, stderr);
});

 

另外,在linux下,还可能遇到生成图片后,字体无法显示的问题。


到/usr/share/fonts/里边补回相应的字体文件即可(可以直接把windows的复制过去)。
复制过去后,需要fc -cache -fv一下,刷新一下系统的字体缓存。

posted @ 2015-11-12 17:56  拂晓风起-Kenko  阅读(7139)  评论(0编辑  收藏  举报