php mpdf导出echarts图表实现流程
遇到的问题
php file_get_contents 无法执行js,导致图表无法生成
模板HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div>
<img src="" id="chartsimg" width="800px" height="500px">
</div>
<div style="width: 300px;height:300px;display: none" id="main"></div>
</body>
</html>
<script type="text/javascript" src="/static/plugins/echarts/echarts.min.js"></script>
<script type="text/javascript">
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line',
animationDuration:0,
}
]
};
option && myChart.setOption(option);
var chartsImg = document.getElementById('chartsimg');
var info = myChart.getConnectedDataURL();
chartsImg.src = info;
</script>
安装依赖
安装mpdf
composer require mpdf/mpdf
安装querylist
composer require jaeger/querylist
安装phantomjs
composer require jaeger/querylist-phantomjs //PHP版本必须 >=7.0
安装phantomjs
PhantomJS是一个基于webkit的JavaScript API。它使用QtWebKit作为它核心浏览器的功能,使用webkit来编译解释执行JavaScript代码。任何你可以在基于webkit浏览器做的事情,它都能做到。它不仅是个隐形的浏览器,提供了诸如CSS选择器、支持Web标准、DOM操作、JSON、HTML5、Canvas、SVG等,同时也提供了处理文件I/O的操作,从而使你可以向操作系统读写文件等。PhantomJS的用处可谓非常广泛,诸如网络监测、网页截屏、无需浏览器的 Web 测试、页面访问自动化等。
作者:i_1312
链接:www.jianshu.com/p/f87f4894f39d
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
MAC系统安装时可能会遇到,无法验证应用完整性
选择安全与隐私,选择仍然信任
代码参考
<?php
namespace app\device\controller;
use think\Controller;
use think\Request;
use QL\QueryList;
use QL\Ext\PhantomJs;
class QueryListBrowser extends Controller
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
$title = '数据报告';
$pdf = new \Mpdf\Mpdf();
// 设置打印模式
$pdf->SetAuthor('迷途');
$pdf->SetTitle($title);
//$pdf->SetHTMLHeader('<div style="text-align: left;"><img src="/baseImg/pdf_header.png" width="200px"></div>');
$pdf->SetSubject('温湿度数据');
$pdf->SetKeywords('温度,湿度');
// 设置左、上、右的间距
//$pdf->SetMargins('1', '1', '1');
// 设置是否自动分页 距离底部多少距离时分页
//$pdf->SetAutoPageBreak(TRUE, '15');
$pdf->setAutoBottomMargin = 'stretch';
$pdf->setAutoTopMargin = 'stretch';
//开启字段文字和样式
$pdf->autoScriptToLang = true;
$pdf->autoLangToFont = true;
//$pdf->AddPage();
// 设置字体
$pdf->SetFont('stsongstdlight', '', 8, '', true);
$ql = QueryList::getInstance();
// 安装时需要设置PhantomJS二进制文件路径
$ql->use(PhantomJs::class, '/opt/homebrew/bin/phantomjs');
//or Custom function name
$ql->use(PhantomJs::class, '/opt/homebrew/bin/phantomjs', 'browser');
$ql->use(PhantomJs::class, '/opt/homebrew/bin/phantomjs');
$content = $ql->browser('http://127.0.0.1:9035/index.php/device/pdf/template?id=3')->getHtml();
$pdf->WriteHTML($content);
// $pdf->Image('test.pdf', 0, 0, 210, 297, 'jpg', '', true, false);
$pdf->Output('test.pdf');
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接