Skip to content

Referencia de Interfaces

El módulo Contracts (TcpdfNext\Contracts) define las interfaces compartidas contra las que programan todos los módulos de TCPDF-Next. Al depender de contratos en lugar de clases concretas puedes sustituir dobles de prueba, crear implementaciones alternativas y mantener una API pública estable entre versiones mayores.


PdfDocumentInterface

Namespace: TcpdfNext\Contracts\PdfDocumentInterface

El contrato API principal implementado por Document. Cualquier clase que cumpla esta interface puede usarse como reemplazo directo del modelo de documento integrado.

Métodos

pageSize(PageSize $size): static
Establecer el tamaño de página predeterminado para nuevas páginas.
orientation(Orientation $orientation): static
Establecer la orientación de página predeterminada.
margin(Margin $margin): static
Establecer los márgenes de página predeterminados.
metadata(?string $title = null, ?string $author = null, ?string $subject = null, ?string $keywords = null, ?string $creator = null): static
Establecer metadatos a nivel de documento. Todos los parámetros son opcionales; pasa solo los que quieras establecer.
addPage(?PageSize $pageSize = null, ?Orientation $orientation = null): static
Agregar una nueva página, opcionalmente sobrescribiendo los valores predeterminados para esta página.
font(string $family, float $size = 12.0, string $style = ''): static
Seleccionar una fuente por nombre de familia, tamaño y estilo.
text(string $content): static
Escribir una línea de texto en la posición actual del cursor.
output(OutputDestination $destination = OutputDestination::String, ?string $filename = null, ?string $path = null): string|bool
Renderizar el PDF al destino elegido.
currentPage(): int
Retornar el número de página actual (basado en 1).
pageCount(): int
Retornar el número total de páginas.

Ejemplo

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

Define la carga, registro, subsetting y búsqueda de métricas de fuentes. El FontManager integrado implementa esta interface, pero puedes proporcionar una implementación personalizada para fuentes de origen especializado.

Métodos

registerFont(string $path, string $alias = ''): static
Registrar un archivo de fuente TrueType u OpenType. Si alias está vacío, se usa el nombre de familia de fuente del archivo.
hasFont(string $family, string $style = ''): bool
Verificar si una combinación de familia y estilo de fuente está disponible.
getFont(string $family, string $style = ''): FontInfo
Retornar un objeto FontInfo readonly con métricas para la fuente especificada.
stringWidth(string $text, string $family, float $size, string $style = ''): float
Calcular el ancho de una cadena en unidades de usuario.
subset(string $family, string $style, string $chars): string
Crear un binario de subconjunto de fuente conteniendo solo los glifos necesarios para los caracteres dados.
registeredFamilies(): array
Retornar una lista de todos los nombres de familia de fuentes registrados.

Ejemplo

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

Define el contrato para cualquier proveedor de firma digital. Implementa esta interface para integrarte con certificados de software, bóvedas de claves en la nube o módulos de seguridad de hardware (HSMs).

Métodos

sign(string $data): string
Firmar los datos proporcionados y retornar los bytes de firma CMS/CAdES sin procesar.
certificate(): string
Retornar el certificado de firma codificado en DER.
chain(): array
Retornar un array de certificados intermedios codificados en DER (del firmante a la raíz).
estimatedSize(): int
Retornar el tamaño máximo estimado (en bytes) de la firma. Se usa para preasignar el placeholder de ByteRange.
algorithm(): string
Retornar el OID o nombre del algoritmo de firma (ej., 'sha256WithRSAEncryption').

Ejemplo

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

Extiende SignerInterface para módulos de seguridad de hardware que nunca exponen la clave privada. En lugar de firmar datos sin procesar, el HSM firma un digest precomputado.

Métodos

Todos los métodos de SignerInterface, más:

signDigest(string $digest, string $algorithm): string
Firmar un digest de mensaje precomputado. El parámetro algorithm identifica el hash usado (ej., 'sha256').

Ejemplo

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

Uso de interfaces para testing

Las cuatro interfaces están diseñadas para ser fácilmente mockeables 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);
    }
}

Ver también

Distribuido bajo la licencia LGPL-3.0-or-later.