簡單分享一下,後臺使用nodejs結合highcharts、phantomjs生成報表圖片的方法。這主要應用在日報郵件。node
關鍵是使用phantomjs模擬瀏覽器環境,這個是一個綠色的程序,無需安裝。win7和64bit linux上親測ok。linux
phantomjs是linux版,phantomjs.exe就是windows版。git
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
爲了不空格引號什麼的問題,這裏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); });
到/usr/share/fonts/裏邊補回相應的字體文件便可(能夠直接把windows的複製過去)。
複製過去後,須要fc -cache -fv一下,刷新一下系統的字體緩存。windows