跳轉到

CodeIgniter — 框架整合套件

NextPDF CodeIgniter

nextpdf/codeigniter 以 CodeIgniter 4 的 Services 模式整合 NextPDF Core,提供符合 CI4 慣例的開發體驗:透過靜態 Services 工廠取得 DocumentFactory,以全域 helper 函式 pdf()pdf_document() 快速生成 PDF,以及 GeneratePdfJob 支援 CodeIgniter Tasks 或第三方 Queue 套件的背景處理。


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.

核心元件

元件 功能
Services::pdf() 取得 DocumentFactory 服務實例(單例)
pdf() helper 全域 helper,快速建立並輸出 PDF
pdf_document() helper 回傳 Document 物件供進一步操作
GeneratePdfJob 背景 PDF 生成任務(CI4 Tasks 相容)

安裝

composer require nextpdf/codeigniter

app/Config/Autoload.php 中啟用套件提供的 Helper:

// app/Config/Autoload.php
public $helpers = ['nextpdf'];  // 啟用 pdf() 與 pdf_document() helper

或在控制器中按需載入:

helper('nextpdf');

快速開始

<?php

declare(strict_types=1);

namespace App\Controllers;

use CodeIgniter\HTTP\ResponseInterface;

final class InvoiceController extends BaseController
{
    public function download(int $id): ResponseInterface
    {
        // 使用 pdf() helper 快速生成並輸出
        $pdfBytes = pdf_document()
            ->addPage()
            ->text("Invoice #{$id}", x: 20, y: 30)
            ->output();

        return $this->response
            ->setHeader('Content-Type', 'application/pdf')
            ->setHeader('Content-Disposition', "attachment; filename=\"invoice-{$id}.pdf\"")
            ->setBody($pdfBytes);
    }
}

Services 工廠

use Config\Services;
use NextPDF\Core\Contracts\DocumentFactoryInterface;

// 取得 DocumentFactory 服務(預設為共享單例)
$factory = Services::pdf();

// 建立非共享實例(每次呼叫返回新實例)
$factory = Services::pdf(getShared: false);

// 直接透過 DI 取得
$factory = service('pdf');

設定

建立 app/Config/NextPdf.php 設定檔:

<?php

declare(strict_types=1);

namespace Config;

use CodeIgniter\Config\BaseConfig;

final class NextPdf extends BaseConfig
{
    /** @var non-empty-string */
    public string $pageSize = 'A4';

    /** @var 'portrait'|'landscape' */
    public string $orientation = 'portrait';

    public float $marginMm = 15.0;

    /** @var non-empty-string|null */
    public ?string $author = null;

    public bool $spectrumEnabled = false;

    /** @var non-empty-string|null */
    public ?string $spectrumBinary = null;
}

參見