You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP Chrome HTML 2 PDF生成PDF时Header/Footer不显示问题求解

解决方案

根因说明

Chrome Headless 生成PDF时默认不会给Header、Footer预留显示空间,同时头尾模板的默认渲染规则要求必须指定明确样式,否则即使开启displayHeaderFooter参数也无法正常显示内容。

修正步骤

  • 新增页边距配置,给Header和Footer预留显示空间,marginTop、marginBottom参数建议至少设置为1.5cm以上
  • 优化Header、Footer模板代码,添加明确的内联样式,Chrome头尾模板仅支持内联CSS,不支持外部样式或内部style标签
  • 如需使用页码、总页数等动态参数,可直接调用Chrome内置的模板类名变量即可自动解析

修正后可运行代码

<?php
use Spiritix\Html2Pdf\Converter;
use Spiritix\Html2Pdf\Input\StringInput;
use Spiritix\Html2Pdf\Output\DownloadOutput;
require_once 'vendor/autoload.php';
$html="<p>This is the Content</p>";
$input = new StringInput();
$input->setHtml($html);

$converter = new Converter($input, new DownloadOutput());

$converter->setOption('landscape', false);
$converter->setOption('displayHeaderFooter', true);
// 新增页边距配置,预留头尾显示空间
$converter->setOption('marginTop', '2cm');
$converter->setOption('marginBottom', '2cm');
// 优化模板添加内联样式确保可见
$converter->setOption('headerTemplate', '<p style="font-size: 12px; text-align: center; width: 100%; margin: 0;">Header Here</p>');
$converter->setOption('footerTemplate', '<p style="font-size: 12px; text-align: center; width: 100%; margin: 0;">Page <span class="pageNumber"></span> of <span class="totalPages"></span></p>');

$output = $converter->convert();
$output->download('SOL-'.date('Y-m-d-h-i-s').'.pdf');
?>

注意:如果模板内容超出预留的边距高度,超出部分会被自动截断,可根据实际显示效果调整边距参数和模板字体大小

内容的提问来源于stack exchange,提问作者Somsuvra Ganguly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:45:05