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(); +} 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/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/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/Layout/Engine.php b/src/Layout/Engine.php index c67f089..aebf1f8 100644 --- a/src/Layout/Engine.php +++ b/src/Layout/Engine.php @@ -93,6 +93,26 @@ final class Engine */ private ?int $totalPagesHint = null; + /** 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. * @@ -138,6 +158,29 @@ 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 = []; + + /** + * 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 = []; + + /** @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; + /** Font ascent and descent, in em, used to place a baseline in its line. */ private const LINE_ASCENT = 0.905; @@ -250,19 +293,31 @@ private function applyFallbackChain(?PdfFont $primary, ?string $text): ?PdfFont public function render(AstDocument $document): PdfDocument { - // Two-pass for NUMPAGES resolution: - // - 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). - $this->totalPagesHint = null; - $firstPass = $this->renderOnce($document); - $this->totalPagesHint = $firstPass->pageCount(); - - $finalPass = $this->renderOnce($document); + // 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; + try { + $firstPass = $this->renderOnce($document); + if (! $this->totalPagesUsed) { + return $firstPass; + } + $this->totalPagesHint = $firstPass->pageCount(); + if (! $this->totalPagesInBody && $this->redrawPageTotals($firstPass)) { + return $firstPass; + } - return $finalPass; + return $this->renderOnce($document); + } finally { + $this->totalPagesHint = null; + $this->totalPagesSlots = []; + $this->widthCache = []; + } } /** Walks the tree once and gives every footnote its number. */ @@ -283,6 +338,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])) { @@ -399,6 +458,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); @@ -416,6 +479,11 @@ 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 // are met would tie numbering to the order of layout passes, and a @@ -2372,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; @@ -2606,6 +2790,21 @@ 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; + $this->totalPagesResolved++; + if (! $this->inPageFurniture) { + $this->totalPagesInBody = true; + } + + return $ctx !== null ? $this->displayedTotalPages($ctx) : ($this->totalPagesHint ?? 99); + } + private function displayedTotalPages(LayoutContext $ctx): int { $count = $this->totalPagesHint ?? 1; @@ -3277,9 +3476,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( @@ -3465,9 +3664,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() : '?', @@ -4257,17 +4454,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); } /** @@ -4276,6 +4487,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 +4537,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 @@ -4338,11 +4563,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; } @@ -4449,6 +4670,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); @@ -4819,6 +5045,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)); } @@ -5461,13 +5691,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, }; @@ -5519,7 +5748,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; } @@ -6056,8 +6286,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..5a7e4d2 100644 --- a/src/Pdf/ContentStream.php +++ b/src/Pdf/ContentStream.php @@ -1025,27 +1025,90 @@ 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. */ 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/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/src/Pdf/PdfFont.php b/src/Pdf/PdfFont.php index 9d570dc..09e667a 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). @@ -433,6 +441,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 +507,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 +582,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); @@ -609,9 +648,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 +669,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)} @@ -722,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 @@ -734,7 +813,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.'>'; @@ -762,19 +842,19 @@ public function encodeTextTjArray(string $utf8): array { $result = []; $currentRun = ''; - $prevGid = null; - foreach ($this->shapedGlyphs($utf8) as $shaped) { - $gid = $shaped['gid']; - if ($prevGid !== null) { - $kern = $this->kerningPdfUnits($prevGid, $gid); - if ($kern !== 0) { - $result[] = '<'.$currentRun.'>'; - $result[] = $kern; - $currentRun = ''; - } + // 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 ($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 .= sprintf('%04X', $this->ttf->cidForGlyph($gid)); - $prevGid = $gid; + $currentRun .= $this->cidHex[$gid] ??= sprintf('%04X', $this->ttf->cidForGlyph($gid)); } if ($currentRun !== '') { $result[] = '<'.$currentRun.'>'; 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..7f86c5a 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); @@ -95,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/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index e0e5ee0..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,12 +552,14 @@ private static function walkElement(\SimpleXMLElement $el, Page $page, callable default => null, }; } + array_shift(self::$parents); } /** - * 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 +571,36 @@ 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; + + 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))), + '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,39 +712,31 @@ 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 { + array_unshift(self::$parents, $el); 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, + ); } + array_shift(self::$parents); } /** 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); + } +} 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])); + } } diff --git a/tests/Layout/FieldResolutionTest.php b/tests/Layout/FieldResolutionTest.php index c33b309..fc7f131 100644 --- a/tests/Layout/FieldResolutionTest.php +++ b/tests/Layout/FieldResolutionTest.php @@ -5,13 +5,18 @@ namespace Dskripchenko\PhpPdf\Tests\Layout; 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; +use Dskripchenko\PhpPdf\Element\Table; use Dskripchenko\PhpPdf\Font\Ttf\TtfFile; 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; @@ -105,4 +110,73 @@ 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)); + } + + /** @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]); + } } diff --git a/tests/Pdf/PdfFontTextEncodingTest.php b/tests/Pdf/PdfFontTextEncodingTest.php new file mode 100644 index 0000000..985a736 --- /dev/null +++ b/tests/Pdf/PdfFontTextEncodingTest.php @@ -0,0 +1,138 @@ + */ + 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('')); + } + + #[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; + 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); + } +} 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)); + } + } + } }