Skip to content

インターフェースリファレンス

Contractsモジュール(TcpdfNext\Contracts)は、すべてのTCPDF-Nextモジュールがプログラミングする対象となる共有インターフェースを定義しています。具体的なクラスではなくコントラクトに依存することで、テストダブルの代入、代替実装の作成、およびメジャーバージョン間での安定したパブリックAPIの維持が可能になります。


PdfDocumentInterface

名前空間: TcpdfNext\Contracts\PdfDocumentInterface

Documentが実装する主要なAPIコントラクトです。このインターフェースを満たすクラスであれば、組み込みのドキュメントモデルのドロップイン代替として使用できます。

メソッド

pageSize(PageSize $size): static
新しいページのデフォルトページサイズを設定します。
orientation(Orientation $orientation): static
デフォルトのページ方向を設定します。
margin(Margin $margin): static
デフォルトのページマージンを設定します。
metadata(?string $title = null, ?string $author = null, ?string $subject = null, ?string $keywords = null, ?string $creator = null): static
ドキュメントレベルのメタデータを設定します。すべてのパラメータはオプションです。設定したいもののみ渡してください。
addPage(?PageSize $pageSize = null, ?Orientation $orientation = null): static
新しいページを追加します。オプションでこのページのデフォルトを上書きできます。
font(string $family, float $size = 12.0, string $style = ''): static
ファミリ名、サイズ、スタイルでフォントを選択します。
text(string $content): static
現在のカーソル位置にテキスト行を書き込みます。
output(OutputDestination $destination = OutputDestination::String, ?string $filename = null, ?string $path = null): string|bool
選択した出力先にPDFをレンダリングします。
currentPage(): int
現在のページ番号(1始まり)を返します。
pageCount(): int
総ページ数を返します。

サンプル

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

名前空間: TcpdfNext\Contracts\FontManagerInterface

フォントの読み込み、登録、サブセット化、メトリクス参照を定義します。組み込みのFontManagerがこのインターフェースを実装していますが、特殊なフォントソース用にカスタム実装を提供することもできます。

メソッド

registerFont(string $path, string $alias = ''): static
TrueTypeまたはOpenTypeフォントファイルを登録します。aliasが空の場合、ファイルのフォントファミリ名が使用されます。
hasFont(string $family, string $style = ''): bool
フォントファミリとスタイルの組み合わせが利用可能かどうかを確認します。
getFont(string $family, string $style = ''): FontInfo
指定されたフォントのメトリクスを持つ読み取り専用FontInfoオブジェクトを返します。
stringWidth(string $text, string $family, float $size, string $style = ''): float
ユーザー単位で文字列の幅を計算します。
subset(string $family, string $style, string $chars): string
指定された文字に必要なグリフのみを含むサブセットフォントバイナリを作成します。
registeredFamilies(): array
登録されたすべてのフォントファミリ名のリストを返します。

サンプル

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

名前空間: TcpdfNext\Contracts\SignerInterface

デジタル署名プロバイダのコントラクトを定義します。ソフトウェア証明書、クラウドベースの鍵保管庫、またはハードウェアセキュリティモジュール(HSM)と統合するために、このインターフェースを実装してください。

メソッド

sign(string $data): string
指定されたデータに署名し、生のCMS/CAdES署名バイトを返します。
certificate(): string
DERエンコードされた署名証明書を返します。
chain(): array
DERエンコードされた中間証明書の配列を返します(署名者からルートの順)。
estimatedSize(): int
署名の推定最大サイズ(バイト単位)を返します。ByteRangeプレースホルダの事前確保に使用されます。
algorithm(): string
署名アルゴリズムのOIDまたは名前(例:'sha256WithRSAEncryption')を返します。

サンプル

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(/* ... */);
        // 生の署名バイトを返す
    }

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

HsmSignerInterface

名前空間: TcpdfNext\Contracts\HsmSignerInterface

秘密鍵を公開しないハードウェアセキュリティモジュール用にSignerInterfaceを拡張します。生データに署名する代わりに、HSMは事前計算されたダイジェストに署名します。

メソッド

SignerInterfaceのすべてのメソッドに加えて:

signDigest(string $digest, string $algorithm): string
事前計算されたメッセージダイジェストに署名します。algorithmパラメータは使用されたハッシュを特定します(例:'sha256')。

サンプル

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'; }
}

テスト用のインターフェースの使用

4つのインターフェースはすべて、PHPUnitや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);
    }
}

関連項目

LGPL-3.0-or-later ライセンスの下で公開されています。