php 生成pdf的方法有很多种,我用的是mpdf,这个是将html转为网页,适合有前端经验的。
安装
使用composer安装
composer require mpdf/mpdf
生成简单的pdf
//实例化mpdf
$mpdf = new \Mpdf\Mpdf([ 'mode' => 'UTF-8', 'format' => 'A4', 'default_font_size' => 40, 'default_font' => '', 'margin_left' => 20, 'margin_right' => 20]);//utf-8
//$mpdf->SetAutoFont(AUTOFONT_ALL);//使用6.0以上版本不需要
//获取要生成的静态文件
// 支持中文
$mpdf->useAdobeCJK = true;
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
//设置pdf显示方式
$mpdf->SetDisplayMode('fullpage');
//设置pdf的尺寸为270mm*397mm
//$mpdf->WriteHTML('<pagebreak sheet-size="270mm 397mm" />');
$time = "2022-8-1";
$html1 = "
<h2 style='text-align: center;font-size: 28px'>标题<h2>
<h4 style='text-align: center;font-size: 20px'>——副标题</h4>
<diV style='font-size: 14px;text-align: left'>报告时间:2022-01-02</diV>
<diV style='font-size: 14px;text-align: left'>报告地点</diV>
<img style='width:400px;height:350px;margin: 0;padding: 0;text-align: center' src='http://sanshi-file.oss-accelerate.aliyuncs.com//uploads/20220718/3bb9164bd8acc75af03d3d9391b05b62.png' >
“
$mpdf->WriteHTML($html1);
$file_path = ROOT_PATH . 'public/uploadpdf/' . Date('Ymd');//保存路径
//如果不存在此目录,则创建此目录
if (!is_dir($file_path)) {
mkdir($file_path, 0777, true);
}
$Name = '123.pdf'; //文件名
$fileName = $file_path . '/' . $Name; //文件路径+名字
//输出pdf
$mpdf->Output($fileName); //可以写成下载此pdf $mpdf->Output('文件名','D');