From 2b912a63452b3a129f39cbfccba1f199c96932db Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Thu, 22 Oct 2026 10:05:30 -0700 Subject: [PATCH 1/3] fix(font): name subset fonts with a tag, escape font names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An embedded TrueType subset was named after the whole font: /BaseFont /Inter-Bold. ISO 32000-1 §9.6.4 requires a subset's name — both /BaseFont entries and the descriptor's /FontName — to start with six uppercase letters and a plus sign: /BaseFont /DCFUHW+Inter-Bold. Without the tag, two subsets of one font in a document share a name. A certificate set in Inter used it for bold and for bold italic, so it carried two different Inter-Bold subsets under one name; a processor that looks fonts up by name (Ghostscript, preflight, merging) can draw one subset's text from the other and lose glyphs. Tools also took the subset for the whole font: pdffonts listed it with sub "no". The tag is taken from a hash of the subset's bytes, so different subsets get different tags and the same subset always gets the same one — the output stays reproducible. Fonts embedded whole (subset: false) and CFF fonts, which are never subset, keep the plain name. The PostScript name was also written into the PDF name unescaped. The OpenType spec keeps delimiters, '#' and non-printable bytes out of it, but a font that broke the rule produced a broken font dictionary; those characters are written as #xx now (§7.3.5). Co-Authored-By: Claude Opus 5.5 --- src/Pdf/PdfFont.php | 50 +++++++++++++++++++++++---- tests/Pdf/PdfFontTest.php | 73 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 115 insertions(+), 8 deletions(-) diff --git a/src/Pdf/PdfFont.php b/src/Pdf/PdfFont.php index 41ea581..ad5af58 100644 --- a/src/Pdf/PdfFont.php +++ b/src/Pdf/PdfFont.php @@ -202,6 +202,7 @@ public function registerWith(Writer $writer, bool $compressStreams = true): int $variableInstance = new \Dskripchenko\PhpPdf\Font\Ttf\VariableInstance($this->ttf, $this->axes); } $isCff = $this->ttf->isCff(); + $fontName = self::encodeName($this->ttf->postScriptName()); if ($isCff) { // FontFile3 carries /Subtype instead of /Length1 (Table 127). $fontBytes = $this->ttf->cffTableBytes(); @@ -212,6 +213,9 @@ public function registerWith(Writer $writer, bool $compressStreams = true): int : $this->ttf->rawBytes(); // Length1 = un-compressed original size (PDF spec). $streamKeys = sprintf('/Length1 %d', strlen($fontBytes)); + if ($this->subset) { + $fontName = self::subsetTag($fontBytes).'+'.$fontName; + } } if ($compressStreams) { $compressed = self::compress($fontBytes); @@ -231,11 +235,11 @@ public function registerWith(Writer $writer, bool $compressStreams = true): int } // 2. FontDescriptor. - $descriptorBody = $this->buildFontDescriptor($fontFileObjId); + $descriptorBody = $this->buildFontDescriptor($fontFileObjId, $fontName); $descriptorId = $writer->addObject($descriptorBody); // 3. CIDFontType2 / CIDFontType0 descendant. - $cidFontBody = $this->buildCIDFont($descriptorId); + $cidFontBody = $this->buildCIDFont($descriptorId, $fontName); $cidFontId = $writer->addObject($cidFontBody); // 4. ToUnicode CMap (placeholder, filled later when usedGlyphs known). @@ -249,7 +253,7 @@ public function registerWith(Writer $writer, bool $compressStreams = true): int '<< /Type /Font /Subtype /Type0 /BaseFont /%s ' .'/Encoding /Identity-H /DescendantFonts [%d 0 R] ' .'/ToUnicode %d 0 R >>', - $this->ttf->postScriptName().($isCff ? '-Identity-H' : ''), + $fontName.($isCff ? '-Identity-H' : ''), $cidFontId, $toUnicodeId, ); @@ -259,6 +263,38 @@ public function registerWith(Writer $writer, bool $compressStreams = true): int return $fontObjectId; } + /** + * Tag for a subset font's name, as in `ABCDEF+Inter-Bold` + * (ISO 32000-1 §9.6.4): six uppercase letters. + * + * Taken from the subset's bytes, so two different subsets of one font in + * a document never share a name, and the same subset always gets the + * same tag — the output stays reproducible. + */ + private static function subsetTag(string $subsetBytes): string + { + $tag = ''; + foreach (str_split(substr(hash('xxh3', $subsetBytes, true), 0, 6)) as $byte) { + $tag .= chr(65 + ord($byte) % 26); + } + + return $tag; + } + + /** + * A PDF name's characters (ISO 32000-1 §7.3.5): delimiters, `#` and + * anything outside printable ASCII are written as `#xx`. The OpenType + * spec keeps PostScript names clear of them, but not every font obeys. + */ + private static function encodeName(string $name): string + { + return preg_replace_callback( + '/[^\x21-\x7E]|[#\/()<>\[\]{}%]/', + static fn (array $m): string => sprintf('#%02X', ord($m[0])), + $name, + ) ?? $name; + } + /** * Internal raw-access to TtfFile (for TextMeasurer and LineBreaker, * which should not parse TTF themselves). @@ -741,7 +777,7 @@ public function widthOfGlyphPdfUnits(int $gid): int /** * FontDescriptor - contains metrics and reference to the embedded font file. */ - private function buildFontDescriptor(int $fontFileObjId): string + private function buildFontDescriptor(int $fontFileObjId, string $fontName): string { $upem = $this->ttf->unitsPerEm(); $toPdf = static fn (int $fu): int => (int) round($fu * 1000 / $upem); @@ -778,7 +814,7 @@ private function buildFontDescriptor(int $fontFileObjId): string .'/FontBBox %s /ItalicAngle %d ' .'/Ascent %d /Descent %d /CapHeight %d /StemV 80 ' .'/%s %d 0 R >>', - $this->ttf->postScriptName(), + $fontName, $flags, $bboxStr, $this->ttf->italicAngle(), @@ -797,7 +833,7 @@ private function buildFontDescriptor(int $fontFileObjId): string * Vertical writing adds /WMode 1 + /W2 array (vertical * advance metrics from vmtx). */ - private function buildCIDFont(int $descriptorId): string + private function buildCIDFont(int $descriptorId, string $fontName): string { $verticalParts = ''; if ($this->verticalWriting) { @@ -812,7 +848,7 @@ private function buildCIDFont(int $descriptorId): string .'%s/FontDescriptor %d 0 R ' .'/W %s %s>>', $isCff ? 'CIDFontType0' : 'CIDFontType2', - $this->ttf->postScriptName(), + $fontName, $isCff ? '' : '/CIDToGIDMap /Identity ', $descriptorId, $this->buildWidthsArray(), diff --git a/tests/Pdf/PdfFontTest.php b/tests/Pdf/PdfFontTest.php index 8ccdf45..591fe6a 100644 --- a/tests/Pdf/PdfFontTest.php +++ b/tests/Pdf/PdfFontTest.php @@ -86,7 +86,7 @@ public function register_creates_all_required_objects(): void self::assertStringContainsString('/FontFile2', $pdf); self::assertStringContainsString('/Encoding /Identity-H', $pdf); self::assertStringContainsString('/ToUnicode', $pdf); - self::assertStringContainsString('/BaseFont /LiberationSans', $pdf); + self::assertMatchesRegularExpression('~/BaseFont /[A-Z]{6}\+LiberationSans ~', $pdf); // The ToUnicode CMap has to hold bfchar entries for the glyphs used self::assertStringContainsString('beginbfchar', $pdf); } @@ -129,4 +129,75 @@ public function emoji_chars_get_notdef_glyph(): void $hex = $font->encodeText('😀'); self::assertSame('<0000>', $hex); } + + #[Test] + public function a_subset_font_is_named_with_a_six_letter_tag(): void + { + $font = new PdfFont(TtfFile::fromFile($this->liberationSansPath)); + $font->encodeText('Hello'); + $pdf = $this->embed($font); + + // ISO 32000-1 §9.6.4: the same tag on both /BaseFont entries and /FontName. + self::assertSame(1, preg_match('~/Subtype /Type0 /BaseFont /([A-Z]{6})\+LiberationSans ~', $pdf, $m)); + self::assertStringContainsString('/Subtype /CIDFontType2 /BaseFont /'.$m[1].'+LiberationSans ', $pdf); + self::assertStringContainsString('/FontName /'.$m[1].'+LiberationSans ', $pdf); + } + + #[Test] + public function different_subsets_of_one_font_get_different_tags(): void + { + $tag = function (string $text): string { + $font = new PdfFont(TtfFile::fromFile($this->liberationSansPath)); + $font->encodeText($text); + preg_match('~/FontName /([A-Z]{6})\+~', $this->embed($font), $m); + + return $m[1]; + }; + + self::assertNotSame($tag('Hello'), $tag('World')); + self::assertSame($tag('Hello'), $tag('Hello'), 'the same subset must get the same tag'); + } + + #[Test] + public function a_font_embedded_whole_has_no_tag(): void + { + $font = new PdfFont(TtfFile::fromFile($this->liberationSansPath), subset: false); + $font->encodeText('Hello'); + $pdf = $this->embed($font); + + self::assertStringContainsString('/BaseFont /LiberationSans ', $pdf); + self::assertStringContainsString('/FontName /LiberationSans ', $pdf); + self::assertDoesNotMatchRegularExpression('~/[A-Z]{6}\+LiberationSans~', $pdf); + } + + #[Test] + public function delimiters_in_a_font_name_are_escaped(): void + { + // Same-length swap of the PostScript name in both name-table encodings. + $bytes = (string) file_get_contents($this->liberationSansPath); + $bytes = str_replace('LiberationSans', 'Liberation(S/s', $bytes); + $bytes = str_replace( + mb_convert_encoding('LiberationSans', 'UTF-16BE', 'UTF-8'), + mb_convert_encoding('Liberation(S/s', 'UTF-16BE', 'UTF-8'), + $bytes, + ); + $ttf = new TtfFile($bytes); + self::assertSame('Liberation(S/s', $ttf->postScriptName()); + + $font = new PdfFont($ttf, subset: false); + $font->encodeText('Hi'); + $pdf = $this->embed($font); + + self::assertStringContainsString('/BaseFont /Liberation#28S#2Fs ', $pdf); + self::assertStringContainsString('/FontName /Liberation#28S#2Fs ', $pdf); + } + + private function embed(PdfFont $font): string + { + $writer = new Writer; + $fontId = $font->registerWith($writer); + $writer->setRoot($writer->addObject("<< /Type /Catalog /Pages $fontId 0 R >>")); + + return $writer->toBytes(); + } } From 1235e60e83c39497c14e874b1cb341f3477a1bf3 Mon Sep 17 00:00:00 2001 From: Denis Skripchenko Date: Tue, 27 Oct 2026 15:31:31 +0300 Subject: [PATCH 2/3] fix(font): write a CIDSet for TrueType subsets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the subset tag in /FontName, veraPDF treats the font as a subset and PDF/A-1 requires a CIDSet for it (ISO 19005-1 §6.3.5, rule 6.3.5-3), so pdfa-1b and pdfa-1a stopped validating. The subsetter keeps the glyph numbering and leaves unused glyphs empty, so every GID below numGlyphs is present in the font program, and the CIDSet sets all of them. PDF/A-2 and 3 accept a CIDSet only when it lists every glyph present (§6.2.11.4.2): one of only the used glyphs fails veraPDF there. It is written for every subset, whatever the conformance level: the font does not know it, and the stream is a few hundred bytes. Co-Authored-By: Claude Opus 5.5 --- src/Pdf/PdfFont.php | 45 ++++++++++++++++++++++++++++--- tests/Pdf/PdfFontTest.php | 56 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 95 insertions(+), 6 deletions(-) diff --git a/src/Pdf/PdfFont.php b/src/Pdf/PdfFont.php index ad5af58..d1b2d35 100644 --- a/src/Pdf/PdfFont.php +++ b/src/Pdf/PdfFont.php @@ -234,8 +234,21 @@ public function registerWith(Writer $writer, bool $compressStreams = true): int )); } - // 2. FontDescriptor. - $descriptorBody = $this->buildFontDescriptor($fontFileObjId, $fontName); + // 2. FontDescriptor. A subset also gets a CIDSet (see buildCidSet). + $cidSetObjId = null; + if ($this->subset && ! $isCff) { + $cidSet = $this->buildCidSet(); + if ($compressStreams) { + $cidSet = (string) gzcompress($cidSet, 6); + } + $cidSetObjId = $writer->addObject(sprintf( + "<< /Length %d%s >>\nstream\n%s\nendstream", + strlen($cidSet), + $compressStreams ? ' /Filter /FlateDecode' : '', + $cidSet, + )); + } + $descriptorBody = $this->buildFontDescriptor($fontFileObjId, $fontName, $cidSetObjId); $descriptorId = $writer->addObject($descriptorBody); // 3. CIDFontType2 / CIDFontType0 descendant. @@ -777,7 +790,7 @@ public function widthOfGlyphPdfUnits(int $gid): int /** * FontDescriptor - contains metrics and reference to the embedded font file. */ - private function buildFontDescriptor(int $fontFileObjId, string $fontName): string + private function buildFontDescriptor(int $fontFileObjId, string $fontName, ?int $cidSetObjId = null): string { $upem = $this->ttf->unitsPerEm(); $toPdf = static fn (int $fu): int => (int) round($fu * 1000 / $upem); @@ -813,7 +826,7 @@ private function buildFontDescriptor(int $fontFileObjId, string $fontName): stri '<< /Type /FontDescriptor /FontName /%s /Flags %d ' .'/FontBBox %s /ItalicAngle %d ' .'/Ascent %d /Descent %d /CapHeight %d /StemV 80 ' - .'/%s %d 0 R >>', + .'/%s %d 0 R%s >>', $fontName, $flags, $bboxStr, @@ -823,9 +836,33 @@ private function buildFontDescriptor(int $fontFileObjId, string $fontName): stri $toPdf($this->ttf->ascent()), // CapHeight ~ ascent for POC; refine later $this->ttf->isCff() ? 'FontFile3' : 'FontFile2', $fontFileObjId, + $cidSetObjId !== null ? sprintf(' /CIDSet %d 0 R', $cidSetObjId) : '', ); } + /** + * The CIDSet of a TrueType subset (ISO 32000-1 Table 124): a bitmap with + * one bit per CID, the high bit of the first byte for CID 0. With + * /CIDToGIDMap /Identity a CID is a GID. + * + * PDF/A-1 requires it for every subset CIDFont (ISO 19005-1 §6.3.5); later + * parts accept it as long as it lists every glyph present (ISO 19005-2 + * §6.2.11.4.2). The subsetter keeps the glyph numbering and leaves unused + * glyphs empty rather than removing them, so every GID below numGlyphs is + * present in the font program, and all of them are set. A CIDSet of only + * the used glyphs fails veraPDF for PDF/A-2 and 3. + */ + private function buildCidSet(): string + { + $numGlyphs = $this->ttf->numGlyphs(); + $set = str_repeat("\xFF", intdiv($numGlyphs, 8)); + if ($numGlyphs % 8 !== 0) { + $set .= chr((0xFF00 >> ($numGlyphs % 8)) & 0xFF); + } + + return $set; + } + /** * CIDFontType2 descendant - contains glyph widths and link to the descriptor. * CFF fonts get CIDFontType0, which has no /CIDToGIDMap (§9.7.4.2). diff --git a/tests/Pdf/PdfFontTest.php b/tests/Pdf/PdfFontTest.php index 591fe6a..86fd349 100644 --- a/tests/Pdf/PdfFontTest.php +++ b/tests/Pdf/PdfFontTest.php @@ -192,10 +192,62 @@ public function delimiters_in_a_font_name_are_escaped(): void self::assertStringContainsString('/FontName /Liberation#28S#2Fs ', $pdf); } - private function embed(PdfFont $font): string + #[Test] + public function a_subset_font_lists_every_glyph_of_the_subset_in_a_cid_set(): void + { + $ttf = TtfFile::fromFile($this->liberationSansPath); + $font = new PdfFont($ttf); + // "é" is a composite glyph in Liberation Sans; its components come in + // the subset too. + $font->encodeText('Hé'); + $pdf = $this->embed($font, compress: false); + + self::assertSame(1, preg_match('~/FontDescriptor .*?/CIDSet (\d+) 0 R~', $pdf, $m)); + self::assertSame(1, preg_match('~\b'.$m[1].' 0 obj\s*<< /Length (\d+) >>\nstream\n~', $pdf, $s, PREG_OFFSET_CAPTURE)); + $cidSet = substr($pdf, $s[0][1] + strlen($s[0][0]), (int) $s[1][0]); + + // The subset keeps the glyph numbering, so every GID below numGlyphs + // is in the font program (ISO 19005-2 §6.2.11.4.2) — and nothing past it. + $numGlyphs = $ttf->numGlyphs(); + self::assertSame(intdiv($numGlyphs + 7, 8), strlen($cidSet)); + for ($gid = 0; $gid < strlen($cidSet) * 8; $gid++) { + $set = (ord($cidSet[$gid >> 3]) & (0x80 >> ($gid & 7))) !== 0; + self::assertSame($gid < $numGlyphs, $set, "CID $gid"); + } + self::assertSame($numGlyphs, $this->subsetNumGlyphs($pdf)); + } + + #[Test] + public function a_font_embedded_whole_has_no_cid_set(): void + { + $font = new PdfFont(TtfFile::fromFile($this->liberationSansPath), subset: false); + $font->encodeText('Hello'); + + self::assertStringNotContainsString('/CIDSet', $this->embed($font)); + } + + #[Test] + public function a_cff_font_has_no_cid_set(): void + { + $font = new PdfFont(TtfFile::fromFile(__DIR__.'/../fixtures/fonts/MiniCff-Regular.otf')); + $font->encodeText('A'); + + self::assertStringNotContainsString('/CIDSet', $this->embed($font)); + } + + /** numGlyphs in the `maxp` table of the embedded (uncompressed) FontFile2. */ + private function subsetNumGlyphs(string $pdf): int + { + self::assertSame(1, preg_match('~<< /Length (\d+) /Length1 \d+ >>\nstream\n~', $pdf, $m, PREG_OFFSET_CAPTURE)); + $ttf = new TtfFile(substr($pdf, $m[0][1] + strlen($m[0][0]), (int) $m[1][0])); + + return $ttf->numGlyphs(); + } + + private function embed(PdfFont $font, bool $compress = true): string { $writer = new Writer; - $fontId = $font->registerWith($writer); + $fontId = $font->registerWith($writer, $compress); $writer->setRoot($writer->addObject("<< /Type /Catalog /Pages $fontId 0 R >>")); return $writer->toBytes(); From 5810a08d5bf680e07adca6c628d7dc99b08f4b42 Mon Sep 17 00:00:00 2001 From: Denis Skripchenko Date: Tue, 27 Oct 2026 15:31:43 +0300 Subject: [PATCH 3/3] docs(changelog): subset tags, escaped font names, CIDSet Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1084f32..19011ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ All notable changes to `dskripchenko/php-pdf` are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed +- Embedded TrueType subsets were named after the whole font. Their + `/BaseFont` and `/FontName` now start with a six-letter tag + (ISO 32000-1 §9.6.4), taken from a hash of the subset's bytes, so two + subsets of one font no longer share a name and the output stays + reproducible. The names in the output change: `/BaseFont /LiberationSans` + becomes `/ABCDEF+LiberationSans`. Fonts embedded whole and CFF fonts keep + the plain name. +- PostScript names are written as PDF names (§7.3.5): delimiters, `#`, + whitespace and characters outside printable ASCII are escaped as `#xx`. +- A TrueType subset carries a `/CIDSet` in its font descriptor, which + PDF/A-1 requires for a subset font (ISO 19005-1 §6.3.5). It lists every + glyph of the subset, as PDF/A-2 and 3 require of a CIDSet. + ## [1.25.0] — 2026-10-19 ### Fixed