tc-lib-pdf-image

Technical overview and integration notes for tc-lib-pdf-image

Overview

tc-lib-pdf-image handles image import, conversion, and embedding structures used by PDF generators.

It isolates image-pipeline concerns such as format handling, normalization, and object generation, which reduces complexity in document-level code and improves testability.

Repository and API Docs

Project Metadata

ItemValue
Namespace\Com\Tecnick\Pdf\Image
LicenseGNU LGPL v3

Installation

composer require tecnickcom/tc-lib-pdf-image

Where It Fits

Integrate when PDF workflows include external media assets that must be normalized and embedded safely.

Features

Import Support

  • Native handling for PNG and JPEG
  • Additional format handling through GD processing paths
  • Transparency and palette-related metadata handling

PDF Integration

  • Image caching keys for repeated assets
  • Alternate image support for print/display contexts
  • Output helpers for embedding image objects
  • getImageDimensionsByKey() returns the stored dimensions of an already imported image, optionally scaled to a target box
  • Missing width or height is derived automatically from the source image, preserving its aspect ratio

File Access

The importer takes a configured \Com\Tecnick\File\File helper instead of a plain options array, so host and path allowlists are owned by the calling application:

$fileHelper = new \Com\Tecnick\File\File(
    allowedHosts: ['example.com', 'cdn.example.com'],
    allowedPaths: ['/srv/app/images', __DIR__ . '/images'],
);

$img = new \Com\Tecnick\Pdf\Image\Import(
    kunit: 1.0,
    encrypt: $encrypt,
    fileHelper: $fileHelper,
);

An existing importer can be rebound to a different helper with withFileHelper().

Persistent Image Cache

Processing an image (decode, resize, re-encode, alpha-mask extraction) is the expensive part of importing. By default the result is cached in memory for the lifetime of the Import instance, so reusing the same image within one document is cheap.

To reuse processed images across documents and processes, inject an optional external cache. The library ships only the contract — \Com\Tecnick\Pdf\Image\ImageCacheInterface — and you provide the backend (filesystem, APCu, Redis, a PSR-16 cache, and so on):

interface ImageCacheInterface
{
    /** @return array|null Stored image data, or null on a miss. */
    public function get(string $key): ?array;

    public function set(string $key, array $data): void;
}

Pass an implementation as the imageCache constructor argument; the default null keeps the in-memory-only behavior:

$img = new \Com\Tecnick\Pdf\Image\Import(
    kunit: 1.0,
    encrypt: $encrypt,
    fileHelper: $fileHelper,
    imageCache: $myCache, // any ImageCacheInterface implementation
);

On a miss the processed data is written through to the cache; on a later run a hit short-circuits all processing. For local files the persistent key folds in the file modification time and size, so editing an image in place invalidates its stale entry automatically.

A minimal filesystem-backed implementation:

use Com\Tecnick\Pdf\Image\ImageCacheInterface;

final class FilesystemImageCache implements ImageCacheInterface
{
    public function __construct(private readonly string $dir) {}

    public function get(string $key): ?array
    {
        $file = $this->dir . '/' . hash('xxh128', $key) . '.cache';
        if (!is_file($file)) {
            return null;
        }
        $data = unserialize((string) file_get_contents($file), ['allowed_classes' => false]);

        return is_array($data) ? $data : null;
    }

    public function set(string $key, array $data): void
    {
        $file = $this->dir . '/' . hash('xxh128', $key) . '.cache';
        file_put_contents($file, serialize($data), LOCK_EX);
    }
}

The cache store is a trust boundary: stored bytes are embedded verbatim into generated PDFs, so use a store only your application can write to, and deserialize with object restoration disabled (['allowed_classes' => false]).

Integration Notes

  • Validate image dimensions and type before embedding to avoid memory spikes.
  • Standardize source DPI assumptions to keep layout predictable.
  • Sanitize SVG and untrusted image inputs in security-sensitive systems.

Requirements

  • PHP 8.2 or later
  • Extensions: gd, zlib
  • Package dependencies: tecnickcom/tc-lib-file, tecnickcom/tc-lib-color, tecnickcom/tc-lib-pdf-encrypt
  • Composer

Example

<?php

require_once __DIR__ . '/vendor/autoload.php';

$encrypt = new \Com\Tecnick\Pdf\Encrypt\Encrypt();
$fileHelper = new \Com\Tecnick\File\File(
    allowedPaths: [__DIR__],
);

$img = new \Com\Tecnick\Pdf\Image\Import(
    kunit: 1.0,
    encrypt: $encrypt,
    fileHelper: $fileHelper,
);
$imageId = $img->add(__DIR__ . '/image.png');

// The cache key of an imported image gives access to its stored data and dimensions.
$key = $img->getKey(__DIR__ . '/image.png');

var_dump($imageId, $img->getImageDimensionsByKey($key));

Development and Packaging

  • QA and local checks: make deps, make help, make qa
  • Packaging: make rpm, make deb

Support and Contribution

 

© 2004-2026 – Nicola Asuni - Tecnick.com - All rights reserved.
sponsor - legal notice - privacy