HTML 渲染¶
NextPDF 內建 HTML/CSS 子集渲染器,讓開發者可以直接將 HTML 標記轉換為 PDF 內容。渲染器實作了 HTML 4.01 的核心子集與 CSS 2.1 的版面相關屬性,足以應付大多數報表與文件生成場景。
注意:NextPDF 的 HTML 渲染器是一個 PDF 導向的排版引擎,而非完整的網頁瀏覽器。如需精確還原複雜的網頁版面,請考慮使用 Artisan(Chrome CDP 渲染器)。
基本用法¶
use NextPDF\ValueObjects\Rectangle;
$html = <<<HTML
<h1>Invoice #2026-001</h1>
<p>Dear <strong>Acme Corp</strong>,</p>
<p>Please find your invoice details below:</p>
HTML;
$document->html()->render(
html: $html,
box: Rectangle::fromXY(x: 20.0, y: 30.0, width: 170.0, height: 240.0),
);
支援的 HTML 標籤¶
| 分類 | 標籤 |
|---|---|
| 標題 | h1–h6 |
| 段落 | p, br, hr |
| 文字格式 | strong, b, em, i, u, s, code, pre |
| 清單 | ul, ol, li, dl, dt, dd |
| 表格 | table, thead, tbody, tfoot, tr, th, td, caption |
| 連結 | a |
| 影像 | img |
| 容器 | div, span, section, article, header, footer |
支援的 CSS 屬性¶
/* 文字相關 */
font-family, font-size, font-weight, font-style, font-variant,
color, text-align, text-decoration, text-transform,
letter-spacing, line-height, word-spacing
/* 盒模型 */
margin, margin-top/right/bottom/left,
padding, padding-top/right/bottom/left,
border, border-radius (矩形近似),
width, height, min-width, max-width
/* 背景 */
background-color, background-image (限本地路徑)
/* 表格 */
border-collapse, border-spacing, vertical-align
表格渲染¶
<table style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background-color: #1E3A8A; color: white;">
<th style="padding: 8px; text-align: left;">Description</th>
<th style="padding: 8px; text-align: right;">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td style="padding: 6px; border-bottom: 1px solid #eee;">Professional Services</td>
<td style="padding: 6px; border-bottom: 1px solid #eee; text-align: right;">$5,000.00</td>
</tr>
</tbody>
</table>
圖片嵌入¶
<!-- 本地檔案路徑 -->
<img src="/var/www/assets/logo.png" width="100" alt="Company Logo">
<!-- Base64 Data URI -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." width="80" alt="QR Code">
分頁控制¶
/* CSS 分頁提示 */
.chapter-start { page-break-before: always; }
.keep-together { page-break-inside: avoid; }
參見¶
- 文字渲染 — 純文字輸出 API
- Artisan 渲染器 — Chrome CDP 精確網頁渲染
- 圖片 — ImageRegistry 與圖片格式支援