nodejs搭配phantomjs highcharts後臺生成圖表

簡單分享一下,後臺使用nodejs結合highcharts、phantomjs生成報表圖片的方法。這主要應用在日報郵件。node

主要參考如下資料:

關鍵是使用phantomjs模擬瀏覽器環境,這個是一個綠色的程序,無需安裝。win7和64bit linux上親測ok。linux

而後,大概咱們須要部署一個相似這樣的環境(代碼地址 https://github.com/kenkozheng/HTML5_research/tree/master/NodeJS-Highcharts ):


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

那麼在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的同窗均可以忽略我說的廢話了。github

固然,爲了更方便使用,稍稍修改一下highcharts-convert.js,增長一個input參數,直接傳入數據,而不須要讀文件。

爲了不空格引號什麼的問題,這裏encode一下。json

複製代碼
          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一下,刷新一下系統的字體緩存。windows

kenkofox@qq.com https://github.com/kenkozheng 歡迎投簡歷給我,力推騰訊工做機會
相關文章
相關標籤/搜索