From 1b500388ec291ab945fe459bf9cb7dcdaeccff71 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 13:08:00 -0700 Subject: [PATCH 01/11] feat(pdf): even-odd fill modes for emitPath emitPath() knew 'fill', 'stroke' and 'fillstroke' only, so a caller had no way to ask for the even-odd rule. It takes 'fill-evenodd' (f*) and 'fillstroke-evenodd' (B*) now. An unknown mode still emits f. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +++++ src/Pdf/ContentStream.php | 12 ++++++-- src/Pdf/Page.php | 7 +++++ tests/Pdf/ContentStreamTest.php | 52 +++++++++++++++++++++++++++++++++ 4 files changed, 76 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1084f32..035a31b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to `dskripchenko/php-pdf` are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added +- `Page::emitPath()` and `ContentStream::emitPath()` take the modes + `'fill-evenodd'` (`f*`) and `'fillstroke-evenodd'` (`B*`), which fill by + the even-odd rule: a subpath inside another is a hole whichever way round + it is drawn. + ## [1.25.0] — 2026-10-19 ### Fixed diff --git a/src/Pdf/ContentStream.php b/src/Pdf/ContentStream.php index 5584af7..ff28e35 100644 --- a/src/Pdf/ContentStream.php +++ b/src/Pdf/ContentStream.php @@ -253,7 +253,9 @@ public function fillRectangle( * - ['C', x1, y1, x2, y2, x3, y3] cubic Bezier * - 'Z' close * - * \$mode: 'fill' | 'stroke' | 'fillstroke'. + * \$mode: 'fill' | 'stroke' | 'fillstroke' (f, S, B, nonzero winding + * rule) | 'fill-evenodd' | 'fillstroke-evenodd' (f*, B*, even-odd + * rule). An unknown mode emits f. * * @param list $commands * @param array{r: float, g: float, b: float}|null $fillRgb @@ -270,14 +272,16 @@ public function emitPath( return $this; } $this->body .= "q\n"; - if ($fillRgb !== null && ($mode === 'fill' || $mode === 'fillstroke')) { + $fills = in_array($mode, ['fill', 'fillstroke', 'fill-evenodd', 'fillstroke-evenodd'], true); + $strokes = $mode === 'stroke' || $mode === 'fillstroke' || $mode === 'fillstroke-evenodd'; + if ($fillRgb !== null && $fills) { $this->body .= sprintf("%s %s %s rg\n", $this->formatNumber($fillRgb['r']), $this->formatNumber($fillRgb['g']), $this->formatNumber($fillRgb['b']), ); } - if ($strokeRgb !== null && ($mode === 'stroke' || $mode === 'fillstroke')) { + if ($strokeRgb !== null && $strokes) { $this->body .= sprintf("%s w\n", $this->formatNumber($lineWidthPt)); $this->body .= sprintf("%s %s %s RG\n", $this->formatNumber($strokeRgb['r']), @@ -314,6 +318,8 @@ public function emitPath( $op = match ($mode) { 'stroke' => 'S', 'fillstroke' => 'B', + 'fill-evenodd' => 'f*', + 'fillstroke-evenodd' => 'B*', default => 'f', }; $this->body .= $op."\n"; diff --git a/src/Pdf/Page.php b/src/Pdf/Page.php index 7623438..73dbdf6 100644 --- a/src/Pdf/Page.php +++ b/src/Pdf/Page.php @@ -992,6 +992,13 @@ public function strokePolyline( /** * Emit generic path (with cubic Bezier curves). * + * `$mode` is one of: + * - 'fill', 'stroke', 'fillstroke' — nonzero winding rule (f, S, B); + * - 'fill-evenodd', 'fillstroke-evenodd' — even-odd rule (f*, B*): a + * subpath inside another is a hole whichever way round it is drawn, + * as SVG `fill-rule="evenodd"` asks for. + * An unknown mode fills by the nonzero rule. + * * @param list $commands * @param array{r: float, g: float, b: float}|null $fillRgb * @param array{r: float, g: float, b: float}|null $strokeRgb diff --git a/tests/Pdf/ContentStreamTest.php b/tests/Pdf/ContentStreamTest.php index 348af42..19d5b02 100644 --- a/tests/Pdf/ContentStreamTest.php +++ b/tests/Pdf/ContentStreamTest.php @@ -66,6 +66,58 @@ public function number_formatting_strips_trailing_zeros(): void self::assertStringContainsString('0 100 Td', $s); } + #[Test] + public function emitPath_fill_evenodd_uses_f_star(): void + { + $cs = (new ContentStream)->emitPath(self::twoSquares(), 'fill-evenodd', ['r' => 1, 'g' => 0, 'b' => 0]); + $s = $cs->toString(); + + self::assertStringContainsString('1 0 0 rg', $s); + self::assertStringContainsString("h\nf*\nQ\n", $s); + } + + #[Test] + public function emitPath_fillstroke_evenodd_uses_B_star(): void + { + $cs = (new ContentStream)->emitPath( + self::twoSquares(), 'fillstroke-evenodd', + ['r' => 1, 'g' => 0, 'b' => 0], ['r' => 0, 'g' => 0, 'b' => 1], 2.0, + ); + $s = $cs->toString(); + + // Both colours and the line width are set, as for 'fillstroke'. + self::assertStringContainsString('1 0 0 rg', $s); + self::assertStringContainsString('0 0 1 RG', $s); + self::assertStringContainsString('2 w', $s); + self::assertStringContainsString("h\nB*\nQ\n", $s); + } + + #[Test] + public function emitPath_keeps_nonzero_operators_and_unknown_mode_falls_back_to_f(): void + { + $squares = self::twoSquares(); + + self::assertStringContainsString("h\nf\nQ\n", (new ContentStream)->emitPath($squares, 'fill')->toString()); + self::assertStringContainsString("h\nS\nQ\n", (new ContentStream)->emitPath($squares, 'stroke')->toString()); + self::assertStringContainsString("h\nB\nQ\n", (new ContentStream)->emitPath($squares, 'fillstroke')->toString()); + self::assertStringContainsString("h\nf\nQ\n", (new ContentStream)->emitPath($squares, 'bogus')->toString()); + } + + /** + * A square with a smaller square inside it, both drawn the same way + * round: under the nonzero rule the inner one fills, under even-odd it + * is a hole. + * + * @return list + */ + private static function twoSquares(): array + { + return [ + ['M', 0, 0], ['L', 0, 100], ['L', 100, 100], ['L', 100, 0], 'Z', + ['M', 25, 25], ['L', 25, 75], ['L', 75, 75], ['L', 75, 25], 'Z', + ]; + } + #[Test] public function empty_stream_isEmpty(): void { From 4280c32377c929469f6e172ffbcc6ec912490ac4 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 13:10:08 -0700 Subject: [PATCH 02/11] fix(svg): honour fill-rule="evenodd" on paths and polygons MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SvgRenderer never read fill-rule, so every fill used the nonzero rule. A hole drawn the same way round as its outline — a ring made of two circles in one path, a single-path letter O, nested squares — filled solid, and a five-point star polygon with fill-rule="evenodd" kept its centre filled. fill-rule is resolved like the other inherited properties: the element, its inline style, a style-sheet rule, then the nearest group. Even-odd paths fill with f* (B* with a stroke); even-odd polygons go through emitPath with 'fill-evenodd'. Nonzero output is unchanged byte for byte. Rect, circle and ellipse are single simple outlines, where the two rules agree. clip-rule has nothing to apply to yet: the renderer has no clipPath. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +++ docs/de/USAGE.md | 5 ++ docs/en/USAGE.md | 4 ++ docs/ru/USAGE.md | 4 ++ docs/zh/USAGE.md | 3 + src/Svg/SvgRenderer.php | 72 ++++++++++++++----- tests/Svg/SvgFillRuleTest.php | 130 ++++++++++++++++++++++++++++++++++ 7 files changed, 208 insertions(+), 18 deletions(-) create mode 100644 tests/Svg/SvgFillRuleTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 035a31b..3070e85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). the even-odd rule: a subpath inside another is a hole whichever way round it is drawn. +### Fixed +- SVG ignored `fill-rule`, so every path and polygon filled by the nonzero + rule: a hole drawn the same way round as its outline — a ring of two + circles in one path, a single-path letter O, nested squares — filled + solid, and a five-point star with `fill-rule="evenodd"` had a filled + centre. `fill-rule="evenodd"` on the element, in its `style`, in a style + sheet or inherited from a group fills with `f*` (`B*` with a stroke). + ## [1.25.0] — 2026-10-19 ### Fixed diff --git a/docs/de/USAGE.md b/docs/de/USAGE.md index e99fc35..764bf7b 100644 --- a/docs/de/USAGE.md +++ b/docs/de/USAGE.md @@ -660,6 +660,11 @@ Bézierkurven), Formen (``, ``, ``, ``, Transformationen (`translate`, `scale`, `rotate`, `skewX`, `skewY`, `matrix`), `` / ``, Styling über CSS-Klassen. +`fill-rule="evenodd"` — am Element, in seinem `style`, in einem Stylesheet +oder an einer Gruppe — füllt Pfade und Polygone nach der Gerade-Ungerade-Regel: +Ein Loch, das in derselben Richtung wie sein Umriss gezeichnet ist (ein Ring, +der Buchstabe O), bleibt leer. + `` wird in den Schriften des Dokuments gesetzt — dieselbe Familienkette, dieselben Ersatzschriften und Fett-/Kursivschnitte wie ein Absatz —, kyrillischer und anderer nicht-lateinischer Text erscheint also wie diff --git a/docs/en/USAGE.md b/docs/en/USAGE.md index da840b6..9d235ef 100644 --- a/docs/en/USAGE.md +++ b/docs/en/USAGE.md @@ -637,6 +637,10 @@ shapes (``, ``, ``, ``, ``, (`translate`, `scale`, `rotate`, `skewX`, `skewY`, `matrix`), `` / ``, CSS class styling. +`fill-rule="evenodd"` — on the element, in its `style`, in a style sheet or +on a group — fills paths and polygons by the even-odd rule, so a hole drawn +the same way round as its outline (a ring, the letter O) stays empty. + `` is set in the document's fonts — the same family chain, fallbacks and bold/italic faces as a paragraph — so Cyrillic and other non-Latin text prints as it does in the body; without an embedded font it falls back to a diff --git a/docs/ru/USAGE.md b/docs/ru/USAGE.md index 3c506c6..9258c10 100644 --- a/docs/ru/USAGE.md +++ b/docs/ru/USAGE.md @@ -655,6 +655,10 @@ DocumentBuilder::new() `skewX`, `skewY`, `matrix`), `` / ``, стилизация через CSS-классы. +`fill-rule="evenodd"` — на элементе, в его `style`, в таблице стилей или на +группе — заливает пути и многоугольники по правилу чёт-нечет: отверстие, +нарисованное в ту же сторону, что и контур (кольцо, буква O), остаётся пустым. + `` набирается шрифтами документа — той же цепочкой семейств, запасными шрифтами и начертаниями, что и абзац, — поэтому кириллица и другие нелатинские письменности печатаются как в тексте; без встроенного шрифта diff --git a/docs/zh/USAGE.md b/docs/zh/USAGE.md index 49aa8d2..1f5dbbf 100644 --- a/docs/zh/USAGE.md +++ b/docs/zh/USAGE.md @@ -611,6 +611,9 @@ DocumentBuilder::new() (`translate`、`scale`、`rotate`、`skewX`、`skewY`、`matrix`)、 `` / ``、CSS 类样式。 +`fill-rule="evenodd"`(写在元素上、其 `style` 中、样式表中或分组上)按奇偶规则 +填充 path 与多边形:与外轮廓同向绘制的孔(圆环、字母 O)保持镂空。 + `` 使用文档的字体排版 —— 与段落相同的字体族链、后备字体以及粗体/斜体 字形 —— 因此西里尔字母及其他非拉丁文字的显示与正文一致;没有嵌入字体时, 会退回到只含拉丁字形的 base-14 字体。`font-family`、`font-weight`、 diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index ddac654..ebacd4d 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -771,7 +771,7 @@ private static function renderPolygonXY(\SimpleXMLElement $el, Page $page, calla $sw = (float) ($el['stroke-width'] ?? 1); if ($closed && $hasFill) { - $page->fillPolygon($pts, $fr, $fg, $fb); + self::fillPolygonByRule($el, $page, $pts, $fr, $fg, $fb); } if ($hasStroke) { $line = $pts; @@ -828,13 +828,8 @@ private static function renderPathXY(\SimpleXMLElement $el, Page $page, callable } } - if ($hasFill && $hasStroke) { - $mode = 'fillstroke'; - } elseif ($hasFill) { - $mode = 'fill'; - } elseif ($hasStroke) { - $mode = 'stroke'; - } else { + $mode = self::pathMode($el, $hasFill, $hasStroke); + if ($mode === null) { return; } $page->emitPath( @@ -943,6 +938,53 @@ private static function textWidth(string $text, StandardFont|PdfFont $font, floa return $units * $size / 1000; } + /** + * `fill-rule="evenodd"` on the element, its inline `style`, a style + * sheet rule or an ancestor. SVG's default is nonzero. + */ + private static function isEvenOdd(\SimpleXMLElement $el): bool + { + return strtolower(trim((string) self::inheritedProperty($el, 'fill-rule'))) === 'evenodd'; + } + + /** + * The emitPath() mode for a path with this fill and stroke, by its + * fill rule; null when there is nothing to draw. + */ + private static function pathMode(\SimpleXMLElement $el, bool $hasFill, bool $hasStroke): ?string + { + if (! $hasFill) { + return $hasStroke ? 'stroke' : null; + } + $mode = $hasStroke ? 'fillstroke' : 'fill'; + + return self::isEvenOdd($el) ? $mode.'-evenodd' : $mode; + } + + /** + * Fills a polygon by its fill rule. A self-intersecting polygon — a + * five-point star — has its centre empty under even-odd. + * + * @param list $points in PDF coordinates + */ + private static function fillPolygonByRule(\SimpleXMLElement $el, Page $page, array $points, float $r, float $g, float $b): void + { + if (! self::isEvenOdd($el)) { + $page->fillPolygon($points, $r, $g, $b); + + return; + } + if (count($points) < 3) { + return; + } + $commands = [['M', $points[0][0], $points[0][1]]]; + for ($i = 1, $n = count($points); $i < $n; $i++) { + $commands[] = ['L', $points[$i][0], $points[$i][1]]; + } + $commands[] = 'Z'; + $page->emitPath($commands, 'fill-evenodd', ['r' => $r, 'g' => $g, 'b' => $b]); + } + /** * A presentation property as SVG resolves it: the element's inline * `style`, then its attribute, then the same on the nearest ancestor. @@ -1189,9 +1231,9 @@ private static function renderPolygon(\SimpleXMLElement $el, Page $page, callabl $fillOpacity = self::parseOpacity($el, 'fill-opacity', $globalOpacity); $strokeOpacity = self::parseOpacity($el, 'stroke-opacity', $globalOpacity); - $page->withOpacity($fillOpacity, $strokeOpacity, static function () use ($page, $closed, $hasFill, $hasStroke, $points, $fr, $fg, $fb, $sr, $sg, $sb, $sw, $scaleX): void { + $page->withOpacity($fillOpacity, $strokeOpacity, static function () use ($el, $page, $closed, $hasFill, $hasStroke, $points, $fr, $fg, $fb, $sr, $sg, $sb, $sw, $scaleX): void { if ($closed && $hasFill) { - $page->fillPolygon($points, $fr, $fg, $fb); + self::fillPolygonByRule($el, $page, $points, $fr, $fg, $fb); } if ($hasStroke) { $line = $points; @@ -1247,14 +1289,8 @@ private static function renderPath(\SimpleXMLElement $el, Page $page, callable $ return; } - // Determine fill/stroke mode. - if ($hasFill && $hasStroke) { - $mode = 'fillstroke'; - } elseif ($hasFill) { - $mode = 'fill'; - } elseif ($hasStroke) { - $mode = 'stroke'; - } else { + $mode = self::pathMode($el, $hasFill, $hasStroke); + if ($mode === null) { return; // Nothing to draw. } diff --git a/tests/Svg/SvgFillRuleTest.php b/tests/Svg/SvgFillRuleTest.php new file mode 100644 index 0000000..a157568 --- /dev/null +++ b/tests/Svg/SvgFillRuleTest.php @@ -0,0 +1,130 @@ +'); + + self::assertMatchesRegularExpression('@\nf\n@', $bytes); + self::assertStringNotContainsString("f*\n", $bytes); + } + + #[Test] + public function path_with_fill_rule_evenodd_fills_with_f_star(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("h\nf*\n", $bytes); + } + + #[Test] + public function path_with_fill_rule_nonzero_fills_with_f(): void + { + $bytes = self::render(''); + + self::assertStringNotContainsString("f*\n", $bytes); + } + + #[Test] + public function evenodd_path_with_a_stroke_uses_B_star(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("h\nB*\n", $bytes); + } + + #[Test] + public function fill_rule_is_read_from_inline_style(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("f*\n", $bytes); + } + + #[Test] + public function fill_rule_is_inherited_from_a_group(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("f*\n", $bytes); + } + + #[Test] + public function the_element_overrides_its_group(): void + { + $bytes = self::render(''); + + self::assertStringNotContainsString("f*\n", $bytes); + } + + #[Test] + public function fill_rule_from_a_style_sheet_class(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("f*\n", $bytes); + } + + #[Test] + public function fill_rule_applies_under_a_group_transform(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("f*\n", $bytes); + } + + #[Test] + public function evenodd_star_polygon_fills_with_f_star(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("h\nf*\n", $bytes); + } + + #[Test] + public function star_polygon_without_fill_rule_fills_nonzero(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("h\nf\n", $bytes); + self::assertStringNotContainsString("f*\n", $bytes); + } + + #[Test] + public function evenodd_polygon_under_a_group_transform(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("h\nf*\n", $bytes); + } + + private static function render(string $body): string + { + $svg = ''.$body.''; + $doc = new Document(new Section([new SvgElement($svg)])); + + return $doc->toBytes(new Engine(compressStreams: false)); + } +} From 892ab1e7e02a55f67903f510fc58a4e65bf7a533 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 14:13:12 -0700 Subject: [PATCH 03/11] fix(svg): gradients fill rects inside groups MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit walkElement() reset the gradient table to its default (empty) argument on every , so fill="url(#…)" on a rect inside any group printed black. The table is now set once per document and kept for the whole walk. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ src/Svg/SvgRenderer.php | 14 +++++++---- tests/Svg/SvgGroupsTest.php | 47 +++++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 tests/Svg/SvgGroupsTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 3070e85..d7167e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). solid, and a five-point star with `fill-rule="evenodd"` had a filled centre. `fill-rule="evenodd"` on the element, in its `style`, in a style sheet or inherited from a group fills with `f*` (`B*` with a stroke). +- A gradient fill on a `` inside a `` printed black: walking into + a group dropped the document's gradients. ## [1.25.0] — 2026-10-19 diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index ebacd4d..d58ba34 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -273,7 +273,15 @@ private static function renderDocument(string $svgXml, Page $page, float $boxX, // Collect linearGradient definitions (id → params). $gradients = self::parseGradients($xml); - self::walkElement($xml, $page, $tx, $ty, $scaleX, $scaleY, $gradients); + // Shapes at any depth look gradients up here; set once per document + // so that walking into a group does not lose them. + $previous = self::$currentGradients; + self::$currentGradients = $gradients; + try { + self::walkElement($xml, $page, $tx, $ty, $scaleX, $scaleY); + } finally { + self::$currentGradients = $previous; + } } /** @@ -444,11 +452,9 @@ private static function applyCssToTree(\SimpleXMLElement $el, array $rules): voi /** * @param callable(float): float $tx * @param callable(float): float $ty - * @param array> $gradients */ - private static function walkElement(\SimpleXMLElement $el, Page $page, callable $tx, callable $ty, float $scaleX, float $scaleY, array $gradients = []): void + private static function walkElement(\SimpleXMLElement $el, Page $page, callable $tx, callable $ty, float $scaleX, float $scaleY): void { - self::$currentGradients = $gradients; foreach ($el->children() as $child) { // Apply element-level transform (if present). $elTx = $tx; diff --git a/tests/Svg/SvgGroupsTest.php b/tests/Svg/SvgGroupsTest.php new file mode 100644 index 0000000..a4c8c2a --- /dev/null +++ b/tests/Svg/SvgGroupsTest.php @@ -0,0 +1,47 @@ +'; + + #[Test] + public function gradient_fills_a_rect_inside_a_group(): void + { + $stream = self::stream(self::GRADIENT.''); + + self::assertStringContainsString('/Pattern cs', $stream); + self::assertStringNotContainsString('0 0 0 rg', $stream); + } + + #[Test] + public function gradient_fills_a_rect_in_nested_groups(): void + { + $stream = self::stream(self::GRADIENT.''); + + self::assertStringContainsString('/Pattern cs', $stream); + } + + private static function stream(string $body): string + { + $page = PdfDocument::new()->addPage(customDimensionsPt: [100, 100]); + SvgRenderer::render(''.$body.'', $page, 0, 0, 100, 100); + + return $page->rawContentStream()->toString(); + } +} From 273d661654b8e25d9e502c25fb1a1937337dd221 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 14:14:33 -0700 Subject: [PATCH 04/11] fix(svg): shapes inherit fill and stroke from their groups Every shape read fill, stroke, stroke-width, fill-opacity and stroke-opacity from its own attributes only. A group's fill="#f00" was ignored and its shapes printed black; a group's stroke was dropped. These properties now resolve like the text properties already do: the element's inline style, its attribute, then the nearest ancestor. opacity stays per element, as SVG defines it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +++ src/Svg/SvgRenderer.php | 63 +++++++++++++++++++------------------ tests/Svg/SvgGroupsTest.php | 46 +++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d7167e9..df7a403 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,10 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). sheet or inherited from a group fills with `f*` (`B*` with a stroke). - A gradient fill on a `` inside a `` printed black: walking into a group dropped the document's gradients. +- `fill`, `stroke`, `stroke-width`, `fill-opacity` and `stroke-opacity` + were read from each shape's own attribute only, so a group's + `` was ignored and its shapes printed black. They are + inherited now, and read from inline `style` too, like the text properties. ## [1.25.0] — 2026-10-19 diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index d58ba34..d3a997c 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -45,11 +45,14 @@ private static function namedColorRgb(string $name): ?array */ private static function parseOpacity(\SimpleXMLElement $el, string $attr, float $multiplier = 1.0): float { - $val = $el[$attr] ?? null; + // fill-opacity and stroke-opacity are inherited; opacity is not. + $val = in_array($attr, ['fill-opacity', 'stroke-opacity'], true) + ? self::inheritedProperty($el, $attr) + : (isset($el[$attr]) ? (string) $el[$attr] : null); if ($val === null) { return $multiplier; } - $f = (float) (string) $val; + $f = (float) $val; if ($f < 0) { $f = 0; } @@ -680,9 +683,9 @@ private static function renderRectXY(\SimpleXMLElement $el, Page $page, callable $y = (float) ($el['y'] ?? 0); $w = (float) ($el['width'] ?? 0); $h = (float) ($el['height'] ?? 0); - [$fr, $fg, $fb, $hasFill] = self::parseColor(isset($el['fill']) ? (string) $el['fill'] : '#000'); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : null); - $sw = (float) ($el['stroke-width'] ?? 1); + [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? '#000'); + [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); $corners = [ [$px($x, $y), $py($x, $y)], @@ -710,8 +713,8 @@ private static function renderLineXY(\SimpleXMLElement $el, Page $page, callable $y1 = (float) ($el['y1'] ?? 0); $x2 = (float) ($el['x2'] ?? 0); $y2 = (float) ($el['y2'] ?? 0); - [$sr, $sg, $sb] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : '#000'); - $sw = (float) ($el['stroke-width'] ?? 1); + [$sr, $sg, $sb] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? '#000'); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); $page->strokeLine($px($x1, $y1), $py($x1, $y1), $px($x2, $y2), $py($x2, $y2), $sw * $scaleX, $sr, $sg, $sb); } @@ -729,9 +732,9 @@ private static function renderEllipseXY(\SimpleXMLElement $el, Page $page, calla $rx = (float) ($el['rx'] ?? 0); $ry = (float) ($el['ry'] ?? 0); } - [$fr, $fg, $fb, $hasFill] = self::parseColor(isset($el['fill']) ? (string) $el['fill'] : '#000'); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : null); - $sw = (float) ($el['stroke-width'] ?? 1); + [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? '#000'); + [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); $segments = 36; $points = []; @@ -772,9 +775,9 @@ private static function renderPolygonXY(\SimpleXMLElement $el, Page $page, calla if ($pts === []) { return; } - [$fr, $fg, $fb, $hasFill] = self::parseColor(isset($el['fill']) ? (string) $el['fill'] : ($closed ? '#000' : null)); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : null); - $sw = (float) ($el['stroke-width'] ?? 1); + [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? ($closed ? '#000' : null)); + [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); if ($closed && $hasFill) { self::fillPolygonByRule($el, $page, $pts, $fr, $fg, $fb); @@ -801,9 +804,9 @@ private static function renderPathXY(\SimpleXMLElement $el, Page $page, callable if ($d === '') { return; } - [$fr, $fg, $fb, $hasFill] = self::parseColor(isset($el['fill']) ? (string) $el['fill'] : '#000'); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : null); - $sw = (float) ($el['stroke-width'] ?? 1); + [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? '#000'); + [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); // Wrap point transformers as (svg-x → pdf-x) / (svg-y → pdf-y) // closures that we'd normally pass to parsePathD. parsePathD expects @@ -1024,7 +1027,7 @@ private static function renderRect(\SimpleXMLElement $el, Page $page, callable $ $h = (float) ($el['height'] ?? 0); // Detect fill="url(#id)" → use shading pattern. - $fillAttr = (string) ($el['fill'] ?? '#000'); + $fillAttr = (string) (self::inheritedProperty($el, 'fill') ?? '#000'); $patternName = null; if (preg_match('@^url\(#([^)]+)\)$@', trim($fillAttr), $m)) { $gradId = $m[1]; @@ -1037,8 +1040,8 @@ private static function renderRect(\SimpleXMLElement $el, Page $page, callable $ } [$fr, $fg, $fb, $hasFill] = self::parseColor($fillAttr); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : null); - $sw = (float) ($el['stroke-width'] ?? 1); + [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); $globalOpacity = self::parseOpacity($el, 'opacity', 1.0); $fillOpacity = self::parseOpacity($el, 'fill-opacity', $globalOpacity); @@ -1153,8 +1156,8 @@ private static function renderLine(\SimpleXMLElement $el, Page $page, callable $ $y1 = (float) ($el['y1'] ?? 0); $x2 = (float) ($el['x2'] ?? 0); $y2 = (float) ($el['y2'] ?? 0); - [$sr, $sg, $sb] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : '#000'); - $sw = (float) ($el['stroke-width'] ?? 1); + [$sr, $sg, $sb] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? '#000'); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); $page->strokeLine($tx($x1), $ty($y1), $tx($x2), $ty($y2), $sw * $scaleX, $sr, $sg, $sb); } @@ -1197,9 +1200,9 @@ private static function renderEllipseAt(float $cx, float $cy, float $rx, float $ $angle = 2 * M_PI * $i / $segments; $points[] = [$tx($cx + cos($angle) * $rx), $ty($cy + sin($angle) * $ry)]; } - [$fr, $fg, $fb, $hasFill] = self::parseColor(isset($el['fill']) ? (string) $el['fill'] : '#000'); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : null); - $sw = (float) ($el['stroke-width'] ?? 1); + [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? '#000'); + [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); // Opacity. $globalOpacity = self::parseOpacity($el, 'opacity', 1.0); @@ -1229,9 +1232,9 @@ private static function renderPolygon(\SimpleXMLElement $el, Page $page, callabl if ($points === []) { return; } - [$fr, $fg, $fb, $hasFill] = self::parseColor(isset($el['fill']) ? (string) $el['fill'] : ($closed ? '#000' : null)); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : null); - $sw = (float) ($el['stroke-width'] ?? 1); + [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? ($closed ? '#000' : null)); + [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); $globalOpacity = self::parseOpacity($el, 'opacity', 1.0); $fillOpacity = self::parseOpacity($el, 'fill-opacity', $globalOpacity); @@ -1286,9 +1289,9 @@ private static function renderPath(\SimpleXMLElement $el, Page $page, callable $ if ($d === '') { return; } - [$fr, $fg, $fb, $hasFill] = self::parseColor(isset($el['fill']) ? (string) $el['fill'] : '#000'); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(isset($el['stroke']) ? (string) $el['stroke'] : null); - $sw = (float) ($el['stroke-width'] ?? 1); + [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? '#000'); + [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); $commands = self::parsePathD($d, $tx, $ty); if ($commands === []) { diff --git a/tests/Svg/SvgGroupsTest.php b/tests/Svg/SvgGroupsTest.php index a4c8c2a..63cf836 100644 --- a/tests/Svg/SvgGroupsTest.php +++ b/tests/Svg/SvgGroupsTest.php @@ -37,6 +37,52 @@ public function gradient_fills_a_rect_in_nested_groups(): void self::assertStringContainsString('/Pattern cs', $stream); } + #[Test] + public function shapes_inherit_fill_from_their_group(): void + { + foreach (['', '', '', ''] as $shape) { + self::assertStringContainsString('1 0 0 rg', self::stream(''.$shape.''), $shape); + } + } + + #[Test] + public function transformed_shapes_inherit_fill_too(): void + { + foreach (['', '', ''] as $shape) { + self::assertStringContainsString('1 0 0 rg', self::stream(''.$shape.''), $shape); + } + } + + #[Test] + public function the_nearest_fill_wins(): void + { + $stream = self::stream(''); + + self::assertStringContainsString('0 0 1 rg', $stream); + self::assertStringContainsString('0 1 0 rg', $stream); + self::assertStringNotContainsString('1 0 0 rg', $stream); + } + + #[Test] + public function fill_none_on_a_group_leaves_only_the_stroke(): void + { + $stream = self::stream(''); + + self::assertStringContainsString('0 0 1 RG', $stream); + self::assertStringContainsString('3 w', $stream); + self::assertStringNotContainsString(' rg', $stream); + self::assertMatchesRegularExpression('@\nS\n@', $stream); + } + + #[Test] + public function fill_opacity_is_inherited(): void + { + $page = PdfDocument::new()->addPage(customDimensionsPt: [100, 100]); + SvgRenderer::render('', $page, 0, 0, 100, 100); + + self::assertMatchesRegularExpression('@/Gs\d+ gs@', $page->rawContentStream()->toString()); + } + private static function stream(string $body): string { $page = PdfDocument::new()->addPage(customDimensionsPt: [100, 100]); From c719016527e69b2e44e3e953cee275d315a394fb Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 14:15:34 -0700 Subject: [PATCH 05/11] fix(svg): nested transforms compose Under a transformed group, children were drawn with the group's mapping only; walkElementXY() never read their own transform attribute. A , as BaconQrCode and other generators write it, lost its translate, and a shape's own transform inside a transformed group was dropped. Each child's transform is now composed with its group's, and stroke widths follow the combined scale. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ src/Svg/SvgRenderer.php | 29 ++++++++++++++++++++--------- tests/Svg/SvgGroupsTest.php | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df7a403..a7b40e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,10 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). were read from each shape's own attribute only, so a group's `` was ignored and its shapes printed black. They are inherited now, and read from inline `style` too, like the text properties. +- Inside a transformed group, the `transform` of a nested group or shape + was ignored: ``, as + QR code generators write it, lost its translate. Nested transforms + compose now, and stroke widths follow the combined scale. ## [1.25.0] — 2026-10-19 diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index d3a997c..501faa7 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -565,17 +565,28 @@ private static function walkChildTransformed( private static function walkElementXY(\SimpleXMLElement $el, Page $page, callable $px, callable $py, 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)); + } $tag = $child->getName(); match ($tag) { - 'rect' => self::renderRectXY($child, $page, $px, $py, $scaleX, $scaleY), - 'line' => self::renderLineXY($child, $page, $px, $py, $scaleX), - 'circle' => self::renderEllipseXY($child, $page, $px, $py, $scaleX, true), - 'ellipse' => self::renderEllipseXY($child, $page, $px, $py, $scaleX, false), - 'polygon' => self::renderPolygonXY($child, $page, $px, $py, true, $scaleX), - 'polyline' => self::renderPolygonXY($child, $page, $px, $py, false, $scaleX), - 'path' => self::renderPathXY($child, $page, $px, $py, $scaleX), - 'text' => self::renderTextXY($child, $page, $px, $py, $scaleX), - 'g' => self::walkElementXY($child, $page, $px, $py, $scaleX, $scaleY), + 'rect' => self::renderRectXY($child, $page, $cpx, $cpy, $cScale, $scaleY), + 'line' => self::renderLineXY($child, $page, $cpx, $cpy, $cScale), + 'circle' => self::renderEllipseXY($child, $page, $cpx, $cpy, $cScale, true), + 'ellipse' => self::renderEllipseXY($child, $page, $cpx, $cpy, $cScale, false), + 'polygon' => self::renderPolygonXY($child, $page, $cpx, $cpy, true, $cScale), + 'polyline' => self::renderPolygonXY($child, $page, $cpx, $cpy, false, $cScale), + 'path' => 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, }; } diff --git a/tests/Svg/SvgGroupsTest.php b/tests/Svg/SvgGroupsTest.php index 63cf836..db65904 100644 --- a/tests/Svg/SvgGroupsTest.php +++ b/tests/Svg/SvgGroupsTest.php @@ -83,6 +83,40 @@ public function fill_opacity_is_inherited(): void self::assertMatchesRegularExpression('@/Gs\d+ gs@', $page->rawContentStream()->toString()); } + #[Test] + public function nested_group_transforms_compose(): void + { + // translate(50 0) then translate(0 50): the square covers user (50..100, 50..100). + $stream = self::stream(''); + + self::assertStringContainsString("50 50 m\n100 50 l\n100 0 l\n50 0 l\n", $stream); + } + + #[Test] + public function scale_then_translate_as_qr_generators_nest_them(): void + { + // scale(2) of translate(10 10): user (5, 5) lands on (30, 30), PDF (30, 70). + $stream = self::stream(''); + + self::assertStringContainsString("20 80 m\n30 80 l\n30 70 l\n20 70 l\nh\n", $stream); + } + + #[Test] + public function a_transform_on_a_shape_in_a_transformed_group_applies(): void + { + $stream = self::stream(''); + + self::assertStringContainsString("10 80 m\n20 80 l\n20 70 l\n10 70 l\n", $stream); + } + + #[Test] + public function stroke_width_follows_the_composed_scale(): void + { + $stream = self::stream(''); + + self::assertStringContainsString("4 w\n", $stream); + } + private static function stream(string $body): string { $page = PdfDocument::new()->addPage(customDimensionsPt: [100, 100]); From 45ec0d0ca76af7adf7d6bf8d1249470d6de55462 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 14:20:54 -0700 Subject: [PATCH 06/11] feat(svg): gradient fills on every shape MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fill="url(#…)" worked on a plain only; paths, polygons, circles, ellipses and transformed rects printed black. They are now filled with a shading pattern through Page::fillPathWithPattern(). The pattern's matrix maps gradient space onto the page: the shape's user space (with its group transforms), its bounding box for objectBoundingBox units, then gradientTransform. gradientUnits="userSpaceOnUse" is honoured, so BaconQrCode's gradient QR codes come out as they do in a browser, and they scan. Even-odd paths fill with f*. The plain-rect gradient code and its output are unchanged; the stop handling moves to a shared shadingFunction(). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + docs/de/USAGE.md | 3 + docs/en/USAGE.md | 2 + docs/ru/USAGE.md | 2 + docs/zh/USAGE.md | 2 + src/Pdf/ContentStream.php | 50 ++++-- src/Pdf/Page.php | 14 ++ src/Svg/SvgRenderer.php | 231 +++++++++++++++++++++++----- tests/Pdf/ContentStreamTest.php | 12 ++ tests/Svg/SvgGradientShapesTest.php | 125 +++++++++++++++ 10 files changed, 402 insertions(+), 46 deletions(-) create mode 100644 tests/Svg/SvgGradientShapesTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index a7b40e0..099a9b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,13 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). `'fill-evenodd'` (`f*`) and `'fillstroke-evenodd'` (`B*`), which fill by the even-odd rule: a subpath inside another is a hole whichever way round it is drawn. +- `Page::fillPathWithPattern()` and `ContentStream::fillPathWithPattern()` + fill any path with a registered shading pattern. +- SVG gradients fill paths, polygons, circles, ellipses and transformed + rectangles, not only plain rectangles, and honour + `gradientUnits="userSpaceOnUse"`. The pattern follows the shape's + transforms, its bounding box and `gradientTransform`. Before, those + shapes printed black. ### Fixed - SVG ignored `fill-rule`, so every path and polygon filled by the nonzero diff --git a/docs/de/USAGE.md b/docs/de/USAGE.md index 764bf7b..14909aa 100644 --- a/docs/de/USAGE.md +++ b/docs/de/USAGE.md @@ -664,6 +664,9 @@ Transformationen (`translate`, `scale`, `rotate`, `skewX`, `skewY`, oder an einer Gruppe — füllt Pfade und Polygone nach der Gerade-Ungerade-Regel: Ein Loch, das in derselben Richtung wie sein Umriss gezeichnet ist (ein Ring, der Buchstabe O), bleibt leer. +Verläufe füllen jede Form, in beiden `gradientUnits`; `fill`, `stroke` und +ihre Deckkraft werden von Gruppen geerbt, und verschachtelte Transformationen +werden verkettet. `` wird in den Schriften des Dokuments gesetzt — dieselbe Familienkette, dieselben Ersatzschriften und Fett-/Kursivschnitte wie ein diff --git a/docs/en/USAGE.md b/docs/en/USAGE.md index 9d235ef..add62e4 100644 --- a/docs/en/USAGE.md +++ b/docs/en/USAGE.md @@ -640,6 +640,8 @@ shapes (``, ``, ``, ``, ``, `fill-rule="evenodd"` — on the element, in its `style`, in a style sheet or on a group — fills paths and polygons by the even-odd rule, so a hole drawn the same way round as its outline (a ring, the letter O) stays empty. +Gradients fill any shape, in either `gradientUnits`; `fill`, `stroke` and +their opacities are inherited from groups, and nested transforms compose. `` is set in the document's fonts — the same family chain, fallbacks and bold/italic faces as a paragraph — so Cyrillic and other non-Latin text diff --git a/docs/ru/USAGE.md b/docs/ru/USAGE.md index 9258c10..9eefe43 100644 --- a/docs/ru/USAGE.md +++ b/docs/ru/USAGE.md @@ -658,6 +658,8 @@ CSS-классы. `fill-rule="evenodd"` — на элементе, в его `style`, в таблице стилей или на группе — заливает пути и многоугольники по правилу чёт-нечет: отверстие, нарисованное в ту же сторону, что и контур (кольцо, буква O), остаётся пустым. +Градиенты заливают любую фигуру в обоих `gradientUnits`; `fill`, `stroke` и их +прозрачность наследуются от групп, вложенные преобразования складываются. `` набирается шрифтами документа — той же цепочкой семейств, запасными шрифтами и начертаниями, что и абзац, — поэтому кириллица и другие diff --git a/docs/zh/USAGE.md b/docs/zh/USAGE.md index 1f5dbbf..4e6c3f8 100644 --- a/docs/zh/USAGE.md +++ b/docs/zh/USAGE.md @@ -613,6 +613,8 @@ DocumentBuilder::new() `fill-rule="evenodd"`(写在元素上、其 `style` 中、样式表中或分组上)按奇偶规则 填充 path 与多边形:与外轮廓同向绘制的孔(圆环、字母 O)保持镂空。 +渐变可填充任意图形,支持两种 `gradientUnits`;`fill`、`stroke` 及其不透明度 +从分组继承,嵌套的变换会依次叠加。 `` 使用文档的字体排版 —— 与段落相同的字体族链、后备字体以及粗体/斜体 字形 —— 因此西里尔字母及其他非拉丁文字的显示与正文一致;没有嵌入字体时, diff --git a/src/Pdf/ContentStream.php b/src/Pdf/ContentStream.php index ff28e35..eb2037b 100644 --- a/src/Pdf/ContentStream.php +++ b/src/Pdf/ContentStream.php @@ -289,6 +289,45 @@ public function emitPath( $this->formatNumber($strokeRgb['b']), ); } + $this->appendPathCommands($commands); + $op = match ($mode) { + 'stroke' => 'S', + 'fillstroke' => 'B', + 'fill-evenodd' => 'f*', + 'fillstroke-evenodd' => 'B*', + default => 'f', + }; + $this->body .= $op."\n"; + $this->body .= "Q\n"; + + return $this; + } + + /** + * Fills a path with a shading pattern registered on the page, by the + * nonzero or (with $evenOdd) the even-odd rule. The pattern's matrix + * maps its space onto the page's default coordinates. + * + * @param list $commands as for emitPath() + */ + public function fillPathWithPattern(array $commands, string $patternName, bool $evenOdd = false): self + { + if ($commands === []) { + return $this; + } + $this->body .= "q\n/Pattern cs\n"; + $this->body .= sprintf("/%s scn\n", $patternName); + $this->appendPathCommands($commands); + $this->body .= ($evenOdd ? 'f*' : 'f')."\nQ\n"; + + return $this; + } + + /** + * @param list $commands + */ + private function appendPathCommands(array $commands): void + { foreach ($commands as $cmd) { if ($cmd === 'Z') { $this->body .= "h\n"; @@ -315,17 +354,6 @@ public function emitPath( ); } } - $op = match ($mode) { - 'stroke' => 'S', - 'fillstroke' => 'B', - 'fill-evenodd' => 'f*', - 'fillstroke-evenodd' => 'B*', - default => 'f', - }; - $this->body .= $op."\n"; - $this->body .= "Q\n"; - - return $this; } /** diff --git a/src/Pdf/Page.php b/src/Pdf/Page.php index 73dbdf6..2e6edc8 100644 --- a/src/Pdf/Page.php +++ b/src/Pdf/Page.php @@ -989,6 +989,20 @@ public function strokePolyline( return $this; } + /** + * Fills a path with a shading pattern from registerShadingPattern(), by + * the nonzero or (with $evenOdd) the even-odd rule. The pattern's + * matrix maps its space onto the page's default coordinates. + * + * @param list $commands as for emitPath() + */ + public function fillPathWithPattern(array $commands, string $patternName, bool $evenOdd = false): self + { + $this->stream->fillPathWithPattern($commands, $patternName, $evenOdd); + + return $this; + } + /** * Emit generic path (with cubic Bezier curves). * diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index 501faa7..4363cb9 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -311,6 +311,7 @@ private static function parseGradients(\SimpleXMLElement $root): array : null; $out[$id] = [ 'type' => 'linear', + 'userSpace' => (string) ($g['gradientUnits'] ?? '') === 'userSpaceOnUse', 'x1' => $x1, 'y1' => $y1, 'x2' => $x2, 'y2' => $y2, 'stops' => $stops, 'transform' => $gradTransform, @@ -333,6 +334,7 @@ private static function parseGradients(\SimpleXMLElement $root): array : null; $out[$id] = [ 'type' => 'radial', + 'userSpace' => (string) ($g['gradientUnits'] ?? '') === 'userSpaceOnUse', 'cx' => $cx, 'cy' => $cy, 'r' => $r, 'fx' => $fx, 'fy' => $fy, 'stops' => $stops, 'transform' => $gradTransform, @@ -704,7 +706,8 @@ private static function renderRectXY(\SimpleXMLElement $el, Page $page, callable [$px($x + $w, $y + $h), $py($x + $w, $y + $h)], [$px($x, $y + $h), $py($x, $y + $h)], ]; - if ($hasFill) { + $user = static fn (): array => [[$x, $y], [$x + $w, $y], [$x + $w, $y + $h], [$x, $y + $h]]; + if ($hasFill && ! self::fillGradient($el, $page, self::outline($corners), $user, self::affineXY($px, $py))) { $page->fillPolygon($corners, $fr, $fg, $fb); } if ($hasStroke) { @@ -749,13 +752,15 @@ private static function renderEllipseXY(\SimpleXMLElement $el, Page $page, calla $segments = 36; $points = []; + $userPoints = []; for ($i = 0; $i < $segments; $i++) { $angle = 2 * M_PI * $i / $segments; $sx = $cx + cos($angle) * $rx; $sy = $cy + sin($angle) * $ry; + $userPoints[] = [$sx, $sy]; $points[] = [$px($sx, $sy), $py($sx, $sy)]; } - if ($hasFill) { + if ($hasFill && ! self::fillGradient($el, $page, self::outline($points), static fn (): array => $userPoints, self::affineXY($px, $py))) { $page->fillPolygon($points, $fr, $fg, $fb); } if ($hasStroke) { @@ -778,9 +783,11 @@ private static function renderPolygonXY(\SimpleXMLElement $el, Page $page, calla } $tokens = array_values(array_filter($tokens, fn ($t) => $t !== '')); $pts = []; + $userPoints = []; for ($i = 0; $i + 1 < count($tokens); $i += 2) { $sx = (float) $tokens[$i]; $sy = (float) $tokens[$i + 1]; + $userPoints[] = [$sx, $sy]; $pts[] = [$px($sx, $sy), $py($sx, $sy)]; } if ($pts === []) { @@ -790,7 +797,7 @@ private static function renderPolygonXY(\SimpleXMLElement $el, Page $page, calla [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); - if ($closed && $hasFill) { + if ($closed && $hasFill && ! self::fillGradient($el, $page, self::outline($pts), static fn (): array => $userPoints, self::affineXY($px, $py))) { self::fillPolygonByRule($el, $page, $pts, $fr, $fg, $fb); } if ($hasStroke) { @@ -848,6 +855,10 @@ private static function renderPathXY(\SimpleXMLElement $el, Page $page, callable } } + // A gradient fill is painted on its own; the stroke, if any, follows. + if ($hasFill && self::fillGradient($el, $page, $commands, static fn (): array => self::commandPoints($rawCommands), self::affineXY($px, $py))) { + $hasFill = false; + } $mode = self::pathMode($el, $hasFill, $hasStroke); if ($mode === null) { return; @@ -1084,6 +1095,174 @@ private static function renderRect(\SimpleXMLElement $el, Page $page, callable $ }); } + /** + * The gradient a shape's fill="url(#id)" names, when it is defined and + * has two or more stops; null otherwise. + * + * @return array|null + */ + private static function gradientFor(\SimpleXMLElement $el): ?array + { + $fill = trim((string) self::inheritedProperty($el, 'fill')); + if (preg_match('@^url\(\s*[\'"]?#([^)\'"\s]+)[\'"]?\s*\)@', $fill, $m) !== 1) { + return null; + } + $gradient = self::$currentGradients[$m[1]] ?? null; + + return $gradient !== null && count($gradient['stops']) >= 2 ? $gradient : null; + } + + /** + * Fills a shape with the gradient its fill names, through a shading + * pattern whose matrix maps gradient space onto the page: the shape's + * user space, its bounding box for objectBoundingBox units, then the + * gradientTransform. Returns false when the fill names no gradient, so + * the caller paints its flat colour. + * + * @param list $commands the outline on the page + * @param \Closure(): list $userPoints the outline in user units, for the bounding box + * @param array{0: float, 1: float, 2: float, 3: float, 4: float, 5: float} $toPage user space → page + */ + private static function fillGradient(\SimpleXMLElement $el, Page $page, array $commands, \Closure $userPoints, array $toPage): bool + { + $gradient = self::gradientFor($el); + if ($gradient === null) { + return false; + } + $matrix = $toPage; + if (! ($gradient['userSpace'] ?? false)) { + $points = $userPoints(); + if ($points === []) { + return true; + } + $xs = array_column($points, 0); + $ys = array_column($points, 1); + $w = max($xs) - min($xs); + $h = max($ys) - min($ys); + if ($w <= 0 || $h <= 0) { + return true; // A bounding box gradient on a flat shape paints nothing, as in SVG. + } + $matrix = self::multiplyMatrix($matrix, [$w, 0.0, 0.0, $h, min($xs), min($ys)]); + } + if (is_array($gradient['transform'] ?? null)) { + $matrix = self::multiplyMatrix($matrix, $gradient['transform']); + } + // -0 would print as "-0". + $matrix = array_map(static fn (float $v): float => $v == 0.0 ? 0.0 : $v, $matrix); + + $radial = ($gradient['type'] ?? 'linear') === 'radial'; + $shading = new \Dskripchenko\PhpPdf\Pdf\PdfShading( + shadingType: $radial ? \Dskripchenko\PhpPdf\Pdf\PdfShading::TYPE_RADIAL : \Dskripchenko\PhpPdf\Pdf\PdfShading::TYPE_AXIAL, + coords: $radial + ? [$gradient['fx'], $gradient['fy'], 0.0, $gradient['cx'], $gradient['cy'], $gradient['r']] + : [$gradient['x1'], $gradient['y1'], $gradient['x2'], $gradient['y2']], + function: self::shadingFunction($gradient['stops']), + ); + $name = $page->registerShadingPattern(new \Dskripchenko\PhpPdf\Pdf\PdfPattern($shading, $matrix)); + $page->fillPathWithPattern($commands, $name, self::isEvenOdd($el)); + + return true; + } + + /** + * @param callable(float, float): float $px + * @param callable(float, float): float $py + * @return array{0: float, 1: float, 2: float, 3: float, 4: float, 5: float} + */ + private static function affineXY(callable $px, callable $py): array + { + $e = $px(0.0, 0.0); + $f = $py(0.0, 0.0); + + return [$px(1.0, 0.0) - $e, $py(1.0, 0.0) - $f, $px(0.0, 1.0) - $e, $py(0.0, 1.0) - $f, $e, $f]; + } + + /** + * @param callable(float): float $tx + * @param callable(float): float $ty + * @return array{0: float, 1: float, 2: float, 3: float, 4: float, 5: float} + */ + private static function affineTxTy(callable $tx, callable $ty): array + { + return [$tx(1.0) - $tx(0.0), 0.0, 0.0, $ty(1.0) - $ty(0.0), $tx(0.0), $ty(0.0)]; + } + + /** + * @param list $points + * @return list + */ + private static function outline(array $points): array + { + $commands = []; + foreach ($points as $i => [$x, $y]) { + $commands[] = [$i === 0 ? 'M' : 'L', $x, $y]; + } + $commands[] = 'Z'; + + return $commands; + } + + /** + * Every point a path names, control points included: enough for a + * bounding box that covers the curve. + * + * @param list $commands + * @return list + */ + private static function commandPoints(array $commands): array + { + $points = []; + foreach ($commands as $cmd) { + if (! is_array($cmd)) { + continue; + } + for ($i = 1; $i + 1 < count($cmd); $i += 2) { + $points[] = [(float) $cmd[$i], (float) $cmd[$i + 1]]; + } + } + + return $points; + } + + /** + * The colour function of a gradient: one Type 2 function for two + * stops, a Type 3 stitching of them for more. + * + * @param list $stops + */ + private static function shadingFunction(array $stops): \Dskripchenko\PhpPdf\Pdf\PdfFunction|\Dskripchenko\PhpPdf\Pdf\PdfStitchingFunction + { + // 2 stops — single Type 2 function. + // >2 stops — Type 3 stitching of multiple Type 2 sub-functions. + if (count($stops) === 2) { + return new \Dskripchenko\PhpPdf\Pdf\PdfFunction( + c0: $stops[0]['color'], + c1: $stops[1]['color'], + ); + } + + $subFunctions = []; + $bounds = []; + $encode = []; + for ($i = 0; $i < count($stops) - 1; $i++) { + $subFunctions[] = new \Dskripchenko\PhpPdf\Pdf\PdfFunction( + c0: $stops[$i]['color'], + c1: $stops[$i + 1]['color'], + ); + if ($i < count($stops) - 2) { + $bounds[] = $stops[$i + 1]['offset']; + } + $encode[] = 0; + $encode[] = 1; + } + + return new \Dskripchenko\PhpPdf\Pdf\PdfStitchingFunction( + subFunctions: $subFunctions, + bounds: $bounds, + encode: $encode, + ); + } + /** * Create + register PDF shading pattern from SVG gradient. * @@ -1117,34 +1296,7 @@ private static function createPatternFromGradient( $shadingType = \Dskripchenko\PhpPdf\Pdf\PdfShading::TYPE_AXIAL; } - // 2 stops — single Type 2 function. - // >2 stops — Type 3 stitching of multiple Type 2 sub-functions. - if (count($stops) === 2) { - $function = new \Dskripchenko\PhpPdf\Pdf\PdfFunction( - c0: $stops[0]['color'], - c1: $stops[1]['color'], - ); - } else { - $subFunctions = []; - $bounds = []; - $encode = []; - for ($i = 0; $i < count($stops) - 1; $i++) { - $subFunctions[] = new \Dskripchenko\PhpPdf\Pdf\PdfFunction( - c0: $stops[$i]['color'], - c1: $stops[$i + 1]['color'], - ); - if ($i < count($stops) - 2) { - $bounds[] = $stops[$i + 1]['offset']; - } - $encode[] = 0; - $encode[] = 1; - } - $function = new \Dskripchenko\PhpPdf\Pdf\PdfStitchingFunction( - subFunctions: $subFunctions, - bounds: $bounds, - encode: $encode, - ); - } + $function = self::shadingFunction($stops); $shading = new \Dskripchenko\PhpPdf\Pdf\PdfShading( shadingType: $shadingType, coords: $coords, @@ -1207,10 +1359,13 @@ private static function renderEllipseAt(float $cx, float $cy, float $rx, float $ { $segments = 36; $points = []; + $userPoints = []; for ($i = 0; $i < $segments; $i++) { $angle = 2 * M_PI * $i / $segments; + $userPoints[] = [$cx + cos($angle) * $rx, $cy + sin($angle) * $ry]; $points[] = [$tx($cx + cos($angle) * $rx), $ty($cy + sin($angle) * $ry)]; } + $toPage = self::affineTxTy($tx, $ty); [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? '#000'); [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); @@ -1220,8 +1375,8 @@ private static function renderEllipseAt(float $cx, float $cy, float $rx, float $ $fillOpacity = self::parseOpacity($el, 'fill-opacity', $globalOpacity); $strokeOpacity = self::parseOpacity($el, 'stroke-opacity', $globalOpacity); - $page->withOpacity($fillOpacity, $strokeOpacity, static function () use ($page, $hasFill, $hasStroke, $points, $fr, $fg, $fb, $sr, $sg, $sb, $sw, $scaleX): void { - if ($hasFill) { + $page->withOpacity($fillOpacity, $strokeOpacity, static function () use ($el, $page, $hasFill, $hasStroke, $points, $userPoints, $toPage, $fr, $fg, $fb, $sr, $sg, $sb, $sw, $scaleX): void { + if ($hasFill && ! self::fillGradient($el, $page, self::outline($points), static fn (): array => $userPoints, $toPage)) { $page->fillPolygon($points, $fr, $fg, $fb); } if ($hasStroke) { @@ -1243,6 +1398,8 @@ private static function renderPolygon(\SimpleXMLElement $el, Page $page, callabl if ($points === []) { return; } + $userPoints = self::parsePoints($pointsAttr, static fn (float $x): float => $x, static fn (float $y): float => $y); + $toPage = self::affineTxTy($tx, $ty); [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? ($closed ? '#000' : null)); [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); @@ -1251,8 +1408,8 @@ private static function renderPolygon(\SimpleXMLElement $el, Page $page, callabl $fillOpacity = self::parseOpacity($el, 'fill-opacity', $globalOpacity); $strokeOpacity = self::parseOpacity($el, 'stroke-opacity', $globalOpacity); - $page->withOpacity($fillOpacity, $strokeOpacity, static function () use ($el, $page, $closed, $hasFill, $hasStroke, $points, $fr, $fg, $fb, $sr, $sg, $sb, $sw, $scaleX): void { - if ($closed && $hasFill) { + $page->withOpacity($fillOpacity, $strokeOpacity, static function () use ($el, $page, $closed, $hasFill, $hasStroke, $points, $userPoints, $toPage, $fr, $fg, $fb, $sr, $sg, $sb, $sw, $scaleX): void { + if ($closed && $hasFill && ! self::fillGradient($el, $page, self::outline($points), static fn (): array => $userPoints, $toPage)) { self::fillPolygonByRule($el, $page, $points, $fr, $fg, $fb); } if ($hasStroke) { @@ -1309,6 +1466,10 @@ private static function renderPath(\SimpleXMLElement $el, Page $page, callable $ return; } + $user = static fn (): array => self::commandPoints(self::parsePathD($d, static fn (float $x): float => $x, static fn (float $y): float => $y)); + if ($hasFill && self::fillGradient($el, $page, $commands, $user, self::affineTxTy($tx, $ty))) { + $hasFill = false; + } $mode = self::pathMode($el, $hasFill, $hasStroke); if ($mode === null) { return; // Nothing to draw. diff --git a/tests/Pdf/ContentStreamTest.php b/tests/Pdf/ContentStreamTest.php index 19d5b02..5785f24 100644 --- a/tests/Pdf/ContentStreamTest.php +++ b/tests/Pdf/ContentStreamTest.php @@ -103,6 +103,18 @@ public function emitPath_keeps_nonzero_operators_and_unknown_mode_falls_back_to_ self::assertStringContainsString("h\nf\nQ\n", (new ContentStream)->emitPath($squares, 'bogus')->toString()); } + #[Test] + public function fillPathWithPattern_selects_the_pattern_and_fills(): void + { + $s = (new ContentStream)->fillPathWithPattern(self::twoSquares(), 'P1')->toString(); + self::assertStringStartsWith("q\n/Pattern cs\n/P1 scn\n0 0 m\n", $s); + self::assertStringEndsWith("h\nf\nQ\n", $s); + + $evenOdd = (new ContentStream)->fillPathWithPattern(self::twoSquares(), 'P2', evenOdd: true)->toString(); + self::assertStringEndsWith("h\nf*\nQ\n", $evenOdd); + self::assertTrue((new ContentStream)->fillPathWithPattern([], 'P1')->isEmpty()); + } + /** * A square with a smaller square inside it, both drawn the same way * round: under the nonzero rule the inner one fills, under even-odd it diff --git a/tests/Svg/SvgGradientShapesTest.php b/tests/Svg/SvgGradientShapesTest.php new file mode 100644 index 0000000..9787dde --- /dev/null +++ b/tests/Svg/SvgGradientShapesTest.php @@ -0,0 +1,125 @@ +: the shape is filled + * with a shading pattern whose matrix maps gradient space onto the page. + * + * Each SVG is drawn into a 100 x 100 pt box at the page origin, so user + * space maps onto the page by [1 0 0 -1 0 100]. + */ +final class SvgGradientShapesTest extends TestCase +{ + private const STOPS = ''; + + #[Test] + public function path_is_filled_with_its_bounding_box_gradient(): void + { + // Bounding box (10, 10, 40, 20): gradient space [0..1] covers it. + [$stream, $bytes] = self::render(''.self::STOPS.''); + + self::assertStringContainsString("/Pattern cs\n/P1 scn\n10 90 m\n50 90 l\n50 70 l\n10 70 l\nh\nf\n", $stream); + self::assertStringNotContainsString(' rg', $stream); + self::assertStringContainsString('/ShadingType 2', $bytes); + self::assertMatchesRegularExpression('@/Coords \[0 0 1 0\]@', $bytes); + self::assertStringContainsString('/Matrix [40 0 0 -20 10 90]', $bytes); + } + + #[Test] + public function user_space_gradients_keep_their_coordinates(): void + { + [, $bytes] = self::render(''.self::STOPS.''); + + self::assertMatchesRegularExpression('@/Coords \[0 0 25 25\]@', $bytes); + self::assertStringContainsString('/Matrix [1 0 0 -1 0 100]', $bytes); + } + + #[Test] + public function the_gradient_follows_group_transforms(): void + { + // As BaconQrCode writes it: a scaled group, a translated group, a user-space gradient. + [$stream, $bytes] = self::render(''.self::STOPS.'' + .''); + + self::assertStringContainsString("/P1 scn\n4 96 m\n", $stream); + self::assertStringContainsString("h\nf*\n", $stream); + self::assertStringContainsString('/Matrix [2 0 0 -2 4 96]', $bytes); + } + + #[Test] + public function gradient_transform_applies_inside_the_bounding_box(): void + { + [, $bytes] = self::render(''.self::STOPS.''); + + self::assertStringContainsString('/Matrix [40 0 0 -20 30 90]', $bytes); + } + + #[Test] + public function radial_gradient_fills_a_circle(): void + { + [$stream, $bytes] = self::render(''.self::STOPS.''); + + self::assertStringContainsString('/P1 scn', $stream); + self::assertStringNotContainsString(' rg', $stream); + self::assertStringContainsString('/ShadingType 3', $bytes); + self::assertMatchesRegularExpression('@/Coords \[0\.5 0\.5 0 0\.5 0\.5 0\.5\]@', $bytes); + self::assertStringContainsString('/Matrix [80 0 0 -80 10 90]', $bytes); + } + + #[Test] + public function polygon_and_ellipse_take_gradients(): void + { + $defs = ''.self::STOPS.''; + foreach (['', ''] as $shape) { + [$stream] = self::render($defs.$shape); + self::assertStringContainsString('/P1 scn', $stream, $shape); + self::assertStringNotContainsString(' rg', $stream, $shape); + } + } + + #[Test] + public function transformed_rect_takes_a_gradient(): void + { + [$stream] = self::render(''.self::STOPS.''); + + self::assertStringContainsString('/P1 scn', $stream); + self::assertStringNotContainsString(' rg', $stream); + } + + #[Test] + public function a_gradient_fill_keeps_its_stroke(): void + { + [$stream] = self::render(''.self::STOPS.''); + + self::assertStringContainsString('/P1 scn', $stream); + self::assertStringContainsString('0 1 0 RG', $stream); + self::assertMatchesRegularExpression('@\nS\n@', $stream); + } + + #[Test] + public function an_unknown_gradient_falls_back_to_black_as_before(): void + { + [$stream] = self::render(''); + + self::assertStringContainsString('0 0 0 rg', $stream); + self::assertStringNotContainsString('/Pattern', $stream); + } + + /** @return array{0: string, 1: string} the page's content stream and the whole document */ + private static function render(string $body): array + { + $doc = PdfDocument::new(); + $page = $doc->addPage(customDimensionsPt: [100, 100]); + SvgRenderer::render(''.$body.'', $page, 0, 0, 100, 100); + + return [$page->rawContentStream()->toString(), $doc->toBytes()]; + } +} From 107e8ee917d45d3dff4d1720229a97691fd404a5 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 14:22:30 -0700 Subject: [PATCH 07/11] fix(svg): cap the elements may copy resolveUseReferences() copied every reference in full, and a copy can hold elements that were already expanded, so nested references multiply. A small SVG could expand into millions of shapes and keep a renderer busy for minutes. Copies are now counted before they are made, and a that would take a document past SvgRenderer::MAX_USE_COPIES (50,000 elements) is left out; smaller ones after it are still drawn. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ src/Svg/SvgRenderer.php | 15 +++++++++++++++ tests/Svg/SvgDefsUseTest.php | 25 +++++++++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 099a9b2..6006b97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,10 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). was ignored: ``, as QR code generators write it, lost its translate. Nested transforms compose now, and stroke widths follow the combined scale. +- `` copies are capped at `SvgRenderer::MAX_USE_COPIES` (50,000) + elements per document. `` elements that refer to groups of + `` elements could make a small file expand into millions of shapes + and take minutes to draw. A `` that would pass the cap is left out. ## [1.25.0] — 2026-10-19 diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index 4363cb9..efc6392 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -22,6 +22,13 @@ */ final class SvgRenderer { + /** + * The most elements all references in one document may copy. + * Copies past it are left out, so nested elements cannot + * multiply a small file into millions of shapes. + */ + public const MAX_USE_COPIES = 50_000; + /** * @return array{0: int, 1: int, 2: int}|null */ @@ -393,6 +400,7 @@ private static function resolveUseReferences(\SimpleXMLElement $root): void } // Find all use elements. $uses = $root->xpath('//use') ?: []; + $copied = 0; foreach ($uses as $use) { $href = (string) ($use['href'] ?? $use->attributes('xlink', true)?->href ?? ''); if ($href === '' || ! str_starts_with($href, '#')) { @@ -407,6 +415,13 @@ private static function resolveUseReferences(\SimpleXMLElement $root): void $newName = $ref->getName(); $dom = dom_import_simplexml($use); $refDom = dom_import_simplexml($ref); + // Counted before cloning: an earlier may already have + // copied content into the element this one refers to. + $size = 1 + $refDom->getElementsByTagName('*')->length; + if ($copied + $size > self::MAX_USE_COPIES) { + continue; + } + $copied += $size; $clone = $refDom->cloneNode(true); // Rename use → ref tag by replacing element. $newEl = $dom->ownerDocument->createElement($newName); diff --git a/tests/Svg/SvgDefsUseTest.php b/tests/Svg/SvgDefsUseTest.php index 2f557cd..936f9bd 100644 --- a/tests/Svg/SvgDefsUseTest.php +++ b/tests/Svg/SvgDefsUseTest.php @@ -93,4 +93,29 @@ public function style_inside_defs_applied_к_use(): void ->toBytes(new Engine(compressStreams: false)); self::assertMatchesRegularExpression('@0\s+0\s+1\s+rg@', $bytes); } + + #[Test] + public function use_copies_stop_at_the_limit(): void + { + // Each group holds ten copies of the one before: 10^5 rects in all. + $defs = ''; + for ($i = 1; $i <= 5; $i++) { + $defs .= sprintf('%s', $i, str_repeat(sprintf('', $i - 1), 10)); + } + $page = \Dskripchenko\PhpPdf\Pdf\Document::new()->addPage(customDimensionsPt: [100, 100]); + \Dskripchenko\PhpPdf\Svg\SvgRenderer::render(''.$defs.'', $page, 0, 0, 100, 100); + + $rects = substr_count($page->rawContentStream()->toString(), "1 0 0 rg\n"); + self::assertLessThanOrEqual(\Dskripchenko\PhpPdf\Svg\SvgRenderer::MAX_USE_COPIES, $rects); + } + + #[Test] + public function a_small_use_after_one_over_the_limit_is_still_drawn(): void + { + $big = ''.str_repeat('', \Dskripchenko\PhpPdf\Svg\SvgRenderer::MAX_USE_COPIES).''; + $page = \Dskripchenko\PhpPdf\Pdf\Document::new()->addPage(customDimensionsPt: [100, 100]); + \Dskripchenko\PhpPdf\Svg\SvgRenderer::render(''.$big.'', $page, 0, 0, 100, 100); + + self::assertSame(1, substr_count($page->rawContentStream()->toString(), "1 0 0 rg\n")); + } } From 8003706a2adc52ae48a3c8658698a4a3bb5e57b3 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 14:33:33 -0700 Subject: [PATCH 08/11] test(svg): a group that uses itself stays within the cap references resolve in one pass, so a cycle cannot loop, but each resolved copies its group along with the copies made so far: n references from a group to itself draw 2^n copies. The cap already bounds that; this test keeps it bounded. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++-- tests/Svg/SvgDefsUseTest.php | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6006b97..7668190 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,8 +38,9 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). compose now, and stroke widths follow the combined scale. - `` copies are capped at `SvgRenderer::MAX_USE_COPIES` (50,000) elements per document. `` elements that refer to groups of - `` elements could make a small file expand into millions of shapes - and take minutes to draw. A `` that would pass the cap is left out. + `` elements, or a group with `` references to itself, could + make a small file expand into millions of shapes and take minutes to + draw. A `` that would pass the cap is left out. ## [1.25.0] — 2026-10-19 diff --git a/tests/Svg/SvgDefsUseTest.php b/tests/Svg/SvgDefsUseTest.php index 936f9bd..67e1010 100644 --- a/tests/Svg/SvgDefsUseTest.php +++ b/tests/Svg/SvgDefsUseTest.php @@ -109,6 +109,18 @@ public function use_copies_stop_at_the_limit(): void self::assertLessThanOrEqual(\Dskripchenko\PhpPdf\Svg\SvgRenderer::MAX_USE_COPIES, $rects); } + #[Test] + public function a_group_that_uses_itself_stays_within_the_limit(): void + { + // Each resolved copies the group with the copies made so far: 2^n without the cap. + $page = \Dskripchenko\PhpPdf\Pdf\Document::new()->addPage(customDimensionsPt: [100, 100]); + \Dskripchenko\PhpPdf\Svg\SvgRenderer::render(''.str_repeat('', 40).'', $page, 0, 0, 100, 100); + + $rects = substr_count($page->rawContentStream()->toString(), "1 0 0 rg\n"); + self::assertGreaterThan(0, $rects); + self::assertLessThanOrEqual(\Dskripchenko\PhpPdf\Svg\SvgRenderer::MAX_USE_COPIES, $rects); + } + #[Test] public function a_small_use_after_one_over_the_limit_is_still_drawn(): void { From 84d7e791a5bb3da45972fe08e9b11a04b052d62e Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 14:41:03 -0700 Subject: [PATCH 09/11] perf(svg): stream path data instead of holding it in arrays We hit this drawing complex data visualisations: dense line charts and maps whose paths carry hundreds of thousands of points. parsePathD() split the whole d attribute with one preg_match_all (an array per command), built a second array per command, and only then wrote the path, so a 5 MB path with a million points peaked at about 511 MB. Path commands are now read in place with strcspn() and yielded one at a time, and emitPath() / fillPathWithPattern() take any iterable, writing a generator as it is read. The same path peaks at about 11 MB, mostly the content stream itself; time is about the same. A gradient fill, which reads the path twice, still builds the list. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++ src/Pdf/ContentStream.php | 39 ++++++--- src/Pdf/Page.php | 11 +-- src/Svg/SvgRenderer.php | 143 ++++++++++++++++++++------------- tests/Svg/SvgLargePathTest.php | 64 +++++++++++++++ 5 files changed, 190 insertions(+), 72 deletions(-) create mode 100644 tests/Svg/SvgLargePathTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 7668190..5afccf6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). it is drawn. - `Page::fillPathWithPattern()` and `ContentStream::fillPathWithPattern()` fill any path with a registered shading pattern. +- `emitPath()` and `fillPathWithPattern()` take any iterable of commands, + so a generator is written as it is read. - SVG gradients fill paths, polygons, circles, ellipses and transformed rectangles, not only plain rectangles, and honour `gradientUnits="userSpaceOnUse"`. The pattern follows the shape's @@ -36,6 +38,9 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). was ignored: ``, as QR code generators write it, lost its translate. Nested transforms compose now, and stroke widths follow the combined scale. +- SVG path data is parsed and written as it is read. A dense chart or map + with a million path points peaked at about 500 MB, a PHP array per + command; it now peaks at about 11 MB, mostly the page's content stream. - `` copies are capped at `SvgRenderer::MAX_USE_COPIES` (50,000) elements per document. `` elements that refer to groups of `` elements, or a group with `` references to itself, could diff --git a/src/Pdf/ContentStream.php b/src/Pdf/ContentStream.php index eb2037b..3de1dbd 100644 --- a/src/Pdf/ContentStream.php +++ b/src/Pdf/ContentStream.php @@ -257,18 +257,22 @@ public function fillRectangle( * rule) | 'fill-evenodd' | 'fillstroke-evenodd' (f*, B*, even-odd * rule). An unknown mode emits f. * - * @param list $commands + * The commands can be any iterable: a generator is written as it is + * read, so a long path need not be held in memory. + * + * @param iterable $commands * @param array{r: float, g: float, b: float}|null $fillRgb * @param array{r: float, g: float, b: float}|null $strokeRgb */ public function emitPath( - array $commands, + iterable $commands, string $mode = 'fill', ?array $fillRgb = null, ?array $strokeRgb = null, float $lineWidthPt = 1.0, ): self { - if ($commands === []) { + $commands = self::started($commands); + if ($commands === null) { return $this; } $this->body .= "q\n"; @@ -308,11 +312,12 @@ public function emitPath( * nonzero or (with $evenOdd) the even-odd rule. The pattern's matrix * maps its space onto the page's default coordinates. * - * @param list $commands as for emitPath() + * @param iterable $commands as for emitPath() */ - public function fillPathWithPattern(array $commands, string $patternName, bool $evenOdd = false): self + public function fillPathWithPattern(iterable $commands, string $patternName, bool $evenOdd = false): self { - if ($commands === []) { + $commands = self::started($commands); + if ($commands === null) { return $this; } $this->body .= "q\n/Pattern cs\n"; @@ -324,11 +329,27 @@ public function fillPathWithPattern(array $commands, string $patternName, bool $ } /** - * @param list $commands + * The commands as an iterator at its first entry, or null when there is + * none, so nothing is written for an empty path. + * + * @param iterable $commands + * @return \Iterator|null + */ + private static function started(iterable $commands): ?\Iterator + { + $iterator = is_array($commands) ? new \ArrayIterator($commands) : ($commands instanceof \Iterator ? $commands : new \IteratorIterator($commands)); + $iterator->rewind(); + + return $iterator->valid() ? $iterator : null; + } + + /** + * @param \Iterator $commands already started */ - private function appendPathCommands(array $commands): void + private function appendPathCommands(\Iterator $commands): void { - foreach ($commands as $cmd) { + for (; $commands->valid(); $commands->next()) { + $cmd = $commands->current(); if ($cmd === 'Z') { $this->body .= "h\n"; diff --git a/src/Pdf/Page.php b/src/Pdf/Page.php index 2e6edc8..d386e1f 100644 --- a/src/Pdf/Page.php +++ b/src/Pdf/Page.php @@ -994,9 +994,9 @@ public function strokePolyline( * the nonzero or (with $evenOdd) the even-odd rule. The pattern's * matrix maps its space onto the page's default coordinates. * - * @param list $commands as for emitPath() + * @param iterable $commands as for emitPath() */ - public function fillPathWithPattern(array $commands, string $patternName, bool $evenOdd = false): self + public function fillPathWithPattern(iterable $commands, string $patternName, bool $evenOdd = false): self { $this->stream->fillPathWithPattern($commands, $patternName, $evenOdd); @@ -1011,14 +1011,15 @@ public function fillPathWithPattern(array $commands, string $patternName, bool $ * - 'fill-evenodd', 'fillstroke-evenodd' — even-odd rule (f*, B*): a * subpath inside another is a hole whichever way round it is drawn, * as SVG `fill-rule="evenodd"` asks for. - * An unknown mode fills by the nonzero rule. + * An unknown mode fills by the nonzero rule. `$commands` can be a + * generator, which is written as it is read. * - * @param list $commands + * @param iterable $commands * @param array{r: float, g: float, b: float}|null $fillRgb * @param array{r: float, g: float, b: float}|null $strokeRgb */ public function emitPath( - array $commands, + iterable $commands, string $mode = 'fill', ?array $fillRgb = null, ?array $strokeRgb = null, diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index efc6392..d143514 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -841,27 +841,52 @@ private static function renderPathXY(\SimpleXMLElement $el, Page $page, callable [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); - // Wrap point transformers as (svg-x → pdf-x) / (svg-y → pdf-y) - // closures that we'd normally pass to parsePathD. parsePathD expects - // single-arg tx/ty, so we pass through identity closures and - // post-transform each emitted command: $idTx = static fn (float $x): float => $x; $idTy = static fn (float $y): float => $y; - $rawCommands = self::parsePathD($d, $idTx, $idTy); + if ($hasFill && self::gradientFor($el) !== null) { + // A gradient fill reads the path twice (fill, then stroke). + $rawCommands = self::parsePathD($d, $idTx, $idTy); + $commands = iterator_to_array(self::mapCommands($rawCommands, $px, $py), false); + if (self::fillGradient($el, $page, $commands, static fn (): array => self::commandPoints($rawCommands), self::affineXY($px, $py))) { + $hasFill = false; + } + } else { + $commands = self::mapCommands(self::pathCommands($d, $idTx, $idTy), $px, $py); + } + $mode = self::pathMode($el, $hasFill, $hasStroke); + if ($mode === null) { + return; + } + $page->emitPath( + $commands, + $mode, + $hasFill ? ['r' => $fr, 'g' => $fg, 'b' => $fb] : null, + $hasStroke ? ['r' => $sr, 'g' => $sg, 'b' => $sb] : null, + $sw * $scaleX, + ); + } - // Transform raw SVG-space commands to PDF coords. - $commands = []; - foreach ($rawCommands as $cmd) { + /** + * Path commands in SVG user units → page coordinates, one at a time. + * + * @param iterable $commands + * @param callable(float, float): float $px + * @param callable(float, float): float $py + * @return \Generator + */ + private static function mapCommands(iterable $commands, callable $px, callable $py): \Generator + { + foreach ($commands as $cmd) { if ($cmd === 'Z') { - $commands[] = 'Z'; + yield 'Z'; continue; } $type = $cmd[0]; if ($type === 'M' || $type === 'L') { - $commands[] = [$type, $px($cmd[1], $cmd[2]), $py($cmd[1], $cmd[2])]; + yield [$type, $px($cmd[1], $cmd[2]), $py($cmd[1], $cmd[2])]; } elseif ($type === 'C') { - $commands[] = [ + yield [ 'C', $px($cmd[1], $cmd[2]), $py($cmd[1], $cmd[2]), $px($cmd[3], $cmd[4]), $py($cmd[3], $cmd[4]), @@ -869,22 +894,6 @@ private static function renderPathXY(\SimpleXMLElement $el, Page $page, callable ]; } } - - // A gradient fill is painted on its own; the stroke, if any, follows. - if ($hasFill && self::fillGradient($el, $page, $commands, static fn (): array => self::commandPoints($rawCommands), self::affineXY($px, $py))) { - $hasFill = false; - } - $mode = self::pathMode($el, $hasFill, $hasStroke); - if ($mode === null) { - return; - } - $page->emitPath( - $commands, - $mode, - $hasFill ? ['r' => $fr, 'g' => $fg, 'b' => $fb] : null, - $hasStroke ? ['r' => $sr, 'g' => $sg, 'b' => $sb] : null, - $sw * $scaleX, - ); } /** @@ -1476,14 +1485,19 @@ private static function renderPath(\SimpleXMLElement $el, Page $page, callable $ [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); - $commands = self::parsePathD($d, $tx, $ty); - if ($commands === []) { - return; - } - - $user = static fn (): array => self::commandPoints(self::parsePathD($d, static fn (float $x): float => $x, static fn (float $y): float => $y)); - if ($hasFill && self::fillGradient($el, $page, $commands, $user, self::affineTxTy($tx, $ty))) { - $hasFill = false; + // A gradient fill reads the path twice (fill, then stroke); a flat + // one streams it into the page as it is parsed. + if ($hasFill && self::gradientFor($el) !== null) { + $commands = self::parsePathD($d, $tx, $ty); + if ($commands === []) { + return; + } + $user = static fn (): array => self::commandPoints(self::parsePathD($d, static fn (float $x): float => $x, static fn (float $y): float => $y)); + if (self::fillGradient($el, $page, $commands, $user, self::affineTxTy($tx, $ty))) { + $hasFill = false; + } + } else { + $commands = self::pathCommands($d, $tx, $ty); } $mode = self::pathMode($el, $hasFill, $hasStroke); if ($mode === null) { @@ -1508,16 +1522,16 @@ private static function renderPath(\SimpleXMLElement $el, Page $page, callable $ * * @param callable(float): float $tx * @param callable(float): float $ty - * @return list + * @return \Generator */ - private static function parsePathD(string $d, callable $tx, callable $ty): array + private static function pathCommands(string $d, callable $tx, callable $ty): \Generator { - // Tokenize: split on each command letter (preserve command letters as separators). - $regex = '@([MmLlHhVvCcSsQqTtAaZz])([^MmLlHhVvCcSsQqTtAaZz]*)@'; - if (! preg_match_all($regex, $d, $matches, PREG_SET_ORDER)) { - return []; - } - $commands = []; + // Each command is its letter and the arguments up to the next one, + // read in place: a PHP array per command for a path with a million + // points would take hundreds of megabytes. + $letters = 'MmLlHhVvCcSsQqTtAaZz'; + $length = strlen($d); + $pos = strcspn($d, $letters); $cx = 0; $cy = 0; // current point (SVG units, NOT transformed) $startX = 0; @@ -1527,9 +1541,11 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array $lastQuadCtrlX = null; $lastQuadCtrlY = null; - foreach ($matches as $m) { - $op = $m[1]; - $args = trim($m[2]); + while ($pos < $length) { + $op = $d[$pos]; + $argLength = strcspn($d, $letters, $pos + 1); + $args = trim(substr($d, $pos + 1, $argLength)); + $pos += 1 + $argLength; $nums = $args === '' ? [] : preg_split('@[\s,]+|(?<=[0-9.])-@', $args); if ($nums === false) { $nums = []; @@ -1545,14 +1561,14 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array } $x = $isRel ? $cx + $nums[0] : $nums[0]; $y = $isRel ? $cy + $nums[1] : $nums[1]; - $commands[] = ['M', $tx($x), $ty($y)]; + yield ['M', $tx($x), $ty($y)]; $cx = $x; $cy = $y; $startX = $x; $startY = $y; // Subsequent pairs treated as L. for ($i = 2; $i + 1 < count($nums); $i += 2) { $x = $isRel ? $cx + $nums[$i] : $nums[$i]; $y = $isRel ? $cy + $nums[$i + 1] : $nums[$i + 1]; - $commands[] = ['L', $tx($x), $ty($y)]; + yield ['L', $tx($x), $ty($y)]; $cx = $x; $cy = $y; } $lastCubicCtrlX = $lastCubicCtrlY = null; @@ -1563,7 +1579,7 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array for ($i = 0; $i + 1 < count($nums); $i += 2) { $x = $isRel ? $cx + $nums[$i] : $nums[$i]; $y = $isRel ? $cy + $nums[$i + 1] : $nums[$i + 1]; - $commands[] = ['L', $tx($x), $ty($y)]; + yield ['L', $tx($x), $ty($y)]; $cx = $x; $cy = $y; } $lastCubicCtrlX = $lastCubicCtrlY = null; @@ -1573,7 +1589,7 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array case 'H': foreach ($nums as $n) { $x = $isRel ? $cx + $n : $n; - $commands[] = ['L', $tx($x), $ty($cy)]; + yield ['L', $tx($x), $ty($cy)]; $cx = $x; } $lastCubicCtrlX = $lastCubicCtrlY = null; @@ -1583,7 +1599,7 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array case 'V': foreach ($nums as $n) { $y = $isRel ? $cy + $n : $n; - $commands[] = ['L', $tx($cx), $ty($y)]; + yield ['L', $tx($cx), $ty($y)]; $cy = $y; } $lastCubicCtrlX = $lastCubicCtrlY = null; @@ -1598,7 +1614,7 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array $y2 = $isRel ? $cy + $nums[$i + 3] : $nums[$i + 3]; $x3 = $isRel ? $cx + $nums[$i + 4] : $nums[$i + 4]; $y3 = $isRel ? $cy + $nums[$i + 5] : $nums[$i + 5]; - $commands[] = ['C', $tx($x1), $ty($y1), $tx($x2), $ty($y2), $tx($x3), $ty($y3)]; + yield ['C', $tx($x1), $ty($y1), $tx($x2), $ty($y2), $tx($x3), $ty($y3)]; $cx = $x3; $cy = $y3; $lastCubicCtrlX = $x2; $lastCubicCtrlY = $y2; @@ -1619,7 +1635,7 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array $y2 = $isRel ? $cy + $nums[$i + 1] : $nums[$i + 1]; $x3 = $isRel ? $cx + $nums[$i + 2] : $nums[$i + 2]; $y3 = $isRel ? $cy + $nums[$i + 3] : $nums[$i + 3]; - $commands[] = ['C', $tx($x1), $ty($y1), $tx($x2), $ty($y2), $tx($x3), $ty($y3)]; + yield ['C', $tx($x1), $ty($y1), $tx($x2), $ty($y2), $tx($x3), $ty($y3)]; $cx = $x3; $cy = $y3; $lastCubicCtrlX = $x2; $lastCubicCtrlY = $y2; @@ -1638,7 +1654,7 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array $c1y = $cy + 2 / 3 * ($qy - $cy); $c2x = $ex + 2 / 3 * ($qx - $ex); $c2y = $ey + 2 / 3 * ($qy - $ey); - $commands[] = ['C', $tx($c1x), $ty($c1y), $tx($c2x), $ty($c2y), $tx($ex), $ty($ey)]; + yield ['C', $tx($c1x), $ty($c1y), $tx($c2x), $ty($c2y), $tx($ex), $ty($ey)]; $cx = $ex; $cy = $ey; $lastQuadCtrlX = $qx; $lastQuadCtrlY = $qy; @@ -1660,7 +1676,7 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array $c1y = $cy + 2 / 3 * ($qy - $cy); $c2x = $ex + 2 / 3 * ($qx - $ex); $c2y = $ey + 2 / 3 * ($qy - $ey); - $commands[] = ['C', $tx($c1x), $ty($c1y), $tx($c2x), $ty($c2y), $tx($ex), $ty($ey)]; + yield ['C', $tx($c1x), $ty($c1y), $tx($c2x), $ty($c2y), $tx($ex), $ty($ey)]; $cx = $ex; $cy = $ey; $lastQuadCtrlX = $qx; $lastQuadCtrlY = $qy; @@ -1669,7 +1685,7 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array break; case 'Z': - $commands[] = 'Z'; + yield 'Z'; $cx = $startX; $cy = $startY; $lastCubicCtrlX = $lastCubicCtrlY = null; @@ -1689,7 +1705,7 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array $ey = $isRel ? $cy + $nums[$i + 6] : $nums[$i + 6]; $arcCubics = self::arcToCubics($cx, $cy, $arcRx, $arcRy, $xRot, $largeArc, $sweep, $ex, $ey); foreach ($arcCubics as $cu) { - $commands[] = [ + yield [ 'C', $tx($cu[0]), $ty($cu[1]), $tx($cu[2]), $ty($cu[3]), @@ -1703,10 +1719,21 @@ private static function parsePathD(string $d, callable $tx, callable $ty): array break; } } + } - return $commands; + /** + * pathCommands() as a list, for callers that read the path twice. + * + * @param callable(float): float $tx + * @param callable(float): float $ty + * @return list + */ + private static function parsePathD(string $d, callable $tx, callable $ty): array + { + return iterator_to_array(self::pathCommands($d, $tx, $ty), false); } + /** * Convert elliptical arc to a sequence of cubic Beziers. * diff --git a/tests/Svg/SvgLargePathTest.php b/tests/Svg/SvgLargePathTest.php new file mode 100644 index 0000000..5314814 --- /dev/null +++ b/tests/Svg/SvgLargePathTest.php @@ -0,0 +1,64 @@ +'; + $page = PdfDocument::new()->addPage(customDimensionsPt: [100, 100]); + + gc_collect_cycles(); + $before = memory_get_usage(); + memory_reset_peak_usage(); + SvgRenderer::render($svg, $page, 0, 0, 100, 100); + $peak = memory_get_peak_usage() - $before; + + $stream = $page->rawContentStream()->toString(); + self::assertSame($segments, substr_count($stream, " l\n")); + // The content stream alone is about 1.2 MB; a PHP array per command took about 100 MB. + self::assertLessThan(16 * 1024 * 1024, $peak, sprintf('peak %.1f MB', $peak / 1048576)); + } + + #[Test] + public function emitPath_takes_any_iterable(): void + { + $commands = (static function (): \Generator { + yield ['M', 0.0, 0.0]; + yield ['L', 10.0, 0.0]; + yield 'Z'; + })(); + + self::assertStringContainsString("0 0 m\n10 0 l\nh\nf\n", (new ContentStream)->emitPath($commands)->toString()); + self::assertTrue((new ContentStream)->emitPath((static fn (): \Generator => yield from [])())->isEmpty()); + } + + #[Test] + public function a_gradient_fill_still_sees_the_whole_path(): void + { + $doc = PdfDocument::new(); + $page = $doc->addPage(customDimensionsPt: [100, 100]); + SvgRenderer::render('' + .'', $page, 0, 0, 100, 100); + + $stream = $page->rawContentStream()->toString(); + self::assertSame(2, substr_count($stream, "10 90 m\n50 90 l\n50 70 l\n10 70 l\nh\n")); + self::assertStringContainsString('/Matrix [40 0 0 -20 10 90]', $doc->toBytes()); + } +} From 939382597a50c67069e441dff0d25ee9c329e86a Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 14:50:51 -0700 Subject: [PATCH 10/11] =?UTF-8?q?perf(svg):=20circles=20and=20ellipses=20a?= =?UTF-8?q?s=20four=20B=C3=A9zier=20curves?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each circle and ellipse was a 36-sided polygon, filled and then stroked as two paths. Large ones showed their facets, and scatter plots paid for 36 points a dot: about 640 bytes of content each. They are now four cubic Béziers (control distance 4/3 (sqrt 2 - 1), within 0.03% of the true outline), filled and stroked as one path through emitPath(), with gradients and fill-rule as for any path. A 25,000-dot scatter plot takes 1.2 s instead of 2.5 s, peaks at 19 MB instead of 46 MB, and its PDF is 1.8 MB instead of 5.2 MB. A zero or negative radius now draws nothing, as SVG defines. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++ src/Svg/SvgRenderer.php | 97 ++++++++++++++++++++---------------- tests/Svg/SvgCirclesTest.php | 89 +++++++++++++++++++++++++++++++++ 3 files changed, 147 insertions(+), 44 deletions(-) create mode 100644 tests/Svg/SvgCirclesTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 5afccf6..021afa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,11 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). was ignored: ``, as QR code generators write it, lost its translate. Nested transforms compose now, and stroke widths follow the combined scale. +- SVG circles and ellipses are drawn as four cubic Béziers instead of + 36-sided polygons, so they are round at any size, and filled and + stroked as one path. A 25,000-dot scatter plot renders in half the + time with less than half the memory, and its PDF is a third of the size + (1.8 MB instead of 5.2 MB). A zero radius draws nothing, as SVG defines. - SVG path data is parsed and written as it is read. A dense chart or map with a million path points peaked at about 500 MB, a PHP array per command; it now peaks at about 11 MB, mostly the page's content stream. diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index d143514..e31abce 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -761,28 +761,7 @@ private static function renderEllipseXY(\SimpleXMLElement $el, Page $page, calla $rx = (float) ($el['rx'] ?? 0); $ry = (float) ($el['ry'] ?? 0); } - [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? '#000'); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); - $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); - - $segments = 36; - $points = []; - $userPoints = []; - for ($i = 0; $i < $segments; $i++) { - $angle = 2 * M_PI * $i / $segments; - $sx = $cx + cos($angle) * $rx; - $sy = $cy + sin($angle) * $ry; - $userPoints[] = [$sx, $sy]; - $points[] = [$px($sx, $sy), $py($sx, $sy)]; - } - if ($hasFill && ! self::fillGradient($el, $page, self::outline($points), static fn (): array => $userPoints, self::affineXY($px, $py))) { - $page->fillPolygon($points, $fr, $fg, $fb); - } - if ($hasStroke) { - $closed = $points; - $closed[] = $points[0]; - $page->strokePolyline($closed, $sw * $scaleX, $sr, $sg, $sb); - } + self::drawEllipse($el, $page, $cx, $cy, $rx, $ry, $px, $py, $scaleX); } /** @@ -1381,36 +1360,66 @@ private static function renderEllipse(\SimpleXMLElement $el, Page $page, callabl */ private static function renderEllipseAt(float $cx, float $cy, float $rx, float $ry, \SimpleXMLElement $el, Page $page, callable $tx, callable $ty, float $scaleX, float $scaleY): void { - $segments = 36; - $points = []; - $userPoints = []; - for ($i = 0; $i < $segments; $i++) { - $angle = 2 * M_PI * $i / $segments; - $userPoints[] = [$cx + cos($angle) * $rx, $cy + sin($angle) * $ry]; - $points[] = [$tx($cx + cos($angle) * $rx), $ty($cy + sin($angle) * $ry)]; - } - $toPage = self::affineTxTy($tx, $ty); - [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? '#000'); - [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); - $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); + $px = static fn (float $x, float $y): float => $tx($x); + $py = static fn (float $x, float $y): float => $ty($y); - // Opacity. $globalOpacity = self::parseOpacity($el, 'opacity', 1.0); $fillOpacity = self::parseOpacity($el, 'fill-opacity', $globalOpacity); $strokeOpacity = self::parseOpacity($el, 'stroke-opacity', $globalOpacity); - $page->withOpacity($fillOpacity, $strokeOpacity, static function () use ($el, $page, $hasFill, $hasStroke, $points, $userPoints, $toPage, $fr, $fg, $fb, $sr, $sg, $sb, $sw, $scaleX): void { - if ($hasFill && ! self::fillGradient($el, $page, self::outline($points), static fn (): array => $userPoints, $toPage)) { - $page->fillPolygon($points, $fr, $fg, $fb); - } - if ($hasStroke) { - $closed = $points; - $closed[] = $points[0]; - $page->strokePolyline($closed, $sw * $scaleX, $sr, $sg, $sb); - } + $page->withOpacity($fillOpacity, $strokeOpacity, static function () use ($el, $page, $cx, $cy, $rx, $ry, $px, $py, $scaleX): void { + self::drawEllipse($el, $page, $cx, $cy, $rx, $ry, $px, $py, $scaleX); }); } + /** + * A circle or ellipse as four cubic Béziers, filled and stroked as one + * path. The curves are within 0.03% of the true outline, so they stay + * round at any size, and the path is a fraction of a polygon's size. + * A zero radius draws nothing, as SVG defines. + * + * @param callable(float, float): float $px + * @param callable(float, float): float $py + */ + private static function drawEllipse(\SimpleXMLElement $el, Page $page, float $cx, float $cy, float $rx, float $ry, callable $px, callable $py, float $scaleX): void + { + if ($rx <= 0 || $ry <= 0) { + return; + } + [$fr, $fg, $fb, $hasFill] = self::parseColor(self::inheritedProperty($el, 'fill') ?? '#000'); + [$sr, $sg, $sb, $hasStroke] = self::parseColor(self::inheritedProperty($el, 'stroke') ?? null); + $sw = (float) (self::inheritedProperty($el, 'stroke-width') ?? 1); + + // 4/3 (sqrt 2 - 1): the control distance of a quarter-circle Bézier. + $kx = $rx * 0.5522847498; + $ky = $ry * 0.5522847498; + $user = [ + ['M', $cx + $rx, $cy], + ['C', $cx + $rx, $cy + $ky, $cx + $kx, $cy + $ry, $cx, $cy + $ry], + ['C', $cx - $kx, $cy + $ry, $cx - $rx, $cy + $ky, $cx - $rx, $cy], + ['C', $cx - $rx, $cy - $ky, $cx - $kx, $cy - $ry, $cx, $cy - $ry], + ['C', $cx + $kx, $cy - $ry, $cx + $rx, $cy - $ky, $cx + $rx, $cy], + 'Z', + ]; + $commands = iterator_to_array(self::mapCommands($user, $px, $py), false); + + // The control points lie on the bounding box, so they give it exactly. + if ($hasFill && self::fillGradient($el, $page, $commands, static fn (): array => self::commandPoints($user), self::affineXY($px, $py))) { + $hasFill = false; + } + $mode = self::pathMode($el, $hasFill, $hasStroke); + if ($mode === null) { + return; + } + $page->emitPath( + $commands, + $mode, + $hasFill ? ['r' => $fr, 'g' => $fg, 'b' => $fb] : null, + $hasStroke ? ['r' => $sr, 'g' => $sg, 'b' => $sb] : null, + $sw * $scaleX, + ); + } + /** * @param callable(float): float $tx * @param callable(float): float $ty diff --git a/tests/Svg/SvgCirclesTest.php b/tests/Svg/SvgCirclesTest.php new file mode 100644 index 0000000..b4ec1ac --- /dev/null +++ b/tests/Svg/SvgCirclesTest.php @@ -0,0 +1,89 @@ +'); + + self::assertStringContainsString("90 50 m\n", $stream); + // The first quarter, to the bottom of the circle: control points 40 * 0.5523 out. + self::assertStringContainsString("90 27.9086 72.0914 10 50 10 c\n", $stream); + self::assertSame(4, substr_count($stream, " c\n")); + self::assertSame(0, substr_count($stream, " l\n")); + self::assertStringContainsString("h\nf\n", $stream); + } + + #[Test] + public function an_ellipse_uses_both_radii(): void + { + $stream = self::stream(''); + + self::assertStringContainsString("90 50 m\n90 38.9543 72.0914 30 50 30 c\n", $stream); + self::assertSame(4, substr_count($stream, " c\n")); + } + + #[Test] + public function fill_and_stroke_are_one_path(): void + { + $stream = self::stream(''); + + self::assertSame(4, substr_count($stream, " c\n")); + self::assertStringContainsString("h\nB\n", $stream); + self::assertStringContainsString('2 w', $stream); + } + + #[Test] + public function a_zero_radius_draws_nothing(): void + { + self::assertStringNotContainsString(' c', self::stream('')); + } + + #[Test] + public function a_transformed_circle_stays_curved(): void + { + // translate(10 0): the start point moves from (90, 50) to (100, 50). + $stream = self::stream(''); + + self::assertStringContainsString("100 50 m\n", $stream); + self::assertSame(4, substr_count($stream, " c\n")); + } + + #[Test] + public function a_scatter_plot_stays_small(): void + { + $dots = ''; + for ($i = 0; $i < 1000; $i++) { + $dots .= sprintf('', fmod($i * 7.31, 100), fmod($i * 3.17, 100)); + } + $stream = self::stream($dots); + + // A 36-sided outline took about 600 bytes a dot. + self::assertLessThan(250 * 1000, strlen($stream)); + } + + private static function stream(string $body): string + { + $page = PdfDocument::new()->addPage(customDimensionsPt: [100, 100]); + SvgRenderer::render(''.$body.'', $page, 0, 0, 100, 100); + + return $page->rawContentStream()->toString(); + } +} From 5db367e934bcb53fdc78d9867c675ec9d2f1640f Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Tue, 20 Oct 2026 15:06:38 -0700 Subject: [PATCH 11/11] perf(svg): find a shape's ancestors once, not per property Inherited fill and stroke made every shape look up about six properties, and each lookup ran its own ancestor-or-self XPath query: 30,000 rects went from 0.086 s to 0.157 s. The ancestor chain is now kept for the element being drawn (keyed by the object every lookup receives) and dropped when the render ends; the same rects take 0.114 s. Co-Authored-By: Claude Opus 5.5 --- src/Svg/SvgRenderer.php | 22 +++++++++++++++++++--- tests/Svg/SvgGroupsTest.php | 11 +++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index e31abce..2d7f278 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -291,6 +291,8 @@ private static function renderDocument(string $svgXml, Page $page, float $boxX, self::walkElement($xml, $page, $tx, $ty, $scaleX, $scaleY); } finally { self::$currentGradients = $previous; + self::$chainOf = null; + self::$chain = []; } } @@ -469,6 +471,15 @@ private static function applyCssToTree(\SimpleXMLElement $el, array $rules): voi */ private static array $currentGradients = []; + /** + * The element whose ancestors $chain holds, nearest first. Held, so + * the object cannot be freed and its identity reused. + */ + private static ?\SimpleXMLElement $chainOf = null; + + /** @var list<\SimpleXMLElement> */ + private static array $chain = []; + /** * @param callable(float): float $tx * @param callable(float): float $ty @@ -1025,9 +1036,14 @@ private static function fillPolygonByRule(\SimpleXMLElement $el, Page $page, arr */ private static function inheritedProperty(\SimpleXMLElement $el, string $name): ?string { - // xpath() gives document order, root first: the nearest is the last. - $chain = array_reverse($el->xpath('ancestor-or-self::*') ?: []); - foreach ($chain as $node) { + // A shape asks for several properties in a row, through the same + // object: find its ancestors once. xpath() gives document order, + // root first, so the nearest is the last. + if ($el !== self::$chainOf) { + self::$chain = array_reverse($el->xpath('ancestor-or-self::*') ?: []); + self::$chainOf = $el; + } + foreach (self::$chain as $node) { $style = (string) ($node['style'] ?? ''); if ($style !== '' && preg_match('/(?:^|;)\s*'.preg_quote($name, '/').'\s*:\s*([^;]+)/i', $style, $m) === 1) { return trim($m[1]); diff --git a/tests/Svg/SvgGroupsTest.php b/tests/Svg/SvgGroupsTest.php index db65904..ed1c592 100644 --- a/tests/Svg/SvgGroupsTest.php +++ b/tests/Svg/SvgGroupsTest.php @@ -117,6 +117,17 @@ public function stroke_width_follows_the_composed_scale(): void self::assertStringContainsString("4 w\n", $stream); } + #[Test] + public function each_render_resolves_its_own_groups(): void + { + // Back-to-back renders, the same shape in different groups: nothing carries over. + self::assertStringContainsString('1 0 0 rg', self::stream('')); + self::assertStringContainsString('0 0 1 rg', self::stream('')); + $both = self::stream(''); + self::assertStringContainsString('1 0 0 rg', $both); + self::assertStringContainsString('0 1 0 rg', $both); + } + private static function stream(string $body): string { $page = PdfDocument::new()->addPage(customDimensionsPt: [100, 100]);