Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8",
"roave/security-advisories": "dev-latest"
"roave/security-advisories": "dev-latest",
"signerphp/pdf-core": "^0.1.2"
},
"autoload": {
"psr-4": {
Expand Down
232 changes: 232 additions & 0 deletions src/Pdf/SignerPhpCoreXObjectResourceBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
<?php

// SPDX-FileCopyrightText: 2026 LibreSign
// SPDX-License-Identifier: AGPL-3.0-or-later

declare(strict_types=1);

namespace LibreSign\XObjectTemplate\Pdf;

use Closure;
use InvalidArgumentException;
use Throwable;
use SignerPHP\PdfCore\PdfDocument;
use SignerPHP\PdfCore\PdfValue\PDFValueReference;
use SignerPHP\PdfCore\PdfValue\PDFValueString;

/**
* Materializes Unicode fonts and compiled images in the signature PDF document.
*
* The exported resource array cannot contain internal font or image placeholders.
* Call resourcesBuilder() when constructing an AppearanceXObject supporting resource builders.
*/
final readonly class SignerPhpCoreXObjectResourceBuilder
{
private PdfImageEmbedderInterface $imageEmbedder;

public function __construct(?PdfImageEmbedderInterface $imageEmbedder = null)
{
$this->imageEmbedder = $imageEmbedder ?? new FilesystemPdfImageEmbedder();
}

/**
* @return Closure(PdfDocument, array<string, mixed>): array<string, mixed>
*/
public function resourcesBuilder(): Closure
{
return $this->materialize(...);
}

/**
* @param array<string, mixed> $resources
* @return array<string, mixed>
*/
public function materialize(PdfDocument $document, array $resources): array
{
$fonts = $this->requireDictionary($resources['Font'] ?? [], 'Font');
$images = $this->requireDictionary($resources['XObject'] ?? [], 'XObject');
$preparedImages = $this->prepareImages($images);
// A failed resource must not leave unreachable objects or consume IDs in the signing document.
$originalObjects = $document->getPdfObjects();
$originalMaxOid = $document->getMaxOid();
try {
$resources['Font'] = $this->materializeFonts($document, $fonts);

if ($images !== []) {
$resources['XObject'] = $this->materializeImages($document, $images, $preparedImages);
}

return $resources;
} catch (Throwable $error) {
$document->setPdfObjects($originalObjects);
$document->setMaxOid($originalMaxOid);
throw $error;
}
}

/**
* @return array<string, mixed>
*/
private function requireDictionary(mixed $value, string $name): array
{
if (!is_array($value)) {
throw new InvalidArgumentException(sprintf('XObject %s resources must be a dictionary.', $name));
}
foreach (array_keys($value) as $key) {
if (!is_string($key)) {
throw new InvalidArgumentException(sprintf('XObject %s resources must have string keys.', $name));
}
}
/** @var array<string, mixed> $value */
return $value;
}

/**
* @param array<string, mixed> $images
* @return array<string, EmbeddedPdfImage>
*/
private function prepareImages(array $images): array
{
$prepared = [];
foreach ($images as $alias => $resource) {
if (!is_array($resource) || !array_key_exists('Source', $resource)) {
continue;
}
if (!is_string($resource['Source']) || $resource['Source'] === '') {
throw new InvalidArgumentException('Image XObject requires a non-empty Source.');
}
$prepared[$alias] = $this->imageEmbedder->embed($resource['Source']);
}
return $prepared;
}

/**
* @param array<string, mixed> $fonts
* @return array<string, mixed>
*/
private function materializeFonts(PdfDocument $document, array $fonts): array
{
$makeDictionary = fn (array $dictionary): string => $this->createDictionary(
$document,
$this->requireDictionary($dictionary, 'generated'),
);
$makeStream = fn (array $dictionary, string $data): string => $this->createStream(
$document,
$this->requireDictionary($dictionary, 'generated'),
$data,
);
$writer = new UnicodeFontPdfWriter($makeStream, $makeDictionary);

foreach ($fonts as $alias => $font) {
if (!is_array($font) || !array_key_exists('__TrueTypeFont', $font)) {
continue;
}
$reference = $writer->createWithFactories(
$this->requireDictionary($font, 'Font'),
$makeDictionary,
$makeStream,
);
$fonts[$alias] = $this->asReference($reference);
}
return $fonts;
}

/**
* @param array<string, mixed> $images
* @param array<string, EmbeddedPdfImage> $preparedImages
* @return array<string, mixed>
*/
private function materializeImages(PdfDocument $document, array $images, array $preparedImages): array
{
foreach ($preparedImages as $alias => $image) {
$images[$alias] = $this->createImageObject($document, $image);
}
return $images;
}

private function createImageObject(PdfDocument $document, EmbeddedPdfImage $image): PDFValueReference
{
$dictionary = $image->dictionary;
if ($image->softMask !== null) {
$dictionary['SMask'] = $this->createStream(
$document,
$image->softMask->dictionary,
$image->softMask->stream,
);
}
return $this->asReference($this->createStream($document, $dictionary, $image->stream));
}

/**
* @param array<string, mixed> $dictionary
*/
private function createDictionary(PdfDocument $document, array $dictionary): string
{
$object = $document->createObject($this->convertDictionary($dictionary));
return sprintf('%d 0 R', $object->getOid());
}

/**
* @param array<string, mixed> $dictionary
*/
private function createStream(PdfDocument $document, array $dictionary, string $bytes): string
{
$object = $document->createObject($this->convertDictionary($dictionary));
// Resource factories already supply the bytes in the declared filter encoding.
$object->setStream($bytes, true);
$object->setField('Length', strlen($bytes));
return sprintf('%d 0 R', $object->getOid());
}

/**
* @param array<string, mixed> $dictionary
* @return array<string, mixed>
*/
/** @psalm-suppress MixedAssignment Generated PDF resources contain dynamic scalar and nested values. */
private function convertDictionary(array $dictionary): array
{
$converted = [];
foreach ($dictionary as $key => $value) {
if ($key === 'CIDSystemInfo' && is_array($value)) {
$converted[$key] = [
'Registry' => new PDFValueString($value['Registry']),
'Ordering' => new PDFValueString($value['Ordering']),
'Supplement' => $value['Supplement'],
];
continue;
}
$converted[$key] = $this->convertValue($value);
}
return $converted;
}

/**
* @return PDFValueReference|array<array-key, mixed>|string|int|float|bool
* @psalm-suppress MixedAssignment Dynamic PDF dictionaries are validated as they are converted.
*/
private function convertValue(mixed $value): PDFValueReference|array|string|int|float|bool
{
if (is_string($value) && preg_match('/^[1-9][0-9]* 0 R$/D', $value) === 1) {
return $this->asReference($value);
}
if (is_string($value) || is_int($value) || is_float($value) || is_bool($value)) {
return $value;
}
if (!is_array($value)) {
throw new InvalidArgumentException('Unsupported value in generated PDF resource.');
}
$converted = [];
foreach ($value as $key => $item) {
$converted[$key] = $this->convertValue($item);
}
return $converted;
}

private function asReference(string $reference): PDFValueReference
{
if (preg_match('/^[1-9][0-9]* 0 R$/D', $reference) !== 1) {
throw new InvalidArgumentException('Invalid generated PDF object reference.');
}
return new PDFValueReference(strtok($reference, ' '));
}
}
44 changes: 30 additions & 14 deletions src/Pdf/UnicodeFontPdfWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,44 @@ public function __construct(
*/
public function create(array &$objects, array $resource): string
{
return $this->createWithFactories(
$resource,
function (array $dictionary) use (&$objects): string {
return $this->createDictionary($objects, $dictionary);
},
function (array $dictionary, string $data) use (&$objects): string {
return $this->createStream($objects, $dictionary, $data);
},
);
}

/**
* Materialize a Type 0 font using the destination document's object allocator.
*
* @param array<string, mixed> $resource
* @param Closure(array<string, mixed>): string $dictionaryFactory
* @param Closure(array<string, mixed>, string): string $streamFactory
*/
public function createWithFactories(
array $resource,
Closure $dictionaryFactory,
Closure $streamFactory,
): string {
$font = $resource['__TrueTypeFont'] ?? null;
if (!$font instanceof TrueTypeFont) {
throw new InvalidArgumentException('Invalid Unicode font resource.');
}
$mappings = $this->requireMappings($resource['__Mappings'] ?? null);

$fontName = 'LibreSignUnicode' . substr(hash('sha256', $font->fontData()), 0, 12);
$fontRef = $this->createFontFile($objects, $font->fontData());
[$widths, $cidMap, $cmapEntries] = $this->collectMappings($font, $mappings);
$cidMapRef = $this->createStream($objects, [], $cidMap);
$toUnicodeRef = $this->createStream($objects, [], $this->createToUnicode($cmapEntries));
$fontData = $font->fontData();
$fontRef = $streamFactory(['Length1' => strlen($fontData)], $fontData);
$cidMapRef = $streamFactory([], $cidMap);
$toUnicodeRef = $streamFactory([], $this->createToUnicode($cmapEntries));
$descriptor = $font->descriptor($fontName, $fontRef);
$descriptorRef = $this->createDictionary($objects, $descriptor);
$cidFontRef = $this->createDictionary($objects, [
$descriptorRef = $dictionaryFactory($descriptor);
$cidFontRef = $dictionaryFactory([
'Type' => '/Font',
'Subtype' => '/CIDFontType2',
'BaseFont' => '/' . $fontName,
Expand All @@ -54,7 +78,7 @@ public function create(array &$objects, array $resource): string
'DW' => 1000,
'W' => [1, $widths],
]);
return $this->createDictionary($objects, [
return $dictionaryFactory([
'Type' => '/Font',
'Subtype' => '/Type0',
'BaseFont' => '/' . $fontName,
Expand Down Expand Up @@ -93,14 +117,6 @@ private function assertMapping(mixed $entry): void
}
}

/**
* @param array<int, string|null> $objects
*/
private function createFontFile(array &$objects, string $data): string
{
return $this->createStream($objects, ['Length1' => strlen($data)], $data);
}

/**
* @param list<array{glyph: int, unicode: list<int>}> $mappings
* @return array{list<int>, string, list<string>}
Expand Down
Loading