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 许可证发布。