输出 (HasOutput)
保存至文件
生成 PDF 最简单的方式是直接写入磁盘:
php
use Yeeefang\TcpdfNext\Core\Document;
$pdf = Document::create()
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, 'Hello, World!')
->save('/path/to/output.pdf');save(string $path) 会将渲染后的 PDF 写入指定路径,并返回 static。
含目的地控制的输出
若需要更精细的传递控制,可搭配 OutputDestination 枚举使用 output() 方法:
php
use Yeeefang\TcpdfNext\Core\Document;
use Yeeefang\TcpdfNext\Contracts\OutputDestination;
$pdf = Document::create()
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, 'Hello, World!');
// 在浏览器中显示(内嵌)
$pdf->output('document.pdf', OutputDestination::Inline);
// 强制下载
$pdf->output('document.pdf', OutputDestination::Download);
// 保存至文件
$pdf->output('document.pdf', OutputDestination::File);
// 返回字符串
$pdf->output('document.pdf', OutputDestination::String);OutputDestination 枚举
| 值 | 行为 | HTTP 标头 |
|---|---|---|
Inline | 在浏览器中显示 | Content-Type: application/pdf、Content-Disposition: inline |
Download | 强制下载对话框 | Content-Type: application/pdf、Content-Disposition: attachment |
File | 保存至服务器文件系统 | 无 |
String | 返回原始 PDF 字节 | 无 |
使用 Inline 或 Download 时,TCPDF-Next 会在输出 PDF 内容之前自动发送适当的 Content-Type 与 Content-Disposition 标头。
获取 PDF 字符串
使用 toString() 可获取原始 PDF 字节,而不写入磁盘或发送标头。这在电子邮件附件、存储空间 API 或后续处理时特别实用:
php
use Yeeefang\TcpdfNext\Core\Document;
$pdf = Document::create()
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, '月报');
$content = $pdf->toString();
// 手动写入磁盘
file_put_contents('/path/to/output.pdf', $content);
// 或作为电子邮件附件
Mail::send([], [], function ($message) use ($content) {
$message->attachData($content, 'report.pdf', ['mime' => 'application/pdf']);
});流式输出(PdfWriterChunked)
对于数千页的大型文件,将整份 PDF 保留在内存中的成本相当高。PdfWriterChunked 会将 PDF 内容以增量方式写入流:
php
use Yeeefang\TcpdfNext\Core\Document;
$pdf = Document::create();
$pdf->addPage()->setFont('Helvetica', '', 10);
for ($i = 0; $i < 5000; $i++) {
$pdf->cell(0, 5, "Row {$i}: data content here", newLine: true);
}
// 流式在内部自动处理 — save 触发分段写入
$pdf->save('large-report.pdf');分段写入器会在页面数据定稿后逐步清出,无需在写入前缓冲整份文件。这对调用端完全透明 — 相同的 save() 与 output() API 照常适用。
线性化(Linearizer)— 快速 Web 查看
线性化会重新排列 PDF 对象,让第一页能在整份文件下载完成前就开始渲染。这对通过 Web 传递的 PDF 至关重要:
php
use Yeeefang\TcpdfNext\Core\Document;
$pdf = Document::create()
->setLinearization(true)
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, '针对 Web 查看优化')
->save('linearized.pdf');Linearizer 会写入提示流(hint streams),告知 PDF 查看器如何渐进式渲染文件。当 PDF 将通过 HTTP 提供并在浏览器中查看时,建议启用此功能。