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
4 changes: 2 additions & 2 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Install CJK font fixture and PDF extraction utility
run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils
- name: Install PDF, font and shaping test dependencies
run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils libharfbuzz-bin libfribidi-bin
- name: Detect minimum PHP from composer.json
id: php_min
run: |
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/mutation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Install PDF extraction and CJK test fixtures
run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils
- name: Install PDF and text shaping test dependencies
run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils libharfbuzz-bin libfribidi-bin
- name: Detect minimum PHP from composer.json
id: php_min
run: |
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/test-integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Install CJK font fixture and PDF extraction utility
run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils
- name: Install PDF, font and shaping test dependencies
run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils libharfbuzz-bin libfribidi-bin
- name: Detect minimum PHP from composer.json
id: php_min
run: |
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"css"
],
"require": {
"php": "^8.2"
"php": "^8.2",
"symfony/process": "^7.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8",
Expand Down
1 change: 1 addition & 0 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ theme:
nav:
- Home: index.md
- Getting started: guides/getting-started.md
- Unicode fonts: guides/unicode-fonts.md
- Examples: reference/examples.md
- Visible signature use case: use-cases/visible-signatures.md

Expand Down
47 changes: 47 additions & 0 deletions docs/source/guides/unicode-fonts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<!-- SPDX-FileCopyrightText: 2026 LibreSign -->
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->

# Unicode text in PDF XObjects

The compiler preserves Unicode names using embedded TrueType fonts, a Type 0/CIDFontType2 font resource, and a `ToUnicode` map. Plain single-byte PDF Type 1 fonts do not cover Arabic, Hebrew, CJK, and many other scripts.

## Configure fonts

```php
use LibreSign\XObjectTemplate\Dto\CompileRequest;
use LibreSign\XObjectTemplate\Pdf\TemplateDocumentBuilder;
use LibreSign\XObjectTemplate\XObjectTemplateCompiler;

$builder = (new TemplateDocumentBuilder())->withUnicodeFontFiles([
'/path/to/embeddable/DejaVuSans.ttf',
'/path/to/embeddable/CJK-font.ttf',
]);
$compiler = new XObjectTemplateCompiler(documentBuilder: $builder);
$result = $compiler->compile(new CompileRequest(
html: '<div>Signed by محمد</div>',
width: 400,
height: 90,
));
```

Only supply trusted, valid `.ttf` files with embedding rights. Fonts are loaded from explicitly configured paths, **not** discovered from arbitrary template input. The first configured font covering an entire line is preferred. Otherwise, the compiler selects fonts for contiguous runs without separating a grapheme (base character and its combining marks). Missing glyph coverage for a complete grapheme raises an exception rather than silently substituting a character. A mixed line such as `Signed by محمد / 山田太郎` can use both configured fonts.

### Complex scripts

HarfBuzz handles OpenType glyph substitution/positioning; FriBidi provides paragraph directions and visual ordering. Deployments that use Arabic, Hebrew or combining marks must provide the `hb-shape` and `fribidi` executables on `PATH`. For Debian/Ubuntu these are packaged as `libharfbuzz-bin` and `libfribidi-bin`. No native tools are required for the simpler direct-glyph path. A missing or failing native tool produces an error, never a silently incorrect PDF.

Both tools are executed with argument arrays, a fixed timeout and limited input. The shaping font is a temporary private file, deleted in a `finally` block. Inputs are decoded and validated as Unicode scalars.

For shaped text, FriBidi determines visual runs before font fallback. HarfBuzz receives the surrounding text context when a directional run is split across fonts, preserving joining behavior where the selected fonts support it. PDF appearance operators use exact glyph IDs and positioning with a logical Unicode `ActualText` span; font switches use the embedded font resources of the corresponding run. Different PDF extractors can report bidirectional text in visual order despite `ActualText`; test extraction with more than one independent reader when interoperability matters.

### Signed PDF integration

For signature appearance XObjects, the resource dictionary must be materialized **in the destination PDF document**, not simply embedded as PHP arrays. The `SignerPhpCoreXObjectResourceBuilder` adapter supplies the resources-builder closure to the compatible `SignerPHP/pdf-core` `AppearanceXObject`. Pass it using the named `resourcesBuilder:` parameter so older versions fail explicitly instead of ignoring an extra positional argument. This depends on the optional resource-builder API introduced in [SignerPHP/pdf-core PR #5](https://github.com/SignerPHP/pdf-core/pull/5). A consumer must first use a `pdf-core` version containing that API; older releases cannot process these indirect resources.

Test signature appearance output cryptographically (CMS/ByteRange), structurally (font file, descendant font and `ToUnicode`) and visually. Passing just one of these checks is insufficient.

### Limits

* Complete font files are currently embedded; glyph subsetting is not implemented. This increases signed-PDF size. FontTools' `pyftsubset --retain-gids` is a possible **future** optimization, but needs reproducible tests for CID/GID stability and licensing before adoption.
* The library handles the scripts exercised by its integration matrix; it does not claim full OpenType coverage for every language, variation-selector sequence or color font.
* Complex shaping requires the external binaries at runtime and appropriate fonts in the deployment environment.
1 change: 1 addition & 0 deletions docs/source/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
## Start here

- [Getting started](guides/getting-started.md)
- [Unicode text and font resources](guides/unicode-fonts.md)
- [Examples](reference/examples.md)
- [Visible signature use case](use-cases/visible-signatures.md)

Expand Down
6 changes: 4 additions & 2 deletions src/Layout/TextLineBreaker.php
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,10 @@ private function splitWords(string $text): array
*/
private function splitCharacters(string $text): array
{
$characters = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
// A fallback line break must not split a combining sequence or
// another extended grapheme cluster into separate rendered lines.
preg_match_all('/\X/u', $text, $matches);

return $characters === false ? [] : $characters;
return $matches[0];
}
}
31 changes: 31 additions & 0 deletions src/Pdf/ComplexTextShaperInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

// SPDX-FileCopyrightText: 2026 LibreSign
// SPDX-License-Identifier: AGPL-3.0-or-later

declare(strict_types=1);

namespace LibreSign\XObjectTemplate\Pdf;

interface ComplexTextShaperInterface
{
/**
* Glyphs are ordered visually, with exact advances/offsets in thousandths of an em.
*
* @return list<array{
* glyph: int, glyphId: int, unicode: list<int>,
* advance: int, dx: int, dy: int, cluster: int, logical: int
* }>
*/
public function shape(string $text, TrueTypeFont $font): array;

/**
* Resolve bidirectional order before splitting shaping runs among configured fonts.
* @param list<TrueTypeFont> $fonts
* @return list<array{
* fontIndex: int, glyph: int, glyphId: int, unicode: list<int>,
* advance: int, dx: int, dy: int, cluster: int, logical: int
* }>
*/
public function shapeWithFonts(string $text, array $fonts): array;
}
151 changes: 151 additions & 0 deletions src/Pdf/FriBidiParagraphMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
<?php

// SPDX-FileCopyrightText: 2026 LibreSign
// SPDX-License-Identifier: AGPL-3.0-or-later

declare(strict_types=1);

namespace LibreSign\XObjectTemplate\Pdf;

use Closure;
use InvalidArgumentException;

/** @internal Convert logical Unicode characters into visual, directional shaping runs. */
final readonly class FriBidiParagraphMapper
{
/** @param Closure(list<string>, ?string): string $run */
public function __construct(
private string $binary,
private Closure $run,
) {
}

/**
* @param list<string> $characters
* @return list<array{text: string, rtl: bool, visual: int, start: int}>
*/
public function runs(string $text, array $characters): array
{
[$visual, $levels] = $this->bidiMaps($text, count($characters));
return $this->visualRuns($characters, $visual, $levels);
}

/**
* @return array{list<int>, list<int>}
*/
private function bidiMaps(string $text, int $count): array
{
$output = ($this->run)([
$this->binary,
'--novisual',
'--ltov',
'--vtol',
'--levels',
'--basedir',
'--charset=UTF-8',
'--nopad',
], $text . "\n");
$lines = explode("\n", trim($output));
if (count($lines) !== 4 || !str_starts_with($lines[0], 'Base direction: ')) {
throw new InvalidArgumentException('FriBidi returned an invalid paragraph map.');
}
$visual = $this->parseMap($lines[1], $count);
$inverse = $this->parseMap($lines[2], $count);
$levels = $this->parseMap($lines[3], $count);
foreach ($visual as $logicalIndex => $visualIndex) {
if ($visualIndex < 0 || $visualIndex >= $count || $inverse[$visualIndex] !== $logicalIndex) {
throw new InvalidArgumentException('FriBidi returned inconsistent visual positions.');
}
}
return [$visual, $levels];
}

/** @return list<int> */
private function parseMap(string $line, int $count): array
{
$tokens = preg_split('/\s+/', trim($line));
if (count($tokens) !== $count) {
throw new InvalidArgumentException('FriBidi returned an inconsistent character map.');
}
$values = [];
foreach ($tokens as $token) {
if (!ctype_digit($token)) {
throw new InvalidArgumentException('FriBidi returned a nonnumeric character map.');
}
$values[] = intval($token);
}
return $values;
}

/**
* @param list<string> $characters
* @param list<int> $visualPositions
* @param list<int> $levels
* @return list<array{text: string, rtl: bool, visual: int, start: int}>
*/
private function visualRuns(array $characters, array $visualPositions, array $levels): array
{
$runs = [];
$start = 0;
$script = $this->scriptOf($characters[0]);
for ($i = 1, $length = count($characters); $i <= $length; $i++) {
$nextScript = $i < $length ? $this->scriptOf($characters[$i]) : '';
if ($this->shouldContinueRun($i, $length, $levels, $start, $nextScript, $script)) {
$script = $nextScript !== '' ? $nextScript : $script;
continue;
}
/** @var non-empty-list<int> $positions Run boundaries always contain at least one character. */
$positions = array_slice($visualPositions, $start, $i - $start);
$runs[] = [
'text' => implode('', array_slice($characters, $start, $i - $start)),
'rtl' => ($levels[$start] % 2) === 1,
'visual' => min($positions),
'start' => $start,
];
$start = $i;
$script = $nextScript;
}
usort($runs, static fn (array $first, array $second): int => $first['visual'] <=> $second['visual']);
return $runs;
}

/** @param list<int> $levels */
private function shouldContinueRun(
int $index,
int $count,
array $levels,
int $start,
string $nextScript,
string $script,
): bool {
return $index < $count
&& $levels[$index] === $levels[$start]
&& ($nextScript === $script || $nextScript === '' || $script === '');
}

private function scriptOf(string $character): string
{
// Marks inherit the base's script even when PCRE's Script_Extensions
// data assigns them to several scripts (or a different primary script).
if (preg_match('/\p{M}/u', $character) === 1) {
return '';
}
$patterns = [
'/\p{sc=Arabic}/u' => 'Arab',
'/\p{sc=Hebrew}/u' => 'Hebr',
'/\p{sc=Latin}/u' => 'Latn',
'/\p{sc=Cyrillic}/u' => 'Cyrl',
'/\p{sc=Greek}/u' => 'Grek',
'/\p{sc=Han}/u' => 'Hani',
'/\p{sc=Hiragana}/u' => 'Hira',
'/\p{sc=Katakana}/u' => 'Kana',
'/\p{sc=Hangul}/u' => 'Hang',
];
foreach ($patterns as $pattern => $script) {
if (preg_match($pattern, $character) === 1) {
return $script;
}
}
return '';
}
}
Loading