Skip to content

Interfaces Reference

The Contracts module (TcpdfNext\Contracts) defines the shared interfaces that all TCPDF-Next modules program against. By depending on contracts rather than concrete classes you can substitute test doubles, create alternative implementations, and maintain a stable public API across major versions.


PdfDocumentInterface

Namespace: TcpdfNext\Contracts\PdfDocumentInterface

The primary API contract implemented by Document. Any class that fulfills this interface can be used as a drop-in replacement for the built-in document model.

Methods

pageSize(PageSize $size): static
Set the default page size for new pages.
orientation(Orientation $orientation): static
Set the default page orientation.
margin(Margin $margin): static
Set the default page margins.
metadata(?string $title = null, ?string $author = null, ?string $subject = null, ?string $keywords = null, ?string $creator = null): static
Set document-level metadata. All parameters are optional; pass only the ones you want to set.
addPage(?PageSize $pageSize = null, ?Orientation $orientation = null): static
Add a new page, optionally overriding the defaults for this page.
font(string $family, float $size = 12.0, string $style = ''): static
Select a font by family name, size, and style.
text(string $content): static
Write a line of text at the current cursor position.
output(OutputDestination $destination = OutputDestination::String, ?string $filename = null, ?string $path = null): string|bool
Render the PDF to the chosen destination.
currentPage(): int
Return the current page number (1-based).
pageCount(): int
Return the total number of pages.

Example

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

Defines font loading, registration, subsetting, and metric lookup. The built-in FontManager implements this interface, but you can provide a custom implementation for specialized font sources.

Methods

registerFont(string $path, string $alias = ''): static
Register a TrueType or OpenType font file. If alias is empty, the font family name from the file is used.
hasFont(string $family, string $style = ''): bool
Check whether a font family and style combination is available.
getFont(string $family, string $style = ''): FontInfo
Return a readonly FontInfo object with metrics for the specified font.
stringWidth(string $text, string $family, float $size, string $style = ''): float
Calculate the width of a string in user units.
subset(string $family, string $style, string $chars): string
Create a subset font binary containing only the glyphs needed for the given characters.
registeredFamilies(): array
Return a list of all registered font family names.

Example

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

Defines the contract for any digital signature provider. Implement this interface to integrate with software certificates, cloud-based key vaults, or hardware security modules (HSMs).

Methods

sign(string $data): string
Sign the given data and return the raw CMS/CAdES signature bytes.
certificate(): string
Return the DER-encoded signing certificate.
chain(): array
Return an array of DER-encoded intermediate certificates (from signer to root).
estimatedSize(): int
Return the estimated maximum size (in bytes) of the signature. Used to pre-allocate the ByteRange placeholder.
algorithm(): string
Return the signing algorithm OID or name (e.g., 'sha256WithRSAEncryption').

Example

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(/* ... */);
        // Return raw signature bytes
    }

    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

Extends SignerInterface for hardware security modules that never expose the private key. Instead of signing raw data, the HSM signs a pre-computed digest.

Methods

All methods from SignerInterface, plus:

signDigest(string $digest, string $algorithm): string
Sign a pre-computed message digest. The algorithm parameter identifies the hash used (e.g., 'sha256').

Example

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

Using Interfaces for Testing

All four interfaces are designed to be easily mockable with PHPUnit or 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);
    }
}

See Also

  • API Overview -- All packages at a glance
  • Enums Reference -- Enums used by these interfaces (Orientation, Alignment, OutputDestination)
  • Document API -- The concrete class that implements PdfDocumentInterface
  • Security Guide -- Full guide to encryption and digital signatures

Released under the LGPL-3.0-or-later License.