目錄¶
TocBuilder 在 finalize() 時自動收集文件中所有標記的標題,計算其最終頁碼,並生成格式化的目錄頁面。目錄條目自動附帶可點擊的連結,讓讀者直接跳轉到對應章節。
啟用目錄¶
use NextPDF\Navigation\TocBuilder;
use NextPDF\Navigation\TocConfig;
// 在文件開頭預留目錄頁面(頁碼會在 finalize() 後填入)
$toc = $document->toc();
$toc->reserve(pageCount: 2); // 預留 2 頁給目錄
// 繼續新增文件內容...
$document->addPage();
標記標題¶
// 在渲染文字時標記為目錄條目
$document->text()->write(
text: 'Chapter 1: Introduction',
position: Position::at(x: 20.0, y: 50.0),
style: FontStyle::create(fontSize: 18.0, bold: true),
tocEntry: TocEntry::level(level: 1), // H1 層級
);
$document->text()->write(
text: '1.1 Background',
position: Position::at(x: 20.0, y: 70.0),
style: FontStyle::create(fontSize: 14.0),
tocEntry: TocEntry::level(level: 2), // H2 層級
);
目錄樣式設定¶
use NextPDF\Navigation\TocStyle;
use NextPDF\Navigation\LeaderStyle;
$toc->configure(
config: TocConfig::create(
title: 'Contents',
titleStyle: FontStyle::create(fontSize: 18.0, bold: true),
maxDepth: 3, // 最多顯示 3 層
showPageNumbers: true,
leaderStyle: LeaderStyle::Dots, // 引導點(⋯⋯)
),
);
// 各層級樣式
$toc->setLevelStyle(
level: 1,
style: TocStyle::create(
fontStyle: FontStyle::create(fontSize: 12.0, bold: true),
indent: 0.0,
marginBottom: 3.0,
),
);
$toc->setLevelStyle(
level: 2,
style: TocStyle::create(
fontStyle: FontStyle::create(fontSize: 10.0),
indent: 10.0,
marginBottom: 1.5,
),
);
引導點(Leader)格式¶
use NextPDF\Navigation\LeaderStyle;
LeaderStyle::Dots // 目錄標題 .......... 12
LeaderStyle::Dashes // 目錄標題 ---------- 12
LeaderStyle::Lines // 目錄標題 ────────── 12
LeaderStyle::None // 目錄標題 12
與書籤同步¶
// 目錄條目自動生成對應書籤
$toc->autoGenerateBookmarks(true);
// 控制書籤深度(可與目錄深度不同)
$toc->setBookmarkDepth(2); // 書籤只顯示前 2 層
HTML 渲染器整合¶
// 在 HTML 渲染時自動收集標題
$document->html()->render(
html: $articleHtml,
box: Rectangle::fromXY(x: 20.0, y: 30.0, width: 170.0, height: 240.0),
collectTocEntries: true, // 自動從 h1-h6 收集目錄條目
);