Skip to content

Laravel Package

TCPDF-Next Laravel
Laravel · LGPL-3.0

Laravel package (yeeefang/tcpdf-next-laravel) cung cấp tích hợp Laravel 12 đầy đủ với:

  • ServiceProvider tự động phát hiện — DI binding, scoped service an toàn cho Octane
  • Pdf Facade — truy cập static tiện lợi
  • PdfResponse — helper HTTP response bảo mật (inline/download)
  • GeneratePdfJob — tạo PDF bất đồng bộ qua queue

Cài đặt

bash
composer require yeeefang/tcpdf-next-laravel

Yêu cầu: Laravel ^12.0

ServiceProvider được tự động phát hiện. Publish config:

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

Bắt đầu nhanh

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 #{$invoice->number}")
            ->addPage()
            ->setFont('DejaVuSans', '', 12)
            ->cell(0, 10, "Invoice #{$invoice->number}");

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

Service Provider Binding

InterfaceBindingScope
PdfDocumentInterfaceDocument::create()Factory (tạo mới mỗi lần resolve)
FontManagerInterfaceFontManagerScoped (refresh mỗi request, an toàn cho Octane)
SignerInterfaceCấu hình từ config/tcpdf-next.phpFactory

TcpdfServiceProvider merge các giá trị mặc định từ file config đi kèm và đăng ký mọi binding trước khi ứng dụng boot. Trong môi trường Laravel Octane, scoped binding được tự động flush giữa các request để ngăn rò rỉ state.

Cấu trúc Package

Yeeefang\TcpdfNext\Laravel\
├── TcpdfServiceProvider       # DI binding, config publishing
├── Facades\
│   └── Pdf                    # Static proxy tới Document factory
├── Http\
│   └── PdfResponse            # Helper response inline / download
└── Jobs\
    └── GeneratePdfJob         # Tạo PDF bất đồng bộ qua queue

Dependency Injection

Thay vì dùng Facade, inject contract trực tiếp:

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, 'Monthly Report')
            ->setFont('Helvetica', '', 12)
            ->cell(0, 10, "Generated: " . now()->format('F j, Y'))
            ->output();
    }
}

Bước tiếp theo

  • Pdf Facade — Truy cập static và helper test
  • HTTP Response — Hiển thị inline và download bảo mật
  • Queue Job — Tạo PDF bất đồng bộ với callback
  • Cấu hình — Tham chiếu config đầy đủ

Phân phối theo giấy phép LGPL-3.0-or-later.