From bccef19357524fc8ebb13f3bc80f4b86abfd30b2 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Mon, 2 Nov 2026 15:36:15 -0800 Subject: [PATCH 01/13] perf(layout): stop re-measuring top-aligned cells, cache font lookup Every table cell's content was measured twice: once for the row height and again in renderCellContent, where the height only matters for center or bottom alignment. Top-aligned cells, the default, now skip the second measure. standardFontFor re-parsed the CSS font-family list for every word it measured. The base-14 face is now cached per family/bold/italic, and the parsed family list is cached too (capped at 256 entries for long-running workers). The 100-page invoice bench drops from ~920ms to ~685ms with byte-identical output. Co-Authored-By: Claude Opus 5.5 --- src/Layout/Engine.php | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/Layout/Engine.php b/src/Layout/Engine.php index c67f089..094cd8c 100644 --- a/src/Layout/Engine.php +++ b/src/Layout/Engine.php @@ -138,6 +138,14 @@ final class Engine private ?PdfFontResolver $resolver = null; + /** + * Base-14 face for each family/bold/italic seen, so a CSS family list + * isn't parsed again for every word measured. + * + * @var array + */ + private array $standardFontCache = []; + /** Font ascent and descent, in em, used to place a baseline in its line. */ private const LINE_ASCENT = 0.905; @@ -4276,6 +4284,13 @@ private function measureWidth(string $text, RunStyle $style): float * mono → Courier, sans → Helvetica), in the run's weight and slant. */ private function standardFontFor(RunStyle $style): StandardFont + { + $key = ($style->bold ? 'b' : '-').($style->italic ? 'i' : '-').$style->fontFamily; + + return $this->standardFontCache[$key] ??= $this->resolveStandardFont($style); + } + + private function resolveStandardFont(RunStyle $style): StandardFont { $base = self::standardFamily($this->fallbackStandard); foreach (self::families((string) $style->fontFamily) as $family) { @@ -4319,7 +4334,14 @@ private function standardFontFor(RunStyle $style): StandardFont */ private static function families(string $fontFamily): array { - return array_values(array_filter(array_map('trim', explode(',', $fontFamily)), static fn (string $f): bool => $f !== '')); + // Shared across renders; capped so a long-running worker fed many + // distinct family strings doesn't grow it without bound. + static $cache = []; + if (count($cache) >= 256 && ! isset($cache[$fontFamily])) { + $cache = []; + } + + return $cache[$fontFamily] ??= array_values(array_filter(array_map('trim', explode(',', $fontFamily)), static fn (string $f): bool => $f !== '')); } private static function standardFamily(StandardFont $font): ?string @@ -5461,13 +5483,12 @@ private function renderCellContent( LayoutContext $ctx, ): void { $contentWidth = $cellWidth - $cs->paddingLeftPt - $cs->paddingRightPt; - $contentHeight = $this->measureBlockListHeight($cell->children, $contentWidth); - - // Vertical alignment. + // Vertical alignment. Only center and bottom need the content's + // height, so top-aligned cells (the default) skip measuring it again. $availableHeight = $rowHeight - $cs->paddingTopPt - $cs->paddingBottomPt; $vOffset = match ($cs->verticalAlign) { - VerticalAlignment::Center => max(0, ($availableHeight - $contentHeight) / 2), - VerticalAlignment::Bottom => max(0, $availableHeight - $contentHeight), + VerticalAlignment::Center => max(0, ($availableHeight - $this->measureBlockListHeight($cell->children, $contentWidth)) / 2), + VerticalAlignment::Bottom => max(0, $availableHeight - $this->measureBlockListHeight($cell->children, $contentWidth)), default => 0, }; From e40129652136a6fc239bc4f4a33fdaaa2c93ff17 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Mon, 2 Nov 2026 15:38:19 -0800 Subject: [PATCH 02/13] perf(elements): share one default style instead of a copy per element Run, Paragraph, Cell and Field each created their own all-defaults RunStyle, ParagraphStyle or CellStyle, as did the cell and paragraph builders: four style objects per plain table cell. The style classes are immutable, so each now has a shared default() instance that elements fall back to when no style is given. The constructors take ?XStyle $style = null; existing callers are unaffected. A plain cell drops from ~1.9KB to ~800 bytes. The 100-page invoice bench peaks at 25MB instead of 47MB, with byte-identical output. effectiveCellStyle no longer allocates a CellStyle per cell to compare against. Co-Authored-By: Claude Opus 5.5 --- src/Build/CellBuilder.php | 2 +- src/Build/ParagraphBuilder.php | 6 +- src/Element/Cell.php | 5 +- src/Element/Field.php | 18 +++--- src/Element/Paragraph.php | 13 +++- src/Element/Run.php | 8 ++- src/Layout/Engine.php | 3 +- src/Style/CellStyle.php | 12 ++++ src/Style/ParagraphStyle.php | 12 ++++ src/Style/RunStyle.php | 12 ++++ tests/Element/SharedDefaultStyleTest.php | 78 ++++++++++++++++++++++++ 11 files changed, 151 insertions(+), 18 deletions(-) create mode 100644 tests/Element/SharedDefaultStyleTest.php diff --git a/src/Build/CellBuilder.php b/src/Build/CellBuilder.php index 0a05b40..52fc8f7 100644 --- a/src/Build/CellBuilder.php +++ b/src/Build/CellBuilder.php @@ -34,7 +34,7 @@ final class CellBuilder public function __construct() { - $this->style = new CellStyle; + $this->style = CellStyle::default(); } public static function new(): self diff --git a/src/Build/ParagraphBuilder.php b/src/Build/ParagraphBuilder.php index 89da536..9ff896e 100644 --- a/src/Build/ParagraphBuilder.php +++ b/src/Build/ParagraphBuilder.php @@ -40,8 +40,8 @@ final class ParagraphBuilder public function __construct() { - $this->style = new ParagraphStyle; - $this->defaultRunStyle = new RunStyle; + $this->style = ParagraphStyle::default(); + $this->defaultRunStyle = RunStyle::default(); } public static function new(): self @@ -53,7 +53,7 @@ public static function new(): self public function text(string $text, ?RunStyle $style = null): self { - $this->children[] = new Run($text, $style ?? new RunStyle); + $this->children[] = new Run($text, $style); return $this; } diff --git a/src/Element/Cell.php b/src/Element/Cell.php index d01e53b..2eba23a 100644 --- a/src/Element/Cell.php +++ b/src/Element/Cell.php @@ -15,15 +15,18 @@ */ final readonly class Cell { + public CellStyle $style; + /** * @param list $children */ public function __construct( public array $children = [], - public CellStyle $style = new CellStyle, + ?CellStyle $style = null, public int $columnSpan = 1, public int $rowSpan = 1, ) { + $this->style = $style ?? CellStyle::default(); if ($columnSpan < 1) { throw new \InvalidArgumentException("columnSpan must be ≥ 1, got $columnSpan"); } diff --git a/src/Element/Field.php b/src/Element/Field.php index 14198c4..69cd8fd 100644 --- a/src/Element/Field.php +++ b/src/Element/Field.php @@ -35,32 +35,36 @@ public const MERGEFIELD = 'MERGEFIELD'; + public RunStyle $style; + public function __construct( public string $instruction, - public RunStyle $style = new RunStyle, - ) {} + ?RunStyle $style = null, + ) { + $this->style = $style ?? RunStyle::default(); + } - public static function page(RunStyle $style = new RunStyle): self + public static function page(?RunStyle $style = null): self { return new self(self::PAGE, $style); } - public static function totalPages(RunStyle $style = new RunStyle): self + public static function totalPages(?RunStyle $style = null): self { return new self(self::NUMPAGES, $style); } - public static function date(string $format = 'dd.MM.yyyy', RunStyle $style = new RunStyle): self + public static function date(string $format = 'dd.MM.yyyy', ?RunStyle $style = null): self { return new self(self::DATE.':'.$format, $style); } - public static function time(string $format = 'HH:mm', RunStyle $style = new RunStyle): self + public static function time(string $format = 'HH:mm', ?RunStyle $style = null): self { return new self(self::TIME.':'.$format, $style); } - public static function mergeField(string $name, RunStyle $style = new RunStyle): self + public static function mergeField(string $name, ?RunStyle $style = null): self { return new self(self::MERGEFIELD.':'.$name, $style); } diff --git a/src/Element/Paragraph.php b/src/Element/Paragraph.php index 4db6e8c..efc0581 100644 --- a/src/Element/Paragraph.php +++ b/src/Element/Paragraph.php @@ -15,15 +15,22 @@ */ final readonly class Paragraph implements BlockElement { + public ParagraphStyle $style; + + public RunStyle $defaultRunStyle; + /** * @param list $children */ public function __construct( public array $children = [], - public ParagraphStyle $style = new ParagraphStyle, + ?ParagraphStyle $style = null, public ?int $headingLevel = null, - public RunStyle $defaultRunStyle = new RunStyle, - ) {} + ?RunStyle $defaultRunStyle = null, + ) { + $this->style = $style ?? ParagraphStyle::default(); + $this->defaultRunStyle = $defaultRunStyle ?? RunStyle::default(); + } public function isEmpty(): bool { diff --git a/src/Element/Run.php b/src/Element/Run.php index 6701f0a..e0dddbc 100644 --- a/src/Element/Run.php +++ b/src/Element/Run.php @@ -15,8 +15,12 @@ */ final readonly class Run implements InlineElement { + public RunStyle $style; + public function __construct( public string $text, - public RunStyle $style = new RunStyle, - ) {} + ?RunStyle $style = null, + ) { + $this->style = $style ?? RunStyle::default(); + } } diff --git a/src/Layout/Engine.php b/src/Layout/Engine.php index 094cd8c..8d7f03e 100644 --- a/src/Layout/Engine.php +++ b/src/Layout/Engine.php @@ -5540,7 +5540,8 @@ private function effectiveCellStyle(Table $t, Cell $cell): CellStyle // cell.style is identical-equal to a bare-default CellStyle (i.e. // the user did not set their own style). This is a heuristic — // a full cascade with explicit merging is a future improvement. - if ($cell->style == new CellStyle) { + $default = CellStyle::default(); + if ($cell->style === $default || $cell->style == $default) { return $t->style->defaultCellStyle; } diff --git a/src/Style/CellStyle.php b/src/Style/CellStyle.php index 4210d9d..fd6fed8 100644 --- a/src/Style/CellStyle.php +++ b/src/Style/CellStyle.php @@ -32,6 +32,18 @@ public function __construct( public ?float $minHeightPt = null, ) {} + /** + * The all-defaults style, shared. It is immutable, so every element + * created without a style can point at the same one instead of each + * holding its own copy. + */ + public static function default(): self + { + static $default = null; + + return $default ??= new self; + } + public function withPadding(float $pt): self { return $this->copy( diff --git a/src/Style/ParagraphStyle.php b/src/Style/ParagraphStyle.php index 348f7e0..db06d12 100644 --- a/src/Style/ParagraphStyle.php +++ b/src/Style/ParagraphStyle.php @@ -43,6 +43,18 @@ public function __construct( public ?string $backgroundColor = null, ) {} + /** + * The all-defaults style, shared. It is immutable, so every element + * created without a style can point at the same one instead of each + * holding its own copy. + */ + public static function default(): self + { + static $default = null; + + return $default ??= new self; + } + public function isEmpty(): bool { return $this->alignment === Alignment::Start diff --git a/src/Style/RunStyle.php b/src/Style/RunStyle.php index 8bb3e26..5977b85 100644 --- a/src/Style/RunStyle.php +++ b/src/Style/RunStyle.php @@ -34,6 +34,18 @@ public function __construct( public ?float $letterSpacingPt = null, ) {} + /** + * The all-defaults style, shared. It is immutable, so every element + * created without a style can point at the same one instead of each + * holding its own copy. + */ + public static function default(): self + { + static $default = null; + + return $default ??= new self; + } + public function withBold(bool $value = true): self { return $this->copy(bold: $value); diff --git a/tests/Element/SharedDefaultStyleTest.php b/tests/Element/SharedDefaultStyleTest.php new file mode 100644 index 0000000..03e93b3 --- /dev/null +++ b/tests/Element/SharedDefaultStyleTest.php @@ -0,0 +1,78 @@ +style); + self::assertSame(RunStyle::default(), (new Field(Field::PAGE))->style); + self::assertSame(RunStyle::default(), Field::page()->style); + self::assertSame(ParagraphStyle::default(), (new Paragraph)->style); + self::assertSame(RunStyle::default(), (new Paragraph)->defaultRunStyle); + self::assertSame(CellStyle::default(), (new Cell)->style); + } + + #[Test] + public function the_shared_default_equals_a_fresh_style(): void + { + self::assertEquals(new RunStyle, RunStyle::default()); + self::assertEquals(new ParagraphStyle, ParagraphStyle::default()); + self::assertEquals(new CellStyle, CellStyle::default()); + } + + #[Test] + public function a_given_style_is_kept(): void + { + $bold = (new RunStyle)->withBold(); + self::assertSame($bold, (new Run('a', $bold))->style); + self::assertTrue((new ParagraphBuilder)->bold('a')->build()->children[0]->style->bold); + } + + #[Test] + public function builders_use_the_shared_defaults(): void + { + $cell = (new CellBuilder)->text('a')->build(); + self::assertSame(CellStyle::default(), $cell->style); + + $paragraph = $cell->children[0]; + self::assertInstanceOf(Paragraph::class, $paragraph); + self::assertSame(ParagraphStyle::default(), $paragraph->style); + self::assertSame(RunStyle::default(), $paragraph->children[0]->style); + } + + #[Test] + public function a_large_table_of_plain_cells_stays_small(): void + { + $before = memory_get_usage(); + $cells = []; + for ($i = 0; $i < 5000; $i++) { + $cells[] = (new CellBuilder)->text("Item $i")->build(); + } + $perCell = (memory_get_usage() - $before) / count($cells); + + // ~800 bytes with shared styles, ~1900 with a copy per element. + self::assertLessThan(1200, $perCell); + } +} From 4564706c9e89f9993a5346ebc1d11d078b091a85 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Mon, 2 Nov 2026 15:41:50 -0800 Subject: [PATCH 03/13] perf(layout): render once unless the document shows the page total Engine::render always laid the document out twice: the first pass only counted pages so NUMPAGES fields could show the total. Most documents have no NUMPAGES, so half of every render was thrown away. The first pass now records whether it resolved a NUMPAGES field, and is returned as the result when it didn't. Outline entries, previously skipped in the first pass to save work, are registered on every pass. Render time halves for documents without a page total, with byte-identical output: the 100-page invoice bench drops from ~630ms to ~320ms. Co-Authored-By: Claude Opus 5.5 --- src/Layout/Engine.php | 34 ++++++++++++++++++++-------- tests/Layout/FieldResolutionTest.php | 20 ++++++++++++++++ 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/src/Layout/Engine.php b/src/Layout/Engine.php index 8d7f03e..e2604b7 100644 --- a/src/Layout/Engine.php +++ b/src/Layout/Engine.php @@ -93,6 +93,9 @@ final class Engine */ private ?int $totalPagesHint = null; + /** Whether the pass being rendered resolved a NUMPAGES field. */ + private bool $totalPagesUsed = false; + /** * Footnote bookkeeping, keyed by the footnote element itself. * @@ -258,13 +261,15 @@ private function applyFallbackChain(?PdfFont $primary, ?string $text): ?PdfFont public function render(AstDocument $document): PdfDocument { - // Two-pass for NUMPAGES resolution: + // Two passes only when NUMPAGES needs the page count: // - Pass 1: render with totalPagesHint=null, count pages // - Pass 2: render with known totalPagesHint, NUMPAGES → actual count - // If the document has no NUMPAGES (or no Fields at all), the double - // pass still runs, but it is cheap (~2× memory peak for a short time). + // A document that never shows the total is finished after pass 1. $this->totalPagesHint = null; $firstPass = $this->renderOnce($document); + if (! $this->totalPagesUsed) { + return $firstPass; + } $this->totalPagesHint = $firstPass->pageCount(); $finalPass = $this->renderOnce($document); @@ -424,6 +429,8 @@ private function footnotesIn(iterable $nodes): array private function renderOnce(AstDocument $document): PdfDocument { + $this->totalPagesUsed = false; + // Numbers are handed out in a single walk of the tree, in document // order, before anything is laid out. Assigning them as footnotes // are met would tie numbering to the order of layout passes, and a @@ -2614,6 +2621,17 @@ private function displayedPageNumber(LayoutContext $ctx): int return $physical + ($ctx->pageSetup->firstPageNumber - 1); } + /** + * NUMPAGES: the displayed total, or 99 while measuring in the first + * pass. Notes that the document needs a second pass for the real count. + */ + private function resolveTotalPages(?LayoutContext $ctx): int + { + $this->totalPagesUsed = true; + + return $ctx !== null ? $this->displayedTotalPages($ctx) : ($this->totalPagesHint ?? 99); + } + private function displayedTotalPages(LayoutContext $ctx): int { $count = $this->totalPagesHint ?? 1; @@ -3285,9 +3303,9 @@ private function renderParagraph(Paragraph $p, LayoutContext $ctx): void $ctx->contentWidth -= $insetLeft + $insetRight; } - // Outline entry for heading paragraph (only in the final pass — - // not needed during the first pass). - if ($p->headingLevel !== null && $this->totalPagesHint !== null) { + // Outline entry for heading paragraph. Registered on every pass: + // the first pass is the final one unless NUMPAGES needs a second. + if ($p->headingLevel !== null) { $title = $this->extractPlainText($p->children); if ($title !== '') { $ctx->pdf->registerOutlineEntry( @@ -3473,9 +3491,7 @@ private function resolveField(Field $f, ?LayoutContext $ctx): string { return match ($f->kind()) { Field::PAGE => (string) ($ctx !== null ? $this->displayedPageNumber($ctx) : 1), - Field::NUMPAGES => (string) ($ctx !== null - ? $this->displayedTotalPages($ctx) - : ($this->totalPagesHint ?? 99)), + Field::NUMPAGES => (string) $this->resolveTotalPages($ctx), Field::DATE => $this->formatDateTime($f->format() ?: 'dd.MM.yyyy'), Field::TIME => $this->formatDateTime($f->format() ?: 'HH:mm'), Field::MERGEFIELD => $f->format() !== '' ? $f->format() : '?', diff --git a/tests/Layout/FieldResolutionTest.php b/tests/Layout/FieldResolutionTest.php index c33b309..7f60fe6 100644 --- a/tests/Layout/FieldResolutionTest.php +++ b/tests/Layout/FieldResolutionTest.php @@ -5,9 +5,12 @@ namespace Dskripchenko\PhpPdf\Tests\Layout; use Dskripchenko\PhpPdf\Document; +use Dskripchenko\PhpPdf\Element\Cell; use Dskripchenko\PhpPdf\Element\Field; use Dskripchenko\PhpPdf\Element\Paragraph; +use Dskripchenko\PhpPdf\Element\Row; use Dskripchenko\PhpPdf\Element\Run; +use Dskripchenko\PhpPdf\Element\Table; use Dskripchenko\PhpPdf\Font\Ttf\TtfFile; use Dskripchenko\PhpPdf\Layout\Engine; use Dskripchenko\PhpPdf\Pdf\PdfFont; @@ -105,4 +108,21 @@ public function numpages_reflects_multi_page_document(): void self::assertStringContainsString("Total pages: $pageCount", $text); self::assertStringContainsString("END total: $pageCount", $text); } + + #[Test] + public function numpages_met_only_on_the_last_page_still_gets_the_real_count(): void + { + // A document without NUMPAGES is finished after one pass; the second + // pass must still run when the only total sits deep in the last page. + $blocks = []; + for ($i = 0; $i < 100; $i++) { + $blocks[] = new Paragraph([new Run("Paragraph $i for filler text content")]); + } + $blocks[] = new Table([new Row([new Cell([new Paragraph([new Run('Cell total: '), Field::totalPages()])])])]); + + $bytes = (new Document(new Section($blocks)))->toBytes(new Engine(compressStreams: false, defaultFont: $this->font())); + $pageCount = substr_count($bytes, '/Type /Page '); + self::assertGreaterThan(1, $pageCount); + self::assertStringContainsString("Cell total: $pageCount", $this->pdftotext($bytes)); + } } From a80f123c771f5c6f3f16686425e497f02cb3b7a4 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Mon, 2 Nov 2026 15:49:16 -0800 Subject: [PATCH 04/13] perf(layout): cache text widths for the length of a render MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit measureWidth ran for every word three times — for the block's height, for line breaking and when drawing — and tables repeat the same words row after row: a 100-page invoice made 126,300 calls for 4,100 distinct inputs. Widths are now cached by size, weight, slant, family and text for one render. The cache is cleared when the render ends and starts over past 20,000 entries. Render time drops 17-35% (the invoice ~315ms → ~265ms, with an embedded font ~440ms → ~325ms) with no change in peak memory. Co-Authored-By: Claude Opus 5.5 --- src/Layout/Engine.php | 56 +++++++++++++++++++++++++++++++++---------- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/src/Layout/Engine.php b/src/Layout/Engine.php index e2604b7..ff06e55 100644 --- a/src/Layout/Engine.php +++ b/src/Layout/Engine.php @@ -149,6 +149,18 @@ final class Engine */ private array $standardFontCache = []; + /** + * Text widths measured in the current render, by style and text. A word + * is measured for the block's height, again for line breaking and again + * when drawn, and tables repeat the same words row after row. + * + * @var array + */ + private array $widthCache = []; + + /** Entries kept before the width cache starts over. */ + private const WIDTH_CACHE_LIMIT = 20000; + /** Font ascent and descent, in em, used to place a baseline in its line. */ private const LINE_ASCENT = 0.905; @@ -265,17 +277,21 @@ public function render(AstDocument $document): PdfDocument // - Pass 1: render with totalPagesHint=null, count pages // - Pass 2: render with known totalPagesHint, NUMPAGES → actual count // A document that never shows the total is finished after pass 1. + // The width cache lives for one render only, so its memory goes + // with it. $this->totalPagesHint = null; - $firstPass = $this->renderOnce($document); - if (! $this->totalPagesUsed) { - return $firstPass; - } - $this->totalPagesHint = $firstPass->pageCount(); - - $finalPass = $this->renderOnce($document); - $this->totalPagesHint = null; + try { + $firstPass = $this->renderOnce($document); + if (! $this->totalPagesUsed) { + return $firstPass; + } + $this->totalPagesHint = $firstPass->pageCount(); - return $finalPass; + return $this->renderOnce($document); + } finally { + $this->totalPagesHint = null; + $this->widthCache = []; + } } /** Walks the tree once and gives every footnote its number. */ @@ -4281,17 +4297,31 @@ private function leadingSpaceIndent(Paragraph $p, RunStyle $default): float } private function measureWidth(string $text, RunStyle $style): float + { + // Everything the width depends on: the font (family, weight, slant + // and, through the fallback chain, the text) and the size. + $sizePt = $style->sizePt ?? $this->defaultFontSizePt; + $key = ($style->bold ? 'b' : '-').($style->italic ? 'i' : '-').pack('e', $sizePt).$style->fontFamily."\0".$text; + if (isset($this->widthCache[$key])) { + return $this->widthCache[$key]; + } + if (count($this->widthCache) >= self::WIDTH_CACHE_LIMIT) { + $this->widthCache = []; + } + + return $this->widthCache[$key] = $this->computeWidth($text, $style, $sizePt); + } + + private function computeWidth(string $text, RunStyle $style, float $sizePt): float { // SHY is invisible → strip for width estimation. $text = self::stripSoftHyphens($text); $font = $this->resolveEmbeddedFont($style, $text); if ($font !== null) { - $m = new TextMeasurer($font, $style->sizePt ?? $this->defaultFontSizePt); - - return $m->widthPt($text); + return (new TextMeasurer($font, $sizePt))->widthPt($text); } - return $this->standardWidth($text, $this->standardFontFor($style), $style->sizePt ?? $this->defaultFontSizePt); + return $this->standardWidth($text, $this->standardFontFor($style), $sizePt); } /** From c6ec477319fb324f34138a79fb0559cbc531c8a1 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Mon, 2 Nov 2026 16:01:54 -0800 Subject: [PATCH 05/13] perf(layout): trim per-word overhead in layout and content streams MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Small costs paid for every word, each now cheaper with byte-identical output: - RunStyle::inheritFrom returns the other side when one side is all defaults, instead of building a copy; heading styles are built once per level. - ContentStream::escapeString returns text with nothing to escape as is, and escapes the rest in one strtr instead of byte by byte. - Base-14 widths are summed from the font's table in one call instead of one call per byte. - spanWidth skips array_slice/array_sum for single-column cells, splitWords drops its filter closure, and the footnote walks skip text runs. Render time drops 8-17% (the invoice ~265ms → ~235ms, real prose ~23ms → ~19ms) with no change in memory. Co-Authored-By: Claude Opus 5.5 --- src/Layout/Engine.php | 30 ++++++++++---- src/Pdf/ContentStream.php | 28 +++++++------ .../Forms/Appearance/StandardFontMetrics.php | 19 +++++++++ src/Style/RunStyle.php | 9 ++++ tests/Style/RunStyleTest.php | 41 +++++++++++++++++++ 5 files changed, 107 insertions(+), 20 deletions(-) diff --git a/src/Layout/Engine.php b/src/Layout/Engine.php index ff06e55..b5bb15a 100644 --- a/src/Layout/Engine.php +++ b/src/Layout/Engine.php @@ -158,6 +158,9 @@ final class Engine */ private array $widthCache = []; + /** @var array Base run style per heading level, 0 for body text. */ + private array $headingStyles = []; + /** Entries kept before the width cache starts over. */ private const WIDTH_CACHE_LIMIT = 20000; @@ -312,6 +315,10 @@ private function assignFootnoteNumbers(AstDocument $document): void private function collectFootnotes(iterable $nodes): void { foreach ($nodes as $node) { + // Text runs are leaves and the bulk of any tree. + if ($node instanceof Run) { + continue; + } if ($node instanceof \Dskripchenko\PhpPdf\Element\Footnote) { $id = spl_object_id($node); if (! isset($this->footnoteNumbers[$id])) { @@ -428,6 +435,10 @@ private function footnotesIn(iterable $nodes): array { $numbers = []; foreach ($nodes as $node) { + // Text runs are leaves and the bulk of any tree. + if ($node instanceof Run) { + continue; + } if ($node instanceof \Dskripchenko\PhpPdf\Element\Footnote) { $numbers[] = $this->footnoteNumberFor($node); @@ -4406,11 +4417,7 @@ private function standardWidth(string $text, StandardFont $font, float $sizePt): if (! StandardFontMetrics::has($font->value)) { return mb_strlen($text, 'UTF-8') * $sizePt * 0.5; } - $units = 0; - $bytes = WinAnsi::encodeLossy($text); - for ($i = 0, $n = strlen($bytes); $i < $n; $i++) { - $units += StandardFontMetrics::width($font->value, ord($bytes[$i])); - } + $units = StandardFontMetrics::stringWidth($font->value, WinAnsi::encodeLossy($text)); return $units * $sizePt / 1000; } @@ -4517,6 +4524,11 @@ private function effectiveLineHeightPt(Paragraph $p, float $fontSize): float * Can be overridden by the caller via explicit RunStyle/ParagraphStyle. */ private function headingStyle(?int $level): RunStyle + { + return $this->headingStyles[$level ?? 0] ??= $this->makeHeadingStyle($level); + } + + private function makeHeadingStyle(?int $level): RunStyle { if ($level === null) { return new RunStyle(sizePt: $this->defaultFontSizePt); @@ -4887,6 +4899,10 @@ private function rowSpanGeometry(Table $t, int $rowIdx, array $heights): array */ private function spanWidth(array $colWidths, int $start, int $span): float { + if ($span === 1) { + return (float) ($colWidths[$start] ?? 0.0); + } + return (float) array_sum(array_slice($colWidths, $start, $span)); } @@ -6124,8 +6140,6 @@ private function formatListMarker(int $n, ListFormat $f): string */ private function splitWords(string $text): array { - $parts = preg_split('/\s+/u', trim($text)) ?: []; - - return array_values(array_filter($parts, fn (string $p): bool => $p !== '')); + return preg_split('/\s+/u', trim($text), -1, PREG_SPLIT_NO_EMPTY) ?: []; } } diff --git a/src/Pdf/ContentStream.php b/src/Pdf/ContentStream.php index b2f9e33..9f9f881 100644 --- a/src/Pdf/ContentStream.php +++ b/src/Pdf/ContentStream.php @@ -1031,21 +1031,25 @@ public function isEmpty(): bool */ private function escapeString(string $s): string { - $out = ''; - for ($i = 0; $i < strlen($s); $i++) { - $c = $s[$i]; - $ord = ord($c); - if ($c === '\\' || $c === '(' || $c === ')') { - $out .= '\\'.$c; - } elseif ($ord < 0x20 || $ord > 0x7E) { - // Non-printable / non-ASCII: octal \nnn. - $out .= sprintf("\\%03o", $ord); - } else { - $out .= $c; + // Backslash and parentheses get a backslash; non-printable and + // non-ASCII bytes become octal \nnn. Most text needs neither. + static $special = null; + static $map = null; + if ($special === null) { + $special = '\\()'; + $map = ['\\' => '\\\\', '(' => '\\(', ')' => '\\)']; + for ($ord = 0; $ord < 256; $ord++) { + if ($ord < 0x20 || $ord > 0x7E) { + $special .= chr($ord); + $map[chr($ord)] = sprintf('\\%03o', $ord); + } } } + if (strcspn($s, $special) === strlen($s)) { + return $s; + } - return $out; + return strtr($s, $map); } /** diff --git a/src/Pdf/Forms/Appearance/StandardFontMetrics.php b/src/Pdf/Forms/Appearance/StandardFontMetrics.php index f37a44f..d192e55 100644 --- a/src/Pdf/Forms/Appearance/StandardFontMetrics.php +++ b/src/Pdf/Forms/Appearance/StandardFontMetrics.php @@ -42,4 +42,23 @@ public static function width(string $baseFont, int $code): int return $code >= 32 && $code <= 255 ? $table[$code - 32] : 0; } + + /** Advance width of a string of WinAnsi bytes, in 1/1000 em. */ + public static function stringWidth(string $baseFont, string $bytes): int + { + $n = strlen($bytes); + if (str_starts_with($baseFont, 'Courier')) { + return $n * self::COURIER_WIDTH; + } + $table = self::WIDTHS[$baseFont] ?? self::WIDTHS['Helvetica']; + $units = 0; + for ($i = 0; $i < $n; $i++) { + $code = ord($bytes[$i]); + if ($code >= 32) { + $units += $table[$code - 32]; + } + } + + return $units; + } } diff --git a/src/Style/RunStyle.php b/src/Style/RunStyle.php index 5977b85..7f86c5a 100644 --- a/src/Style/RunStyle.php +++ b/src/Style/RunStyle.php @@ -107,6 +107,15 @@ public function withLetterSpacingPt(float $pt): self */ public function inheritFrom(self $parent): self { + // An all-defaults side adds nothing: the result has the other + // side's values, so hand that back instead of a copy. + if ($parent === $this || $parent->isEmpty()) { + return $this; + } + if ($this->isEmpty()) { + return $parent; + } + return new self( sizePt: $this->sizePt ?? $parent->sizePt, color: $this->color ?? $parent->color, diff --git a/tests/Style/RunStyleTest.php b/tests/Style/RunStyleTest.php index e497664..15ab740 100644 --- a/tests/Style/RunStyleTest.php +++ b/tests/Style/RunStyleTest.php @@ -82,4 +82,45 @@ public function size_pt_via_with(): void $s = (new RunStyle)->withSizePt(14.5); self::assertSame(14.5, $s->sizePt); } + + #[Test] + public function inheritFrom_with_a_default_side_returns_the_other(): void + { + $styled = new RunStyle(sizePt: 14, color: 'ff0000', bold: true); + + self::assertSame($styled, $styled->inheritFrom(new RunStyle)); + self::assertSame($styled, RunStyle::default()->inheritFrom($styled)); + self::assertSame($styled, (new RunStyle)->inheritFrom($styled)); + self::assertSame($styled, $styled->inheritFrom($styled)); + } + + #[Test] + public function inheritFrom_shortcuts_give_the_same_values_as_a_merge(): void + { + $styles = [ + new RunStyle, + new RunStyle(sizePt: 9), + new RunStyle(color: '00ff00', italic: true), + new RunStyle(fontFamily: 'Times', underline: true, letterSpacingPt: 0.5), + ]; + foreach ($styles as $child) { + foreach ($styles as $parent) { + $merged = new RunStyle( + sizePt: $child->sizePt ?? $parent->sizePt, + color: $child->color ?? $parent->color, + backgroundColor: $child->backgroundColor ?? $parent->backgroundColor, + fontFamily: $child->fontFamily ?? $parent->fontFamily, + bold: $child->bold || $parent->bold, + italic: $child->italic || $parent->italic, + underline: $child->underline || $parent->underline, + strikethrough: $child->strikethrough || $parent->strikethrough, + superscript: $child->superscript || $parent->superscript, + subscript: $child->subscript || $parent->subscript, + highlight: $child->highlight ?? $parent->highlight, + letterSpacingPt: $child->letterSpacingPt ?? $parent->letterSpacingPt, + ); + self::assertEquals($merged, $child->inheritFrom($parent)); + } + } + } } From bc651384401c09fd359e67d70e244d3398dabf8b Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 3 Nov 2026 09:01:33 -0800 Subject: [PATCH 06/13] chore(bench): an SVG dashboards scenario Ten pages, each a different metrics dashboard: a 4 x 3 grid of line, bar, scatter and area charts with gridlines and labels, about 1,200 shapes a page. The files differ so that a library caching images by name still draws every page. They are written before the clock starts, through a bench_prepare_() hook in one.php, and read inside the timed run by every library. FPDF has no SVG and is skipped. Co-Authored-By: Claude Opus 5.5 --- scripts/bench/one.php | 6 ++ scripts/bench/run.php | 8 +- scripts/bench/scenarios.php | 175 ++++++++++++++++++++++++++++++++++++ 3 files changed, 186 insertions(+), 3 deletions(-) diff --git a/scripts/bench/one.php b/scripts/bench/one.php index 7dd08bd..76e973c 100644 --- a/scripts/bench/one.php +++ b/scripts/bench/one.php @@ -16,6 +16,12 @@ exit(2); } +// Untimed setup a scenario may need, such as writing its fixtures. +$prepare = "bench_prepare_{$scenario}"; +if (function_exists($prepare)) { + $prepare(); +} + $start = hrtime(true); $bytes = $fn(); $ms = (hrtime(true) - $start) / 1e6; diff --git a/scripts/bench/run.php b/scripts/bench/run.php index 84bc393..2380362 100644 --- a/scripts/bench/run.php +++ b/scripts/bench/run.php @@ -28,6 +28,7 @@ 'invoice' => ['label' => '100-page invoice (50 rows/page)'], 'images' => ['label' => 'Image grid (20 pages × 4 JPEGs)'], 'html' => ['label' => 'HTML → PDF article (~5 pages)'], + 'svg' => ['label' => 'SVG dashboards (10 pages, ~1,200 shapes each)'], ]; $libs = ['phppdf', 'mpdf', 'tcpdf', 'dompdf', 'fpdf']; @@ -244,7 +245,7 @@ function summary_table(array $scenarios, array $results): string { $out = "| Scenario | dskripchenko/php-pdf | mpdf | tcpdf | dompdf | FPDF |\n"; $out .= "|---|---:|---:|---:|---:|---:|\n"; - foreach (['html', 'invoice', 'images', 'hello'] as $key) { + foreach (['html', 'invoice', 'images', 'svg', 'hello'] as $key) { if (! isset($scenarios[$key])) { continue; } @@ -322,9 +323,10 @@ function emit_benchmarks_doc(array $scenarios, array $results, array $meta): str | `invoice` | 100 pages × 50 rows; each page has an `

` heading and a 4-column table. | | `images` | 20 pages × 4 JPEG thumbnails (250 × 180 pt each). | | `html` | One `

`, two `

` sections, 24 paragraphs of Lorem with bold/italic/link plus bullet lists. ~5 pages. | +| `svg` | 10 pages, each a different metrics-dashboard SVG: 12 panels of line, bar, scatter and area charts with gridlines and labels, ~1,200 shapes. | -FPDF has no HTML support and is therefore skipped on the `html` -scenario. +FPDF has no HTML or SVG support and is therefore skipped on the +`html` and `svg` scenarios. ## How to reproduce diff --git a/scripts/bench/scenarios.php b/scripts/bench/scenarios.php index abaf028..fc8e06c 100644 --- a/scripts/bench/scenarios.php +++ b/scripts/bench/scenarios.php @@ -294,3 +294,178 @@ function bench_article_html(): string . '

Section B

' . $body . ''; } + +// ---------- SVG dashboards ---------- +// +// Ten metrics dashboards, one per page: a 4 × 3 grid of panels with +// gridlines and tick labels, holding two-series line charts (300 points +// each), 48-bar charts, 250-point translucent scatters and filled area +// paths — about 1,200 shapes per page. Each page is a different file, so a +// library that caches images by name still draws all ten. Every library +// reads the files inside the timed run. FPDF has no SVG. + +const BENCH_SVG_PAGES = 10; +const BENCH_SVG_WIDTH_PT = 523.0; +const BENCH_SVG_HEIGHT_PT = 523.0 * 800 / 1200; + +function bench_prepare_svg(): void +{ + $dir = bench_svg_dir(); + if (! is_dir($dir)) { + mkdir($dir, 0777, true); + } + foreach (bench_svg_files() as $i => $file) { + if (! is_file($file)) { + file_put_contents($file, bench_svg_dashboard($i + 1)); + } + } +} + +function bench_svg_dir(): string +{ + // The version keeps files of an older generator from being reused. + return sys_get_temp_dir().'/php-pdf-bench-svg-v1'; +} + +/** @return list */ +function bench_svg_files(): array +{ + $files = []; + for ($p = 1; $p <= BENCH_SVG_PAGES; $p++) { + $files[] = bench_svg_dir()."/dashboard-$p.svg"; + } + + return $files; +} + +function bench_svg_dashboard(int $seed): string +{ + mt_srand($seed); + $W = 1200; $H = 800; $cols = 4; $rows = 3; $pad = 12; + $pw = ($W - $pad * ($cols + 1)) / $cols; + $ph = ($H - $pad * ($rows + 1)) / $rows; + $f = fn (float $v): string => rtrim(rtrim(sprintf('%.2f', $v), '0'), '.'); + $o = [sprintf('', $W, $H, $W, $H)]; + $o[] = sprintf('', $W, $H); + $kinds = ['line', 'bar', 'scatter', 'area']; + for ($r = 0; $r < $rows; $r++) { + for ($c = 0; $c < $cols; $c++) { + $kind = $kinds[($r * $cols + $c) % 4]; + $o[] = sprintf('', $f($pad + $c * ($pw + $pad)), $f($pad + $r * ($ph + $pad))); + $o[] = sprintf('', $f($pw), $f($ph)); + $o[] = sprintf('%s metric %d', ucfirst($kind), $r * $cols + $c + 1); + $cx0 = 34; $cy0 = 28; $cw = $pw - 44; $ch = $ph - 48; + for ($g = 0; $g <= 5; $g++) { + $gy = $cy0 + $ch - $g * $ch / 5; + $o[] = sprintf('', $cx0, $f($gy), $f($cx0 + $cw), $f($gy)); + $o[] = sprintf('%d', $cx0 - 4, $f($gy + 2.5), $g * 20); + } + for ($t = 0; $t <= 6; $t++) { + $o[] = sprintf('%02d:00', $f($cx0 + $t * $cw / 6), $f($cy0 + $ch + 11), $t * 4); + } + $sy = fn (float $v): float => $cy0 + $ch - $v * $ch; + switch ($kind) { + case 'line': + foreach (['#2563eb', '#dc2626'] as $color) { + $v = mt_rand(30, 70) / 100; + $pts = []; + for ($i = 0; $i < 300; $i++) { + $v = max(0.02, min(0.98, $v + mt_rand(-100, 100) / 2500)); + $pts[] = $f($cx0 + $i * $cw / 299).','.$f($sy($v)); + } + $o[] = sprintf('', $color, implode(' ', $pts)); + } + break; + case 'bar': + $bw = $cw / 48; + for ($i = 0; $i < 48; $i++) { + $v = mt_rand(5, 95) / 100; + $o[] = sprintf('', $f($cx0 + $i * $bw + 0.5), $f($sy($v)), $f($bw - 1), $f($v * $ch)); + } + break; + case 'scatter': + for ($i = 0; $i < 250; $i++) { + $a = mt_rand(0, 1000) / 1000; + $b = max(0.02, min(0.98, $a * 0.8 + mt_rand(-150, 150) / 1000 + 0.1)); + $o[] = sprintf('', $f($cx0 + $a * $cw), $f($sy($b))); + } + break; + case 'area': + $v = 0.4; + $area = sprintf('M%s,%s', $cx0, $f($cy0 + $ch)); + $line = ''; + for ($i = 0; $i < 200; $i++) { + $v = max(0.05, min(0.95, $v + mt_rand(-100, 100) / 2000)); + $pt = $f($cx0 + $i * $cw / 199).','.$f($sy($v)); + $area .= ' L'.$pt; + $line .= ($i === 0 ? 'M' : ' L').$pt; + } + $area .= sprintf(' L%s,%s Z', $f($cx0 + $cw), $f($cy0 + $ch)); + $o[] = sprintf('', $area); + $o[] = sprintf('', $line); + break; + } + $o[] = ''; + } + } + $o[] = ''; + + return implode("\n", $o)."\n"; +} + +function bench_phppdf_svg(): string +{ + $b = DocumentBuilder::new(); + foreach (bench_svg_files() as $i => $file) { + if ($i > 0) { + $b->pageBreak(); + } + $b->block(new \Dskripchenko\PhpPdf\Element\SvgElement( + (string) file_get_contents($file), BENCH_SVG_WIDTH_PT, BENCH_SVG_HEIGHT_PT, + )); + } + + return $b->toBytes(); +} + +function bench_mpdf_svg(): string +{ + $pdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => 'A4']); + foreach (bench_svg_files() as $i => $file) { + if ($i > 0) { + $pdf->AddPage(); + } + $pdf->WriteHTML(sprintf('', $file, BENCH_SVG_WIDTH_PT, BENCH_SVG_HEIGHT_PT)); + } + + return $pdf->Output('', 'S'); +} + +function bench_tcpdf_svg(): string +{ + $pdf = new \TCPDF('P', 'pt', 'A4', true, 'UTF-8', false); + $pdf->setPrintHeader(false); + $pdf->setPrintFooter(false); + foreach (bench_svg_files() as $file) { + $pdf->AddPage(); + $pdf->ImageSVG('@'.file_get_contents($file), 36, 36, BENCH_SVG_WIDTH_PT, BENCH_SVG_HEIGHT_PT); + } + + return $pdf->Output('', 'S'); +} + +function bench_dompdf_svg(): string +{ + $pdf = new \Dompdf\Dompdf(['chroot' => bench_svg_dir(), 'isRemoteEnabled' => false]); + $html = ''; + foreach (bench_svg_files() as $i => $file) { + if ($i > 0) { + $html .= '
'; + } + $html .= sprintf('', $file, BENCH_SVG_WIDTH_PT, BENCH_SVG_HEIGHT_PT); + } + $pdf->loadHtml($html.''); + $pdf->render(); + + return $pdf->output(); +} From f616dce79f956744692106e6bbe408d7fbdec311 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 3 Nov 2026 09:07:23 -0800 Subject: [PATCH 07/13] perf(svg): compose nested transforms into one matrix Under a , every coordinate went through a closure per level of nesting, down to the page mapping, and px and py each worked the same affine out again. The walk now multiplies each transform into the page mapping on the way down, so a point costs one closure call however deep it sits. The two walkers that each held the nine-way element match share drawTransformed(). The SVG dashboards scenario drops from ~432 ms to ~394 ms (-9%). Coordinates are rounded the same way but reached in a different order, so about 1 line in 150 of the dense benchmark changes in its fourth decimal; rendered at 720 dpi, 14-28 of ~50 million pixels a page differ, by at most 8% in one channel. Co-Authored-By: Claude Opus 5.5 --- src/Svg/SvgRenderer.php | 108 ++++++++++++++++------------------------ 1 file changed, 44 insertions(+), 64 deletions(-) diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index e0e5ee0..fb7c1a8 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -534,9 +534,10 @@ private static function walkElement(\SimpleXMLElement $el, Page $page, callable } /** - * Apply transform matrix to element-level coords; coords - * then pass through original tx/ty (PDF mapping). + * A child with a transform, under the page mapping $origTx / $origTy. * + * @param callable(float): float $origTx + * @param callable(float): float $origTy * @param array{0: float, 1: float, 2: float, 3: float, 4: float, 5: float} $matrix [a, b, c, d, e, f] */ private static function walkChildTransformed( @@ -548,46 +549,35 @@ private static function walkChildTransformed( float $scaleX, float $scaleY, ): void { - [$a, $b, $c, $d, $e, $f] = $matrix; - // Composed transform: SVG coord (x, y) → transformed (a*x+c*y+e, b*x+d*y+f) → PDF. - // Single-arg signatures cannot represent cross-coupling, so we - // construct point-transforming closures for each method. - // Simplest: wrap tx/ty to accept transformed inputs precomputed - // by callers. That requires callers compute (a*x + c*y + e, b*x + d*y + f) - // before calling tx/ty. - + [$a, $b, $c, $d] = $matrix; // Effective scale for stroke-width = sqrt(|a*d - b*c|). $effScale = $scaleX * sqrt(max(abs($a * $d - $b * $c), 1e-9)); + self::drawTransformed($el, $page, self::multiplyMatrix(self::affineTxTy($origTx, $origTy), $matrix), $effScale, $scaleY); + } - $newTx = static function (float $x) use ($a, $c, $e, $origTx): float { - // y component injected later through cross-coupled wrappers. - // Fallback if used standalone: y = 0. - return $origTx($a * $x + $c * 0 + $e); - }; - $newTy = static function (float $y) use ($b, $d, $f, $origTy): float { - return $origTy($b * 0 + $d * $y + $f); - }; - - // Properly transform requires cross-axis coupling. Use combined - // wrapper that accepts both x and y as a pair: emit points directly. - $px = static function (float $x, float $y) use ($a, $c, $e, $origTx): float { - return $origTx($a * $x + $c * $y + $e); - }; - $py = static function (float $x, float $y) use ($b, $d, $f, $origTy): float { - return $origTy($b * $x + $d * $y + $f); - }; - - $tag = $el->getName(); - match ($tag) { - 'rect' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderRectXY($el, $page, $px, $py, $effScale, $scaleY))), - 'line' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderLineXY($el, $page, $px, $py, $effScale))), - 'circle' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderEllipseXY($el, $page, $px, $py, $effScale, true))), - 'ellipse' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderEllipseXY($el, $page, $px, $py, $effScale, false))), - 'polygon' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderPolygonXY($el, $page, $px, $py, true, $effScale))), - 'polyline' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderPolygonXY($el, $page, $px, $py, false, $effScale))), - 'path' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderPathXY($el, $page, $px, $py, $effScale))), - 'text' => self::renderTextXY($el, $page, $px, $py, $effScale), - 'g' => self::walkElementXY($el, $page, $px, $py, $effScale, $scaleY), + /** + * Draws an element under $m, the whole mapping from its user space to + * the page. Nested transforms are multiplied into $m as the walk goes + * down, so a point costs one closure call however deep it sits. + * + * @param array{0: float, 1: float, 2: float, 3: float, 4: float, 5: float} $m + */ + private static function drawTransformed(\SimpleXMLElement $el, Page $page, array $m, float $scaleX, float $scaleY): void + { + [$a, $b, $c, $d, $e, $f] = $m; + $px = static fn (float $x, float $y): float => $a * $x + $c * $y + $e; + $py = static fn (float $x, float $y): float => $b * $x + $d * $y + $f; + + match ($el->getName()) { + 'rect' => self::withDash($el, $page, $scaleX, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderRectXY($el, $page, $px, $py, $scaleX, $scaleY))), + 'line' => self::withDash($el, $page, $scaleX, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderLineXY($el, $page, $px, $py, $scaleX))), + 'circle' => self::withDash($el, $page, $scaleX, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderEllipseXY($el, $page, $px, $py, $scaleX, true))), + 'ellipse' => self::withDash($el, $page, $scaleX, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderEllipseXY($el, $page, $px, $py, $scaleX, false))), + 'polygon' => self::withDash($el, $page, $scaleX, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderPolygonXY($el, $page, $px, $py, true, $scaleX))), + 'polyline' => self::withDash($el, $page, $scaleX, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderPolygonXY($el, $page, $px, $py, false, $scaleX))), + 'path' => self::withDash($el, $page, $scaleX, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderPathXY($el, $page, $px, $py, $scaleX))), + 'text' => self::renderTextXY($el, $page, $px, $py, $scaleX), + 'g' => self::walkElementXY($el, $page, $m, $scaleX, $scaleY), default => null, }; } @@ -699,38 +689,28 @@ private static function dashLength(string $token): ?float } /** - * Walk children with (px, py) cross-coupled point transformers. + * Walks a group's children under $m, the group's mapping to the page. * - * @param callable(float, float): float $px - * @param callable(float, float): float $py + * @param array{0: float, 1: float, 2: float, 3: float, 4: float, 5: float} $m */ - private static function walkElementXY(\SimpleXMLElement $el, Page $page, callable $px, callable $py, float $scaleX, float $scaleY): void + private static function walkElementXY(\SimpleXMLElement $el, Page $page, array $m, float $scaleX, float $scaleY): void { foreach ($el->children() as $child) { // A child's own transform applies inside its group's. - $cpx = $px; - $cpy = $py; - $cScale = $scaleX; $matrix = isset($child['transform']) ? self::parseTransform((string) $child['transform']) : null; - if ($matrix !== null) { - [$a, $b, $c, $d, $e, $f] = $matrix; - $cpx = static fn (float $x, float $y): float => $px($a * $x + $c * $y + $e, $b * $x + $d * $y + $f); - $cpy = static fn (float $x, float $y): float => $py($a * $x + $c * $y + $e, $b * $x + $d * $y + $f); - $cScale = $scaleX * sqrt(max(abs($a * $d - $b * $c), 1e-9)); + if ($matrix === null) { + self::drawTransformed($child, $page, $m, $scaleX, $scaleY); + + continue; } - $tag = $child->getName(); - match ($tag) { - 'rect' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderRectXY($child, $page, $cpx, $cpy, $cScale, $scaleY))), - 'line' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderLineXY($child, $page, $cpx, $cpy, $cScale))), - 'circle' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderEllipseXY($child, $page, $cpx, $cpy, $cScale, true))), - 'ellipse' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderEllipseXY($child, $page, $cpx, $cpy, $cScale, false))), - 'polygon' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderPolygonXY($child, $page, $cpx, $cpy, true, $cScale))), - 'polyline' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderPolygonXY($child, $page, $cpx, $cpy, false, $cScale))), - 'path' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderPathXY($child, $page, $cpx, $cpy, $cScale))), - 'text' => self::renderTextXY($child, $page, $cpx, $cpy, $cScale), - 'g' => self::walkElementXY($child, $page, $cpx, $cpy, $cScale, $scaleY), - default => null, - }; + [$a, $b, $c, $d] = $matrix; + self::drawTransformed( + $child, + $page, + self::multiplyMatrix($m, $matrix), + $scaleX * sqrt(max(abs($a * $d - $b * $c), 1e-9)), + $scaleY, + ); } } From a08d69822869af587bbefda7361a1a19b95615cf Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 3 Nov 2026 09:08:05 -0800 Subject: [PATCH 08/13] perf(svg): take a shape's ancestors from the walk inheritedProperty() looked a shape's ancestors up with an ancestor-or-self XPath query, once per shape. The walk already knows them: it now keeps the groups it is inside and hands each shape its chain before drawing it. Any other element still goes through XPath. The SVG dashboards scenario drops from ~394 ms to ~384 ms (-2.5%), byte-identical output. Co-Authored-By: Claude Opus 5.5 --- src/Svg/SvgRenderer.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index fb7c1a8..a9b5718 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -293,6 +293,7 @@ private static function renderDocument(string $svgXml, Page $page, float $boxX, self::$currentGradients = $previous; self::$chainOf = null; self::$chain = []; + self::$parents = []; } } @@ -488,13 +489,33 @@ private static function applyCssToTree(\SimpleXMLElement $el, array $rules): voi /** @var list<\SimpleXMLElement> */ private static array $chain = []; + /** + * The groups the walk is inside, nearest first, so that a shape's + * ancestors are known without asking the document. + * + * @var list<\SimpleXMLElement> + */ + private static array $parents = []; + + /** + * Primes inheritedProperty() with the ancestors of the shape about to + * be drawn, taken from the walk. + */ + private static function enter(\SimpleXMLElement $el): void + { + self::$chainOf = $el; + self::$chain = [$el, ...self::$parents]; + } + /** * @param callable(float): float $tx * @param callable(float): float $ty */ private static function walkElement(\SimpleXMLElement $el, Page $page, callable $tx, callable $ty, float $scaleX, float $scaleY): void { + array_unshift(self::$parents, $el); foreach ($el->children() as $child) { + self::enter($child); // Apply element-level transform (if present). $elTx = $tx; $elTy = $ty; @@ -531,6 +552,7 @@ private static function walkElement(\SimpleXMLElement $el, Page $page, callable default => null, }; } + array_shift(self::$parents); } /** @@ -568,6 +590,7 @@ private static function drawTransformed(\SimpleXMLElement $el, Page $page, array $px = static fn (float $x, float $y): float => $a * $x + $c * $y + $e; $py = static fn (float $x, float $y): float => $b * $x + $d * $y + $f; + self::enter($el); match ($el->getName()) { 'rect' => self::withDash($el, $page, $scaleX, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderRectXY($el, $page, $px, $py, $scaleX, $scaleY))), 'line' => self::withDash($el, $page, $scaleX, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderLineXY($el, $page, $px, $py, $scaleX))), @@ -695,6 +718,7 @@ private static function dashLength(string $token): ?float */ private static function walkElementXY(\SimpleXMLElement $el, Page $page, array $m, float $scaleX, float $scaleY): void { + array_unshift(self::$parents, $el); foreach ($el->children() as $child) { // A child's own transform applies inside its group's. $matrix = isset($child['transform']) ? self::parseTransform((string) $child['transform']) : null; @@ -712,6 +736,7 @@ private static function walkElementXY(\SimpleXMLElement $el, Page $page, array $ $scaleY, ); } + array_shift(self::$parents); } /** From bdc7e33bd2617f9045ef1b64f52133ff38abe2d1 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 3 Nov 2026 10:43:08 -0800 Subject: [PATCH 09/13] perf(layout): redraw page totals in place instead of a second pass A NUMPAGES field anywhere sent the whole document through layout twice, only to learn the page count. "Page X of Y" in a footer is the usual case, and there the body comes out the same on both passes; only the footers change. Pass 1 now notes where each header and footer showing the total was drawn. Once the count is known they are drawn again with it and put in place of what pass 1 drew. Pass 2 still runs whenever that could give a different result: - the total appears in the body or in a fixed block; - a header or footer takes a different height with the real total than with the stand-in, so the body would move; - the redraw adds anything to the page or document (a link annotation, a resource, an outline entry) or leaves the content stream in another state than the commands after it were written against. Output is byte-identical to the two-pass render across the test suite and 30 header/footer cases (centred, right-aligned, first-page, offset sections, tagged, watermark, footnotes, tables, coloured, embedded font). A 200-page invoice with a "Page X of Y" footer drops from ~1000ms to ~540ms, the same as without the footer. Co-Authored-By: Claude Opus 5.5 --- src/Layout/Engine.php | 154 ++++++++++++++++++++++++++- src/Pdf/ContentStream.php | 59 ++++++++++ src/Pdf/Page.php | 27 +++++ tests/Layout/FieldResolutionTest.php | 54 ++++++++++ tests/Pdf/ContentStreamTest.php | 37 +++++++ 5 files changed, 327 insertions(+), 4 deletions(-) diff --git a/src/Layout/Engine.php b/src/Layout/Engine.php index b5bb15a..aebf1f8 100644 --- a/src/Layout/Engine.php +++ b/src/Layout/Engine.php @@ -96,6 +96,23 @@ final class Engine /** Whether the pass being rendered resolved a NUMPAGES field. */ private bool $totalPagesUsed = false; + /** Whether a NUMPAGES field was met outside the headers and footers. */ + private bool $totalPagesInBody = false; + + /** NUMPAGES fields resolved so far in this pass. */ + private int $totalPagesResolved = 0; + + /** Whether headers, footers and fixed blocks are being drawn. */ + private bool $inPageFurniture = false; + + /** + * Headers and footers drawn in the first pass that show the page total, + * with what is needed to draw them again once the total is known. + * + * @var list}, to: array{0: int, 1: array}, after: array, section: Section, fixed: list}> + */ + private array $totalPagesSlots = []; + /** * Footnote bookkeeping, keyed by the footnote element itself. * @@ -276,10 +293,12 @@ private function applyFallbackChain(?PdfFont $primary, ?string $text): ?PdfFont public function render(AstDocument $document): PdfDocument { - // Two passes only when NUMPAGES needs the page count: - // - Pass 1: render with totalPagesHint=null, count pages - // - Pass 2: render with known totalPagesHint, NUMPAGES → actual count - // A document that never shows the total is finished after pass 1. + // NUMPAGES needs the page count, which is known only after layout: + // - Pass 1: render with totalPagesHint=null, count pages. + // - A document that never shows the total is finished. + // - When the total shows only in headers and footers, they are + // drawn again with the count, if that changes nothing else. + // - Otherwise pass 2 renders with the known count. // The width cache lives for one render only, so its memory goes // with it. $this->totalPagesHint = null; @@ -289,10 +308,14 @@ public function render(AstDocument $document): PdfDocument return $firstPass; } $this->totalPagesHint = $firstPass->pageCount(); + if (! $this->totalPagesInBody && $this->redrawPageTotals($firstPass)) { + return $firstPass; + } return $this->renderOnce($document); } finally { $this->totalPagesHint = null; + $this->totalPagesSlots = []; $this->widthCache = []; } } @@ -457,6 +480,9 @@ private function footnotesIn(iterable $nodes): array private function renderOnce(AstDocument $document): PdfDocument { $this->totalPagesUsed = false; + $this->totalPagesInBody = false; + $this->totalPagesResolved = 0; + $this->totalPagesSlots = []; // Numbers are handed out in a single walk of the tree, in document // order, before anything is laid out. Assigning them as footnotes @@ -2414,8 +2440,124 @@ private function applyPerPageMargins(LayoutContext $ctx): void * .. pageHeight]. Cursor starts just below the top edge. * Footer bounds: leftX..leftX+contentWidth × [0 .. bottomMargin]. * Cursor starts sufficiently below the content area. + * + * When they show the page total, what was drawn is noted so that it + * can be drawn again once the total is known. */ private function renderHeaderFooter(LayoutContext $ctx): void + { + $before = clone $ctx; + $from = $ctx->currentPage->contentMark(); + $resolved = $this->totalPagesResolved; + $fixed = $this->fixedPositioned; + $this->inPageFurniture = true; + try { + $this->drawPageFurniture($ctx); + } finally { + $this->inPageFurniture = false; + } + if ($this->totalPagesResolved === $resolved) { + return; + } + if ($this->fixedPositioned !== $fixed) { + // A fixed block met in a header: drawing it again would not do + // the same. Pass 2 handles it. + $this->totalPagesInBody = true; + + return; + } + $this->totalPagesSlots[] = [ + 'ctx' => $before, + 'from' => $from, + 'to' => $ctx->currentPage->contentMark(), + 'after' => self::stateOf($ctx), + 'section' => $this->currentSection, + 'fixed' => $fixed, + ]; + } + + /** + * Draws headers and footers again with the page total, now known, in + * place of what pass 1 drew with a stand-in. + * + * Pass 2 would draw them with the same total, so the result is the + * same as long as they take the same room and change nothing but their + * own content: no resource, annotation or outline entry added, the + * content stream left in the same state. When any of that does not + * hold, false is returned and $pdf is discarded. + */ + private function redrawPageTotals(PdfDocument $pdf): bool + { + $document = self::stateOf($pdf); + $footnotes = [$this->footnoteNumbers, $this->pageFootnotes, $this->pageFootnoteRoom]; + try { + // Last first: a page drawn on twice keeps its earlier offsets. + foreach (array_reverse($this->totalPagesSlots) as $slot) { + $ctx = clone $slot['ctx']; + $page = $ctx->currentPage; + $pageState = self::stateOf($page); + $this->currentSection = $slot['section']; + $this->fixedPositioned = $slot['fixed']; + $redrawn = $page->rewriteContent($slot['from'], $slot['to'], function () use ($ctx): void { + $this->inPageFurniture = true; + try { + $this->drawPageFurniture($ctx); + } finally { + $this->inPageFurniture = false; + } + }); + if (! $redrawn + || self::stateOf($ctx) !== $slot['after'] + || self::stateOf($page) !== $pageState + || $this->fixedPositioned !== $slot['fixed']) { + return false; + } + } + } finally { + $this->currentSection = null; + $this->fixedPositioned = []; + } + + return self::stateOf($pdf) === $document + && [$this->footnoteNumbers, $this->pageFootnotes, $this->pageFootnoteRoom] === $footnotes; + } + + /** + * An object's properties, for telling whether something changed them: + * values as they are, objects by identity and size. The content stream + * of a page is left out. + * + * @return array + */ + private static function stateOf(object $object): array + { + $state = (array) $object; + unset($state["\0".Page::class."\0stream"]); + + return self::stateOfValue($state); + } + + /** + * @param array $values + * @return array + */ + private static function stateOfValue(array $values): array + { + foreach ($values as $key => $value) { + if (is_array($value)) { + $values[$key] = self::stateOfValue($value); + } elseif ($value instanceof \Countable) { + $values[$key] = [spl_object_id($value), count($value)]; + } elseif (is_object($value)) { + $values[$key] = spl_object_id($value); + } + } + + return $values; + } + + /** Draws fixed blocks, header and footer on the current page. */ + private function drawPageFurniture(LayoutContext $ctx): void { if ($this->currentSection === null) { return; @@ -2655,6 +2797,10 @@ private function displayedPageNumber(LayoutContext $ctx): int private function resolveTotalPages(?LayoutContext $ctx): int { $this->totalPagesUsed = true; + $this->totalPagesResolved++; + if (! $this->inPageFurniture) { + $this->totalPagesInBody = true; + } return $ctx !== null ? $this->displayedTotalPages($ctx) : ($this->totalPagesHint ?? 99); } diff --git a/src/Pdf/ContentStream.php b/src/Pdf/ContentStream.php index 9f9f881..5a7e4d2 100644 --- a/src/Pdf/ContentStream.php +++ b/src/Pdf/ContentStream.php @@ -1025,6 +1025,65 @@ public function isEmpty(): bool return $this->body === ''; } + /** + * Where the stream stands: its length, and the state the next command + * is written against. + * + * @internal + * + * @return array{0: int, 1: array} + */ + public function mark(): array + { + $state = get_object_vars($this); + unset($state['body']); + + return [strlen($this->body), $state]; + } + + /** + * Writes the commands between two marks again, with $draw. + * + * The commands after $to were written against the state the old ones + * left, so the new ones must leave the same state. When they don't, the + * stream is left as it was and false is returned. + * + * @internal + * + * @param array{0: int, 1: array} $from + * @param array{0: int, 1: array} $to + * @param \Closure(): void $draw + */ + public function rewrite(array $from, array $to, \Closure $draw): bool + { + $body = $this->body; + $state = $this->mark()[1]; + $this->body = ''; + $this->restoreState($from[1]); + try { + $draw(); + $drawn = $this->body; + $sameEnd = $this->mark()[1] === $to[1]; + } finally { + $this->body = $body; + $this->restoreState($state); + } + if (! $sameEnd) { + return false; + } + $this->body = substr($body, 0, $from[0]).$drawn.substr($body, $to[0]); + + return true; + } + + /** @param array $state */ + private function restoreState(array $state): void + { + foreach ($state as $name => $value) { + $this->{$name} = $value; + } + } + /** * Escape a PDF literal string `(…)`. Per ISO 32000-1 §7.3.4.2: * must escape `\`, `(`, `)`. Also non-printable bytes → \nnn. diff --git a/src/Pdf/Page.php b/src/Pdf/Page.php index 5454cd4..463646f 100644 --- a/src/Pdf/Page.php +++ b/src/Pdf/Page.php @@ -945,6 +945,33 @@ public function endMarkedContent(): self return $this; } + /** + * Where the page's content stands. See {@see ContentStream::mark()}. + * + * @internal + * + * @return array{0: int, 1: array} + */ + public function contentMark(): array + { + return $this->stream->mark(); + } + + /** + * Draws the content between two marks again. See + * {@see ContentStream::rewrite()}. + * + * @internal + * + * @param array{0: int, 1: array} $from + * @param array{0: int, 1: array} $to + * @param \Closure(): void $draw + */ + public function rewriteContent(array $from, array $to, \Closure $draw): bool + { + return $this->stream->rewrite($from, $to, $draw); + } + /** * Begin /Artifact marked content (PDF/UA — content * excluded from struct tree). diff --git a/tests/Layout/FieldResolutionTest.php b/tests/Layout/FieldResolutionTest.php index 7f60fe6..fc7f131 100644 --- a/tests/Layout/FieldResolutionTest.php +++ b/tests/Layout/FieldResolutionTest.php @@ -7,6 +7,7 @@ use Dskripchenko\PhpPdf\Document; use Dskripchenko\PhpPdf\Element\Cell; use Dskripchenko\PhpPdf\Element\Field; +use Dskripchenko\PhpPdf\Element\Hyperlink; use Dskripchenko\PhpPdf\Element\Paragraph; use Dskripchenko\PhpPdf\Element\Row; use Dskripchenko\PhpPdf\Element\Run; @@ -15,6 +16,7 @@ use Dskripchenko\PhpPdf\Layout\Engine; use Dskripchenko\PhpPdf\Pdf\PdfFont; use Dskripchenko\PhpPdf\Section; +use Dskripchenko\PhpPdf\Style\RunStyle; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -125,4 +127,56 @@ public function numpages_met_only_on_the_last_page_still_gets_the_real_count(): self::assertGreaterThan(1, $pageCount); self::assertStringContainsString("Cell total: $pageCount", $this->pdftotext($bytes)); } + + /** @return list */ + private function filler(int $count): array + { + return array_map( + fn (int $i) => new Paragraph([new Run("Paragraph $i with words enough to wrap now and then across the width of the page.")]), + range(1, $count), + ); + } + + #[Test] + public function footer_total_is_right_on_every_page(): void + { + $footer = new Paragraph([new Run('Page '), Field::page(), new Run(' of '), Field::totalPages()]); + $bytes = (new Document(new Section($this->filler(200), footerBlocks: [$footer]))) + ->toBytes(new Engine(compressStreams: false)); + $pageCount = substr_count($bytes, '/Type /Page '); + self::assertGreaterThan(3, $pageCount); + $text = $this->pdftotext($bytes); + for ($page = 1; $page <= $pageCount; $page++) { + self::assertStringContainsString("Page $page of $pageCount", $text); + } + self::assertStringNotContainsString(' of 1'."\n", $text); + } + + #[Test] + public function footer_total_lays_out_as_if_the_number_were_typed(): void + { + // A large footer that takes one more line with the stand-in 99 than + // with the real total: the room it leaves the body must be the room + // the real total needs. + $big = new RunStyle(sizePt: 30); + $footer = fn (Run|Field $total) => new Paragraph([new Run(str_repeat('x', 30).' ', $big), $total]); + $render = fn (Run|Field $total) => (new Document(new Section($this->filler(300), footerBlocks: [$footer($total)]))) + ->toBytes(new Engine(compressStreams: false)); + + $withField = $render(Field::totalPages($big)); + $pageCount = substr_count($withField, '/Type /Page '); + $typed = $render(new Run((string) $pageCount, $big)); + + self::assertSame($this->pdftotext($typed), $this->pdftotext($withField)); + } + + #[Test] + public function footer_link_beside_the_total_is_kept_once_per_page(): void + { + $footer = new Paragraph([Hyperlink::external('https://example.com', [new Run('Site')]), new Run(' · '), Field::totalPages()]); + $bytes = (new Document(new Section($this->filler(200), footerBlocks: [$footer]))) + ->toBytes(new Engine(compressStreams: false)); + + self::assertSame(substr_count($bytes, '/Type /Page '), substr_count($bytes, '/Subtype /Link')); + } } diff --git a/tests/Pdf/ContentStreamTest.php b/tests/Pdf/ContentStreamTest.php index 5785f24..2540462 100644 --- a/tests/Pdf/ContentStreamTest.php +++ b/tests/Pdf/ContentStreamTest.php @@ -138,4 +138,41 @@ public function empty_stream_isEmpty(): void $cs->text('F1', 12, 0, 0, 'x'); self::assertFalse($cs->isEmpty()); } + + #[Test] + public function rewrite_replaces_the_commands_between_two_marks(): void + { + $cs = (new ContentStream)->text('F1', 12, 0, 0, 'head'); + $from = $cs->mark(); + $cs->text('F1', 12, 0, 0, 'old'); + $to = $cs->mark(); + $cs->text('F1', 12, 0, 0, 'tail'); + + self::assertTrue($cs->rewrite($from, $to, function () use ($cs): void { + $cs->text('F1', 12, 0, 0, 'new'); + })); + self::assertSame( + (new ContentStream)->text('F1', 12, 0, 0, 'head')->text('F1', 12, 0, 0, 'new')->text('F1', 12, 0, 0, 'tail')->toString(), + $cs->toString(), + ); + } + + #[Test] + public function rewrite_that_would_leave_another_state_changes_nothing(): void + { + // The red text after the mark was written knowing the fill is + // already red; new commands ending in black would turn it black. + $cs = new ContentStream; + $from = $cs->mark(); + $cs->text('F1', 12, 0, 0, 'old', 1.0, 0.0, 0.0); + $to = $cs->mark(); + $cs->text('F1', 12, 0, 0, 'tail', 1.0, 0.0, 0.0); + $before = $cs->toString(); + + self::assertFalse($cs->rewrite($from, $to, function () use ($cs): void { + $cs->text('F1', 12, 0, 0, 'new'); + })); + self::assertSame($before, $cs->toString()); + self::assertSame($to[1], $cs->mark()[1]); + } } From e588602412cb2f2adb5819004a506ae30adfafff Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Wed, 11 Nov 2026 18:40:11 -0800 Subject: [PATCH 10/13] perf(font): build glyph and codepoint lists only for ligatures shapedGlyphs() built a list of glyph ids and a list of codepoints with two array_map closures on every call, though only the ligature path reads them. Without a ligature table, which is common, both were thrown away. They are now built after the check, with array_column. Also adds PdfFontTextEncodingTest: encodeText() and encodeTextTjArray() against a plain reference (shapedGlyphs, kerningPdfUnits per pair, sprintf per glyph), checking both the output and what the font records for its ToUnicode map, in order, after every string. It covers kerning, CFF, ligatures on and off, Arabic, Hebrew, a glyph shared by two codepoints, emoji and malformed UTF-8, and pins the next commits. Text drawing with an embedded font: 25 pages of prose -4%, 100-page invoice -2%. Output is byte-identical. Co-Authored-By: Claude Opus 5.5 --- src/Pdf/PdfFont.php | 5 +- tests/Pdf/PdfFontTextEncodingTest.php | 129 ++++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 3 deletions(-) create mode 100644 tests/Pdf/PdfFontTextEncodingTest.php diff --git a/src/Pdf/PdfFont.php b/src/Pdf/PdfFont.php index 9d570dc..bdfd536 100644 --- a/src/Pdf/PdfFont.php +++ b/src/Pdf/PdfFont.php @@ -609,9 +609,6 @@ private static function containsArabic(array $cps): bool public function shapedGlyphs(string $utf8): array { $decoded = $this->decodeUtf8($utf8); - $glyphIds = array_map(fn ($e) => $e['gid'], $decoded); - $codepoints = array_map(fn ($e) => $e['cp'], $decoded); - $ligatures = $this->ligaturesEnabled ? $this->ttf->ligatures() : null; if ($ligatures === null) { @@ -633,6 +630,8 @@ public function shapedGlyphs(string $utf8): array return $out; } + $glyphIds = array_column($decoded, 'gid'); + $codepoints = array_column($decoded, 'cp'); $result = $ligatures->apply($glyphIds); // Mapping: source-glyph-index ranges to result glyph + sources. // ligatures->apply() returns {glyphs, sourceMap (ligatureGid -> component-gids)} diff --git a/tests/Pdf/PdfFontTextEncodingTest.php b/tests/Pdf/PdfFontTextEncodingTest.php new file mode 100644 index 0000000..6a7f566 --- /dev/null +++ b/tests/Pdf/PdfFontTextEncodingTest.php @@ -0,0 +1,129 @@ + */ + public static function fonts(): iterable + { + yield 'TrueType with kerning' => ['liberation-fonts-ttf-2.1.5/LiberationSans-Regular.ttf', true]; + yield 'CFF with ligatures' => ['SourceSans3-Regular.otf', true]; + // Space and no-break space share one glyph here, so the order of + // usedGlyphs writes decides which one ToUnicode names. + yield 'CFF without ligatures' => ['SourceSans3-Regular.otf', false]; + yield 'Arabic' => ['Amiri-Regular.ttf', true]; + } + + #[Test] + #[DataProvider('fonts')] + public function tj_array_matches_the_reference(string $file, bool $ligatures): void + { + $reference = $this->font($file, $ligatures); + $font = $this->font($file, $ligatures); + foreach ([...self::TEXTS, ...self::TEXTS] as $text) { + self::assertSame(self::referenceTjArray($reference, $text), @$font->encodeTextTjArray($text), $text); + self::assertSame(self::usedGlyphs($reference), self::usedGlyphs($font), $text); + } + } + + #[Test] + #[DataProvider('fonts')] + public function hex_string_matches_the_reference(string $file, bool $ligatures): void + { + $reference = $this->font($file, $ligatures); + $font = $this->font($file, $ligatures); + foreach (self::TEXTS as $text) { + $hex = ''; + foreach (@$reference->shapedGlyphs($text) as $shaped) { + $hex .= sprintf('%04X', $reference->ttf()->cidForGlyph($shaped['gid'])); + } + self::assertSame('<'.$hex.'>', @$font->encodeText($text), $text); + self::assertSame(self::usedGlyphs($reference), self::usedGlyphs($font), $text); + } + } + + #[Test] + public function decoding_below_hebrew_maps_each_codepoint_through_the_cmap(): void + { + $font = $this->font('liberation-fonts-ttf-2.1.5/LiberationSans-Regular.ttf', true); + $ttf = $font->ttf(); + $expected = []; + foreach ([0x41, 0xE9, 0x416, 0x1F600, 0x20] as $cp) { + $expected[] = ['cp' => $cp, 'gid' => $ttf->glyphIdForChar($cp)]; + } + self::assertSame($expected, $font->decodeUtf8("A\u{E9}\u{416}\u{1F600} ")); + self::assertSame([], $font->decodeUtf8('')); + } + + private function font(string $file, bool $ligatures): PdfFont + { + $path = __DIR__.'/../../.cache/fonts/'.$file; + if (! is_readable($path)) { + self::markTestSkipped($file.' not cached — run scripts/fetch-fonts.sh.'); + } + $font = new PdfFont(TtfFile::fromFile($path)); + + return $ligatures ? $font : $font->disableLigatures(); + } + + /** @return list */ + private static function referenceTjArray(PdfFont $font, string $text): array + { + $result = []; + $run = ''; + $prev = null; + foreach (@$font->shapedGlyphs($text) as $shaped) { + $gid = $shaped['gid']; + if ($prev !== null && ($kern = $font->kerningPdfUnits($prev, $gid)) !== 0) { + $result[] = '<'.$run.'>'; + $result[] = $kern; + $run = ''; + } + $run .= sprintf('%04X', $font->ttf()->cidForGlyph($gid)); + $prev = $gid; + } + if ($run !== '') { + $result[] = '<'.$run.'>'; + } + + return $result; + } + + /** @return array> */ + private static function usedGlyphs(PdfFont $font): array + { + return (new \ReflectionProperty(PdfFont::class, 'usedGlyphs'))->getValue($font); + } +} From 2a947349b174370c0f1ffc828ef378abc908049a Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Wed, 11 Nov 2026 18:40:11 -0800 Subject: [PATCH 11/13] perf(font): decode text below U+0590 without the shaping scans decodeUtf8() scanned every string three times for Arabic, Indic and Hebrew, then looked up each codepoint's glyph with its own method call. Every script that needs shaping or reordering starts at U+0590, so one max() over the codepoints now decides: below it, the glyphs come from the cmap in a single TtfFile::glyphIdsForChars() call; otherwise the shaping pipeline runs as before, moved unchanged into shapeAndMap(). utf8ToCps() decodes ASCII with unpack() and valid UTF-8 through mb_convert_encoding() to UTF-32. Malformed input keeps the existing byte loop, so it decodes exactly as before. Text drawing with an embedded font: 25 pages of prose -4%, 100-page invoice -3%. Output is byte-identical. Co-Authored-By: Claude Opus 5.5 --- src/Font/Ttf/TtfFile.php | 17 +++++++++++ src/Pdf/PdfFont.php | 43 +++++++++++++++++++++++---- tests/Pdf/PdfFontTextEncodingTest.php | 9 ++++++ 3 files changed, 63 insertions(+), 6 deletions(-) diff --git a/src/Font/Ttf/TtfFile.php b/src/Font/Ttf/TtfFile.php index ce52128..531b7de 100644 --- a/src/Font/Ttf/TtfFile.php +++ b/src/Font/Ttf/TtfFile.php @@ -530,6 +530,23 @@ public function glyphIdForChar(int $codepoint): int return $this->cmap[$codepoint] ?? 0; } + /** + * glyphIdForChar() for a list of codepoints at once. + * + * @param list $codepoints + * @return list + */ + public function glyphIdsForChars(array $codepoints): array + { + $cmap = $this->cmap; + $out = []; + foreach ($codepoints as $cp) { + $out[] = $cmap[$cp] ?? 0; + } + + return $out; + } + public function advanceWidth(int $glyphId): int { return $this->advanceWidths[$glyphId] ?? 0; diff --git a/src/Pdf/PdfFont.php b/src/Pdf/PdfFont.php index bdfd536..fa3e640 100644 --- a/src/Pdf/PdfFont.php +++ b/src/Pdf/PdfFont.php @@ -433,6 +433,35 @@ public function decodeUtf8(string $utf8): array $cps = self::utf8ToCps($utf8); + // Every script that needs shaping or reordering starts at U+0590, so + // text below it (Latin, Greek, Cyrillic) skips the three scans. + if ($cps === [] || max($cps) < 0x0590) { + $out = []; + foreach ($this->ttf->glyphIdsForChars($cps) as $i => $gid) { + $out[] = ['cp' => $cps[$i], 'gid' => $gid]; + } + } else { + $out = $this->shapeAndMap($cps); + } + + // Bounded FIFO eviction: drop oldest entry when reached cap. + if (count($this->decodeCache) >= self::DECODE_CACHE_MAX) { + array_shift($this->decodeCache); + } + $this->decodeCache[$utf8] = $out; + + return $out; + } + + /** + * decodeUtf8()'s pipeline for text that may need shaping or reordering: + * Arabic/Indic shaping, Bidi, cmap and rphf. + * + * @param list $cps + * @return list + */ + private function shapeAndMap(array $cps): array + { // Arabic contextual shaping in logical order. if ($this->arabicShapingEnabled && self::containsArabic($cps)) { $cps = \Dskripchenko\PhpPdf\Text\ArabicShaper::shapeLogical($cps); @@ -470,12 +499,6 @@ public function decodeUtf8(string $utf8): array } } - // Bounded FIFO eviction: drop oldest entry when reached cap. - if (count($this->decodeCache) >= self::DECODE_CACHE_MAX) { - array_shift($this->decodeCache); - } - $this->decodeCache[$utf8] = $out; - return $out; } @@ -551,6 +574,14 @@ private static function containsRtl(array $cps): bool */ private static function utf8ToCps(string $utf8): array { + // ASCII (most text) and valid UTF-8 decode in C; the loop below stays + // for malformed input, which it decodes its own way. + if (! preg_match('/[\x80-\xFF]/', $utf8)) { + return $utf8 === '' ? [] : array_values(unpack('C*', $utf8)); + } + if (mb_check_encoding($utf8, 'UTF-8')) { + return array_values(unpack('N*', mb_convert_encoding($utf8, 'UTF-32BE', 'UTF-8'))); + } $cps = []; $i = 0; $len = strlen($utf8); diff --git a/tests/Pdf/PdfFontTextEncodingTest.php b/tests/Pdf/PdfFontTextEncodingTest.php index 6a7f566..985a736 100644 --- a/tests/Pdf/PdfFontTextEncodingTest.php +++ b/tests/Pdf/PdfFontTextEncodingTest.php @@ -87,6 +87,15 @@ public function decoding_below_hebrew_maps_each_codepoint_through_the_cmap(): vo self::assertSame([], $font->decodeUtf8('')); } + #[Test] + public function glyph_ids_for_chars_matches_one_at_a_time(): void + { + $ttf = $this->font('liberation-fonts-ttf-2.1.5/LiberationSans-Regular.ttf', true)->ttf(); + $cps = [0x41, 0x56, 0xE9, 0x416, 0x10FFFF, 0]; + self::assertSame(array_map($ttf->glyphIdForChar(...), $cps), $ttf->glyphIdsForChars($cps)); + self::assertSame([], $ttf->glyphIdsForChars([])); + } + private function font(string $file, bool $ligatures): PdfFont { $path = __DIR__.'/../../.cache/fonts/'.$file; From e272de3b72ad4914dde3184d3f861dc967b04db1 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Wed, 11 Nov 2026 18:40:11 -0800 Subject: [PATCH 12/13] perf(font): hoist font lookups out of the text-encoding loop encodeTextTjArray() called kerningPdfUnits() for every glyph pair, and that fetched the kerning table and em size each time; each glyph's hex code came from its own sprintf(). The table and em size are now read once per string, and each glyph's hex code is formatted once per font and kept. encodeText() shares the hex codes. Text drawing with an embedded font: 25 pages of prose -8%, 100-page invoice -5%. Output is byte-identical. Co-Authored-By: Claude Opus 5.5 --- src/Pdf/PdfFont.php | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/Pdf/PdfFont.php b/src/Pdf/PdfFont.php index fa3e640..0998666 100644 --- a/src/Pdf/PdfFont.php +++ b/src/Pdf/PdfFont.php @@ -382,6 +382,14 @@ public function supportsText(string $text): bool private const DECODE_CACHE_MAX = 2048; + /** + * Glyph id to its 4-digit hex character code, as written in a text + * string: the CID for CFF fonts, the glyph id itself otherwise. + * + * @var array + */ + private array $cidHex = []; + /** * Disable Arabic shaping (for debug or if font handles * shaping itself via GSUB rather than Presentation Forms B). @@ -764,7 +772,8 @@ public function encodeText(string $utf8): string { $hex = ''; foreach ($this->shapedGlyphs($utf8) as $shaped) { - $hex .= sprintf('%04X', $this->ttf->cidForGlyph($shaped['gid'])); + $gid = $shaped['gid']; + $hex .= $this->cidHex[$gid] ??= sprintf('%04X', $this->ttf->cidForGlyph($gid)); } return '<'.$hex.'>'; @@ -793,17 +802,21 @@ public function encodeTextTjArray(string $utf8): array $result = []; $currentRun = ''; $prevGid = null; + // kerningPdfUnits() inline, with the per-font lookups out of the loop. + $kt = $this->ttf->kerningTable(); + $upm = $this->ttf->unitsPerEm(); foreach ($this->shapedGlyphs($utf8) as $shaped) { $gid = $shaped['gid']; - if ($prevGid !== null) { - $kern = $this->kerningPdfUnits($prevGid, $gid); + if ($prevGid !== null && $kt !== null) { + $fu = $kt->lookup($prevGid, $gid); + $kern = $fu === 0 ? 0 : (int) round(-$fu * 1000 / $upm); if ($kern !== 0) { $result[] = '<'.$currentRun.'>'; $result[] = $kern; $currentRun = ''; } } - $currentRun .= sprintf('%04X', $this->ttf->cidForGlyph($gid)); + $currentRun .= $this->cidHex[$gid] ??= sprintf('%04X', $this->ttf->cidForGlyph($gid)); $prevGid = $gid; } if ($currentRun !== '') { From 9144158e1a0a57b37269b5b5f23e31fcf814f4cb Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Wed, 11 Nov 2026 18:40:11 -0800 Subject: [PATCH 13/13] perf(font): encode drawn text from glyph-id lists encodeTextTjArray() went through shapedGlyphs(), which builds an entry per glyph and, through decodeUtf8(), caches whole lines that rarely come back: at ~400 bytes per character, the cache held most of a long document's memory. Without ligatures, glyphs map one to one to codepoints. Drawn text now goes from codepoints to a plain list of glyph ids, and text below U+0590 skips the decode cache. Shaped scripts and fonts with ligatures still go through decodeUtf8() and shapedGlyphs(). Kerning for the whole string comes from one KerningTable::lookupRun() call, and usedGlyphs is written once per distinct glyph of the string, keeping the order and the last-codepoint-wins rule of writing glyph by glyph. Text drawing with an embedded font: 25 pages of prose -17%, peak memory 52.6 MB -> 1.9 MB; 100-page invoice -9%, 20.1 MB -> 16.5 MB. Output is byte-identical. Co-Authored-By: Claude Opus 5.5 --- src/Font/Ttf/KerningTable.php | 19 +++++++++ src/Pdf/PdfFont.php | 65 ++++++++++++++++++++++------- tests/Font/Ttf/KerningTableTest.php | 24 +++++++++++ 3 files changed, 94 insertions(+), 14 deletions(-) diff --git a/src/Font/Ttf/KerningTable.php b/src/Font/Ttf/KerningTable.php index c2ca16c..2792fae 100644 --- a/src/Font/Ttf/KerningTable.php +++ b/src/Font/Ttf/KerningTable.php @@ -162,6 +162,25 @@ public function lookup(int $leftGid, int $rightGid): int return $this->memo[$leftGid][$rightGid] ??= $this->find($leftGid, $rightGid); } + /** + * lookup() for each neighbouring pair of a glyph run: element $i is the + * adjustment between $gids[$i - 1] and $gids[$i] (element 0 is 0). + * + * @param list $gids + * @return list + */ + public function lookupRun(array $gids): array + { + $out = []; + $prev = null; + foreach ($gids as $gid) { + $out[] = $prev === null ? 0 : ($this->memo[$prev][$gid] ??= $this->find($prev, $gid)); + $prev = $gid; + } + + return $out; + } + private function find(int $leftGid, int $rightGid): int { for ($i = count($this->layers) - 1; $i >= 0; $i--) { diff --git a/src/Pdf/PdfFont.php b/src/Pdf/PdfFont.php index 0998666..09e667a 100644 --- a/src/Pdf/PdfFont.php +++ b/src/Pdf/PdfFont.php @@ -760,6 +760,47 @@ public function kerningPdfUnits(int $leftGid, int $rightGid): int return (int) round(-$xAdvanceFu * 1000 / $this->ttf->unitsPerEm()); } + /** + * The glyph ids shapedGlyphs() gives, with the same effect on + * usedGlyphs, for drawing. Without ligatures glyphs map one to one to + * codepoints, so text below U+0590 skips decodeUtf8()'s per-character + * entries and is not cached: a drawn line rarely comes back. + * + * @return list + */ + private function glyphIdsToShow(string $utf8): array + { + if ($this->ligaturesEnabled && $this->ttf->ligatures() !== null) { + return array_column($this->shapedGlyphs($utf8), 'gid'); + } + $decoded = $this->decodeCache[$utf8] ?? null; + if ($decoded === null) { + $cps = self::utf8ToCps($utf8); + if ($cps === [] || max($cps) < 0x0590) { + $gids = $this->ttf->glyphIdsForChars($cps); + } else { + $decoded = $this->decodeUtf8($utf8); + } + } + if ($decoded !== null) { + $cps = array_column($decoded, 'cp'); + $gids = array_column($decoded, 'gid'); + } + // One write per distinct glyph. array_combine keeps each glyph at its + // first position with its last codepoint, as writing them in order + // would; glyph 0 stays out of ToUnicode (see shapedGlyphs()). + $byGid = array_combine($gids, $cps); + unset($byGid[0]); + foreach ($byGid as $gid => $cp) { + $used = $this->usedGlyphs[$gid] ?? null; + if ($used === null || isset($used[1]) || $used[0] !== $cp) { + $this->usedGlyphs[$gid] = [$cp]; + } + } + + return $gids; + } + /** * Encodes UTF-8 text as a hex glyph-ID string for the simple Tj operator * with Identity-H encoding. Applies ligature substitution via @@ -801,23 +842,19 @@ public function encodeTextTjArray(string $utf8): array { $result = []; $currentRun = ''; - $prevGid = null; - // kerningPdfUnits() inline, with the per-font lookups out of the loop. - $kt = $this->ttf->kerningTable(); + // kerningPdfUnits() for the whole run at once; element 0 is always 0. + $gids = $this->glyphIdsToShow($utf8); + $kerns = $this->ttf->kerningTable()?->lookupRun($gids); $upm = $this->ttf->unitsPerEm(); - foreach ($this->shapedGlyphs($utf8) as $shaped) { - $gid = $shaped['gid']; - if ($prevGid !== null && $kt !== null) { - $fu = $kt->lookup($prevGid, $gid); - $kern = $fu === 0 ? 0 : (int) round(-$fu * 1000 / $upm); - if ($kern !== 0) { - $result[] = '<'.$currentRun.'>'; - $result[] = $kern; - $currentRun = ''; - } + foreach ($gids as $i => $gid) { + $fu = $kerns === null ? 0 : $kerns[$i]; + $kern = $fu === 0 ? 0 : (int) round(-$fu * 1000 / $upm); + if ($kern !== 0) { + $result[] = '<'.$currentRun.'>'; + $result[] = $kern; + $currentRun = ''; } $currentRun .= $this->cidHex[$gid] ??= sprintf('%04X', $this->ttf->cidForGlyph($gid)); - $prevGid = $gid; } if ($currentRun !== '') { $result[] = '<'.$currentRun.'>'; diff --git a/tests/Font/Ttf/KerningTableTest.php b/tests/Font/Ttf/KerningTableTest.php index 5298799..b45b242 100644 --- a/tests/Font/Ttf/KerningTableTest.php +++ b/tests/Font/Ttf/KerningTableTest.php @@ -179,4 +179,28 @@ public function a_pair_set_of_zero_adjustments_is_not_kept(): void self::assertFalse($kt->isEmpty()); self::assertSame(-1, $kt->lookup(1, 3)); } + + #[Test] + public function lookup_run_answers_each_neighbouring_pair_like_lookup(): void + { + $table = static function (): KerningTable { + $kt = new KerningTable; + $kt->add(36, 57, -152); + $kt->add(57, 36, -140); + $kt->add(36, 36, 10); + + return $kt; + }; + $gids = [36, 57, 36, 36, 5, 57]; + $expected = [0, -152, -140, 10, 0, 0]; + + self::assertSame($expected, $table()->lookupRun($gids)); + + $warmed = $table(); + $warmed->lookup(36, 57); + self::assertSame($expected, $warmed->lookupRun($gids)); + + self::assertSame([], $warmed->lookupRun([])); + self::assertSame([0], $warmed->lookupRun([36])); + } }