简单分享一下,后台使用nodejs结合highcharts、phantomjs生成报表图片的方法。这主要应用在日报邮件。
关键是使用phantomjs模拟浏览器环境,这个是一个绿色的程序,无需安装。win7和64bit linux上亲测ok。
phantomjs是linux版,phantomjs.exe就是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的同学都可以忽略我说的废话了。
为了避免空格引号什么的问题,这里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);
});
到/usr/share/fonts/里边补回相应的字体文件即可(可以直接把windows的复制过去)。 复制过去后,需要fc -cache -fv一下,刷新一下系统的字体缓存。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有