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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
91 changes: 82 additions & 9 deletions src/Pdf/PdfFont.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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);
Expand All @@ -230,12 +234,25 @@ public function registerWith(Writer $writer, bool $compressStreams = true): int
));
}

// 2. FontDescriptor.
$descriptorBody = $this->buildFontDescriptor($fontFileObjId);
// 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.
$cidFontBody = $this->buildCIDFont($descriptorId);
$cidFontBody = $this->buildCIDFont($descriptorId, $fontName);
$cidFontId = $writer->addObject($cidFontBody);

// 4. ToUnicode CMap (placeholder, filled later when usedGlyphs known).
Expand All @@ -249,7 +266,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,
);
Expand All @@ -259,6 +276,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).
Expand Down Expand Up @@ -741,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
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);
Expand Down Expand Up @@ -777,8 +826,8 @@ private function buildFontDescriptor(int $fontFileObjId): string
'<< /Type /FontDescriptor /FontName /%s /Flags %d '
.'/FontBBox %s /ItalicAngle %d '
.'/Ascent %d /Descent %d /CapHeight %d /StemV 80 '
.'/%s %d 0 R >>',
$this->ttf->postScriptName(),
.'/%s %d 0 R%s >>',
$fontName,
$flags,
$bboxStr,
$this->ttf->italicAngle(),
Expand All @@ -787,17 +836,41 @@ private function buildFontDescriptor(int $fontFileObjId): string
$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).
*
* 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) {
Expand All @@ -812,7 +885,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(),
Expand Down
125 changes: 124 additions & 1 deletion tests/Pdf/PdfFontTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -129,4 +129,127 @@ 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);
}

#[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, $compress);
$writer->setRoot($writer->addObject("<< /Type /Catalog /Pages $fontId 0 R >>"));

return $writer->toBytes();
}
}
Loading