From dc20fb41e3be7d3c57761710b00632793b103356 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:03:00 +0000 Subject: [PATCH 1/5] feat(pdf): materialize Unicode and image resources in SignerPHP PDFs Share the Unicode font object serialization with destination-owned PDF object allocators. Materialize Type0 fonts, ToUnicode, CIDToGIDMap, PNG soft masks and SVG XObjects for signed appearance dictionaries. Refs: LibreSign/xobject-template#33 Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- composer.json | 3 +- .../SignerPhpCoreXObjectResourceBuilder.php | 220 ++++++++++++++++++ src/Pdf/UnicodeFontPdfWriter.php | 44 ++-- 3 files changed, 252 insertions(+), 15 deletions(-) create mode 100644 src/Pdf/SignerPhpCoreXObjectResourceBuilder.php diff --git a/composer.json b/composer.json index f78466f..e9fd61d 100644 --- a/composer.json +++ b/composer.json @@ -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": { diff --git a/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php b/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php new file mode 100644 index 0000000..9078497 --- /dev/null +++ b/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php @@ -0,0 +1,220 @@ +imageEmbedder = $imageEmbedder ?? new FilesystemPdfImageEmbedder(); + } + + /** + * @return Closure(PdfDocument, array): array + */ + public function resourcesBuilder(): Closure + { + return $this->materialize(...); + } + + /** + * @param array $resources + * @return array + */ + public function materialize(PdfDocument $document, array $resources): array + { + $fonts = $this->requireDictionary($resources['Font'] ?? [], 'Font'); + $images = $this->requireDictionary($resources['XObject'] ?? [], 'XObject'); + $preparedImages = $this->prepareImages($images); + $resources['Font'] = $this->materializeFonts($document, $fonts); + + if ($images !== []) { + $resources['XObject'] = $this->materializeImages($document, $images, $preparedImages); + } + + return $resources; + } + + /** + * @return array + */ + 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 $value */ + return $value; + } + + /** + * @param array $images + * @return array + */ + private function prepareImages(array $images): array + { + $prepared = []; + foreach ($images as $alias => $resource) { + if (!is_array($resource) || !isset($resource['Source'])) { + 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 $fonts + * @return array + */ + 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) || !isset($font['__TrueTypeFont'])) { + continue; + } + $reference = $writer->createWithFactories( + $this->requireDictionary($font, 'Font'), + $makeDictionary, + $makeStream, + ); + $fonts[$alias] = $this->asReference($reference); + } + return $fonts; + } + + /** + * @param array $images + * @param array $preparedImages + * @return array + */ + 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 $dictionary + */ + private function createDictionary(PdfDocument $document, array $dictionary): string + { + $object = $document->createObject($this->convertDictionary($dictionary)); + return sprintf('%d 0 R', $object->getOid()); + } + + /** + * @param array $dictionary + */ + private function createStream(PdfDocument $document, array $dictionary, string $bytes): string + { + $object = $document->createObject($this->convertDictionary($dictionary)); + $object->setStream($bytes, false); + return sprintf('%d 0 R', $object->getOid()); + } + + /** + * @param array $dictionary + * @return array + */ + /** @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|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, ' ')); + } +} diff --git a/src/Pdf/UnicodeFontPdfWriter.php b/src/Pdf/UnicodeFontPdfWriter.php index 952435c..7facca6 100644 --- a/src/Pdf/UnicodeFontPdfWriter.php +++ b/src/Pdf/UnicodeFontPdfWriter.php @@ -31,6 +31,29 @@ 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 $resource + * @param Closure(array): string $dictionaryFactory + * @param Closure(array, 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.'); @@ -38,13 +61,14 @@ public function create(array &$objects, array $resource): string $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, @@ -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, @@ -93,14 +117,6 @@ private function assertMapping(mixed $entry): void } } - /** - * @param array $objects - */ - private function createFontFile(array &$objects, string $data): string - { - return $this->createStream($objects, ['Length1' => strlen($data)], $data); - } - /** * @param list}> $mappings * @return array{list, string, list} From aa23d69180a2192178e265b0bf5b84cc089a8b69 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:03:11 +0000 Subject: [PATCH 2/5] test(pdf): cover document-owned Unicode font and image resource bridge Exercise PDF object references, glyph/ToUnicode maps, transparent PNG soft masks, SVG XObjects, invalid resources, multi-resource scenarios, and strict reference validation with data providers. Refs: LibreSign/xobject-template#33 Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- ...ignerPhpCoreXObjectResourceBuilderTest.php | 325 ++++++++++++++++++ 1 file changed, 325 insertions(+) create mode 100644 tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php diff --git a/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php b/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php new file mode 100644 index 0000000..9d66078 --- /dev/null +++ b/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php @@ -0,0 +1,325 @@ +withFont(function (TrueTypeFont $font): void { + $document = new PdfDocument(); + $document->createObject(['Type' => '/Catalog']); + $resources = [ + 'Font' => [ + 'F1' => [ + 'Type' => '/Font', + 'Subtype' => '/Type1', + 'BaseFont' => '/Helvetica', + ], + 'U1' => [ + '__TrueTypeFont' => $font, + '__Mappings' => [ + ['glyph' => 0x41, 'unicode' => [0x41]], + ['glyph' => 0x41, 'unicode' => [0x1F600]], + ], + ], + ], + ]; + + $result = (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, $resources); + + self::assertSame($resources['Font']['F1'], $result['Font']['F1']); + self::assertInstanceOf(PDFValueReference::class, $result['Font']['U1']); + self::assertSame('7 0 R', (string) $result['Font']['U1']); + self::assertCount(7, $document->getPdfObjects()); + self::assertSame(7, $document->getMaxOid()); + self::assertArrayHasKey('__TrueTypeFont', $resources['Font']['U1']); + + $fontFile = $document->getPdfObjects()[2]; + self::assertSame($font->fontData(), $fontFile->getStream(false)); + self::assertStringContainsString('/Length1 ', $fontFile->toPdfEntry()); + + $cidMap = $document->getPdfObjects()[3]; + self::assertSame(pack('nnn', 0, 3, 3), $cidMap->getStream(false)); + + $unicode = $document->getPdfObjects()[4]; + self::assertStringContainsString('<0001> <0041>', $unicode->getStream(false)); + self::assertStringContainsString('<0002> ', $unicode->getStream(false)); + + $descriptor = $document->getPdfObjects()[5]->toPdfEntry(); + self::assertStringContainsString('/FontFile2 2 0 R', $descriptor); + + $cidFont = $document->getPdfObjects()[6]->toPdfEntry(); + self::assertStringContainsString('/CIDToGIDMap 3 0 R', $cidFont); + self::assertStringContainsString('/FontDescriptor 5 0 R', $cidFont); + self::assertStringContainsString('/Registry(Adobe)', $cidFont); + self::assertStringContainsString('/Ordering(Identity)', $cidFont); + + $type0 = $document->getPdfObjects()[7]->toPdfEntry(); + self::assertStringContainsString('/DescendantFonts[6 0 R]', $type0); + self::assertStringContainsString('/ToUnicode 4 0 R', $type0); + }); + } + + public function testRejectsSourceBasedImageResourcesWithoutCreatingPdfObjects(): void + { + $document = new PdfDocument(); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('must be an existing file'); + try { + (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, [ + 'XObject' => ['Im1' => ['Source' => '/tmp/image.png']], + ]); + } finally { + self::assertSame([], $document->getPdfObjects()); + } + } + + public function testEmbedsTransparentPngWithIndirectSoftMask(): void + { + $path = tempnam(sys_get_temp_dir(), 'core-resource-png-'); + self::assertNotFalse($path); + try { + $png = PngFixtureFactory::createRgbaPngFromPixelRenderer( + 1, + 1, + static fn (): array => [255, 0, 0, 128], + ); + self::assertSame(strlen($png), file_put_contents($path, $png)); + + $document = new PdfDocument(); + $result = (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, [ + 'XObject' => ['Im1' => ['Source' => $path]], + ]); + + self::assertInstanceOf(PDFValueReference::class, $result['XObject']['Im1']); + self::assertSame('2 0 R', (string) $result['XObject']['Im1']); + self::assertCount(2, $document->getPdfObjects()); + $softMask = $document->getPdfObjects()[1]->toPdfEntry(); + $image = $document->getPdfObjects()[2]->toPdfEntry(); + self::assertStringContainsString('/DeviceGray', $softMask); + self::assertStringContainsString('/SMask 1 0 R', $image); + self::assertStringContainsString('/Subtype/Image', $image); + } finally { + unlink($path); + } + } + + public function testEmbedsSvgFormResourceInSamePdfDocument(): void + { + $path = tempnam(sys_get_temp_dir(), 'core-resource-svg-'); + self::assertNotFalse($path); + try { + file_put_contents( + $path, + '' + . '', + ); + $document = new PdfDocument(); + $result = (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, [ + 'XObject' => ['S1' => ['Source' => $path]], + ]); + self::assertSame('1 0 R', (string) $result['XObject']['S1']); + $form = $document->getPdfObjects()[1]; + self::assertStringContainsString('/Subtype/Form', $form->toPdfEntry()); + self::assertStringContainsString("\nf\n", $form->getStream(false)); + } finally { + unlink($path); + } + } + + public function testRejectsInvalidFontMappingsWithoutCreatingPdfObjects(): void + { + $this->withFont(function (TrueTypeFont $font): void { + $document = new PdfDocument(); + $this->expectException(InvalidArgumentException::class); + try { + (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, [ + 'Font' => ['U1' => ['__TrueTypeFont' => $font, '__Mappings' => []]], + ]); + } finally { + self::assertSame([], $document->getPdfObjects()); + } + }); + } + + #[DataProvider('invalidResourceDictionaryProvider')] + public function testRejectsInvalidResourceDictionary(string $key, mixed $invalid): void + { + $document = new PdfDocument(); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('resources must'); + (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, [$key => $invalid]); + } + + /** @return iterable */ + public static function invalidResourceDictionaryProvider(): iterable + { + yield 'font string' => ['Font', 'invalid']; + yield 'image string' => ['XObject', 'invalid']; + yield 'font numeric key' => ['Font', [7 => []]]; + yield 'image numeric key' => ['XObject', [7 => []]]; + } + + #[DataProvider('invalidImageResourceProvider')] + public function testRejectsInvalidImageSource(mixed $source): void + { + $document = new PdfDocument(); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('non-empty Source'); + (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, [ + 'XObject' => ['Im1' => ['Source' => $source]], + ]); + } + + /** @return iterable */ + public static function invalidImageResourceProvider(): iterable + { + yield 'empty' => ['']; + yield 'integer' => [1]; + yield 'false' => [false]; + yield 'array' => [[]]; + } + + public function testMaterializesMultipleImagesAndPreservesNonImageResources(): void + { + $calls = []; + $embedder = new class ($calls) implements PdfImageEmbedderInterface { + /** @var list */ + public array $sources = []; + public function __construct(array &$calls) + { + $this->sources = &$calls; + } + + public function embed(string $source): EmbeddedPdfImage + { + $this->sources[] = $source; + return new EmbeddedPdfImage( + dictionary: ['Type' => '/XObject', 'Subtype' => '/Form', 'BBox' => [0, 0, 1, 1]], + stream: 'q /' . $source . ' Q', + ); + } + }; + $builder = new SignerPhpCoreXObjectResourceBuilder($embedder); + $document = new PdfDocument(); + $resources = [ + 'ExtGState' => ['GS0' => ['Type' => '/ExtGState']], + 'Font' => ['F1' => ['Type' => '/Font', 'BaseFont' => '/Helvetica']], + 'XObject' => [ + 'preserved' => ['Type' => '/XObject'], + 'ImA' => ['Source' => 'A'], + 'ImB' => ['Source' => 'B'], + 'legacy' => new PDFValueReference(42), + ], + ]; + $mapped = ($builder->resourcesBuilder())($document, $resources); + self::assertSame(['A', 'B'], $calls); + self::assertSame($resources['ExtGState'], $mapped['ExtGState']); + self::assertSame($resources['Font'], $mapped['Font']); + self::assertSame($resources['XObject']['preserved'], $mapped['XObject']['preserved']); + self::assertSame('1 0 R', (string) $mapped['XObject']['ImA']); + self::assertSame('2 0 R', (string) $mapped['XObject']['ImB']); + self::assertSame($resources['XObject']['legacy'], $mapped['XObject']['legacy']); + self::assertCount(2, $document->getPdfObjects()); + self::assertStringContainsString('/A', $document->getPdfObjects()[1]->getStream(false)); + self::assertStringContainsString('/B', $document->getPdfObjects()[2]->getStream(false)); + } + + public function testStreamObjectsHaveCorrectLengthAndBinaryContent(): void + { + $this->withFont(function (TrueTypeFont $font): void { + $document = new PdfDocument(); + (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, [ + 'Font' => ['U1' => [ + '__TrueTypeFont' => $font, + '__Mappings' => [['glyph' => 0x41, 'unicode' => [0x41]]], + ]], + ]); + $object = $document->getPdfObjects()[1]; + self::assertStringContainsString('/Length ' . strlen($font->fontData()), $object->toPdfEntry()); + self::assertSame($font->fontData(), $object->getStream(false)); + }); + } + + #[DataProvider('invalidReferenceProvider')] + public function testReferenceParserRejectsMalformedReferences(string $value): void + { + $builder = new SignerPhpCoreXObjectResourceBuilder(); + $method = new \ReflectionMethod($builder, 'asReference'); + $this->expectException(InvalidArgumentException::class); + $method->invoke($builder, $value); + } + + /** @return iterable */ + public static function invalidReferenceProvider(): iterable + { + yield 'leading garbage' => ['prefix12 0 R']; + yield 'trailing garbage' => ['12 0 R suffix']; + yield 'trailing newline' => ["12 0 R\n"]; + yield 'zero oid' => ['0 0 R']; + yield 'generation one' => ['12 1 R']; + yield 'not a reference' => ['12']; + } + + #[DataProvider('plainValueProvider')] + public function testLiteralPdfValueIsNotMistakenForObjectReference(mixed $value): void + { + $builder = new SignerPhpCoreXObjectResourceBuilder(); + $method = new \ReflectionMethod($builder, 'convertValue'); + self::assertSame($value, $method->invoke($builder, $value)); + } + + /** @return iterable */ + public static function plainValueProvider(): iterable + { + yield 'leading garbage' => ['prefix12 0 R']; + yield 'trailing garbage' => ['12 0 R suffix']; + yield 'trailing newline' => ["12 0 R\n"]; + yield 'ordinary literal' => ['text']; + yield 'zero oid' => ['0 0 R']; + yield 'true' => [true]; + yield 'integer' => [15]; + yield 'float' => [1.5]; + } + + public function testConvertsNestedReferencesAndRejectsUnsupportedValues(): void + { + $builder = new SignerPhpCoreXObjectResourceBuilder(); + $method = new \ReflectionMethod($builder, 'convertValue'); + $value = $method->invoke($builder, ['ref' => '3 0 R', 'other' => [true, 4]]); + self::assertSame('3 0 R', (string) $value['ref']); + self::assertSame([true, 4], $value['other']); + + $this->expectException(InvalidArgumentException::class); + $method->invoke($builder, new \stdClass()); + } + + private function withFont(callable $callback): void + { + $path = tempnam(sys_get_temp_dir(), 'core-unicode-font-'); + self::assertNotFalse($path); + try { + file_put_contents($path, SyntheticTrueTypeFontTest::makeFont()); + $callback(new TrueTypeFont($path)); + } finally { + unlink($path); + } + } +} From b1313b10bd3e0bcd8f300ae895434077beb4fb2b Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:56:14 +0000 Subject: [PATCH 3/5] fix(pdf): preserve encoded image resource streams Avoid recompressing PNG image and soft-mask streams when materializing resources in a SignerPHP document. Verify decoded pixel bytes and stream lengths for transparent, grayscale and RGB PNGs. Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../SignerPhpCoreXObjectResourceBuilder.php | 4 ++- ...ignerPhpCoreXObjectResourceBuilderTest.php | 33 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php b/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php index 9078497..568b79c 100644 --- a/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php +++ b/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php @@ -162,7 +162,9 @@ private function createDictionary(PdfDocument $document, array $dictionary): str private function createStream(PdfDocument $document, array $dictionary, string $bytes): string { $object = $document->createObject($this->convertDictionary($dictionary)); - $object->setStream($bytes, false); + // 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()); } diff --git a/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php b/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php index 9d66078..c6a6a23 100644 --- a/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php +++ b/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php @@ -116,11 +116,44 @@ public function testEmbedsTransparentPngWithIndirectSoftMask(): void self::assertStringContainsString('/DeviceGray', $softMask); self::assertStringContainsString('/SMask 1 0 R', $image); self::assertStringContainsString('/Subtype/Image', $image); + $maskStream = $document->getPdfObjects()[1]->getStream(); + $imageStream = $document->getPdfObjects()[2]->getStream(); + self::assertSame("\x00\x80", gzuncompress($maskStream)); + self::assertSame("\x00\xff\x00\x00", gzuncompress($imageStream)); + self::assertStringContainsString('/Length ' . strlen($maskStream), $softMask); + self::assertStringContainsString('/Length ' . strlen($imageStream), $image); } finally { unlink($path); } } + #[DataProvider('opaquePngProvider')] + public function testPreservesEncodedOpaquePngStreams(int $colorType, string $scanline): void + { + $path = tempnam(sys_get_temp_dir(), 'core-resource-png-'); + self::assertNotFalse($path); + try { + file_put_contents($path, PngFixtureFactory::createPng(1, 1, $colorType, $scanline)); + $document = new PdfDocument(); + (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, [ + 'XObject' => ['Im1' => ['Source' => $path]], + ]); + self::assertCount(1, $document->getPdfObjects()); + $object = $document->getPdfObjects()[1]; + self::assertSame($scanline, gzuncompress($object->getStream())); + self::assertStringContainsString('/Length ' . strlen($object->getStream()), $object->toPdfEntry()); + } finally { + unlink($path); + } + } + + /** @return iterable */ + public static function opaquePngProvider(): iterable + { + yield 'grayscale' => [0, "\x00\x7f"]; + yield 'RGB' => [2, "\x00\xff\x00\x00"]; + } + public function testEmbedsSvgFormResourceInSamePdfDocument(): void { $path = tempnam(sys_get_temp_dir(), 'core-resource-svg-'); From 805efe94fa46f4f217de63aadd89ae3d7d4955b1 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:01:48 +0000 Subject: [PATCH 4/5] test(pdf): satisfy Rector stream length checks Cast stream bytes explicitly for strlen() in PNG resource regression tests. Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php b/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php index c6a6a23..adbc51d 100644 --- a/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php +++ b/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php @@ -120,8 +120,8 @@ public function testEmbedsTransparentPngWithIndirectSoftMask(): void $imageStream = $document->getPdfObjects()[2]->getStream(); self::assertSame("\x00\x80", gzuncompress($maskStream)); self::assertSame("\x00\xff\x00\x00", gzuncompress($imageStream)); - self::assertStringContainsString('/Length ' . strlen($maskStream), $softMask); - self::assertStringContainsString('/Length ' . strlen($imageStream), $image); + self::assertStringContainsString('/Length ' . strlen((string) $maskStream), $softMask); + self::assertStringContainsString('/Length ' . strlen((string) $imageStream), $image); } finally { unlink($path); } @@ -141,7 +141,7 @@ public function testPreservesEncodedOpaquePngStreams(int $colorType, string $sca self::assertCount(1, $document->getPdfObjects()); $object = $document->getPdfObjects()[1]; self::assertSame($scanline, gzuncompress($object->getStream())); - self::assertStringContainsString('/Length ' . strlen($object->getStream()), $object->toPdfEntry()); + self::assertStringContainsString('/Length ' . strlen((string) $object->getStream()), $object->toPdfEntry()); } finally { unlink($path); } From 3a8380b8af836d3524a2742c4777cc1e968a4b4d Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:15:15 +0000 Subject: [PATCH 5/5] fix(pdf): roll back failed appearance resource materialization Restore the destination document object table and allocator on failure. Reject null internal font and image placeholders instead of emitting them. Cover failure after a valid font and successful retry on the same document. Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../SignerPhpCoreXObjectResourceBuilder.php | 24 +++++++++---- ...ignerPhpCoreXObjectResourceBuilderTest.php | 36 +++++++++++++++++++ 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php b/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php index 568b79c..0e5d221 100644 --- a/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php +++ b/src/Pdf/SignerPhpCoreXObjectResourceBuilder.php @@ -9,6 +9,7 @@ use Closure; use InvalidArgumentException; +use Throwable; use SignerPHP\PdfCore\PdfDocument; use SignerPHP\PdfCore\PdfValue\PDFValueReference; use SignerPHP\PdfCore\PdfValue\PDFValueString; @@ -45,13 +46,22 @@ public function materialize(PdfDocument $document, array $resources): array $fonts = $this->requireDictionary($resources['Font'] ?? [], 'Font'); $images = $this->requireDictionary($resources['XObject'] ?? [], 'XObject'); $preparedImages = $this->prepareImages($images); - $resources['Font'] = $this->materializeFonts($document, $fonts); + // 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); + } - if ($images !== []) { - $resources['XObject'] = $this->materializeImages($document, $images, $preparedImages); + return $resources; + } catch (Throwable $error) { + $document->setPdfObjects($originalObjects); + $document->setMaxOid($originalMaxOid); + throw $error; } - - return $resources; } /** @@ -79,7 +89,7 @@ private function prepareImages(array $images): array { $prepared = []; foreach ($images as $alias => $resource) { - if (!is_array($resource) || !isset($resource['Source'])) { + if (!is_array($resource) || !array_key_exists('Source', $resource)) { continue; } if (!is_string($resource['Source']) || $resource['Source'] === '') { @@ -108,7 +118,7 @@ private function materializeFonts(PdfDocument $document, array $fonts): array $writer = new UnicodeFontPdfWriter($makeStream, $makeDictionary); foreach ($fonts as $alias => $font) { - if (!is_array($font) || !isset($font['__TrueTypeFont'])) { + if (!is_array($font) || !array_key_exists('__TrueTypeFont', $font)) { continue; } $reference = $writer->createWithFactories( diff --git a/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php b/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php index adbc51d..bb4dedb 100644 --- a/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php +++ b/tests/Unit/Pdf/SignerPhpCoreXObjectResourceBuilderTest.php @@ -192,6 +192,41 @@ public function testRejectsInvalidFontMappingsWithoutCreatingPdfObjects(): void }); } + public function testFailureInLaterFontLeavesExistingDocumentUnchanged(): void + { + $this->withFont(function (TrueTypeFont $font): void { + $document = new PdfDocument(); + $original = $document->createObject(['Type' => '/Catalog']); + $document->setMaxOid(10); + $valid = [ + '__TrueTypeFont' => $font, + '__Mappings' => [['glyph' => 0x41, 'unicode' => [0x41]]], + ]; + $invalid = ['__TrueTypeFont' => $font, '__Mappings' => []]; + $builder = new SignerPhpCoreXObjectResourceBuilder(); + try { + $builder->materialize($document, ['Font' => ['U1' => $valid, 'U2' => $invalid]]); + self::fail('Invalid font mappings must be rejected.'); + } catch (InvalidArgumentException $error) { + self::assertSame('Invalid Unicode font mappings.', $error->getMessage()); + } + self::assertSame([1 => $original], $document->getPdfObjects()); + self::assertSame(10, $document->getMaxOid()); + $result = $builder->materialize($document, ['Font' => ['U1' => $valid]]); + self::assertSame('16 0 R', (string) $result['Font']['U1']); + }); + } + + public function testRejectsNullFontPlaceholder(): void + { + $document = new PdfDocument(); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid Unicode font resource.'); + (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, [ + 'Font' => ['U1' => ['__TrueTypeFont' => null]], + ]); + } + #[DataProvider('invalidResourceDictionaryProvider')] public function testRejectsInvalidResourceDictionary(string $key, mixed $invalid): void { @@ -225,6 +260,7 @@ public function testRejectsInvalidImageSource(mixed $source): void public static function invalidImageResourceProvider(): iterable { yield 'empty' => ['']; + yield 'null' => [null]; yield 'integer' => [1]; yield 'false' => [false]; yield 'array' => [[]];