簡單分享一下,后台使用nodejs結合highcharts、phantomjs生成報表圖片的方法。這主要應用在日報郵件。
主要參考以下資料:
- http://www.highcharts.com/component/content/article/2-news/52-serverside-generated-charts#phantom_usage
- https://bitbucket.org/ariya/phantomjs/downloads
- https://github.com/highslide-software/highcharts.com/tree/master/exporting-server/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一下,刷新一下系統的字體緩存。