本文详解如何利用 dompdf 动态为 html 内容的每一页单独指定纸张尺寸与方向(如前3页横向、后3页纵向),并合并输出为单个 pdf 文件。
本文详解如何利用 dompdf 动态为 html 内容的每一页单独指定纸张尺寸与方向(如前3页横向、后3页纵向),并合并输出为单个 pdf 文件。
Dompdf 原生不支持在单次渲染中混合多种页面方向(例如在一个
中用 CSS 指定某 section 为 landscape),但可通过分页加载 + 动态设置纸张的方式,将多个 HTML 片段(或同一文件中的逻辑分页)依次渲染并拼接为一个 PDF。关键在于:每次调用 loadHtml() 前,必须通过 setPaper() 显式设置当前页的尺寸与方向;且所有页面需在一次 render() 流程中完成(而非多次独立 render)——但这需要 DOM 操作干预。更可靠、推荐的做法是:将各页内容按顺序拼接为一个 HTML 字符串,并在每页✅ 正确实现方式(推荐 —— 单文件、单 PDF、混合方向):
require_once 'vendor/autoload.php';
use Dompdf\Dompdf;
// 初始化 Dompdf(禁用远程资源加载以提升安全与性能)
$options = new \Dompdf\Options();
$options->set('isRemoteEnabled', false);
$options->set('defaultFont', 'sans-serif');
$dompdf = new Dompdf($options);
// 构建包含6页的完整 HTML(每页用 <section> 包裹,并添加 page-break-after)
$html = '
<meta charset="UTF-8">
<style>
@page { size: A4 portrait; margin: 0; }
@page landscape { size: A4 landscape; margin: 0; }
.page { page-break-after: always; width: 100%; height: 100vh; }
.section-1, .section-2, .section-3 { page: landscape; }
.section-4, .section-5, .section-6 { page: default; }
/* 可选:为视觉区分添加背景色 */
.section-1 { background: #e6f7ff; }
.section-4 { background: #fff0f6; }
</style>';
// 页面1(横向)
$html .= '<section class="page section-1"><h1 style="text-align:center;margin-top:200px;">Page 1 — Landscape</h1></section>';
// 页面2(横向)
$html .= '<section class="page section-2"><h1 style="text-align:center;margin-top:200px;">Page 2 — Landscape</h1></section>';
// 页面3(横向)
$html .= '<section class="page section-3"><h1 style="text-align:center;margin-top:200px;">Page 3 — Landscape</h1></section>';
// 页面4(纵向)
$html .= '<section class="page section-4"><h1 style="text-align:center;margin-top:200px;">Page 4 — Portrait</h1></section>';
// 页面5(纵向)
$html .= '<section class="page section-5"><h1 style="text-align:center;margin-top:200px;">Page 5 — Portrait</h1></section>';
// 页面6(纵向)
$html .= '<section class="page section-6"><h1 style="text-align:center;margin-top:200px;">Page 6 — Portrait</h1></section>';
$html .= '';
// 加载并渲染
$dompdf->loadHtml($html);
$dompdf->setPaper('A4'); // 此处设为基准尺寸,实际由 @page 控制
$dompdf->render();
// 输出为浏览器下载(不保存附件)
$dompdf->stream('multi_orientation_report.pdf', ['Attachment' => false]);</section>
⚠️ 注意事项:
- Dompdf 对 @page 规则的支持较基础,必须为每页
添加 page 属性(如 page: landscape)并提前定义 @page landscape ,否则方向不会生效; - 避免在 HTML 中使用 PHP 标签(如 ),Dompdf 不执行 PHP,仅解析静态 HTML/CSS;
- 若需从外部 .html 文件读取内容,建议先 file_get_contents() 并拼接进 $html 字符串,再统一 loadHtml();
- page-break-after: always 是确保分页的关键;若内容过长导致自动分页,可添加 break-inside: avoid; 到 .page 类中;
- 中文显示需确保字体支持(推荐设置 defaultFont 并在 CSS 中声明 font-family: "DejaVu Sans", sans-serif;,并启用 dompdf/lib/fonts/dejavu-sans.font.php)。
? 总结:
Dompdf 实现混合方向 PDF 的核心不是“多次 render”,而是单次加载含 @page 规则的结构化 HTML。通过语义化分节 + CSS 分页指令,即可精准控制每页尺寸与朝向,最终输出专业、合规的多页 PDF 报告。











