Skip to content

Tham chiếu Interface

Module Contracts (TcpdfNext\Contracts) định nghĩa interface dùng chung mà mọi module TCPDF-Next lập trình theo. Bằng cách phụ thuộc vào contract thay vì class cụ thể, bạn có thể thay thế test double, tạo implement thay thế và duy trì API public ổn định qua các phiên bản chính.


PdfDocumentInterface

Namespace: TcpdfNext\Contracts\PdfDocumentInterface

Contract API chính được implement bởi Document. Bất kỳ class nào đáp ứng interface này có thể được dùng thay thế cho mô hình document tích hợp.

Method

pageSize(PageSize $size): static
Đặt kích thước trang mặc định cho trang mới.
orientation(Orientation $orientation): static
Đặt hướng trang mặc định.
margin(Margin $margin): static
Đặt margin trang mặc định.
metadata(?string $title = null, ?string $author = null, ?string $subject = null, ?string $keywords = null, ?string $creator = null): static
Đặt metadata cấp document. Mọi tham số đều tùy chọn; chỉ truyền những cái bạn muốn đặt.
addPage(?PageSize $pageSize = null, ?Orientation $orientation = null): static
Thêm trang mới, tùy chọn ghi đè mặc định cho trang này.
font(string $family, float $size = 12.0, string $style = ''): static
Chọn font theo tên family, kích thước và style.
text(string $content): static
Viết một dòng text tại vị trí con trỏ hiện tại.
output(OutputDestination $destination = OutputDestination::String, ?string $filename = null, ?string $path = null): string|bool
Render PDF đến đích chọn.
currentPage(): int
Trả về số trang hiện tại (1-based).
pageCount(): int
Trả về tổng số trang.

Ví dụ

php
use TcpdfNext\Contracts\PdfDocumentInterface;
use TcpdfNext\Contracts\OutputDestination;

function generateReport(PdfDocumentInterface $pdf): string
{
    return $pdf
        ->addPage()
        ->font('Helvetica', size: 14)
        ->text('Quarterly Report')
        ->output(OutputDestination::String);
}

FontManagerInterface

Namespace: TcpdfNext\Contracts\FontManagerInterface

Định nghĩa tải, đăng ký, subsetting và tra cứu metric font. FontManager tích hợp implement interface này, nhưng bạn có thể cung cấp implement tùy chỉnh cho nguồn font chuyên biệt.

Method

registerFont(string $path, string $alias = ''): static
Đăng ký file font TrueType hoặc OpenType. Nếu alias trống, tên font family từ file được dùng.
hasFont(string $family, string $style = ''): bool
Kiểm tra tổ hợp font family và style có sẵn hay không.
getFont(string $family, string $style = ''): FontInfo
Trả về object FontInfo readonly với metric cho font chỉ định.
stringWidth(string $text, string $family, float $size, string $style = ''): float
Tính chiều rộng chuỗi tính bằng đơn vị người dùng.
subset(string $family, string $style, string $chars): string
Tạo subset font nhị phân chỉ chứa glyph cần cho ký tự cho trước.
registeredFamilies(): array
Trả về danh sách mọi tên font family đã đăng ký.

Ví dụ

php
use TcpdfNext\Contracts\FontManagerInterface;

function addCustomFonts(FontManagerInterface $fonts): void
{
    $fonts->registerFont('/fonts/NotoSans-Regular.ttf', 'NotoSans');
    $fonts->registerFont('/fonts/NotoSans-Bold.ttf', 'NotoSans');

    if ($fonts->hasFont('NotoSans', 'B')) {
        $info = $fonts->getFont('NotoSans', 'B');
        echo "Ascender: {$info->ascender}";
    }
}

SignerInterface

Namespace: TcpdfNext\Contracts\SignerInterface

Định nghĩa contract cho bất kỳ nhà cung cấp chữ ký số nào. Implement interface này để tích hợp với chứng chỉ phần mềm, cloud-based key vault hoặc hardware security module (HSM).

Method

sign(string $data): string
Ký dữ liệu cho trước và trả về byte chữ ký CMS/CAdES thô.
certificate(): string
Trả về chứng chỉ ký mã hóa DER.
chain(): array
Trả về mảng chứng chỉ trung gian mã hóa DER (từ signer đến root).
estimatedSize(): int
Trả về kích thước tối đa ước tính (byte) của chữ ký. Dùng để cấp phát trước placeholder ByteRange.
algorithm(): string
Trả về OID hoặc tên thuật toán ký (vd: 'sha256WithRSAEncryption').

Ví dụ

php
use TcpdfNext\Contracts\SignerInterface;

class FileSigner implements SignerInterface
{
    public function __construct(
        private readonly string $certPath,
        private readonly string $keyPath,
        private readonly string $password,
    ) {}

    public function sign(string $data): string
    {
        $cert = file_get_contents($this->certPath);
        $key = openssl_pkey_get_private(
            file_get_contents($this->keyPath),
            $this->password,
        );
        openssl_pkcs7_sign(/* ... */);
        // Trả về byte chữ ký thô
    }

    public function certificate(): string { /* ... */ }
    public function chain(): array { return []; }
    public function estimatedSize(): int { return 8192; }
    public function algorithm(): string { return 'sha256WithRSAEncryption'; }
}

HsmSignerInterface

Namespace: TcpdfNext\Contracts\HsmSignerInterface

Mở rộng SignerInterface cho hardware security module không bao giờ lộ private key. Thay vì ký dữ liệu thô, HSM ký digest đã tính trước.

Method

Mọi method từ SignerInterface, cộng thêm:

signDigest(string $digest, string $algorithm): string
Ký message digest đã tính trước. Tham số algorithm xác định hash đã dùng (vd: 'sha256').

Ví dụ

php
use TcpdfNext\Contracts\HsmSignerInterface;

class AwsCloudHsmSigner implements HsmSignerInterface
{
    public function __construct(
        private readonly string $keyId,
        private readonly AwsKmsClient $kms,
        private readonly string $certPem,
    ) {}

    public function sign(string $data): string
    {
        $digest = hash('sha256', $data, binary: true);
        return $this->signDigest($digest, 'sha256');
    }

    public function signDigest(string $digest, string $algorithm): string
    {
        $result = $this->kms->sign([
            'KeyId' => $this->keyId,
            'Message' => $digest,
            'MessageType' => 'DIGEST',
            'SigningAlgorithm' => 'RSASSA_PKCS1_V1_5_SHA_256',
        ]);
        return $result['Signature'];
    }

    public function certificate(): string { return $this->certPem; }
    public function chain(): array { return []; }
    public function estimatedSize(): int { return 16384; }
    public function algorithm(): string { return 'sha256WithRSAEncryption'; }
}

Dùng Interface cho Testing

Cả bốn interface được thiết kế để dễ mock với PHPUnit hoặc Mockery.

php
use PHPUnit\Framework\TestCase;
use TcpdfNext\Contracts\FontManagerInterface;

class TextRendererTest extends TestCase
{
    public function testCalculatesWidth(): void
    {
        $fonts = $this->createMock(FontManagerInterface::class);
        $fonts->method('hasFont')->willReturn(true);
        $fonts->method('stringWidth')
            ->with('Hello', 'Helvetica', 12.0, '')
            ->willReturn(26.64);

        $renderer = new TextRenderer($fonts);
        $this->assertEqualsWithDelta(26.64, $renderer->width('Hello'), 0.01);
    }
}

Xem thêm

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