Skip to content

Riferimento Interface

Il modulo Contracts (TcpdfNext\\Contracts) definisce le interface condivise contro le quali tutti i moduli TCPDF-Next programmano. Dipendendo da contratti anziché da classi concrete puoi sostituire test double, creare implementazioni alternative e mantenere un'API pubblica stabile tra versioni principali.


PdfDocumentInterface

Namespace: TcpdfNext\\Contracts\\PdfDocumentInterface

Il contratto API primario implementato da Document. Qualsiasi classe che soddisfa questa interface può essere utilizzata come sostituto drop-in per il modello di documento integrato.

Metodi

pageSize(PageSize $size): static
Imposta le dimensioni predefinite della pagina per le nuove pagine.
orientation(Orientation $orientation): static
Imposta l'orientamento predefinito della pagina.
margin(Margin $margin): static
Imposta i margini predefiniti della pagina.
metadata(?string $title = null, ?string $author = null, ?string $subject = null, ?string $keywords = null, ?string $creator = null): static
Imposta i metadati a livello di documento. Tutti i parametri sono opzionali; passa solo quelli che vuoi impostare.
addPage(?PageSize $pageSize = null, ?Orientation $orientation = null): static
Aggiunge una nuova pagina, opzionalmente sovrascrivendo le impostazioni predefinite per questa pagina.
font(string $family, float $size = 12.0, string $style = ''): static
Seleziona un font per nome famiglia, dimensione e stile.
text(string $content): static
Scrive una riga di testo alla posizione corrente del cursore.
output(OutputDestination $destination = OutputDestination::String, ?string $filename = null, ?string $path = null): string|bool
Renderizza il PDF alla destinazione scelta.
currentPage(): int
Restituisce il numero della pagina corrente (basato su 1).
pageCount(): int
Restituisce il numero totale di pagine.

Esempio

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

Definisce caricamento, registrazione, subsetting e ricerca metriche dei font. Il FontManager integrato implementa questa interface, ma puoi fornire un'implementazione personalizzata per sorgenti font specializzate.

Metodi

registerFont(string $path, string $alias = ''): static
Registra un file font TrueType o OpenType. Se alias è vuoto, viene utilizzato il nome famiglia font dal file.
hasFont(string $family, string $style = ''): bool
Verifica se è disponibile una combinazione famiglia font e stile.
getFont(string $family, string $style = ''): FontInfo
Restituisce un oggetto FontInfo readonly con metriche per il font specificato.
stringWidth(string $text, string $family, float $size, string $style = ''): float
Calcola la larghezza di una stringa in unità utente.
subset(string $family, string $style, string $chars): string
Crea un binario font subset contenente solo i glifi necessari per i caratteri specificati.
registeredFamilies(): array
Restituisce un elenco di tutti i nomi famiglia font registrati.

Esempio

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

Definisce il contratto per qualsiasi fornitore di firma digitale. Implementa questa interface per integrarti con certificati software, key vault basati su cloud o moduli di sicurezza hardware (HSM).

Metodi

sign(string $data): string
Firma i dati specificati e restituisce i byte grezzi della firma CMS/CAdES.
certificate(): string
Restituisce il certificato di firma codificato DER.
chain(): array
Restituisce un array di certificati intermedi codificati DER (dal firmatario alla root).
estimatedSize(): int
Restituisce la dimensione massima stimata (in byte) della firma. Utilizzato per pre-allocare il placeholder ByteRange.
algorithm(): string
Restituisce l'OID o il nome dell'algoritmo di firma (es., 'sha256WithRSAEncryption').

Esempio

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

Estende SignerInterface per moduli di sicurezza hardware che non espongono mai la chiave privata. Invece di firmare dati grezzi, l'HSM firma un digest pre-calcolato.

Metodi

Tutti i metodi da SignerInterface, più:

signDigest(string $digest, string $algorithm): string
Firma un digest del messaggio pre-calcolato. Il parametro algorithm identifica l'hash utilizzato (es., 'sha256').

Esempio

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

Utilizzo delle Interface per i Test

Tutte e quattro le interface sono progettate per essere facilmente mockabili con PHPUnit o 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);
    }
}

Vedi Anche

Rilasciato sotto licenza LGPL-3.0-or-later.