From dd62b791e8f7857de9cabea422cba9da0fc9ba2d Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Sun, 1 Nov 2026 16:26:49 -0800 Subject: [PATCH 1/7] fix(pdfa): build the XMP packet from the /Info values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PDF/A requires every /Info entry to be equivalent to its XMP property (ISO 19005-1 §6.7.3, ISO 19005-2 §6.6.2.3). The XMP packet was built from PdfAConfig alone: its producer was always dskripchenko/php-pdf, its dates the time of the render, and Subject, Keywords and Creator were missing. A document that set metadata() — any producer, creator or creation date — failed veraPDF on PDF/A-1b (6.7.3-1, -6, -7), and the packet changed on every render, so the output was not reproducible even with a fixed creation date. The /Info values are now resolved once and the XMP packet is written from them: dc:title, dc:creator, dc:description, pdf:Keywords, xmp:CreatorTool, pdf:Producer, xmp:CreateDate and xmp:ModifyDate. The config's title and author still apply when the metadata has none, and are written to /Info as well, as PdfXConfig's are. Empty properties are left out instead of written as empty elements. /Info dates are written in UTC. A creation date in another time zone was written with its local clock time but a +00'00' offset — hours off, and a different instant from the XMP date. PdfAConfig::xmpMetadata() keeps its signature and gains an optional $info array. Co-Authored-By: Claude Opus 5.5 --- src/Pdf/Document.php | 44 ++++++++-- src/Pdf/PdfAConfig.php | 76 +++++++++++++--- tests/Pdf/PdfAMetadataTest.php | 154 +++++++++++++++++++++++++++++++++ 3 files changed, 253 insertions(+), 21 deletions(-) create mode 100644 tests/Pdf/PdfAMetadataTest.php diff --git a/src/Pdf/Document.php b/src/Pdf/Document.php index 6002dff..eca8dff 100644 --- a/src/Pdf/Document.php +++ b/src/Pdf/Document.php @@ -834,8 +834,35 @@ private static function iccComponents(string $iccBytes): int private function formatPdfDate(\DateTimeInterface $dt): string { - // PDF date format: D:YYYYMMDDHHmmSS+TZ'mm' - return 'D:'.$dt->format('YmdHis').'+00\'00\''; + // PDF date format: D:YYYYMMDDHHmmSS+TZ'mm', written in UTC. + $utc = \DateTimeImmutable::createFromInterface($dt)->setTimezone(new \DateTimeZone('UTC')); + + return 'D:'.$utc->format('YmdHis').'+00\'00\''; + } + + /** + * The /Info dictionary values: the metadata set on the document, a + * default Producer and CreationDate (most readers expect an Info dict in + * the Properties dialog), and for PDF/A the config's title and author + * where the metadata has none. + * + * @return array + */ + private function infoEntries(): array + { + $info = $this->metadata + [ + 'Producer' => 'dskripchenko/php-pdf', + 'CreationDate' => $this->formatPdfDate(new \DateTimeImmutable), + ]; + if ($this->pdfA !== null) { + foreach (['Title' => $this->pdfA->title, 'Author' => $this->pdfA->author] as $key => $value) { + if (! isset($info[$key]) && $value !== '') { + $info[$key] = $value; + } + } + } + + return array_map(strval(...), $info); } /** @@ -1656,9 +1683,13 @@ private function buildWriter(): Writer } // PDF/A — Metadata stream + OutputIntent + /Lang. + // /Info values, resolved once: PDF/A requires the XMP packet to + // carry the same values (ISO 19005-1 §6.7.3). + $info = $this->infoEntries(); + $pdfARef = ''; if ($this->pdfA !== null) { - $xmp = $this->pdfA->xmpMetadata(); + $xmp = $this->pdfA->xmpMetadata(info: $info); // Metadata stream — not filtered, not encrypted. $metadataId = $writer->addObject(sprintf( "<< /Type /Metadata /Subtype /XML /Length %d >>\nstream\n%s\nendstream", @@ -1885,12 +1916,7 @@ private function buildWriter(): Writer $writer->setRoot($catalogId); - // /Info dictionary is always emitted with default Producer + - // CreationDate (most readers expect Info dict in Properties dialog). - $meta = $this->metadata + [ - 'Producer' => 'dskripchenko/php-pdf', - 'CreationDate' => $this->formatPdfDate(new \DateTimeImmutable), - ]; + $meta = $info; $entries = []; foreach ($meta as $key => $value) { $entries[] = '/'.$key.' '.$this->pdfTextString((string) $value); diff --git a/src/Pdf/PdfAConfig.php b/src/Pdf/PdfAConfig.php index 873ae4a..3d9bad8 100644 --- a/src/Pdf/PdfAConfig.php +++ b/src/Pdf/PdfAConfig.php @@ -79,13 +79,45 @@ public function iccProfileBytes(): string /** * Render XMP metadata stream (XML with PDF/A + Dublin Core namespaces). + * + * $info holds the document's /Info values (Title, Author, Subject, + * Keywords, Creator, Producer, CreationDate, ModDate, dates in PDF form): + * PDF/A requires each to match its XMP property, so they take precedence + * over this config's title, author and $producer. Empty values are left + * out. Without a CreationDate the current time is used. + * + * @param array $info */ - public function xmpMetadata(string $producer = 'dskripchenko/php-pdf'): string + public function xmpMetadata(string $producer = 'dskripchenko/php-pdf', array $info = []): string { - $created = (new \DateTimeImmutable)->format('Y-m-d\TH:i:sP'); - $title = self::xmlEscape($this->title); - $author = self::xmlEscape($this->author); - $producer = self::xmlEscape($producer); + $value = static fn (string $key, string $fallback = ''): string => self::xmlEscape($info[$key] ?? $fallback); + $created = isset($info['CreationDate']) + ? self::xmpDate($info['CreationDate']) + : (new \DateTimeImmutable)->format('Y-m-d\TH:i:sP'); + $modified = isset($info['ModDate']) ? self::xmpDate($info['ModDate']) : $created; + + $properties = []; + if (($title = $value('Title', $this->title)) !== '') { + $properties[] = "$title"; + } + if (($author = $value('Author', $this->author)) !== '') { + $properties[] = "$author"; + } + if (($subject = $value('Subject')) !== '') { + $properties[] = "$subject"; + } + if (($keywords = $value('Keywords')) !== '') { + $properties[] = "$keywords"; + } + if (($creator = $value('Creator')) !== '') { + $properties[] = "$creator"; + } + $properties[] = ''.$value('Producer', $producer).''; + $properties[] = "$created"; + $properties[] = "$modified"; + $properties[] = "{$this->part}"; + $properties[] = "{$this->conformance}"; + $body = implode("\n ", $properties); return << @@ -96,13 +128,7 @@ public function xmpMetadata(string $producer = 'dskripchenko/php-pdf'): string xmlns:pdf="http://ns.adobe.com/pdf/1.3/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/"> - <dc:title><rdf:Alt><rdf:li xml:lang="x-default">$title</rdf:li></rdf:Alt></dc:title> - <dc:creator><rdf:Seq><rdf:li>$author</rdf:li></rdf:Seq></dc:creator> - <pdf:Producer>$producer</pdf:Producer> - <xmp:CreateDate>$created</xmp:CreateDate> - <xmp:ModifyDate>$created</xmp:ModifyDate> - <pdfaid:part>{$this->part}</pdfaid:part> - <pdfaid:conformance>{$this->conformance}</pdfaid:conformance> + $body </rdf:Description> </rdf:RDF> </x:xmpmeta> @@ -110,6 +136,32 @@ public function xmpMetadata(string $producer = 'dskripchenko/php-pdf'): string XMP; } + /** + * A PDF date (D:YYYYMMDDHHmmSS with an optional Z or +HH'mm' offset, + * later fields optional) as an XMP date, the same instant. + */ + private static function xmpDate(string $pdfDate): string + { + if (preg_match("/^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(?:(Z)|([+-])(\\d{2})'?(\\d{2})?'?)?\$/", $pdfDate, $m) !== 1) { + return $pdfDate; + } + $offset = match (true) { + ($m[8] ?? '') !== '' => $m[8].$m[9].':'.(($m[10] ?? '') !== '' ? $m[10] : '00'), + default => '+00:00', + }; + + return sprintf( + '%s-%s-%sT%s:%s:%s%s', + $m[1], + ($m[2] ?? '') !== '' ? $m[2] : '01', + ($m[3] ?? '') !== '' ? $m[3] : '01', + ($m[4] ?? '') !== '' ? $m[4] : '00', + ($m[5] ?? '') !== '' ? $m[5] : '00', + ($m[6] ?? '') !== '' ? $m[6] : '00', + $offset, + ); + } + private static function xmlEscape(string $s): string { return htmlspecialchars($s, ENT_XML1 | ENT_QUOTES, 'UTF-8'); diff --git a/tests/Pdf/PdfAMetadataTest.php b/tests/Pdf/PdfAMetadataTest.php new file mode 100644 index 0000000..d462199 --- /dev/null +++ b/tests/Pdf/PdfAMetadataTest.php @@ -0,0 +1,154 @@ +<?php + +declare(strict_types=1); + +namespace Dskripchenko\PhpPdf\Tests\Pdf; + +use Dskripchenko\PhpPdf\Pdf\Document as PdfDocument; +use Dskripchenko\PhpPdf\Pdf\PdfAConfig; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +/** + * PDF/A (ISO 19005-1 §6.7.3, -2 §6.6.2.3) requires every /Info entry to match + * its XMP property, so the XMP packet is built from the same values as /Info. + */ +final class PdfAMetadataTest extends TestCase +{ + private string $iccPath = __DIR__.'/../fixtures/dummy.icc'; + + #[Test] + public function xmp_carries_the_info_dictionary_values(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage(); + $pdf->metadata( + title: 'Quarterly Report', + author: 'Finance Team', + subject: 'Results for Q3', + keywords: 'finance, q3', + creator: 'Report Builder', + producer: 'Acme PDF', + creationDate: new \DateTimeImmutable('2026-03-02 10:15:30', new \DateTimeZone('UTC')), + ); + $pdf->enablePdfA(new PdfAConfig($this->iccPath)); + $bytes = $pdf->toBytes(); + $xmp = self::xmp($bytes); + + self::assertStringContainsString('/Producer (Acme PDF)', $bytes); + self::assertStringContainsString('<pdf:Producer>Acme PDF</pdf:Producer>', $xmp); + self::assertStringContainsString('<xmp:CreatorTool>Report Builder</xmp:CreatorTool>', $xmp); + self::assertStringContainsString('<rdf:li xml:lang="x-default">Quarterly Report</rdf:li>', $xmp); + self::assertStringContainsString('<rdf:li>Finance Team</rdf:li>', $xmp); + self::assertStringContainsString('<rdf:li xml:lang="x-default">Results for Q3</rdf:li>', $xmp); + self::assertStringContainsString('<pdf:Keywords>finance, q3</pdf:Keywords>', $xmp); + self::assertStringContainsString('/CreationDate (D:20260302101530+00\'00\')', $bytes); + self::assertStringContainsString('<xmp:CreateDate>2026-03-02T10:15:30+00:00</xmp:CreateDate>', $xmp); + } + + #[Test] + public function default_producer_and_date_match_between_info_and_xmp(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage(); + $pdf->enablePdfA(new PdfAConfig($this->iccPath)); + $bytes = $pdf->toBytes(); + $xmp = self::xmp($bytes); + + self::assertStringContainsString('/Producer (dskripchenko/php-pdf)', $bytes); + self::assertStringContainsString('<pdf:Producer>dskripchenko/php-pdf</pdf:Producer>', $xmp); + self::assertSame(1, preg_match("@/CreationDate \(D:(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)\+00'00'\)@", $bytes, $m)); + self::assertStringContainsString("<xmp:CreateDate>$m[1]-$m[2]-$m[3]T$m[4]:$m[5]:$m[6]+00:00</xmp:CreateDate>", $xmp); + } + + #[Test] + public function the_xmp_is_the_same_on_every_render_of_a_dated_document(): void + { + $render = function (): string { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage(); + $pdf->metadata(creationDate: new \DateTimeImmutable('2026-03-02 10:15:30', new \DateTimeZone('UTC'))); + $pdf->enablePdfA(new PdfAConfig($this->iccPath)); + + return self::xmp($pdf->toBytes()); + }; + + $first = $render(); + sleep(1); + self::assertSame($first, $render()); + } + + #[Test] + public function a_creation_date_outside_utc_is_written_as_the_same_instant(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage(); + $pdf->metadata(creationDate: new \DateTimeImmutable('2026-03-02 10:15:30', new \DateTimeZone('-07:00'))); + $pdf->enablePdfA(new PdfAConfig($this->iccPath)); + $bytes = $pdf->toBytes(); + + self::assertStringContainsString('/CreationDate (D:20260302171530+00\'00\')', $bytes); + self::assertStringContainsString('<xmp:CreateDate>2026-03-02T17:15:30+00:00</xmp:CreateDate>', self::xmp($bytes)); + } + + #[Test] + public function the_config_title_and_author_fill_info_when_metadata_has_none(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage(); + $pdf->enablePdfA(new PdfAConfig($this->iccPath, title: 'Archive Title', author: 'Archivist')); + $bytes = $pdf->toBytes(); + $xmp = self::xmp($bytes); + + self::assertStringContainsString('/Title (Archive Title)', $bytes); + self::assertStringContainsString('/Author (Archivist)', $bytes); + self::assertStringContainsString('<rdf:li xml:lang="x-default">Archive Title</rdf:li>', $xmp); + self::assertStringContainsString('<rdf:li>Archivist</rdf:li>', $xmp); + } + + #[Test] + public function metadata_title_wins_over_the_config_title_in_both_places(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage(); + $pdf->metadata(title: 'Document Title'); + $pdf->enablePdfA(new PdfAConfig($this->iccPath, title: 'Config Title')); + $bytes = $pdf->toBytes(); + $xmp = self::xmp($bytes); + + self::assertStringContainsString('/Title (Document Title)', $bytes); + self::assertStringNotContainsString('Config Title', $bytes); + self::assertStringContainsString('<rdf:li xml:lang="x-default">Document Title</rdf:li>', $xmp); + } + + #[Test] + public function empty_entries_are_left_out_of_the_xmp(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage(); + $pdf->enablePdfA(new PdfAConfig($this->iccPath)); + $xmp = self::xmp($pdf->toBytes()); + + self::assertStringNotContainsString('<dc:title>', $xmp); + self::assertStringNotContainsString('<dc:creator>', $xmp); + self::assertStringNotContainsString('<xmp:CreatorTool>', $xmp); + } + + #[Test] + public function xml_special_characters_are_escaped(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage(); + $pdf->metadata(title: 'Smith & Sons <draft>'); + $pdf->enablePdfA(new PdfAConfig($this->iccPath)); + + self::assertStringContainsString('Smith &amp; Sons &lt;draft&gt;', self::xmp($pdf->toBytes())); + } + + private static function xmp(string $bytes): string + { + self::assertSame(1, preg_match('@<x:xmpmeta.*?</x:xmpmeta>@s', $bytes, $m), 'no XMP packet'); + + return $m[0]; + } +} From 7febc8206320c9ebc5e9c66912a26b679f58a80e Mon Sep 17 00:00:00 2001 From: Dan Krieger <dan@codingislife.com> Date: Sun, 1 Nov 2026 16:27:14 -0800 Subject: [PATCH 2/7] fix(annot): set the Print flag on links and form widgets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Link annotations and form-field widgets were written without /F, so their Print flag was off. PDF/A requires /F with Print set on every annotation but a Popup (ISO 19005-1 §6.5.3, ISO 19005-2 §6.3.2), so a PDF/A document with a hyperlink or a form field failed veraPDF (6.5.3-2 on 1b, 6.3.2-1 on 2b and 2u). Without the flag a printed form also leaves its fields blank. All five kinds of link and every widget (text, checkbox, push, submit and reset buttons, combo and list boxes, radio buttons) now carry /F 4, as the signature widget already did. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/Pdf/Document.php | 20 ++++----- tests/Pdf/AnnotationPrintFlagTest.php | 61 +++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 10 deletions(-) create mode 100644 tests/Pdf/AnnotationPrintFlagTest.php diff --git a/src/Pdf/Document.php b/src/Pdf/Document.php index eca8dff..510d41a 100644 --- a/src/Pdf/Document.php +++ b/src/Pdf/Document.php @@ -1246,35 +1246,35 @@ private function buildWriter(): Writer } $body = match ($ann['kind']) { 'uri' => sprintf( - '<< /Type /Annot /Subtype /Link /Rect %s ' + '<< /Type /Annot /Subtype /Link /Rect %s /F 4 ' .'/Border [0 0 0] /A << /S /URI /URI %s >>%s >>', $rect, $this->pdfString($ann['target']), $structParentPart, ), 'named' => sprintf( - '<< /Type /Annot /Subtype /Link /Rect %s ' + '<< /Type /Annot /Subtype /Link /Rect %s /F 4 ' .'/Border [0 0 0] /A << /Type /Action /S /Named /N /%s >>%s >>', $rect, $ann['target'], $structParentPart, ), 'javascript' => sprintf( - '<< /Type /Annot /Subtype /Link /Rect %s ' + '<< /Type /Annot /Subtype /Link /Rect %s /F 4 ' .'/Border [0 0 0] /A << /Type /Action /S /JavaScript /JS %s >>%s >>', $rect, $this->pdfString($ann['target']), $structParentPart, ), 'launch' => sprintf( - '<< /Type /Annot /Subtype /Link /Rect %s ' + '<< /Type /Annot /Subtype /Link /Rect %s /F 4 ' .'/Border [0 0 0] /A << /Type /Action /S /Launch /F %s >>%s >>', $rect, $this->pdfString($ann['target']), $structParentPart, ), default => sprintf( - '<< /Type /Annot /Subtype /Link /Rect %s ' + '<< /Type /Annot /Subtype /Link /Rect %s /F 4 ' .'/Border [0 0 0] /Dest %s%s >>', $rect, $this->pdfNameString($ann['target']), @@ -2245,7 +2245,7 @@ private function buildSimpleFieldObject(Writer $writer, array $field, int $pageI $apRef = sprintf(' /AP << /N %d 0 R >>', $apId); return sprintf( - '<< /Type /Annot /Subtype /Widget /FT /Tx /Rect %s ' + '<< /Type /Annot /Subtype /Widget /FT /Tx /Rect %s /F 4 ' .'%s%s%s /Ff %d /P %d 0 R%s%s >>', $rect, $namePart, $valuePart, $tooltipPart, $flags, $pageId, $apRef, $aaPart, ); @@ -2261,7 +2261,7 @@ private function buildSimpleFieldObject(Writer $writer, array $field, int $pageI $apRef = sprintf(' /AP << /N << /Yes %d 0 R /Off %d 0 R >> >>', $yesId, $offId); return sprintf( - '<< /Type /Annot /Subtype /Widget /FT /Btn /Rect %s ' + '<< /Type /Annot /Subtype /Widget /FT /Btn /Rect %s /F 4 ' .'%s%s%s /Ff %d /P %d 0 R /AS %s%s%s >>', $rect, $namePart, $vPart, $tooltipPart, $flags, $pageId, $isChecked ? '/Yes' : '/Off', @@ -2331,7 +2331,7 @@ private function buildSimpleFieldObject(Writer $writer, array $field, int $pageI $apRef = sprintf(' /AP << /N %d 0 R >>', $apId); return sprintf( - '<< /Type /Annot /Subtype /Widget /FT /Btn /Rect %s ' + '<< /Type /Annot /Subtype /Widget /FT /Btn /Rect %s /F 4 ' .'%s%s /Ff %d /P %d 0 R%s%s%s%s >>', $rect, $namePart, $tooltipPart, $flags, $pageId, $mkPart, $actionPart, $apRef, $aaPart, @@ -2351,7 +2351,7 @@ private function buildSimpleFieldObject(Writer $writer, array $field, int $pageI $apRef = sprintf(' /AP << /N %d 0 R >>', $apId); return sprintf( - '<< /Type /Annot /Subtype /Widget /FT /Ch /Rect %s ' + '<< /Type /Annot /Subtype /Widget /FT /Ch /Rect %s /F 4 ' .'%s%s%s /Opt %s /Ff %d /P %d 0 R%s%s >>', $rect, $namePart, $valuePart, $tooltipPart, $optsArray, $flags, $pageId, $apRef, $aaPart, ); @@ -2398,7 +2398,7 @@ private function emitRadioGroupFields(Writer $writer, int $pageId, array $field, $exportKey = ltrim($exportName, '/'); $apRef = sprintf(' /AP << /N << /%s %d 0 R /Off %d 0 R >> >>', $exportKey, $onId, $offId); $body = sprintf( - '<< /Type /Annot /Subtype /Widget /Rect %s ' + '<< /Type /Annot /Subtype /Widget /Rect %s /F 4 ' .'/Parent %d 0 R /AS %s%s >>', $rect, $parentId, $isChecked ? $exportName : '/Off', $apRef, ); diff --git a/tests/Pdf/AnnotationPrintFlagTest.php b/tests/Pdf/AnnotationPrintFlagTest.php new file mode 100644 index 0000000..2d8d6fc --- /dev/null +++ b/tests/Pdf/AnnotationPrintFlagTest.php @@ -0,0 +1,61 @@ +<?php + +declare(strict_types=1); + +namespace Dskripchenko\PhpPdf\Tests\Pdf; + +use Dskripchenko\PhpPdf\Pdf\Document as PdfDocument; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +/** + * Links and form widgets carry /F 4 (Print), so they print with the page and + * meet PDF/A (ISO 19005-1 §6.5.3, -2 §6.3.2), which requires the flag. + */ +final class AnnotationPrintFlagTest extends TestCase +{ + #[Test] + public function every_kind_of_link_is_printable(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $page = $pdf->addPage(); + $page->addExternalLink(10, 10, 50, 10, 'https://example.com'); + $page->addInternalLink(10, 30, 50, 10, 'target'); + $page->addNamedActionLink(10, 50, 50, 10, 'NextPage'); + $page->addJavaScriptLink(10, 70, 50, 10, 'app.alert(1)'); + $page->addLaunchLink(10, 90, 50, 10, 'other.pdf'); + $pdf->registerDestination('target', $page, 0, 0); + $links = self::annotations($pdf->toBytes(), 'Link'); + + self::assertCount(5, $links); + foreach ($links as $link) { + self::assertStringContainsString('/F 4', $link); + } + } + + #[Test] + public function every_kind_of_form_widget_is_printable(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $page = $pdf->addPage(); + $page->addFormField('text', 'name', 10, 10, 100, 20); + $page->addFormField('checkbox', 'agree', 10, 40, 20, 20); + $page->addFormField('combo', 'colour', 10, 70, 100, 20, options: ['Red', 'Blue']); + $page->addFormField('radio-group', 'size', 10, 100, 20, 20, options: ['S', 'M'], radioWidgets: [['x' => 10, 'y' => 100, 'w' => 14, 'h' => 14], ['x' => 30, 'y' => 100, 'w' => 14, 'h' => 14]]); + $page->addFormField('push', 'go', 10, 130, 60, 20); + $widgets = self::annotations($pdf->toBytes(), 'Widget'); + + self::assertCount(6, $widgets); + foreach ($widgets as $widget) { + self::assertStringContainsString('/F 4', $widget); + } + } + + /** @return list<string> */ + private static function annotations(string $bytes, string $subtype): array + { + preg_match_all('@<< /Type /Annot /Subtype /'.$subtype.'\b.*?>>\s*endobj@s', $bytes, $m); + + return $m[0]; + } +} From a18eda6f548469b1eefd26cc3419a534b83258e2 Mon Sep 17 00:00:00 2001 From: Dan Krieger <dan@codingislife.com> Date: Sun, 1 Nov 2026 16:27:22 -0800 Subject: [PATCH 3/7] test(conformance): PDF/A references with links and full metadata pdfa-1b-annotated and pdfa-2b-annotated have an external and an internal link and set every standard /Info entry (Title, Author, Subject, Keywords, Creator, Producer). The existing references set neither, which is how the two previous fixes went unnoticed: both new files fail veraPDF without them and pass with them. verapdf.sh checks them with the others. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- scripts/conformance/generate.php | 36 +++++++++++++++++++++++++++++++- scripts/conformance/verapdf.sh | 2 +- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/scripts/conformance/generate.php b/scripts/conformance/generate.php index 216c2cd..35d95f3 100644 --- a/scripts/conformance/generate.php +++ b/scripts/conformance/generate.php @@ -8,7 +8,8 @@ * Usage: php scripts/conformance/generate.php [output-dir] * * Output: one PDF per flavour (pdfa-1b, pdfa-1a, pdfa-2b, pdfa-2u, pdfa-3b, - * plus pdfa-2b-signed — signed, with a signature stamp), built with embedded + * plus pdfa-2b-signed — signed, with a signature stamp — and pdfa-1b-annotated / + * pdfa-2b-annotated — links and a full /Info dictionary), built with embedded * Liberation fonts (run scripts/fetch-fonts.sh first), plus pdfa-1b-cff, * pdfa-2u-cff and pdfa-2u-cff-cid — CFF-outline OpenType fonts (Source Sans 3 * and the CID-keyed test font in tests/fixtures/fonts) — and the vendored sRGB @@ -18,8 +19,10 @@ */ use Dskripchenko\PhpPdf\Document; +use Dskripchenko\PhpPdf\Element\Bookmark; use Dskripchenko\PhpPdf\Element\Cell; use Dskripchenko\PhpPdf\Element\Heading; +use Dskripchenko\PhpPdf\Element\Hyperlink; use Dskripchenko\PhpPdf\Element\Paragraph; use Dskripchenko\PhpPdf\Element\Row; use Dskripchenko\PhpPdf\Element\Run; @@ -171,6 +174,37 @@ $failures += $ok ? 0 : 1; } +// Links and a full /Info dictionary: link annotations need the Print flag, +// and every /Info entry has to match its XMP property. +$annotated = new Section([ + new Heading(1, [new Run('Annotated Reference Document')]), + new Paragraph([ + new Run('An external link to '), + Hyperlink::external('https://www.pdfa.org/', [new Run('the PDF Association')]), + new Run(', and an internal link to '), + Hyperlink::internal('tables', [new Run('the table below')]), + new Run('.'), + ]), + new Heading(2, [new Bookmark('tables', [new Run('Tabular data')])]), + new Paragraph([new Run('The link above jumps here.')]), +]); +foreach (['pdfa-1b-annotated' => PdfAConfig::PART_1, 'pdfa-2b-annotated' => PdfAConfig::PART_2] as $name => $part) { + $ok = $emit($name, new Document( + $annotated, + metadata: [ + 'Title' => 'php-pdf conformance reference — '.strtoupper($name), + 'Author' => 'dskripchenko/php-pdf', + 'Subject' => 'Links and document information', + 'Keywords' => 'PDF/A, links, metadata', + 'Creator' => 'scripts/conformance/generate.php', + 'Producer' => 'dskripchenko/php-pdf conformance', + ], + lang: 'en', + pdfA: new PdfAConfig($iccPath, iccProfileName: 'sRGB2014', lang: 'en', part: $part), + )); + $failures += $ok ? 0 : 1; +} + // CFF-outline OpenType fonts: CIDFontType0 + FontFile3/CIDFontType0C. PDF/A-1 // is the strictest case (PDF 1.4 base), the CID-keyed font checks that CIDs // are written through the CFF charset. diff --git a/scripts/conformance/verapdf.sh b/scripts/conformance/verapdf.sh index 1e4a1b2..8263cb8 100755 --- a/scripts/conformance/verapdf.sh +++ b/scripts/conformance/verapdf.sh @@ -13,7 +13,7 @@ set -euo pipefail DIR="${1:-build/conformance}" VERAPDF="${VERAPDF:-verapdf}" -NAMES=(pdfa-1b pdfa-1a pdfa-2b pdfa-2u pdfa-3b pdfa-2b-signed pdfa-1b-cff pdfa-2u-cff pdfa-2u-cff-cid) +NAMES=(pdfa-1b pdfa-1a pdfa-2b pdfa-2u pdfa-3b pdfa-2b-signed pdfa-1b-annotated pdfa-2b-annotated pdfa-1b-cff pdfa-2u-cff pdfa-2u-cff-cid) # pdfa-2b-signed → 2b flavour() { local f="${1#pdfa-}"; echo "${f%%-*}"; } From 72795efd8a94959db459c4e482da1bce921558e6 Mon Sep 17 00:00:00 2001 From: Dan Krieger <dan@codingislife.com> Date: Thu, 12 Nov 2026 05:53:06 -0800 Subject: [PATCH 4/7] feat(annot): a description (/Contents) on links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PDF/UA requires every link annotation to have a description in its /Contents entry, which assistive technology reads for the link (ISO 14289-1 §7.18.5; veraPDF 7.18.1-2 and 7.18.5-2). There was no way to set one, so no document with a link could be PDF/UA. addExternalLink, addInternalLink, addNamedActionLink, addJavaScriptLink and addLaunchLink take an optional $contents, written as a text string (UTF-16BE when it isn't plain ASCII). Without it the annotation is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/Pdf/Document.php | 18 ++++++---- src/Pdf/Page.php | 23 ++++++++---- tests/Pdf/LinkContentsTest.php | 65 ++++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 14 deletions(-) create mode 100644 tests/Pdf/LinkContentsTest.php diff --git a/src/Pdf/Document.php b/src/Pdf/Document.php index 510d41a..2fdbba3 100644 --- a/src/Pdf/Document.php +++ b/src/Pdf/Document.php @@ -1238,11 +1238,15 @@ private function buildWriter(): Writer // Reserve /StructParent number for tagged links — counter // starts after page indices. The annotation dict includes // /StructParent N; ParentTree maps N → struct elem ID. - $structParentPart = ''; + $annotTail = ''; $structParentKey = -1; if ($this->tagged) { $structParentKey = count($this->pages) + count($this->structParentLinkKeys); - $structParentPart = sprintf(' /StructParent %d', $structParentKey); + $annotTail = sprintf(' /StructParent %d', $structParentKey); + } + // Link description for assistive technology (PDF/UA §7.18.5). + if ($ann['contents'] !== null) { + $annotTail = ' /Contents '.$this->pdfTextString($ann['contents']).$annotTail; } $body = match ($ann['kind']) { 'uri' => sprintf( @@ -1250,35 +1254,35 @@ private function buildWriter(): Writer .'/Border [0 0 0] /A << /S /URI /URI %s >>%s >>', $rect, $this->pdfString($ann['target']), - $structParentPart, + $annotTail, ), 'named' => sprintf( '<< /Type /Annot /Subtype /Link /Rect %s /F 4 ' .'/Border [0 0 0] /A << /Type /Action /S /Named /N /%s >>%s >>', $rect, $ann['target'], - $structParentPart, + $annotTail, ), 'javascript' => sprintf( '<< /Type /Annot /Subtype /Link /Rect %s /F 4 ' .'/Border [0 0 0] /A << /Type /Action /S /JavaScript /JS %s >>%s >>', $rect, $this->pdfString($ann['target']), - $structParentPart, + $annotTail, ), 'launch' => sprintf( '<< /Type /Annot /Subtype /Link /Rect %s /F 4 ' .'/Border [0 0 0] /A << /Type /Action /S /Launch /F %s >>%s >>', $rect, $this->pdfString($ann['target']), - $structParentPart, + $annotTail, ), default => sprintf( '<< /Type /Annot /Subtype /Link /Rect %s /F 4 ' .'/Border [0 0 0] /Dest %s%s >>', $rect, $this->pdfNameString($ann['target']), - $structParentPart, + $annotTail, ), }; $linkAnnotId = $writer->addObject($body); diff --git a/src/Pdf/Page.php b/src/Pdf/Page.php index 1396bff..353fb82 100644 --- a/src/Pdf/Page.php +++ b/src/Pdf/Page.php @@ -289,7 +289,7 @@ public function nextMcid(): int /** * Link annotations accumulated on this page. * - * @var list<array{kind: 'uri'|'internal', x1: float, y1: float, x2: float, y2: float, target: string}> + * @var list<array{kind: 'uri'|'internal'|'named'|'javascript'|'launch', x1: float, y1: float, x2: float, y2: float, target: string, contents: ?string}> */ private array $linkAnnotations = []; @@ -1080,14 +1080,19 @@ public function drawImageWithOpacity( /** * External URL link — click inside Rect opens $uri. + * + * $contents is the link's description (/Contents), read by assistive + * technology. PDF/UA requires one on every link (ISO 14289-1 §7.18.5). + * The other add*Link() methods take it too. */ - public function addExternalLink(float $x, float $y, float $width, float $height, string $uri): self + public function addExternalLink(float $x, float $y, float $width, float $height, string $uri, ?string $contents = null): self { $this->linkAnnotations[] = [ 'kind' => 'uri', 'x1' => $x, 'y1' => $y, 'x2' => $x + $width, 'y2' => $y + $height, 'target' => $uri, + 'contents' => $contents, ]; return $this; @@ -1451,13 +1456,14 @@ public function markupAnnotations(): array /** * Internal link — click inside Rect jumps to named destination $destName. */ - public function addInternalLink(float $x, float $y, float $width, float $height, string $destName): self + public function addInternalLink(float $x, float $y, float $width, float $height, string $destName, ?string $contents = null): self { $this->linkAnnotations[] = [ 'kind' => 'internal', 'x1' => $x, 'y1' => $y, 'x2' => $x + $width, 'y2' => $y + $height, 'target' => $destName, + 'contents' => $contents, ]; return $this; @@ -1469,7 +1475,7 @@ public function addInternalLink(float $x, float $y, float $width, float $height, * @param string $action one of: NextPage, PrevPage, FirstPage, LastPage, * Find, Print, SaveAs, GoBack, GoForward. */ - public function addNamedActionLink(float $x, float $y, float $width, float $height, string $action): self + public function addNamedActionLink(float $x, float $y, float $width, float $height, string $action, ?string $contents = null): self { $valid = ['NextPage', 'PrevPage', 'FirstPage', 'LastPage', 'Find', 'Print', 'SaveAs', 'GoBack', 'GoForward']; if (! in_array($action, $valid, true)) { @@ -1480,6 +1486,7 @@ public function addNamedActionLink(float $x, float $y, float $width, float $heig 'x1' => $x, 'y1' => $y, 'x2' => $x + $width, 'y2' => $y + $height, 'target' => $action, + 'contents' => $contents, ]; return $this; @@ -1488,13 +1495,14 @@ public function addNamedActionLink(float $x, float $y, float $width, float $heig /** * JavaScript link — click executes $script. */ - public function addJavaScriptLink(float $x, float $y, float $width, float $height, string $script): self + public function addJavaScriptLink(float $x, float $y, float $width, float $height, string $script, ?string $contents = null): self { $this->linkAnnotations[] = [ 'kind' => 'javascript', 'x1' => $x, 'y1' => $y, 'x2' => $x + $width, 'y2' => $y + $height, 'target' => $script, + 'contents' => $contents, ]; return $this; @@ -1505,20 +1513,21 @@ public function addJavaScriptLink(float $x, float $y, float $width, float $heigh * * Note: most PDF readers disable launch actions by default for security. */ - public function addLaunchLink(float $x, float $y, float $width, float $height, string $filePath): self + public function addLaunchLink(float $x, float $y, float $width, float $height, string $filePath, ?string $contents = null): self { $this->linkAnnotations[] = [ 'kind' => 'launch', 'x1' => $x, 'y1' => $y, 'x2' => $x + $width, 'y2' => $y + $height, 'target' => $filePath, + 'contents' => $contents, ]; return $this; } /** - * @return list<array{kind: 'uri'|'internal', x1: float, y1: float, x2: float, y2: float, target: string}> + * @return list<array{kind: 'uri'|'internal'|'named'|'javascript'|'launch', x1: float, y1: float, x2: float, y2: float, target: string, contents: ?string}> * * @internal */ diff --git a/tests/Pdf/LinkContentsTest.php b/tests/Pdf/LinkContentsTest.php new file mode 100644 index 0000000..11b84ac --- /dev/null +++ b/tests/Pdf/LinkContentsTest.php @@ -0,0 +1,65 @@ +<?php + +declare(strict_types=1); + +namespace Dskripchenko\PhpPdf\Tests\Pdf; + +use Dskripchenko\PhpPdf\Pdf\Document as PdfDocument; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +/** + * A link's description (/Contents) is what assistive technology reads for + * it. PDF/UA requires one on every link annotation (ISO 14289-1 §7.18.5). + */ +final class LinkContentsTest extends TestCase +{ + #[Test] + public function every_kind_of_link_takes_a_description(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $page = $pdf->addPage(); + $page->addExternalLink(10, 10, 50, 10, 'https://example.com', 'Example website'); + $page->addInternalLink(10, 30, 50, 10, 'target', 'Go to the summary'); + $page->addNamedActionLink(10, 50, 50, 10, 'NextPage', 'Next page'); + $page->addJavaScriptLink(10, 70, 50, 10, 'app.alert(1)', 'Show a message'); + $page->addLaunchLink(10, 90, 50, 10, 'other.pdf', 'Open the appendix'); + $pdf->registerDestination('target', $page, 0, 0); + $bytes = $pdf->toBytes(); + + foreach (['Example website', 'Go to the summary', 'Next page', 'Show a message', 'Open the appendix'] as $text) { + self::assertStringContainsString('/Contents ('.$text.')', $bytes); + } + } + + #[Test] + public function a_link_without_a_description_has_no_contents_entry(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage()->addExternalLink(10, 10, 50, 10, 'https://example.com'); + + preg_match('@<< /Type /Annot /Subtype /Link\b.*?>>\s*endobj@s', $pdf->toBytes(), $m); + self::assertNotEmpty($m); + self::assertStringNotContainsString('/Contents', $m[0]); + } + + #[Test] + public function a_tagged_link_keeps_its_struct_parent_beside_the_description(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enableTagged(); + $pdf->addPage()->addExternalLink(10, 10, 50, 10, 'https://example.com', 'Example'); + + self::assertMatchesRegularExpression('@/Contents \(Example\) /StructParent \d+@', $pdf->toBytes()); + } + + #[Test] + public function a_non_ascii_description_is_written_as_a_text_string(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->addPage()->addExternalLink(10, 10, 50, 10, 'https://example.com', 'Café menu'); + + // UTF-16BE with BOM, as every PDF text string outside PDFDocEncoding. + self::assertStringContainsString('/Contents <FEFF', $pdf->toBytes()); + } +} From 2cc789c0c967555c0fff5878981ab6a7feba744a Mon Sep 17 00:00:00 2001 From: Dan Krieger <dan@codingislife.com> Date: Thu, 12 Nov 2026 05:54:41 -0800 Subject: [PATCH 5/7] feat(tagged): attribute objects on struct elements MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A struct element had no way to carry an attribute object (/A, ISO 32000-1 §14.8.5). PDF/UA needs one on table header cells: a TH needs /Scope, or /Headers with IDs, so a reader can tell which cells it heads (ISO 14289-1 §7.5). ColSpan, RowSpan and the list numbering style live there too. addStructElement() and beginStructContainer() take an optional $attributes array, e.g. ['O' => 'Table', 'Scope' => 'Column'], written as /A << /O /Table /Scope /Column >>. String values are names, numbers are numbers. An object without an owner (O), or a name that isn't a plain PDF name, throws, so a value can't break out of the dictionary. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/Pdf/Document.php | 59 +++++++++++++++++++++-- tests/Pdf/StructAttributesTest.php | 77 ++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 5 deletions(-) create mode 100644 tests/Pdf/StructAttributesTest.php diff --git a/src/Pdf/Document.php b/src/Pdf/Document.php index 2fdbba3..d541295 100644 --- a/src/Pdf/Document.php +++ b/src/Pdf/Document.php @@ -357,7 +357,7 @@ public function attachFile(string $name, string $bytes, ?string $mimeType = null * carry mcid = null plus a list of child element indexes. Hierarchy * lives in the structure tree — marked-content sequences never nest. * - * @var list<array{type: string, mcid: ?int, page: Page, altText?: ?string, parent: ?int, children: list<int>, objr?: int}> + * @var list<array{type: string, mcid: ?int, page: Page, altText?: ?string, parent: ?int, children: list<int>, objr?: int, attributes?: string}> */ private array $structElements = []; @@ -405,8 +405,15 @@ public function isTagged(): bool /** * @internal Used by the Engine to register leaf struct elements * (the ones owning a marked-content sequence). + * + * $attributes is the element's attribute object (/A): an owner under + * 'O' and its attributes, e.g. ['O' => 'Table', 'Scope' => 'Column'] + * for a column header cell (ISO 32000-1 §14.8.5). String values are + * written as names, numbers as numbers. + * + * @param array<string, string|int|float> $attributes */ - public function addStructElement(string $type, int $mcid, Page $page, ?string $altText = null): void + public function addStructElement(string $type, int $mcid, Page $page, ?string $altText = null, array $attributes = []): void { $parent = $this->structContainerStack === [] ? null @@ -415,6 +422,7 @@ public function addStructElement(string $type, int $mcid, Page $page, ?string $a $this->structElements[] = [ 'type' => $type, 'mcid' => $mcid, 'page' => $page, 'altText' => $altText, 'parent' => $parent, 'children' => [], + 'attributes' => self::structAttributes($attributes), ]; if ($parent !== null) { $this->structElements[$parent]['children'][] = $idx; @@ -425,8 +433,11 @@ public function addStructElement(string $type, int $mcid, Page $page, ?string $a * @internal Open a grouping struct element (Table, TR, TD, L, LI...). * Containers have no marked content of their own — their /K is the * list of child elements, so MCID sequences never nest. + * $attributes as for addStructElement() — e.g. a TH container's scope. + * + * @param array<string, string|int|float> $attributes */ - public function beginStructContainer(string $type, Page $page): void + public function beginStructContainer(string $type, Page $page, array $attributes = []): void { $parent = $this->structContainerStack === [] ? null @@ -435,6 +446,7 @@ public function beginStructContainer(string $type, Page $page): void $this->structElements[] = [ 'type' => $type, 'mcid' => null, 'page' => $page, 'altText' => null, 'parent' => $parent, 'children' => [], + 'attributes' => self::structAttributes($attributes), ]; if ($parent !== null) { $this->structElements[$parent]['children'][] = $idx; @@ -450,6 +462,42 @@ public function endStructContainer(): void array_pop($this->structContainerStack); } + /** + * An attribute object as a PDF dictionary, or '' for none. + * + * @param array<string, string|int|float> $attributes + */ + private static function structAttributes(array $attributes): string + { + if ($attributes === []) { + return ''; + } + if (! isset($attributes['O'])) { + throw new \InvalidArgumentException('A struct attribute object needs an owner under \'O\' (e.g. Table, List, Layout).'); + } + $entries = []; + foreach ($attributes as $key => $value) { + if (preg_match('/^[A-Za-z][A-Za-z0-9]*$/', $key) !== 1) { + throw new \InvalidArgumentException(sprintf('Invalid struct attribute name "%s".', $key)); + } + if (is_string($value)) { + if (preg_match('/^[A-Za-z][A-Za-z0-9]*$/', $value) !== 1) { + throw new \InvalidArgumentException(sprintf('Invalid value "%s" for struct attribute %s: expected a name.', $value, $key)); + } + $entries[] = '/'.$key.' /'.$value; + } elseif (is_int($value)) { + $entries[] = '/'.$key.' '.$value; + } else { + if (! is_finite($value)) { + throw new \InvalidArgumentException(sprintf('Struct attribute %s must be finite.', $key)); + } + $entries[] = '/'.$key.' '.rtrim(rtrim(sprintf('%.4F', $value), '0'), '.'); + } + } + + return '<< '.implode(' ', $entries).' >>'; + } + /** * Enable PDF/A compliance. Conformance 'A' (accessibility) auto-enables * Tagged PDF. @@ -1619,9 +1667,10 @@ private function buildWriter(): Writer } else { $kPart = (string) $elem['mcid']; } + $attrPart = ($elem['attributes'] ?? '') !== '' ? ' /A '.$elem['attributes'] : ''; $writer->setObject($elemId, sprintf( - '<< /Type /StructElem /S /%s /P %d 0 R /Pg %d 0 R /K %s%s >>', - $elem['type'], $parentRef, $pageId, $kPart, $altPart, + '<< /Type /StructElem /S /%s /P %d 0 R /Pg %d 0 R /K %s%s%s >>', + $elem['type'], $parentRef, $pageId, $kPart, $altPart, $attrPart, )); if ($elem['parent'] === null) { $childIds[] = $elemId; diff --git a/tests/Pdf/StructAttributesTest.php b/tests/Pdf/StructAttributesTest.php new file mode 100644 index 0000000..d07a763 --- /dev/null +++ b/tests/Pdf/StructAttributesTest.php @@ -0,0 +1,77 @@ +<?php + +declare(strict_types=1); + +namespace Dskripchenko\PhpPdf\Tests\Pdf; + +use Dskripchenko\PhpPdf\Pdf\Document as PdfDocument; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +/** + * Struct elements can carry an attribute object (/A, ISO 32000-1 §14.8.5). + * PDF/UA needs one on table header cells: a TH without /Scope (or + * /Headers and IDs) fails ISO 14289-1 §7.5. + */ +final class StructAttributesTest extends TestCase +{ + #[Test] + public function a_leaf_writes_its_attribute_object(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enableTagged(); + $page = $pdf->addPage(); + $pdf->beginStructContainer('Table', $page); + $pdf->beginStructContainer('TR', $page); + $mcid = $page->nextMcid(); + $pdf->addStructElement('TH', $mcid, $page, attributes: ['O' => 'Table', 'Scope' => 'Column']); + $pdf->endStructContainer(); + $pdf->endStructContainer(); + + self::assertMatchesRegularExpression('@/S /TH .*?/A << /O /Table /Scope /Column >> >>@', $pdf->toBytes()); + } + + #[Test] + public function a_container_writes_its_attribute_object_with_numbers(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enableTagged(); + $page = $pdf->addPage(); + $pdf->beginStructContainer('TD', $page, ['O' => 'Table', 'ColSpan' => 2, 'RowSpan' => 1]); + $pdf->addStructElement('P', $page->nextMcid(), $page); + $pdf->endStructContainer(); + + self::assertStringContainsString('/A << /O /Table /ColSpan 2 /RowSpan 1 >>', $pdf->toBytes()); + } + + #[Test] + public function no_attributes_write_no_attribute_object(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enableTagged(); + $page = $pdf->addPage(); + $pdf->addStructElement('P', $page->nextMcid(), $page); + + self::assertStringNotContainsString('/A <<', $pdf->toBytes()); + } + + #[Test] + public function an_attribute_object_needs_an_owner(): void + { + $pdf = PdfDocument::new(); + $page = $pdf->addPage(); + + $this->expectException(\InvalidArgumentException::class); + $pdf->addStructElement('TH', 0, $page, attributes: ['Scope' => 'Column']); + } + + #[Test] + public function a_value_that_is_not_a_name_is_rejected(): void + { + $pdf = PdfDocument::new(); + $page = $pdf->addPage(); + + $this->expectException(\InvalidArgumentException::class); + $pdf->addStructElement('TH', 0, $page, attributes: ['O' => 'Table', 'Scope' => 'Column >> /K 99']); + } +} From 898d8e3fe7e24d1f2f6091630617fca29c473dbf Mon Sep 17 00:00:00 2001 From: Dan Krieger <dan@codingislife.com> Date: Thu, 12 Nov 2026 05:56:19 -0800 Subject: [PATCH 6/7] feat(tagged): place link elements in reading order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every link's struct element was added at the end of the root, after all the content, with only the annotation in it. A screen reader met the links after the document, detached from their text, and a Link could not hold the text it labels, which PDF/UA asks for (ISO 14289-1 §7.18.5: the link text and the annotation in one Link element). Document::placeLinkInStructure($page) puts the link last added to $page into the tree where it is called. Inside a Link container opened around the link's text, the annotation joins that element, whose /K then lists the text and the OBJR. Elsewhere a Link element is added under the innermost open container. The annotation's /StructParent and the ParentTree point at the placed element. Links that are not placed keep the old behaviour, and the call does nothing on an untagged document. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/Pdf/Document.php | 90 +++++++++++++--- tests/Pdf/TaggedLinkPlacementTest.php | 148 ++++++++++++++++++++++++++ 2 files changed, 226 insertions(+), 12 deletions(-) create mode 100644 tests/Pdf/TaggedLinkPlacementTest.php diff --git a/src/Pdf/Document.php b/src/Pdf/Document.php index d541295..0616e6e 100644 --- a/src/Pdf/Document.php +++ b/src/Pdf/Document.php @@ -357,7 +357,7 @@ public function attachFile(string $name, string $bytes, ?string $mimeType = null * carry mcid = null plus a list of child element indexes. Hierarchy * lives in the structure tree — marked-content sequences never nest. * - * @var list<array{type: string, mcid: ?int, page: Page, altText?: ?string, parent: ?int, children: list<int>, objr?: int, attributes?: string}> + * @var list<array{type: string, mcid: ?int, page: Page, altText?: ?string, parent: ?int, children: list<int>, objr?: int, attributes?: string, holdsLink?: bool}> */ private array $structElements = []; @@ -377,6 +377,14 @@ public function attachFile(string $name, string $bytes, ?string $mimeType = null */ private array $structParentLinkKeys = []; + /** + * Links given a place in the structure tree by placeLinkInStructure(): + * page index → link annotation index → struct element index. + * + * @var array<int, array<int, int>> + */ + private array $placedLinks = []; + /** * Enable Tagged PDF (accessibility). * @@ -462,6 +470,52 @@ public function endStructContainer(): void array_pop($this->structContainerStack); } + /** + * Puts the link annotation last added to $page into the structure tree + * here, in reading order. Inside an open Link container (opened with + * beginStructContainer('Link', ...) around the link's text) the + * annotation joins that element, so it holds both the text and the + * annotation, as PDF/UA asks (ISO 14289-1 §7.18.5). Otherwise a Link + * element is added under the innermost open container. + * + * Links that are not placed keep their default: a Link element at the + * end of the root. Does nothing on an untagged document. + */ + public function placeLinkInStructure(Page $page): void + { + if (! $this->tagged) { + return; + } + $annotations = count($page->linkAnnotations()); + if ($annotations === 0) { + throw new \LogicException('placeLinkInStructure() needs a link annotation on the page; add the link first.'); + } + $pageIndex = array_search($page, $this->pages, true); + if ($pageIndex === false) { + throw new \LogicException('placeLinkInStructure() was given a page of another document.'); + } + $parent = $this->structContainerStack === [] + ? null + : $this->structContainerStack[count($this->structContainerStack) - 1]; + // One annotation per Link container: a second link inside it gets + // an element of its own. + if ($parent !== null && $this->structElements[$parent]['type'] === 'Link' + && ! ($this->structElements[$parent]['holdsLink'] ?? false)) { + $idx = $parent; + $this->structElements[$parent]['holdsLink'] = true; + } else { + $idx = count($this->structElements); + $this->structElements[] = [ + 'type' => 'Link', 'mcid' => null, 'page' => $page, + 'altText' => null, 'parent' => $parent, 'children' => [], + ]; + if ($parent !== null) { + $this->structElements[$parent]['children'][] = $idx; + } + } + $this->placedLinks[(int) $pageIndex][$annotations - 1] = $idx; + } + /** * An attribute object as a PDF dictionary, or '' for none. * @@ -1276,7 +1330,8 @@ private function buildWriter(): Writer // Annotations: emit /Annot objects + reference array. $annotIds = []; - foreach ($page->linkAnnotations() as $ann) { + $placedOnPage = $this->placedLinks[$i] ?? []; + foreach ($page->linkAnnotations() as $annIndex => $ann) { $rect = sprintf( '[%s %s %s %s]', $this->fmt($ann['x1']), $this->fmt($ann['y1']), @@ -1339,16 +1394,23 @@ private function buildWriter(): Writer // Tagged PDF — register /Link struct element referencing // this annotation via /OBJR; reserve a ParentTree entry // under the reserved StructParent key. + // A link placed with placeLinkInStructure() already has its + // element in reading order; any other goes at the root. if ($this->tagged) { - $structIdx = count($this->structElements); - $this->structElements[] = [ - 'type' => 'Link', - 'mcid' => null, - 'page' => $page, - 'objr' => $linkAnnotId, - 'parent' => null, - 'children' => [], - ]; + $structIdx = $placedOnPage[$annIndex] ?? null; + if ($structIdx !== null) { + $this->structElements[$structIdx]['objr'] = $linkAnnotId; + } else { + $structIdx = count($this->structElements); + $this->structElements[] = [ + 'type' => 'Link', + 'mcid' => null, + 'page' => $page, + 'objr' => $linkAnnotId, + 'parent' => null, + 'children' => [], + ]; + } $this->structParentLinkKeys[$structIdx] = $structParentKey; } } @@ -1656,13 +1718,17 @@ private function buildWriter(): Writer if (! empty($elem['altText'])) { $altPart = ' /Alt '.$this->pdfTextString((string) $elem['altText']); } - if (! empty($elem['objr'])) { + if (! empty($elem['objr']) && $elem['children'] === []) { $kPart = sprintf('<< /Type /OBJR /Obj %d 0 R >>', $elem['objr']); } elseif ($elem['mcid'] === null) { $kids = array_map( fn (int $childIdx) => sprintf('%d 0 R', $elemIds[$childIdx]), array_values(array_filter($elem['children'], fn (int $c) => isset($elemIds[$c]))), ); + // A Link container holds its text and its annotation. + if (! empty($elem['objr'])) { + $kids[] = sprintf('<< /Type /OBJR /Obj %d 0 R >>', $elem['objr']); + } $kPart = '['.implode(' ', $kids).']'; } else { $kPart = (string) $elem['mcid']; diff --git a/tests/Pdf/TaggedLinkPlacementTest.php b/tests/Pdf/TaggedLinkPlacementTest.php new file mode 100644 index 0000000..727c8af --- /dev/null +++ b/tests/Pdf/TaggedLinkPlacementTest.php @@ -0,0 +1,148 @@ +<?php + +declare(strict_types=1); + +namespace Dskripchenko\PhpPdf\Tests\Pdf; + +use Dskripchenko\PhpPdf\Pdf\Document as PdfDocument; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +/** + * placeLinkInStructure() puts a link's struct element where the link is in + * reading order, instead of at the end of the root, and lets a Link + * element hold both the link text and the annotation (ISO 14289-1 §7.18.5). + */ +final class TaggedLinkPlacementTest extends TestCase +{ + #[Test] + public function a_placed_link_sits_inside_its_container_in_reading_order(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enableTagged(); + $page = $pdf->addPage(); + $pdf->beginStructContainer('Sect', $page); + $pdf->addStructElement('P', $page->nextMcid(), $page); + $page->addExternalLink(10, 10, 50, 10, 'https://example.com', 'Example'); + $pdf->placeLinkInStructure($page); + $pdf->addStructElement('P', $page->nextMcid(), $page); + $pdf->endStructContainer(); + $bytes = $pdf->toBytes(); + + $elems = self::structElements($bytes); + $sect = self::single($elems, 'Sect'); + $kids = self::refs($sect['K']); + self::assertCount(3, $kids); + self::assertSame(['P', 'Link', 'P'], array_map(fn (int $id) => $elems[$id]['S'], $kids)); + // Exactly one Link element: the placed one, not a second one at the root. + self::assertSame(1, substr_count($bytes, '/S /Link')); + } + + #[Test] + public function a_link_container_holds_its_text_and_its_annotation(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enableTagged(); + $page = $pdf->addPage(); + $pdf->beginStructContainer('Link', $page); + $pdf->addStructElement('Span', $page->nextMcid(), $page); + $page->addExternalLink(10, 10, 50, 10, 'https://example.com', 'Example'); + $pdf->placeLinkInStructure($page); + $pdf->endStructContainer(); + $bytes = $pdf->toBytes(); + + $link = self::single(self::structElements($bytes), 'Link'); + self::assertMatchesRegularExpression('@^\[\d+ 0 R << /Type /OBJR /Obj \d+ 0 R >>\]$@', $link['K']); + self::assertSame(1, substr_count($bytes, '/S /Link')); + } + + #[Test] + public function the_annotation_points_back_at_the_placed_element(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enableTagged(); + $page = $pdf->addPage(); + $pdf->beginStructContainer('Sect', $page); + $page->addExternalLink(10, 10, 50, 10, 'https://example.com', 'Example'); + $pdf->placeLinkInStructure($page); + $pdf->endStructContainer(); + $bytes = $pdf->toBytes(); + + preg_match('@/Subtype /Link\b.*?/StructParent (\d+)@s', $bytes, $m); + $key = $m[1]; + preg_match('@/ParentTree (\d+) 0 R@', $bytes, $pt); + preg_match('@\n'.$pt[1].' 0 obj\s*<< /Nums \[(.*?)\] >>@s', $bytes, $nums); + preg_match('@(?:^|\s)'.$key.' (\d+) 0 R@', $nums[1], $target); + $linkId = array_search('Link', array_map(fn (array $e) => $e['S'], self::structElements($bytes)), true); + self::assertSame($linkId, (int) $target[1]); + } + + #[Test] + public function links_that_are_not_placed_still_go_at_the_root(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enableTagged(); + $page = $pdf->addPage(); + $pdf->beginStructContainer('Sect', $page); + $pdf->addStructElement('P', $page->nextMcid(), $page); + $page->addExternalLink(10, 10, 50, 10, 'https://example.com'); + $pdf->endStructContainer(); + + $elems = self::structElements($pdf->toBytes()); + self::assertCount(1, self::refs(self::single($elems, 'Sect')['K'])); + } + + #[Test] + public function placing_on_an_untagged_document_does_nothing(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $page = $pdf->addPage(); + $page->addExternalLink(10, 10, 50, 10, 'https://example.com'); + $pdf->placeLinkInStructure($page); + + self::assertStringNotContainsString('/StructTreeRoot', $pdf->toBytes()); + } + + #[Test] + public function placing_without_a_link_throws(): void + { + $pdf = PdfDocument::new(); + $pdf->enableTagged(); + $page = $pdf->addPage(); + + $this->expectException(\LogicException::class); + $pdf->placeLinkInStructure($page); + } + + /** @return array<int, array{S: string, K: string}> struct elements by object id */ + private static function structElements(string $bytes): array + { + preg_match_all('@\n(\d+) 0 obj\s*<< /Type /StructElem /S /(\w+) .*?/K (\[.*?\]|<< .*? >>|\d+)(?: /| >>)@s', $bytes, $m, PREG_SET_ORDER); + $out = []; + foreach ($m as $match) { + $out[(int) $match[1]] = ['S' => $match[2], 'K' => $match[3]]; + } + + return $out; + } + + /** + * @param array<int, array{S: string, K: string}> $elems + * @return array{S: string, K: string} + */ + private static function single(array $elems, string $type): array + { + $found = array_values(array_filter($elems, fn (array $e) => $e['S'] === $type)); + self::assertCount(1, $found); + + return $found[0]; + } + + /** @return list<int> */ + private static function refs(string $k): array + { + preg_match_all('@(\d+) 0 R@', preg_replace('@<< /Type /OBJR .*? >>@', '', $k) ?? $k, $m); + + return array_map(intval(...), $m[1]); + } +} From 623bb18a2ba271c68946931d0c531c9a4d13ba79 Mon Sep 17 00:00:00 2001 From: Dan Krieger <dan@codingislife.com> Date: Thu, 12 Nov 2026 06:04:11 -0800 Subject: [PATCH 7/7] feat(pdfua): identify a document as PDF/UA-1 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A tagged document could not claim PDF/UA. ISO 14289-1 §5 and §7.1 want the Catalog's XMP metadata with pdfuaid:part, a dc:title and DisplayDocTitle; php-pdf wrote XMP only for PDF/A and PDF/X, so veraPDF failed every tagged document on 7.1-8 however well it was tagged. Document::enablePdfUa() enables Tagged PDF and at render: - writes an XMP packet with pdfuaid:part 1 from the same /Info values PDF/A uses (title, author, subject, keywords, creator, producer, dates), or adds pdfuaid to the PDF/A packet when PDF/A is enabled too, with the extension schema PDF/A needs for a schema it doesn't predefine (ISO 19005-2 §6.6.2.3.2); - sets DisplayDocTitle, merged into any other viewer preferences; - gives pages that have annotations /Tabs /S (§7.18.3) unless a tab order was set; - throws without a document title. PDF/UA with PDF/X throws too, as both write their own packet. The XMP builder moves out of PdfAConfig into an internal XmpPacket, so both share it; a PDF/A-only packet is byte for byte as before. New conformance references: pdfua-1, a tagged document built on the low-level writer (headings, a paragraph whose link sits in its Link element with the text, a table with header scope, artifacts), and pdfa-2u-ua1, the same as PDF/A-2u too. verapdf.sh checks the first against PDF/UA-1 and the second against both PDF/A-2u and PDF/UA-1; all pass with veraPDF 1.30.3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/en/CONFORMANCE.md | 9 +- scripts/conformance/generate.php | 87 ++++++++++++++++++ scripts/conformance/verapdf.sh | 25 +++--- src/Pdf/Document.php | 87 +++++++++++++++--- src/Pdf/PdfAConfig.php | 85 +++--------------- src/Pdf/XmpPacket.php | 150 +++++++++++++++++++++++++++++++ tests/Pdf/PdfUaTest.php | 150 +++++++++++++++++++++++++++++++ 7 files changed, 497 insertions(+), 96 deletions(-) create mode 100644 src/Pdf/XmpPacket.php create mode 100644 tests/Pdf/PdfUaTest.php diff --git a/docs/en/CONFORMANCE.md b/docs/en/CONFORMANCE.md index 0f2a918..f6cd03b 100644 --- a/docs/en/CONFORMANCE.md +++ b/docs/en/CONFORMANCE.md @@ -13,6 +13,7 @@ summary page. | Check | Standard | Tool | References | |---|---|---|---| | PDF/A validation | ISO 19005 | [veraPDF](https://verapdf.org) — the industry-standard open-source validator | PDF/A-1b, 1a, 2b, 2u, 3b, and a signed PDF/A-2b with a signature stamp | +| PDF/UA validation | ISO 14289-1 | veraPDF, PDF/UA-1 profile (its machine-checkable rules) | a tagged PDF/UA-1 document built on the low-level writer (headings, a link in its Link element, a table with header scope, artifacts), and the same document as PDF/A-2u + PDF/UA-1, checked against both | | PDF/X structure | ISO 15930 | Ghostscript render (`-dPDFSTOPONERROR`) + byte-level assertions (OutputIntent `/GTS_PDFX`, CMYK profile and RGB-operator ban for X-1a, Info keys, trailer `/ID`, TrimBox/ArtBox per page, no encryption) | PDF/X-1a, X-3, X-4 | | Visual regression | — | poppler `pdftoppm` render diffed against committed golden PNGs (ImageMagick, 5% fuzz, ≤0.5% differing pixels) | reference pages, form fill, signature stamps | | Signatures | ETSI EN 319 142 (PAdES), RFC 5652, RFC 3161 | OpenSSL CLI: `openssl cms -verify` over the exact `/ByteRange` bytes up to a test root CA, `openssl ts -verify` for timestamps; tampering must break verification. [pyHanko](https://github.com/MatthiasValvekens/pyHanko) validates the signed PDFs as a whole (trust, timestamp, whole-file coverage) | test suite (`Signature*Test`, `PadesSignatureTest`, `CmsBuilderTest`) | @@ -35,7 +36,7 @@ with the sRGB2014 ICC profile vendored in bash scripts/fetch-fonts.sh php scripts/conformance/generate.php -# PDF/A — requires veraPDF (https://verapdf.org, or `brew install verapdf`) +# PDF/A and PDF/UA — requires veraPDF (https://verapdf.org, or `brew install verapdf`) bash scripts/conformance/verapdf.sh # PDF/X — requires Ghostscript @@ -59,6 +60,12 @@ vendor/bin/phpunit tests/Pdf/SignatureOpenSslTest.php not sufficient, conditions. - veraPDF emits "Nested MCID" *warnings* (not violations) for tagged documents; tightening the tagged emission is tracked as future work. +- **PDF/UA** has rules no validator can check — that alternate text + describes the image, that the reading order makes sense, that the tags + match what the content is. veraPDF checks the machine-checkable ones; + the rest needs a person with a screen reader (or the PAC/Matterhorn + human checks). `enablePdfUa()` writes the identification and metadata; + tagging the content correctly is the caller's job. - Signature verification by the OpenSSL CLI proves cryptographic correctness over `/ByteRange`; the Acrobat signature panel is verified manually as part of the [viewer matrix](VIEWER-MATRIX.md). diff --git a/scripts/conformance/generate.php b/scripts/conformance/generate.php index 35d95f3..ea3faaf 100644 --- a/scripts/conformance/generate.php +++ b/scripts/conformance/generate.php @@ -361,4 +361,91 @@ signature: $signature, )) ? 0 : 1; +// PDF/UA-1: a tagged document built on the low-level writer, as a layout +// engine on top of php-pdf would — headings, a paragraph with a link held +// in its Link element, a table whose header cells have a scope, and a +// running footer marked as an artifact. pdfua-1 is PDF/UA alone; +// pdfa-2u-ua1 is the same document as PDF/A-2u too, checked against both. +$pdfUaReference = function (?PdfAConfig $pdfA) use ($fontDir): PdfDocument { + $regular = new PdfFont(TtfFile::fromFile($fontDir.'/LiberationSans-Regular.ttf')); + $bold = new PdfFont(TtfFile::fromFile($fontDir.'/LiberationSans-Bold.ttf')); + $pdf = PdfDocument::new(); + if ($pdfA !== null) { + $pdf->enablePdfA($pdfA); + } + $pdf->enablePdfUa(); + $pdf->setLang('en'); + $pdf->metadata( + title: 'php-pdf conformance reference — PDF/UA-1', + author: 'dskripchenko/php-pdf', + creationDate: new DateTimeImmutable('2026-01-01 00:00:00', new DateTimeZone('UTC')), + ); + $page = $pdf->addPage(); + $leaf = function (string $type, \Closure $draw, array $attributes = []) use ($pdf, $page): void { + $mcid = $page->nextMcid(); + $pdf->addStructElement($type, $mcid, $page, attributes: $attributes); + $page->beginMarkedContent($type, $mcid); + $draw(); + $page->endMarkedContent(); + }; + + $pdf->beginStructContainer('Document', $page); + $leaf('H1', fn () => $page->showEmbeddedText('Accessible Reference Document', 72, 760, $bold, 20)); + $leaf('P', fn () => $page->showEmbeddedText('Every piece of content here is tagged, and the footer is an artifact.', 72, 730, $regular, 11)); + + $pdf->beginStructContainer('P', $page); + $leaf('Span', fn () => $page->showEmbeddedText('Read more at ', 72, 710, $regular, 11)); + $pdf->beginStructContainer('Link', $page); + $leaf('Span', fn () => $page->showEmbeddedText('the PDF Association', 140, 710, $regular, 11, 0.1, 0.2, 0.6)); + $page->addExternalLink(140, 706, 104, 14, 'https://pdfa.org/', 'The PDF Association website'); + $pdf->placeLinkInStructure($page); + $pdf->endStructContainer(); + $leaf('Span', fn () => $page->showEmbeddedText('.', 244, 710, $regular, 11)); + $pdf->endStructContainer(); + + $leaf('H2', fn () => $page->showEmbeddedText('Standards', 72, 670, $bold, 14)); + $rows = [['Standard', 'Number'], ['PDF/A-2', 'ISO 19005-2'], ['PDF/UA-1', 'ISO 14289-1']]; + $pdf->beginStructContainer('Table', $page); + foreach ($rows as $r => $cells) { + $y = 645 - $r * 20; + $pdf->beginStructContainer('TR', $page); + foreach ($cells as $c => $text) { + $header = $r === 0; + $leaf( + $header ? 'TH' : 'TD', + fn () => $page->showEmbeddedText($text, 72 + $c * 150, $y, $header ? $bold : $regular, 11), + $header ? ['O' => 'Table', 'Scope' => 'Column'] : [], + ); + } + $pdf->endStructContainer(); + $page->beginArtifact('Layout'); + $page->strokeLine(72, $y - 6, 372, $y - 6, 0.5, 0.6, 0.6, 0.6); + $page->endMarkedContent(); + } + $pdf->endStructContainer(); + $pdf->endStructContainer(); + + $page->beginArtifact('Pagination'); + $page->showEmbeddedText('Page 1', 72, 40, $regular, 9); + $page->endMarkedContent(); + + return $pdf; +}; +foreach (['pdfua-1' => null, 'pdfa-2u-ua1' => new PdfAConfig( + $iccPath, + iccProfileName: 'sRGB2014', + lang: 'en', + part: PdfAConfig::PART_2, + conformance: PdfAConfig::CONFORMANCE_U, +)] as $name => $pdfA) { + $path = $outDir.'/'.$name.'.pdf'; + try { + file_put_contents($path, $pdfUaReference($pdfA)->toBytes()); + echo "generated $path\n"; + } catch (\Throwable $e) { + fwrite(STDERR, "FAILED $name: {$e->getMessage()}\n"); + $failures++; + } +} + exit($failures > 0 ? 1 : 0); diff --git a/scripts/conformance/verapdf.sh b/scripts/conformance/verapdf.sh index 8263cb8..d22d9d0 100755 --- a/scripts/conformance/verapdf.sh +++ b/scripts/conformance/verapdf.sh @@ -1,36 +1,41 @@ #!/usr/bin/env bash -# Validate the reference PDF/A documents with veraPDF. +# Validate the reference PDF/A and PDF/UA documents with veraPDF. # # Usage: scripts/conformance/verapdf.sh [dir] # dir — directory with the generated references (default build/conformance) # # Env: VERAPDF — path to the veraPDF CLI (default: `verapdf` on PATH). # -# Writes per-file JSON reports (<name>.verapdf.json) and a summary.md table +# Writes per-file JSON reports (<name>.<flavour>.verapdf.json) and a summary.md table # into the same directory. Exits non-zero if any document is non-compliant. set -euo pipefail DIR="${1:-build/conformance}" VERAPDF="${VERAPDF:-verapdf}" -NAMES=(pdfa-1b pdfa-1a pdfa-2b pdfa-2u pdfa-3b pdfa-2b-signed pdfa-1b-annotated pdfa-2b-annotated pdfa-1b-cff pdfa-2u-cff pdfa-2u-cff-cid) -# pdfa-2b-signed → 2b -flavour() { local f="${1#pdfa-}"; echo "${f%%-*}"; } +# name, or name:flavour when the flavour isn't the part after "pdfa-" +# (pdfa-2b-signed → 2b). pdfa-2u-ua1 is checked as PDF/A-2u and as PDF/UA-1. +NAMES=(pdfa-1b pdfa-1a pdfa-2b pdfa-2u pdfa-3b pdfa-2b-signed pdfa-1b-annotated pdfa-2b-annotated pdfa-1b-cff pdfa-2u-cff pdfa-2u-cff-cid pdfua-1:ua1 pdfa-2u-ua1 pdfa-2u-ua1:ua1) +flavour() { + if [[ "$1" == *:* ]]; then echo "${1#*:}"; return; fi + local f="${1#pdfa-}"; echo "${f%%-*}" +} version="$("$VERAPDF" --version 2>/dev/null | head -1 || echo 'veraPDF')" summary="$DIR/summary.md" { - echo "## PDF/A conformance — $version" + echo "## PDF/A and PDF/UA conformance — $version" echo echo "| Document | Flavour | Compliant | Failed rules |" echo "|---|---|---|---|" } > "$summary" fail=0 -for name in "${NAMES[@]}"; do - fl="$(flavour "$name")" +for entry in "${NAMES[@]}"; do + fl="$(flavour "$entry")" + name="${entry%%:*}" pdf="$DIR/$name.pdf" - json="$DIR/$name.verapdf.json" + json="$DIR/$name.$fl.verapdf.json" if [[ ! -f "$pdf" ]]; then echo "MISSING $pdf" >&2 @@ -40,7 +45,7 @@ for name in "${NAMES[@]}"; do fi # veraPDF exits non-zero for non-compliant files — capture, don't abort. - "$VERAPDF" -f "$fl" --format json "$pdf" > "$json" 2> "$DIR/$name.verapdf.log" || true + "$VERAPDF" -f "$fl" --format json "$pdf" > "$json" 2> "$DIR/$name.$fl.verapdf.log" || true read -r compliant failed_rules < <(python3 - "$json" <<'PY' import json, sys diff --git a/src/Pdf/Document.php b/src/Pdf/Document.php index 0616e6e..9b00f23 100644 --- a/src/Pdf/Document.php +++ b/src/Pdf/Document.php @@ -233,6 +233,9 @@ private function buildPageTree(array $pageIds, int $rootId, Writer $writer): arr */ private array $viewerPreferences = []; + /** PDF/UA part claimed in the XMP metadata, or null for none. */ + private ?int $pdfUaPart = null; + /** BCP 47 language tag for /Lang in Catalog. */ private ?string $lang = null; @@ -552,6 +555,35 @@ private static function structAttributes(array $attributes): string return '<< '.implode(' ', $entries).' >>'; } + /** + * Identify the document as PDF/UA-1 (ISO 14289-1, universal + * accessibility). Enables Tagged PDF, writes an XMP metadata stream + * with pdfuaid:part 1 (inside the PDF/A packet when PDF/A is enabled + * too) and sets DisplayDocTitle, so viewers show the title rather than + * the file name. + * + * The document needs a title (metadata(title: ...)); toBytes() throws + * without one. Everything else PDF/UA asks of the content is the + * caller's: a struct element for all real content and artifacts for + * the rest, alt text on figures, a description on links, /Lang + * (setLang()), headings in sequence, embedded fonts. + */ + public function enablePdfUa(): self + { + if ($this->pdfX !== null) { + throw new \LogicException('PDF/UA with PDF/X is not supported — both write their own XMP metadata.'); + } + $this->pdfUaPart = 1; + $this->enableTagged(); + + return $this; + } + + public function isPdfUa(): bool + { + return $this->pdfUaPart !== null; + } + /** * Enable PDF/A compliance. Conformance 'A' (accessibility) auto-enables * Tagged PDF. @@ -595,6 +627,9 @@ public function enablePdfX(PdfXConfig $config): self if ($this->pdfA !== null) { throw new \LogicException('Cannot combine PDF/X and PDF/A — choose one variant.'); } + if ($this->pdfUaPart !== null) { + throw new \LogicException('PDF/UA with PDF/X is not supported — both write their own XMP metadata.'); + } $this->pdfX = $config; // PDF/X-4 requires PDF 1.6+; X-1a/X-3 require PDF 1.4+. if ($config->variant === PdfXConfig::VARIANT_X4) { @@ -1063,6 +1098,9 @@ private function buildWriter(): Writer // (the spec requires ≥ 1 page in the page tree). $this->addPage(); } + if ($this->pdfUaPart !== null && trim($this->infoEntries()['Title'] ?? '') === '') { + throw new \LogicException('PDF/UA requires a document title — set it with metadata(title: ...).'); + } // XRef streams auto-disabled with PKCS#7 signing — the signing path // patches /ByteRange + /Contents in classic xref layout. @@ -1528,8 +1566,14 @@ private function buildWriter(): Writer // /Parent points to the immediate parent (root or intermediate). $parentId = $pageTree['parentOf'][$i]; - // Optional /Tabs entry for form field tab navigation. - $tabsRef = $page->tabOrder() !== null ? ' /Tabs /'.$page->tabOrder() : ''; + // Optional /Tabs entry for form field tab navigation. PDF/UA + // requires structure order on every page with annotations + // (ISO 14289-1 §7.18.3), so that is the default there. + $tabOrder = $page->tabOrder(); + if ($tabOrder === null && $this->pdfUaPart !== null && $annotIds !== []) { + $tabOrder = 'S'; + } + $tabsRef = $tabOrder !== null ? ' /Tabs /'.$tabOrder : ''; $writer->setObject($pageIds[$i], sprintf( '<< /Type /Page /Parent %d 0 R /MediaBox [0 0 %s %s] ' .'/Contents %d 0 R /Resources %s%s%s%s%s%s%s%s%s >>', @@ -1808,7 +1852,7 @@ private function buildWriter(): Writer $pdfARef = ''; if ($this->pdfA !== null) { - $xmp = $this->pdfA->xmpMetadata(info: $info); + $xmp = $this->pdfA->xmpMetadata(info: $info, pdfUaPart: $this->pdfUaPart); // Metadata stream — not filtered, not encrypted. $metadataId = $writer->addObject(sprintf( "<< /Type /Metadata /Subtype /XML /Length %d >>\nstream\n%s\nendstream", @@ -1843,6 +1887,20 @@ private function buildWriter(): Writer ); } + // PDF/UA without PDF/A — an XMP packet of its own, from the same + // /Info values (ISO 14289-1 §7.1: the Catalog's /Metadata with + // pdfuaid:part). + if ($this->pdfUaPart !== null && $this->pdfA === null) { + $xmp = XmpPacket::build($info, 'dskripchenko/php-pdf', identification: [ + 'pdfuaid' => ['part' => (string) $this->pdfUaPart], + ]); + $pdfARef = sprintf(' /Metadata %d 0 R', $writer->addObject(sprintf( + "<< /Type /Metadata /Subtype /XML /Length %d >>\nstream\n%s\nendstream", + strlen($xmp), + $xmp, + ))); + } + // PDF/X — Metadata stream + OutputIntent with /S /GTS_PDFX. if ($this->pdfX !== null) { $xmp = $this->pdfX->xmpMetadata(); @@ -1951,7 +2009,12 @@ private function buildWriter(): Writer // /ViewerPreferences dict. $viewerPrefsRef = ''; - if ($this->viewerPreferences !== []) { + $viewerPreferences = $this->viewerPreferences; + if ($this->pdfUaPart !== null) { + // PDF/UA: show the title, not the file name (ISO 14289-1 §7.1). + $viewerPreferences['displayDocTitle'] = true; + } + if ($viewerPreferences !== []) { $entries = []; $boolKeys = [ 'hideToolbar' => 'HideToolbar', 'hideMenubar' => 'HideMenubar', @@ -1959,18 +2022,18 @@ private function buildWriter(): Writer 'centerWindow' => 'CenterWindow', 'displayDocTitle' => 'DisplayDocTitle', ]; foreach ($boolKeys as $k => $name) { - if (isset($this->viewerPreferences[$k])) { - $entries[] = "/$name ".($this->viewerPreferences[$k] ? 'true' : 'false'); + if (isset($viewerPreferences[$k])) { + $entries[] = "/$name ".($viewerPreferences[$k] ? 'true' : 'false'); } } - if (isset($this->viewerPreferences['direction'])) { - $entries[] = '/Direction /'.$this->viewerPreferences['direction']; + if (isset($viewerPreferences['direction'])) { + $entries[] = '/Direction /'.$viewerPreferences['direction']; } - if (isset($this->viewerPreferences['printScaling'])) { - $entries[] = '/PrintScaling /'.$this->viewerPreferences['printScaling']; + if (isset($viewerPreferences['printScaling'])) { + $entries[] = '/PrintScaling /'.$viewerPreferences['printScaling']; } - if (isset($this->viewerPreferences['duplex'])) { - $entries[] = '/Duplex /'.$this->viewerPreferences['duplex']; + if (isset($viewerPreferences['duplex'])) { + $entries[] = '/Duplex /'.$viewerPreferences['duplex']; } if ($entries !== []) { $viewerPrefsRef = ' /ViewerPreferences << '.implode(' ', $entries).' >>'; diff --git a/src/Pdf/PdfAConfig.php b/src/Pdf/PdfAConfig.php index 3d9bad8..f3d55ae 100644 --- a/src/Pdf/PdfAConfig.php +++ b/src/Pdf/PdfAConfig.php @@ -86,84 +86,23 @@ public function iccProfileBytes(): string * over this config's title, author and $producer. Empty values are left * out. Without a CreationDate the current time is used. * + * $pdfUaPart adds the PDF/UA identification (pdfuaid:part) for a + * document that is both PDF/A and PDF/UA. + * * @param array<string, string> $info */ - public function xmpMetadata(string $producer = 'dskripchenko/php-pdf', array $info = []): string + public function xmpMetadata(string $producer = 'dskripchenko/php-pdf', array $info = [], ?int $pdfUaPart = null): string { - $value = static fn (string $key, string $fallback = ''): string => self::xmlEscape($info[$key] ?? $fallback); - $created = isset($info['CreationDate']) - ? self::xmpDate($info['CreationDate']) - : (new \DateTimeImmutable)->format('Y-m-d\TH:i:sP'); - $modified = isset($info['ModDate']) ? self::xmpDate($info['ModDate']) : $created; - - $properties = []; - if (($title = $value('Title', $this->title)) !== '') { - $properties[] = "<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">$title</rdf:li></rdf:Alt></dc:title>"; - } - if (($author = $value('Author', $this->author)) !== '') { - $properties[] = "<dc:creator><rdf:Seq><rdf:li>$author</rdf:li></rdf:Seq></dc:creator>"; - } - if (($subject = $value('Subject')) !== '') { - $properties[] = "<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">$subject</rdf:li></rdf:Alt></dc:description>"; - } - if (($keywords = $value('Keywords')) !== '') { - $properties[] = "<pdf:Keywords>$keywords</pdf:Keywords>"; + $identification = ['pdfaid' => ['part' => (string) $this->part, 'conformance' => $this->conformance]]; + if ($pdfUaPart !== null) { + $identification['pdfuaid'] = ['part' => (string) $pdfUaPart]; } - if (($creator = $value('Creator')) !== '') { - $properties[] = "<xmp:CreatorTool>$creator</xmp:CreatorTool>"; - } - $properties[] = '<pdf:Producer>'.$value('Producer', $producer).'</pdf:Producer>'; - $properties[] = "<xmp:CreateDate>$created</xmp:CreateDate>"; - $properties[] = "<xmp:ModifyDate>$modified</xmp:ModifyDate>"; - $properties[] = "<pdfaid:part>{$this->part}</pdfaid:part>"; - $properties[] = "<pdfaid:conformance>{$this->conformance}</pdfaid:conformance>"; - $body = implode("\n ", $properties); - - return <<<XMP -<?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?> -<x:xmpmeta xmlns:x="adobe:ns:meta/"> - <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> - <rdf:Description rdf:about="" - xmlns:dc="http://purl.org/dc/elements/1.1/" - xmlns:pdf="http://ns.adobe.com/pdf/1.3/" - xmlns:xmp="http://ns.adobe.com/xap/1.0/" - xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/"> - $body - </rdf:Description> - </rdf:RDF> -</x:xmpmeta> -<?xpacket end="w"?> -XMP; - } - /** - * A PDF date (D:YYYYMMDDHHmmSS with an optional Z or +HH'mm' offset, - * later fields optional) as an XMP date, the same instant. - */ - private static function xmpDate(string $pdfDate): string - { - if (preg_match("/^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(?:(Z)|([+-])(\\d{2})'?(\\d{2})?'?)?\$/", $pdfDate, $m) !== 1) { - return $pdfDate; - } - $offset = match (true) { - ($m[8] ?? '') !== '' => $m[8].$m[9].':'.(($m[10] ?? '') !== '' ? $m[10] : '00'), - default => '+00:00', - }; - - return sprintf( - '%s-%s-%sT%s:%s:%s%s', - $m[1], - ($m[2] ?? '') !== '' ? $m[2] : '01', - ($m[3] ?? '') !== '' ? $m[3] : '01', - ($m[4] ?? '') !== '' ? $m[4] : '00', - ($m[5] ?? '') !== '' ? $m[5] : '00', - ($m[6] ?? '') !== '' ? $m[6] : '00', - $offset, + return XmpPacket::build( + $info, + $producer, + ['Title' => $this->title, 'Author' => $this->author], + $identification, ); } - - private static function xmlEscape(string $s): string - { - return htmlspecialchars($s, ENT_XML1 | ENT_QUOTES, 'UTF-8'); - } } diff --git a/src/Pdf/XmpPacket.php b/src/Pdf/XmpPacket.php new file mode 100644 index 0000000..51a1bc3 --- /dev/null +++ b/src/Pdf/XmpPacket.php @@ -0,0 +1,150 @@ +<?php + +declare(strict_types=1); + +namespace Dskripchenko\PhpPdf\Pdf; + +/** + * An XMP metadata packet built from the document's /Info values, plus the + * identification schemas of the standards it claims (pdfaid, pdfuaid). + * + * PDF/A and PDF/UA both require the /Info entries and their XMP + * properties to be equivalent, so the packet takes the /Info values as + * they are written: Title, Author, Subject, Keywords, Creator, Producer, + * CreationDate and ModDate (dates in PDF form). Empty values are left out. + * Without a CreationDate the current time is used. + * + * @internal + */ +final class XmpPacket +{ + public const NS_PDFAID = 'http://www.aiim.org/pdfa/ns/id/'; + + public const NS_PDFUAID = 'http://www.aiim.org/pdfua/ns/id/'; + + private const PDFUAID_EXTENSION = <<<'XMP' + + <rdf:Description rdf:about="" + xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/" + xmlns:pdfaSchema="http://www.aiim.org/pdfa/ns/schema#" + xmlns:pdfaProperty="http://www.aiim.org/pdfa/ns/property#"> + <pdfaExtension:schemas> + <rdf:Bag> + <rdf:li rdf:parseType="Resource"> + <pdfaSchema:schema>PDF/UA Universal Accessibility Schema</pdfaSchema:schema> + <pdfaSchema:namespaceURI>http://www.aiim.org/pdfua/ns/id/</pdfaSchema:namespaceURI> + <pdfaSchema:prefix>pdfuaid</pdfaSchema:prefix> + <pdfaSchema:property> + <rdf:Seq> + <rdf:li rdf:parseType="Resource"> + <pdfaProperty:name>part</pdfaProperty:name> + <pdfaProperty:valueType>Integer</pdfaProperty:valueType> + <pdfaProperty:category>internal</pdfaProperty:category> + <pdfaProperty:description>Part of ISO 14289 the document conforms to</pdfaProperty:description> + </rdf:li> + </rdf:Seq> + </pdfaSchema:property> + </rdf:li> + </rdf:Bag> + </pdfaExtension:schemas> + </rdf:Description> +XMP; + + /** + * @param array<string, string> $info /Info values + * @param array<string, string> $fallback Title or Author to use when $info has none + * @param array<string, array<string, string>> $identification prefix → [property → value], e.g. ['pdfuaid' => ['part' => '1']] + */ + public static function build(array $info, string $producer, array $fallback = [], array $identification = []): string + { + $value = static fn (string $key): string => self::xmlEscape($info[$key] ?? $fallback[$key] ?? ''); + $created = isset($info['CreationDate']) + ? self::xmpDate($info['CreationDate']) + : (new \DateTimeImmutable)->format('Y-m-d\TH:i:sP'); + $modified = isset($info['ModDate']) ? self::xmpDate($info['ModDate']) : $created; + + $properties = []; + if (($title = $value('Title')) !== '') { + $properties[] = "<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">$title</rdf:li></rdf:Alt></dc:title>"; + } + if (($author = $value('Author')) !== '') { + $properties[] = "<dc:creator><rdf:Seq><rdf:li>$author</rdf:li></rdf:Seq></dc:creator>"; + } + if (($subject = $value('Subject')) !== '') { + $properties[] = "<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">$subject</rdf:li></rdf:Alt></dc:description>"; + } + if (($keywords = $value('Keywords')) !== '') { + $properties[] = "<pdf:Keywords>$keywords</pdf:Keywords>"; + } + if (($creator = $value('Creator')) !== '') { + $properties[] = "<xmp:CreatorTool>$creator</xmp:CreatorTool>"; + } + $properties[] = '<pdf:Producer>'.self::xmlEscape($info['Producer'] ?? $producer).'</pdf:Producer>'; + $properties[] = "<xmp:CreateDate>$created</xmp:CreateDate>"; + $properties[] = "<xmp:ModifyDate>$modified</xmp:ModifyDate>"; + + $namespaces = ''; + foreach ($identification as $prefix => $values) { + $uri = match ($prefix) { + 'pdfaid' => self::NS_PDFAID, + 'pdfuaid' => self::NS_PDFUAID, + default => throw new \InvalidArgumentException("Unknown XMP identification schema: $prefix"), + }; + $namespaces .= "\n xmlns:$prefix=\"$uri\""; + foreach ($values as $property => $v) { + $properties[] = "<$prefix:$property>".self::xmlEscape($v)."</$prefix:$property>"; + } + } + $body = implode("\n ", $properties); + // PDF/A accepts only predefined XMP schemas unless an extension + // schema describes the others (ISO 19005-2 §6.6.2.3.2); pdfuaid + // isn't predefined, so a PDF/A + PDF/UA packet declares it. + $extension = isset($identification['pdfaid'], $identification['pdfuaid']) ? self::PDFUAID_EXTENSION : ''; + + return <<<XMP +<?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?> +<x:xmpmeta xmlns:x="adobe:ns:meta/"> + <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> + <rdf:Description rdf:about="" + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:pdf="http://ns.adobe.com/pdf/1.3/" + xmlns:xmp="http://ns.adobe.com/xap/1.0/"$namespaces> + $body + </rdf:Description>$extension + </rdf:RDF> +</x:xmpmeta> +<?xpacket end="w"?> +XMP; + } + + /** + * A PDF date (D:YYYYMMDDHHmmSS with an optional Z or +HH'mm' offset, + * later fields optional) as an XMP date, the same instant. + */ + private static function xmpDate(string $pdfDate): string + { + if (preg_match("/^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(?:(Z)|([+-])(\\d{2})'?(\\d{2})?'?)?\$/", $pdfDate, $m) !== 1) { + return $pdfDate; + } + $offset = match (true) { + ($m[8] ?? '') !== '' => $m[8].$m[9].':'.(($m[10] ?? '') !== '' ? $m[10] : '00'), + default => '+00:00', + }; + + return sprintf( + '%s-%s-%sT%s:%s:%s%s', + $m[1], + ($m[2] ?? '') !== '' ? $m[2] : '01', + ($m[3] ?? '') !== '' ? $m[3] : '01', + ($m[4] ?? '') !== '' ? $m[4] : '00', + ($m[5] ?? '') !== '' ? $m[5] : '00', + ($m[6] ?? '') !== '' ? $m[6] : '00', + $offset, + ); + } + + private static function xmlEscape(string $s): string + { + return htmlspecialchars($s, ENT_XML1 | ENT_QUOTES, 'UTF-8'); + } +} diff --git a/tests/Pdf/PdfUaTest.php b/tests/Pdf/PdfUaTest.php new file mode 100644 index 0000000..00f81e4 --- /dev/null +++ b/tests/Pdf/PdfUaTest.php @@ -0,0 +1,150 @@ +<?php + +declare(strict_types=1); + +namespace Dskripchenko\PhpPdf\Tests\Pdf; + +use Dskripchenko\PhpPdf\Pdf\Document as PdfDocument; +use Dskripchenko\PhpPdf\Pdf\PdfAConfig; +use Dskripchenko\PhpPdf\Pdf\PdfXConfig; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +/** + * enablePdfUa() identifies the document as PDF/UA-1 (ISO 14289-1 §5, §7.1): + * pdfuaid:part in the Catalog's XMP metadata, a dc:title, DisplayDocTitle. + */ +final class PdfUaTest extends TestCase +{ + #[Test] + public function it_writes_xmp_with_the_pdfua_identification(): void + { + $bytes = self::document()->toBytes(); + + self::assertMatchesRegularExpression('@/Type /Catalog [^\n]*/Metadata \d+ 0 R@', $bytes); + self::assertStringContainsString('xmlns:pdfuaid="http://www.aiim.org/pdfua/ns/id/"', $bytes); + self::assertStringContainsString('<pdfuaid:part>1</pdfuaid:part>', $bytes); + self::assertStringContainsString('<rdf:li xml:lang="x-default">Annual report</rdf:li>', $bytes); + self::assertStringNotContainsString('pdfaid:', $bytes); + } + + #[Test] + public function it_tags_the_document_and_shows_the_title(): void + { + $pdf = self::document(); + + self::assertTrue($pdf->isTagged()); + self::assertTrue($pdf->isPdfUa()); + self::assertStringContainsString('/DisplayDocTitle true', $pdf->toBytes()); + } + + #[Test] + public function display_doc_title_joins_other_viewer_preferences(): void + { + $pdf = self::document(); + $pdf->setViewerPreferences(['fitWindow' => true, 'displayDocTitle' => false]); + $bytes = $pdf->toBytes(); + + self::assertStringContainsString('/FitWindow true', $bytes); + self::assertStringContainsString('/DisplayDocTitle true', $bytes); + self::assertStringNotContainsString('/DisplayDocTitle false', $bytes); + } + + #[Test] + public function pages_with_annotations_use_structure_tab_order(): void + { + $pdf = self::document(); + $pdf->addPage()->addExternalLink(10, 10, 50, 10, 'https://example.com', 'Example'); + $bytes = $pdf->toBytes(); + + // Only the page with the link; an explicit tab order would win. + self::assertSame(1, substr_count($bytes, '/Tabs /S')); + } + + #[Test] + public function xmp_values_match_the_info_dictionary(): void + { + $pdf = self::document(); + $pdf->metadata(title: 'Annual report', author: 'Finance', creationDate: new \DateTimeImmutable('2026-03-04 05:06:07', new \DateTimeZone('UTC'))); + $bytes = $pdf->toBytes(); + + self::assertStringContainsString("/CreationDate (D:20260304050607+00'00')", $bytes); + self::assertStringContainsString('<xmp:CreateDate>2026-03-04T05:06:07+00:00</xmp:CreateDate>', $bytes); + self::assertStringContainsString('<dc:creator><rdf:Seq><rdf:li>Finance</rdf:li></rdf:Seq></dc:creator>', $bytes); + } + + #[Test] + public function with_pdfa_both_identifications_share_one_packet(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enablePdfA(new PdfAConfig(self::icc(), part: PdfAConfig::PART_2, conformance: PdfAConfig::CONFORMANCE_U)); + $pdf->enablePdfUa(); + $pdf->metadata(title: 'Annual report'); + $pdf->addPage(); + $bytes = $pdf->toBytes(); + + self::assertSame(1, substr_count($bytes, '/Type /Metadata')); + self::assertStringContainsString('<pdfaid:part>2</pdfaid:part>', $bytes); + self::assertStringContainsString('<pdfuaid:part>1</pdfuaid:part>', $bytes); + // PDF/A only accepts pdfuaid with an extension schema describing it. + self::assertStringContainsString('<pdfaSchema:prefix>pdfuaid</pdfaSchema:prefix>', $bytes); + } + + #[Test] + public function pdfa_alone_has_no_extension_schema(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enablePdfA(new PdfAConfig(self::icc(), part: PdfAConfig::PART_2, conformance: PdfAConfig::CONFORMANCE_U)); + $pdf->addPage(); + + self::assertStringNotContainsString('pdfaExtension', $pdf->toBytes()); + } + + #[Test] + public function a_document_without_a_title_throws(): void + { + $pdf = PdfDocument::new(); + $pdf->enablePdfUa(); + $pdf->addPage(); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('title'); + $pdf->toBytes(); + } + + #[Test] + public function pdfua_and_pdfx_cannot_be_combined(): void + { + $pdf = PdfDocument::new(); + $pdf->enablePdfUa(); + + $this->expectException(\LogicException::class); + $pdf->enablePdfX(new PdfXConfig(self::icc())); + } + + #[Test] + public function an_untagged_document_has_no_metadata_stream(): void + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->metadata(title: 'Plain'); + $pdf->addPage(); + + self::assertStringNotContainsString('/Type /Metadata', $pdf->toBytes()); + } + + private static function document(): PdfDocument + { + $pdf = PdfDocument::new(compressStreams: false); + $pdf->enablePdfUa(); + $pdf->metadata(title: 'Annual report'); + $pdf->setLang('en'); + $pdf->addPage(); + + return $pdf; + } + + private static function icc(): string + { + return dirname(__DIR__, 2).'/resources/icc/sRGB2014.icc'; + } +}