Skip to content
Closed
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
50 changes: 43 additions & 7 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 @@ -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).
Expand All @@ -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,
);
Expand All @@ -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).
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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(),
Expand All @@ -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) {
Expand All @@ -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(),
Expand Down
73 changes: 72 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,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();
}
}