使用mpdf生成pdf

html 生成 pdf 是很常见的场景,有很多实现方式,这里我使用的是 mpdf

对于如何寻找需要的库,我一般是 github 上按语言去搜索,用star倒序排,一般会尝试用前面几个且比较活跃的项目,然后看效果与需求匹配度。

安装

必须开启 PHP mbstring 和 gd 扩展。某些高级功能可能需要额外的扩展,例如用于压缩输出和嵌入资源(例如字体)的 zlib 、用于生成条形码的 bcmath 或用于字符集的 xml 转换和 SVG 处理。

使用 composer 安装即可。

composer require mpdf/mpdf

使用

$mpdf = new \Mpdf\Mpdf([
    'autoScriptToLang' => true,
    'autoLangToFont'   => true
]);
$html = '<div style="margin: 0 auto; width: 600px; padding: 40px 20px; font-size: 20px;">
<div style="font-size: 50px; padding: 16px 0; text-align: center; color: red; font-weight: 900; border-bottom: 4px solid red;">
    这是一个测试pdf
</div>
<div style="line-height: 40px; margin-top: 30px;  height: 500px; margin-top: 30px; letter-spacing: 2px;">
    <p style="text-indent: 2em; ">
        感谢puresai的大力支持!
    </p>
</div>
<div style="height: 40px; text-align: right; letter-spacing: 2px;">
</div>
<div style="line-height: 32px; text-align: right; letter-spacing: 1px;">'.
    date('Y年m月d日').
'</div>
</div>';
$mpdf->WriteHTML($html);
$path = dirname(__DIR__).'/public/pdf/puresai.pdf';
$mpdf->OutputFile($path);

使用非常简单,来看一下效果。
mpdf

感谢 https://github.com/mpdf/mpdf


使用mpdf生成pdf
https://blog.puresai.com/2023/11/07/490/
作者
puresai
许可协议