图层 (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 查看器可能会忽略图层。
- 图层对文件大小的影响极小,因为它们只是元数据标志,并非重复的内容。