Dompdf 0.8 导 200 页 PDF 超 60 秒 分批渲染怎么拼回一个文件

合同导出从 30 页涨到 200 页,接口 504,Nginx 日志 upstream timed out 60s。Dompdf 0.8.6,memory_limit 512M,报错里没有内存,只有 Maximum execution time of 60 seconds exceeded。

我先 set_time_limit(0),再把 memory_limit 调到 1G。任务能跑完,但要 140 秒,前端早就断了,队列里的 worker 也被占死。

关掉 isRemoteEnabled 和字体子集,快了 12 秒,杯水车薪。Dompdf 是把整份 HTML 一次性布局成页面对象,200 页的表格全在内存里排版,页数越多越慢,不是线性。

换成按章节切。后端先把合同按 20 页一组拆成 10 段 HTML,每段单独 render 成 PDF 落到 /tmp,再用 FPDI 按顺序合并。单段 7 到 9 秒,总耗时 38 秒。

合并时踩了个坑,FPDI 免费版不认 Dompdf 输出的压缩对象流,报 FPDF error: Unable to find object。给 Dompdf 加 set_option('compress', 0) 之后能读了。

接口改成异步:提交任务立刻返回 task_id,前端轮询。生成完把文件传到对象存储,给 7 天有效的签名链接。

验收用一份 214 页的合同,页数、页码、表格边框都对得上,总耗时 41 秒,接口响应 200ms。

$dompdf = new Dompdf(['isRemoteEnabled' => false]);
$dompdf->set_option('compress', 0);
foreach ($chunks as $i => $htmlPart) {
    $dompdf->loadHtml($htmlPart, 'UTF-8');
    $dompdf->setPaper('A4');
    $dompdf->render();
    file_put_contents("/tmp/part_{$i}.pdf", $dompdf->output());
}

您可以还会对下面的文章感兴趣: