文件附件
TCPDF-Next 可以在 PDF 文件中嵌入任意文件。附件系统由 Navigation\FileAttachment 管理,并通过 Document 流畅 API 访问。附件会随 PDF 一起传递 — 收件者可直接从阅读器中提取嵌入的文件。
所有方法皆返回 static,因此可以链式串接。
快速参考
| 方法 | 用途 |
|---|---|
addFileAttachment() | 将文件嵌入 PDF 文件中 |
基本范例
php
use Yeeefang\TcpdfNext\Core\Document;
$pdf = Document::create()
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, 'Invoice #2026-001', newLine: true)
->cell(0, 10, 'The original spreadsheet is attached to this PDF.', newLine: true)
// 附加支持文件
->addFileAttachment('/path/to/invoice-data.xlsx', 'invoice-data.xlsx', 'Original invoice data')
->addFileAttachment('/path/to/zugferd.xml', 'factur-x.xml', 'Factur-X e-invoice XML')
->save('invoice-with-attachments.pdf');1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
addFileAttachment()
php
$pdf->addFileAttachment(
string $file,
string $name = '',
string $desc = '',
string $mimeType = '',
string $relationship = 'Unspecified'
): static1
2
3
4
5
6
7
2
3
4
5
6
7
| 参数 | 类型 | 说明 |
|---|---|---|
$file | string | 要嵌入的文件绝对路径 |
$name | string | 阅读器附件面板中的显示名称(默认为原始文件名) |
$desc | string | 附件的人类可读描述 |
$mimeType | string | MIME 类型(留空则自动检测) |
$relationship | string | PDF 2.0 关联文件关系(Data、Source、Alternative、Supplement、Unspecified) |
常见使用场景
附加原始数据、补充文件或高分辨率原文件:
php
$pdf->addFileAttachment('/path/to/report-data.csv', 'report-data.csv', 'Raw CSV export')
->addFileAttachment('/path/to/terms.pdf', 'terms-and-conditions.pdf', 'Terms & Conditions')
->addFileAttachment('/path/to/photo-full.tiff', 'photo-full.tiff', 'Full-resolution original');1
2
3
2
3
PDF/A-3 与 PDF/A-4 合规
PDF/A-3 与 PDF/A-4 存档标准允许嵌入文件,使附件成为结构化数据交换的关键功能。最常见的应用场景是 ZUGFeRD / Factur-X 电子发票 — 将机器可读的 XML 发票嵌入人类可读的 PDF 中。
php
use Yeeefang\TcpdfNext\Core\Document;
$pdf = Document::create()
->setPDFVersion('2.0')
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, 'Electronic Invoice', newLine: true)
->cell(0, 10, 'This PDF contains a Factur-X XML attachment.', newLine: true)
// Factur-X / ZUGFeRD 电子发票附件
->addFileAttachment(
'/path/to/factur-x.xml',
'factur-x.xml',
'Factur-X BASIC invoice data',
'text/xml',
'Data'
)
->save('e-invoice.pdf');1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
TIP
以 PDF/A-3 或 PDF/A-4 为目标时,请设置 $relationship 参数来描述附件与文件的关系。常用值为 Data(结构化数据表示)、Source(原始来源文件)与 Alternative(替代表示形式)。
附件元数据
嵌入的文件带有元数据,阅读器会在附件面板中显示这些信息:
| 元数据 | 来源 |
|---|---|
| 文件名 | $name 参数(或原始文件名) |
| 描述 | $desc 参数 |
| MIME 类型 | $mimeType 参数(留空则自动检测) |
| 大小 | 从文件自动计算 |
| 修改日期 | 从文件系统的时间戳读取 |
提示
- 附件会使 PDF 文件大小增加约等于嵌入文件的大小。建议在嵌入前先压缩大型附件。
- Adobe Acrobat、Foxit Reader 与大多数桌面 PDF 阅读器支持附件。浏览器内置的查看器通常不会显示附件面板。
- 没有格式限制 — 你可以附加任何文件类型(CSV、XLSX、XML、PNG、ZIP 等)。
- 进行电子发票流程时,嵌入前请务必将 XML 与相关标准纲要(ZUGFeRD、Factur-X 或 XRechnung)进行验证。