Pdf Facade¶
Pdf Facade 是 NextPDF\Core\Contracts\DocumentFactoryInterface 的靜態代理,透過 Laravel 服務容器解析底層實作。所有公開方法均支援 PHP IDE 的型別提示(透過 @method PHPDoc 或 IDE helper 套件)。
PHP Compatibility
This example uses PHP 8.5 syntax. If your environment runs PHP 8.1 or 7.4, use NextPDF Backport for a backward-compatible build.
匯入¶
或在 config/app.php 的 aliases 中設定全域別名:
'aliases' => Facade::defaultAliases()->merge([
'Pdf' => NextPDF\Laravel\Facades\Pdf::class,
])->toArray(),
建立文件¶
use NextPDF\Laravel\Facades\Pdf;
use NextPDF\ValueObjects\PageSize;
use NextPDF\ValueObjects\Margin;
// 使用預設設定(來自 config/nextpdf.php)
$document = Pdf::create();
// 覆寫特定選項
$document = Pdf::create(
pageSize: PageSize::Letter,
margin: Margin::symmetric(vertical: 20.0, horizontal: 25.0),
title: 'Q1 Financial Report',
author: 'Finance Department',
);
鏈式操作¶
use NextPDF\Laravel\Facades\Pdf;
$pdfBytes = Pdf::create()
->addPage()
->text('Annual Report 2026', x: 20, y: 30, fontSize: 24)
->newLine()
->text('Prepared by Finance Team', x: 20, fontSize: 12)
->addPage()
->text('Summary', x: 20, y: 30)
->output(); // 回傳 PDF bytes (string)
從 Blade 視圖生成¶
use NextPDF\Laravel\Facades\Pdf;
// 渲染 Blade 模板為 PDF(需安裝 nextpdf/artisan 或使用 Core HTML 渲染器)
$pdfBytes = Pdf::fromView(
view: 'reports.invoice',
data: ['invoice' => $invoice],
pageSize: 'A4',
)->output();
對應的 Blade 模板 resources/views/reports/invoice.blade.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
@page { size: A4; margin: 15mm; }
body { font-family: sans-serif; }
</style>
</head>
<body>
<h1>Invoice #{{ $invoice->id }}</h1>
<p>{{ $invoice->customer->name }}</p>
</body>
</html>
從 URL 生成(搭配 Artisan)¶
use NextPDF\Laravel\Facades\Pdf;
// 需安裝 nextpdf/artisan
$pdfBytes = Pdf::fromUrl(
url: route('reports.show', $reportId),
headers: ['Authorization' => 'Bearer ' . $internalToken],
)->output();
儲存到磁碟¶
use NextPDF\Laravel\Facades\Pdf;
use Illuminate\Support\Facades\Storage;
$pdfBytes = Pdf::create()
->addPage()
->text('Contract', x: 20, y: 30)
->output();
// 存至 Laravel Storage(支援 S3、本機等任何 driver)
Storage::disk('s3')->put(
"contracts/{$contractId}.pdf",
$pdfBytes,
['ContentType' => 'application/pdf'],
);
假物件(測試用)¶
use NextPDF\Laravel\Facades\Pdf;
// 在測試中 fake Facade
Pdf::fake();
// 執行受測程式碼
$this->post('/reports/generate');
// 斷言 PDF 已被建立
Pdf::assertCreated();
Pdf::assertCreatedWith(fn ($doc) => $doc->getTitle() === 'Q1 Report');
Pdf::assertCreatedCount(1);
參見¶
- Laravel 套件總覽 — 套件功能概覽
- Service Provider — 容器綁定與設定
- HTTP 回應 — 將生成的 PDF 以 HTTP 回應送出
- Queue Job — 非同步背景生成