我一直致力于整合PhantomJS以帮助在我的服务器上创建图像,然后可以在HTML模板中使用该图像并使用mPDF将其保存为PDF。我正在使用Yii2,并设法使用一些伪脚本生成并保存图像。但我不确定如何为动态数据做到这一点。与PHP循环一起使用PhantomJs
目前我有这种非常粗略的实现:
shell.php
if(exec('C:\xampp\htdocs\phantomjs\bin\phantomjs C:\xampp\htdocs\ reporting\views\site\test.php')){
echo 'yes';
} else echo 'no';
我test.php
文件基本上是用PHP扩展的JavaScript文件。
test.php的
var system = require('system');
var page = require('webpage').create();
var fs = require('fs');
// load JS libraries
if(page.injectJs('C:\\xampp\\htdocs\\phantomjs\\jquery.1.9.1.min.js')){
console.log('Jquery used');
}
if(page.injectJs('C:\\xampp\\htdocs\\phantomjs\\highcharts.js')){
console.log('highcharts used');
}
if(page.injectJs('C:\\xampp\\htdocs\\phantomjs\\highcharts-convert.js')){
console.log('highcharts-convert used');
}
var args = {
width: 600,
height: 500
};
var svg = page.evaluate(function(opt){
$('body').prepend('<div id="container"></div>');
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
width: opt.width,
height: opt.height
},
exporting: {
enabled: false
},
title: {
text: 'Combination chart'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Bananas', 'Plums']
},
yAxis: {
title: {
text: 'Y-values'
}
},
labels: {
items: [{
html: 'Total fruit consumption',
style: {
left: '40px',
top: '8px',
color: 'black'
}
}]
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
},
series: {
enableMouseTracking: false,
shadow: false,
animation: false
}
},
series: [{
type: 'column',
name: 'Andrii',
data: [3, 2, 1, 3, 4]
}, {
type: 'column',
name: 'Fabian',
data: [2, 3, 5, 7, 6]
}, {
type: 'column',
name: 'Joan',
data: [4, 3, 3, 9, 0]
}, {
type: 'spline',
name: 'Average',
data: [3, 2.67, 3, 6.33, 3.33],
marker: {
lineWidth: 2,
lineColor: 'white'
}
}, {
type: 'pie',
name: 'Total consumption',
data: [{
name: 'Andrii',
y: 13,
color: '#4572A7'
}, {
name: 'Fabian',
y: 23,
color: '#AA4643'
}, {
name: 'Joan',
y: 19,
color: '#89A54E'
}],
center: [100, 80],
size: 100,
showInLegend: false,
dataLabels: {
enabled: false
}
}]
});
return chart.getSVG();
}, args);
// Saving SVG to a file
fs.write("test.svg", svg);
// Saving diagram as PDF
//setTimeout(function(){
page.render('test.png', {format: 'png', quality: '100'});
phantom.exit();
这产生并保存png
文件(虽然尺寸未设定)。
我已经认识到,但我不能在这个文件中使用PHP。 exec()
调用永远不会返回,我只是最终取消它。我假设这是因为PhantomJS在遇到<?php
标签时不知道该怎么做。
什么是尝试使用PHP来生成和保存图表循环数据库数据的最佳方式?
你有没有尝试过像返回1;而不是phantom.exit(); –
@thomasw_lrd我没有没有。它在幻影文档中说始终使用exit()。 – Jonnny