php 8.6用dompdf生成中文pdf时,除了安装库,还要提供覆盖中文字符的字体,并将本地资源限制在专用目录。下面从固定模板生成一页a4文档,关闭远程资源、php执行和pdf javascript;不是把任意用户html交给服务端排版。

Dompdf官方文档中的Dompdf
准备字体和缓存目录
composer require dompdf/dompdf composer check-platform-reqs
需要DOM和mbstring等实际安装版本要求的扩展。在项目下建立pdf-assets、pdf-cache目录,前者放有合法使用权的中文TTF字体并命名为CJK-Regular.ttf;后者可写且不对外提供。字体文件必须真实覆盖所需中文字符,不能只修改文件名。

Dompdf官方文档中的Usage
用固定模板渲染PDF
<?php
require __DIR__.'/vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;
$assets=realpath(__DIR__.'/pdf-assets');$cache=realpath(__DIR__.'/pdf-cache');
if (!$assets || !$cache || !is_writable($cache)
|| !is_file($assets.'/CJK-Regular.ttf')) throw new RuntimeException('PDF资源未准备');
$options=new Options();
$options->set('chroot',[$assets]);$options->set('isRemoteEnabled',false);
$options->set('isPhpEnabled',false);$options->set('isJavascriptEnabled',false);
$options->set('fontDir',$cache);$options->set('fontCache',$cache);$options->set('tempDir',$cache);
$pdf=new Dompdf($options);
$title=htmlspecialchars('中文报表示例',ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8');
$doc='<html><head><meta charset="utf-8"><style>'.
'@font-face{font-family:CJK;src:url("CJK-Regular.ttf") format("truetype");}'.
'body{font-family:CJK;font-size:12pt}</style></head><body><h1>'.$title.'</h1>'.
'<p>数量:3;状态:已生成。</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Build MCP servers and clients for PHP applications with the official PHP SDK" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK">Build MCP servers and clients for PHP applications with the official PHP SDK</a>
<p>使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。</p>
</div>
<a href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div></body></html>';
$pdf->setBasePath($assets.'/');$pdf->loadHtml($doc,'UTF-8');
$pdf->setPaper('A4','portrait');$pdf->render();
$pdf->stream('report.pdf',['Attachment'=>true]);检查字体与分页结果
打开生成文件,核对中文是否缺字、内容是否被截断及分页是否正确。Dompdf不是完整浏览器排版引擎,官方列出Flexbox、Grid等限制;跨页表格行也有限制。每份独立文档创建新的Dompdf实例,不能因页面能打开就认定所有复杂布局已得到支持。


















