HTTPレスポンス
PdfResponse クラスは、PDFをブラウザに配信するためのセキュアで標準準拠のHTTPレスポンスヘルパーを提供します。MIMEスニッフィングの防止や機密ドキュメントのキャッシュ防止を含むセキュリティヘッダーを含め、必要なすべてのヘッダーを自動的に設定します。
php
use Yeeefang\TcpdfNext\Laravel\Http\PdfResponse;インライン表示
Content-Disposition: inline でブラウザの組み込みビューアにPDFを直接レンダリングします:
php
use Yeeefang\TcpdfNext\Laravel\Facades\Pdf;
use Yeeefang\TcpdfNext\Laravel\Http\PdfResponse;
public function preview(Invoice $invoice)
{
$pdf = Pdf::create()
->setTitle("Invoice #{$invoice->number}")
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, "Invoice #{$invoice->number}");
return PdfResponse::inline($pdf, "invoice-{$invoice->number}.pdf");
}強制ダウンロード
Content-Disposition: attachment でブラウザのファイル保存ダイアログをトリガーします:
php
public function download(Invoice $invoice)
{
$pdf = Pdf::create()
->setTitle("Invoice #{$invoice->number}")
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, "Invoice #{$invoice->number}");
return PdfResponse::download($pdf, "invoice-{$invoice->number}.pdf");
}セキュリティヘッダー
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のキャッシュ防止 |
Content-Length | <バイト数> | ダウンロード進行状況バーの有効化 |
これらのデフォルトはOWASPセキュアヘッダーの推奨事項に従っています。
大規模PDFのストリーミング
利用可能なメモリを超えるドキュメントの場合、出力バッファに直接チャンクをストリーミングします:
php
public function downloadLargeReport()
{
$pdf = Pdf::create()->setTitle('Annual Report');
foreach ($sections as $section) {
$pdf->addPage()
->setFont('Helvetica', '', 11)
->multiCell(0, 6, $section->content);
}
return PdfResponse::stream($pdf, 'annual-report.pdf');
}PdfResponse::stream() はドキュメントサイズに関係なく一定のメモリ使用量で StreamedResponse を返します。
メソッドシグネチャ
php
public static function inline(PdfDocumentInterface $pdf, string $filename): Response;
public static function download(PdfDocumentInterface $pdf, string $filename): Response;
public static function stream(PdfDocumentInterface $pdf, string $filename): StreamedResponse;レスポンスマクロ
パッケージは便利なレスポンスマクロを2つ登録します:
php
return response()->pdf($pdf, 'report.pdf'); // ダウンロード
return response()->pdfInline($pdf, 'report.pdf'); // インラインこれらのマクロは PdfResponse メソッドに委譲するため、すべてのセキュリティヘッダーが適用されます。
ファイル名のサニタイズ
PdfResponse はヘッダーインジェクションを防ぐためにファイル名をサニタイズします。[a-zA-Z0-9._-] 以外の文字は除去され、.pdf が強制されます:
php
// 入力: "../../etc/passwd" -> サニタイズ後: "etcpasswd.pdf"
return PdfResponse::download($pdf, $userInput);