圖層 (OCG)
PDF 圖層的正式名稱為「選用內容群組」(Optional Content Groups, OCG),可讓你建立能在閱讀器中開關的內容,或選擇性地在列印時納入或排除。圖層系統由 Graphics\LayerManager 管理,並透過 Document 流暢 API 存取。
所有方法皆回傳 static,因此可以鏈式串接。
快速參考
| 方法 | 用途 |
|---|---|
startLayer() | 以指定名稱開始一個新圖層 |
endLayer() | 結束目前的圖層 |
基本範例
php
use Yeeefang\TcpdfNext\Core\Document;
$pdf = Document::create()
->addPage()
->setFont('Helvetica', '', 12)
// 螢幕可見,列印時隱藏
->startLayer('Screen Only', print: false, view: true)
->cell(0, 10, 'This text appears on screen but not when printed', newLine: true)
->endLayer()
// 僅列印時可見
->startLayer('Print Only', print: true, view: false)
->cell(0, 10, 'This text appears only when printed', newLine: true)
->endLayer()
// 始終可見
->cell(0, 10, 'This text is always visible', newLine: true);startLayer()
php
$pdf->startLayer(string $name, bool $print = true, bool $view = true): static開始一個新圖層。此呼叫之後繪製的所有內容都屬於該圖層,直到呼叫 endLayer() 為止。
| 參數 | 型別 | 說明 |
|---|---|---|
$name | string | 在閱讀器圖層面板中顯示的名稱 |
$print | bool | 圖層內容是否在列印時出現 |
$view | bool | 圖層內容是否在螢幕上顯示 |
endLayer()
結束目前的圖層。此呼叫之後繪製的內容不再屬於任何圖層。
圖層可見性模式
$print 與 $view 的組合可產生四種實用的可見性模式:
$print | $view | 行為 |
|---|---|---|
true | true | 始終可見(預設) |
false | true | 僅螢幕 — 列印時隱藏 |
true | false | 僅列印 — 螢幕上隱藏 |
false | false | 預設全部隱藏(使用者可手動切換) |
巢狀圖層
圖層可以巢狀使用。子圖層會繼承父圖層的可見性約束 — 當父圖層隱藏時,子圖層也會隨之隱藏。
php
$pdf->startLayer('Parent')
->cell(0, 10, 'Parent content', newLine: true)
->startLayer('Child', print: false, view: true)
->cell(0, 10, 'Child content — screen only', newLine: true)
->endLayer()
->endLayer();使用情境
多語言 PDF
將每種翻譯放在獨立的圖層上,讀者即可在圖層面板中切換語言:
php
$pdf->startLayer('English')
->cell(0, 10, 'Hello, World!', newLine: true)
->endLayer()
->startLayer('Chinese')
->cell(0, 10, '你好,世界!', newLine: true)
->endLayer();浮水印(僅螢幕顯示)
php
$pdf->startLayer('Watermark', print: false, view: true)
->setFont('Helvetica', 'B', 48)
->setTextColor(200, 200, 200)
->text(60, 140, 'DRAFT')
->endLayer();僅列印的裁切標記
php
$pdf->startLayer('Crop Marks', print: true, view: false)
->cropMark(20, 20, 10, 10)
->cropMark(190, 20, 10, 10)
->endLayer();提示
- 圖層名稱應簡短且具描述性 — 它們會原封不動地顯示在閱讀器的圖層面板中。
- Adobe Acrobat 與 Foxit Reader 完整支援 OCG;瀏覽器內建的 PDF 檢視器可能會忽略圖層。
- 圖層對檔案大小的影響極小,因為它們只是中繼資料旗標,並非重複的內容。