Skip to content

輸出 (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/pdfContent-Disposition: inline
Download強制下載對話框Content-Type: application/pdfContent-Disposition: attachment
File儲存至伺服器檔案系統
String回傳原始 PDF 位元組

使用 InlineDownload 時,TCPDF-Next 會在輸出 PDF 內容之前自動送出適當的 Content-TypeContent-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 提供並在瀏覽器中檢視時,建議啟用此功能。

以 LGPL-3.0-or-later 授權釋出。