yii2里面带有生成PDF的插件,我们通过安装就可以使用。
参考地址:(https://github.com/mpdf/mpdf)
https://mpdf.github.io/
通过composer 安装mpdf插件:
命令:$ composer require mpdf/mpdf
或者是:php composer.phar require mpdf/mpdf
"dev-master"
安装好插件后就可以生成PDF。
在生成PDF时使用中文总会出现中文乱码的问题,可以如下解决:
$mpdf = new mPDF('zh-CN');
$mpdf->useAdobeCJK
= true;
通过上面的地址将mpdf的插件下载到本地,里面有例子,可以参照例子来实现自己需要的功能。
我生成PDF文件时主要是通过HTML的方式。
下面举一个例子:
$mpdf = new
mPDF('zh-CN','A4','','',23,23,40);//创建mpdf对象,‘zh-CN’:对应中文,‘23,23‘,页眉和页脚的距离。
【 $header = '
'
; 】
这段主要是如何向PDF里添加页眉,当然还有其他方式,可以参考插件里提供的方法,
【 $html=$header.'
1234
';
$mpdf->WriteHTML($html);
header('Content-Type: application/mpdf');
header('Content-Disposition: attachment;filename=1234.pdf');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be
needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the
past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); //
always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$mpdf->Output('php://output');
exit; 】
上面的写法是PDF导出的写发放,如果想要保存到服务器的某个地方,只需要改变
【$mpdf->Output('php://output');】output方法里的路径即可。