HTTP 回應
PdfResponse 類別提供安全且符合標準的 HTTP 回應輔助,將 PDF 傳遞至瀏覽器。它自動設定所有必要的標頭,包括防止 MIME 嗅探和敏感文件快取的安全標頭。
php
use Yeeefang\TcpdfNext\Laravel\Http\PdfResponse;內嵌顯示
在瀏覽器內建的檢視器中直接呈現 PDF:
php
use Yeeefang\TcpdfNext\Laravel\Facades\Pdf;
use Yeeefang\TcpdfNext\Laravel\Http\PdfResponse;
public function preview(Invoice $invoice)
{
$pdf = Pdf::create()
->setTitle("發票 #{$invoice->number}")
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, "發票 #{$invoice->number}");
return PdfResponse::inline($pdf, "invoice-{$invoice->number}.pdf");
}回應設定 Content-Disposition: inline,指示瀏覽器顯示 PDF 而非觸發檔案下載。
強制下載
強制瀏覽器將 PDF 儲存為檔案:
php
public function download(Invoice $invoice)
{
$pdf = Pdf::create()
->setTitle("發票 #{$invoice->number}")
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, "發票 #{$invoice->number}");
return PdfResponse::download($pdf, "invoice-{$invoice->number}.pdf");
}回應設定 Content-Disposition: attachment,觸發瀏覽器的儲存檔案對話框。
安全標頭
inline() 與 download() 皆自動包含以下安全標頭:
| 標頭 | 值 | 用途 |
|---|---|---|
Content-Type | application/pdf | 正確的 MIME 類型 |
Content-Disposition | inline 或 attachment | 顯示模式 |
X-Content-Type-Options | nosniff | 防止 MIME 嗅探攻擊 |
Cache-Control | no-store, no-cache, must-revalidate | 防止敏感 PDF 被快取 |
Pragma | no-cache | HTTP/1.0 快取防護 |
Content-Length | <位元組數> | 啟用下載進度條 |
這些預設值遵循 OWASP 安全標頭建議。
串流大型 PDF
對於超出可用記憶體的文件,使用串流模式。這會將 PDF 區塊直接寫入輸出緩衝區,而非在記憶體中建立整份文件:
php
public function downloadLargeReport()
{
$pdf = Pdf::create()
->setTitle('年度報告');
foreach ($sections as $section) {
$pdf->addPage()
->setFont('Helvetica', '', 11)
->multiCell(0, 6, $section->content);
}
return PdfResponse::stream($pdf, 'annual-report.pdf');
}PdfResponse::stream() 回傳一個 StreamedResponse,以區塊方式刷新 PDF。無論文件大小,記憶體用量都維持恆定。
方法簽章
php
/** 在瀏覽器中內嵌顯示 PDF。 */
public static function inline(
PdfDocumentInterface $pdf,
string $filename,
): Response;
/** 以附件方式強制下載 PDF。 */
public static function download(
PdfDocumentInterface $pdf,
string $filename,
): Response;
/** 以串流方式傳遞 PDF,節省記憶體。 */
public static function stream(
PdfDocumentInterface $pdf,
string $filename,
): StreamedResponse;回應巨集
套件註冊了兩個回應巨集,提供便捷用法:
php
// 直接使用 response() 輔助函式
return response()->pdf($pdf, 'report.pdf'); // 下載
return response()->pdfInline($pdf, 'report.pdf'); // 內嵌這些巨集分別委派給 PdfResponse::download() 與 PdfResponse::inline(),所有安全標頭皆會套用。
檔名清理
PdfResponse 自動清理檔名參數,防止標頭注入攻擊。[a-zA-Z0-9._-] 以外的字元會被移除,並強制加上 .pdf 副檔名:
php
// 輸入:"../../etc/passwd"
// 清理後:"etcpasswd.pdf"
return PdfResponse::download($pdf, $userInput);下一步
- Pdf 門面 — 文件建立與測試
- 佇列任務 — 將大型 PDF 交給背景工作者處理
- Laravel 設定 — 自訂預設標頭與行為