Skip to content

Laravel 套件

Laravel · LGPL-3.0

Laravel 套件(yeeefang/tcpdf-nextlaravel)為 Laravel 12 提供一流的整合,包含:

  • 自動發現的服務提供者 — DI 綁定、Octane 安全的作用域服務
  • Pdf 門面 — 方便的靜態存取介面
  • PdfResponse — 安全的 HTTP 回應輔助(內嵌 / 下載)
  • GeneratePdfJob — 基於佇列的非同步 PDF 產生

安裝

bash
composer require yeeefang/tcpdf-nextlaravel

需求: Laravel ^12.0

服務提供者會自動發現。發布設定檔:

bash
php artisan vendor:publish --tag=tcpdf-next-config

快速開始

php
use Yeeefang\TcpdfNext\Laravel\Facades\Pdf;
use Yeeefang\TcpdfNext\Laravel\Http\PdfResponse;

class InvoiceController extends Controller
{
    public function download(Invoice $invoice)
    {
        $pdf = Pdf::create()
            ->setTitle("發票 #{$invoice->number}")
            ->addPage()
            ->setFont('DejaVuSans', '', 12)
            ->cell(0, 10, "發票 #{$invoice->number}");

        return PdfResponse::download($pdf, "invoice-{$invoice->number}.pdf");
    }
}

服務提供者綁定

介面綁定作用域
PdfDocumentInterfaceDocument::create()Factory(每次解析產生新實例)
FontManagerInterfaceFontManagerScoped(每次請求重新建立,Octane 安全)
SignerInterfaceconfig/tcpdf-next.php 讀取設定Factory

TcpdfServiceProvider 會合併套件內建的預設設定,並在應用程式啟動前完成所有綁定註冊。在 Laravel Octane 環境中,作用域綁定會在請求之間自動清除,避免狀態洩漏。

套件結構

Yeeefang\TcpdfNext\Laravel\
├── TcpdfServiceProvider       # DI 綁定、設定發布
├── Facades\
│   └── Pdf                    # Document 工廠的靜態代理
├── Http\
│   └── PdfResponse            # 內嵌 / 下載回應輔助
└── Jobs\
    └── GeneratePdfJob         # 可排隊的非同步 PDF 產生

依賴注入

除了門面之外,也可以直接注入合約:

php
use Yeeefang\TcpdfNext\Contracts\PdfDocumentInterface;

class ReportService
{
    public function __construct(
        private readonly PdfDocumentInterface $pdf,
    ) {}

    public function generate(array $data): string
    {
        return $this->pdf
            ->addPage()
            ->setFont('Helvetica', 'B', 16)
            ->cell(0, 10, '月度報告')
            ->setFont('Helvetica', '', 12)
            ->cell(0, 10, '產生日期:' . now()->format('Y-m-d'))
            ->output();
    }
}

下一步

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