diff --git a/CHANGELOG.md b/CHANGELOG.md index dac2be6..0d38915 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ 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. +- `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. A generator is consumed once. +- 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. The `objectBoundingBox` of a curved path is the + curve's own extent, not the box of its control points, as in a browser. - `TtfFile::exportState()` and `TtfFile::fromState()` save a parsed font, kerning included, as plain data and restore it without parsing — for a cache across requests. A restore takes well under a millisecond against @@ -53,6 +67,42 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). the same errors as before. ### 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). +- 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. +- 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. +- 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. +- `` 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 + make a small file expand into millions of shapes and take minutes to + draw. A `` that would pass the cap is left out, and later + references to the same element are refused without counting it again, + so thousands of `` elements on one oversized group stay fast. +- `fill="url('#g')"` — a gradient reference in quotes or with spaces — + filled paths and other shapes but printed a plain `` black. +- `opacity`, `fill-opacity` and `stroke-opacity` were applied only to + untransformed rectangles, circles, ellipses and polygons: shapes under a + `transform`, and every `` and ``, printed opaque. - Embedded font subsets kept the source font's `head.checkSumAdjustment`, and the `head` entry of their table directory was summed with it, so the subset's checksums were wrong: strict validators and font tools flag such diff --git a/docs/de/USAGE.md b/docs/de/USAGE.md index f674c6c..ba156f9 100644 --- a/docs/de/USAGE.md +++ b/docs/de/USAGE.md @@ -722,6 +722,14 @@ 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. +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 Absatz —, kyrillischer und anderer nicht-lateinischer Text erscheint also wie diff --git a/docs/en/USAGE.md b/docs/en/USAGE.md index b9772f4..8121b9f 100644 --- a/docs/en/USAGE.md +++ b/docs/en/USAGE.md @@ -696,6 +696,12 @@ 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. +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 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 1627999..295466a 100644 --- a/docs/ru/USAGE.md +++ b/docs/ru/USAGE.md @@ -715,6 +715,12 @@ DocumentBuilder::new() `skewX`, `skewY`, `matrix`), `` / ``, стилизация через CSS-классы. +`fill-rule="evenodd"` — на элементе, в его `style`, в таблице стилей или на +группе — заливает пути и многоугольники по правилу чёт-нечет: отверстие, +нарисованное в ту же сторону, что и контур (кольцо, буква O), остаётся пустым. +Градиенты заливают любую фигуру в обоих `gradientUnits`; `fill`, `stroke` и их +прозрачность наследуются от групп, вложенные преобразования складываются. + `` набирается шрифтами документа — той же цепочкой семейств, запасными шрифтами и начертаниями, что и абзац, — поэтому кириллица и другие нелатинские письменности печатаются как в тексте; без встроенного шрифта diff --git a/docs/zh/USAGE.md b/docs/zh/USAGE.md index 4cc9619..7e6ee2a 100644 --- a/docs/zh/USAGE.md +++ b/docs/zh/USAGE.md @@ -665,6 +665,11 @@ DocumentBuilder::new() (`translate`、`scale`、`rotate`、`skewX`、`skewY`、`matrix`)、 `` / ``、CSS 类样式。 +`fill-rule="evenodd"`(写在元素上、其 `style` 中、样式表中或分组上)按奇偶规则 +填充 path 与多边形:与外轮廓同向绘制的孔(圆环、字母 O)保持镂空。 +渐变可填充任意图形,支持两种 `gradientUnits`;`fill`、`stroke` 及其不透明度 +从分组继承,嵌套的变换会依次叠加。 + `` 使用文档的字体排版 —— 与段落相同的字体族链、后备字体以及粗体/斜体 字形 —— 因此西里尔字母及其他非拉丁文字的显示与正文一致;没有嵌入字体时, 会退回到只含拉丁字形的 base-14 字体。`font-family`、`font-weight`、 diff --git a/src/Pdf/ContentStream.php b/src/Pdf/ContentStream.php index 5584af7..3728f25 100644 --- a/src/Pdf/ContentStream.php +++ b/src/Pdf/ContentStream.php @@ -253,31 +253,40 @@ 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 + * The commands can be any iterable: a generator is written as it is + * read, so a long path need not be held in memory. A generator is + * consumed once; pass a fresh one, or an array, to draw a path again. + * + * @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"; - 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']), @@ -285,7 +294,64 @@ public function emitPath( $this->formatNumber($strokeRgb['b']), ); } - foreach ($commands as $cmd) { + $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. A generator of + * commands is consumed once, as in emitPath(). + * + * @param iterable $commands as for emitPath() + */ + public function fillPathWithPattern(iterable $commands, string $patternName, bool $evenOdd = false): self + { + $commands = self::started($commands); + if ($commands === null) { + 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; + } + + /** + * 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(\Iterator $commands): void + { + for (; $commands->valid(); $commands->next()) { + $cmd = $commands->current(); if ($cmd === 'Z') { $this->body .= "h\n"; @@ -311,15 +377,6 @@ public function emitPath( ); } } - $op = match ($mode) { - 'stroke' => 'S', - 'fillstroke' => '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 7623438..1396bff 100644 --- a/src/Pdf/Page.php +++ b/src/Pdf/Page.php @@ -989,15 +989,38 @@ 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. A + * generator of commands is consumed once, as in emitPath(). + * + * @param iterable $commands as for emitPath() + */ + public function fillPathWithPattern(iterable $commands, string $patternName, bool $evenOdd = false): self + { + $this->stream->fillPathWithPattern($commands, $patternName, $evenOdd); + + return $this; + } + /** * Emit generic path (with cubic Bezier curves). * - * @param list $commands + * `$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. `$commands` can be a + * generator, which is written as it is read and consumed once. + * + * @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 ddac654..c0aac0f 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 */ @@ -45,11 +52,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; } @@ -273,7 +283,17 @@ 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; + self::$chainOf = null; + self::$chain = []; + } } /** @@ -300,6 +320,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, @@ -322,6 +343,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, @@ -380,13 +402,20 @@ private static function resolveUseReferences(\SimpleXMLElement $root): void } // Find all use elements. $uses = $root->xpath('//use') ?: []; + $copied = 0; + // Ids whose element was too big for what was left of the cap. It + // only grows and the room only shrinks, so they stay refused. + $refused = []; foreach ($uses as $use) { + if ($copied >= self::MAX_USE_COPIES) { + break; // Every copy takes at least one element. + } $href = (string) ($use['href'] ?? $use->attributes('xlink', true)?->href ?? ''); if ($href === '' || ! str_starts_with($href, '#')) { continue; } $refId = substr($href, 1); - if (! isset($idMap[$refId])) { + if (! isset($idMap[$refId]) || isset($refused[$refId])) { continue; } $ref = $idMap[$refId]; @@ -394,6 +423,15 @@ 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) { + $refused[$refId] = true; + + continue; + } + $copied += $size; $clone = $refDom->cloneNode(true); // Rename use → ref tag by replacing element. $newEl = $dom->ownerDocument->createElement($newName); @@ -441,14 +479,21 @@ 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 - * @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; @@ -473,12 +518,12 @@ private static function walkElement(\SimpleXMLElement $el, Page $page, callable $tag = $child->getName(); match ($tag) { 'rect' => self::renderRect($child, $page, $elTx, $elTy, $scaleX, $scaleY), - 'line' => self::renderLine($child, $page, $elTx, $elTy, $scaleX), + 'line' => self::withShapeOpacity($child, $page, static fn () => self::renderLine($child, $page, $elTx, $elTy, $scaleX)), 'circle' => self::renderCircle($child, $page, $elTx, $elTy, $scaleX, $scaleY), 'ellipse' => self::renderEllipse($child, $page, $elTx, $elTy, $scaleX, $scaleY), 'polygon' => self::renderPolygon($child, $page, $elTx, $elTy, true, $scaleX), 'polyline' => self::renderPolygon($child, $page, $elTx, $elTy, false, $scaleX), - 'path' => self::renderPath($child, $page, $elTx, $elTy, $scaleX), + 'path' => self::withShapeOpacity($child, $page, static fn () => self::renderPath($child, $page, $elTx, $elTy, $scaleX)), 'text' => self::renderText($child, $page, $elTx, $elTy, $scaleX), 'g' => self::walkElement($child, $page, $elTx, $elTy, $scaleX, $scaleY), 'defs' => null, // children referenced by , not rendered directly. @@ -534,19 +579,35 @@ private static function walkChildTransformed( $tag = $el->getName(); match ($tag) { - 'rect' => self::renderRectXY($el, $page, $px, $py, $effScale, $scaleY), - 'line' => self::renderLineXY($el, $page, $px, $py, $effScale), - 'circle' => self::renderEllipseXY($el, $page, $px, $py, $effScale, true), - 'ellipse' => self::renderEllipseXY($el, $page, $px, $py, $effScale, false), - 'polygon' => self::renderPolygonXY($el, $page, $px, $py, true, $effScale), - 'polyline' => self::renderPolygonXY($el, $page, $px, $py, false, $effScale), - 'path' => self::renderPathXY($el, $page, $px, $py, $effScale), + 'rect' => self::withShapeOpacity($el, $page, static fn () => self::renderRectXY($el, $page, $px, $py, $effScale, $scaleY)), + 'line' => self::withShapeOpacity($el, $page, static fn () => self::renderLineXY($el, $page, $px, $py, $effScale)), + 'circle' => self::withShapeOpacity($el, $page, static fn () => self::renderEllipseXY($el, $page, $px, $py, $effScale, true)), + 'ellipse' => self::withShapeOpacity($el, $page, static fn () => self::renderEllipseXY($el, $page, $px, $py, $effScale, false)), + 'polygon' => self::withShapeOpacity($el, $page, static fn () => self::renderPolygonXY($el, $page, $px, $py, true, $effScale)), + 'polyline' => self::withShapeOpacity($el, $page, static fn () => self::renderPolygonXY($el, $page, $px, $py, false, $effScale)), + 'path' => self::withShapeOpacity($el, $page, static fn () => self::renderPathXY($el, $page, $px, $py, $effScale)), 'text' => self::renderTextXY($el, $page, $px, $py, $effScale), 'g' => self::walkElementXY($el, $page, $px, $py, $effScale, $scaleY), default => null, }; } + /** + * Draws a shape inside its opacity, fill-opacity and stroke-opacity, + * for the renderers that do not apply them themselves. + * + * @param \Closure(): mixed $draw + */ + private static function withShapeOpacity(\SimpleXMLElement $el, Page $page, \Closure $draw): void + { + $opacity = self::parseOpacity($el, 'opacity', 1.0); + $page->withOpacity( + self::parseOpacity($el, 'fill-opacity', $opacity), + self::parseOpacity($el, 'stroke-opacity', $opacity), + $draw, + ); + } + /** * Walk children with (px, py) cross-coupled point transformers. * @@ -556,17 +617,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::withShapeOpacity($child, $page, static fn () => self::renderRectXY($child, $page, $cpx, $cpy, $cScale, $scaleY)), + 'line' => self::withShapeOpacity($child, $page, static fn () => self::renderLineXY($child, $page, $cpx, $cpy, $cScale)), + 'circle' => self::withShapeOpacity($child, $page, static fn () => self::renderEllipseXY($child, $page, $cpx, $cpy, $cScale, true)), + 'ellipse' => self::withShapeOpacity($child, $page, static fn () => self::renderEllipseXY($child, $page, $cpx, $cpy, $cScale, false)), + 'polygon' => self::withShapeOpacity($child, $page, static fn () => self::renderPolygonXY($child, $page, $cpx, $cpy, true, $cScale)), + 'polyline' => self::withShapeOpacity($child, $page, static fn () => self::renderPolygonXY($child, $page, $cpx, $cpy, false, $cScale)), + 'path' => self::withShapeOpacity($child, $page, static fn () => self::renderPathXY($child, $page, $cpx, $cpy, $cScale)), + 'text' => self::renderTextXY($child, $page, $cpx, $cpy, $cScale), + 'g' => self::walkElementXY($child, $page, $cpx, $cpy, $cScale, $scaleY), default => null, }; } @@ -674,9 +746,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)], @@ -684,7 +756,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) { @@ -704,8 +777,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); } @@ -723,26 +796,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(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); - - $segments = 36; - $points = []; - for ($i = 0; $i < $segments; $i++) { - $angle = 2 * M_PI * $i / $segments; - $sx = $cx + cos($angle) * $rx; - $sy = $cy + sin($angle) * $ry; - $points[] = [$px($sx, $sy), $py($sx, $sy)]; - } - if ($hasFill) { - $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); } /** @@ -758,20 +812,22 @@ 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 === []) { 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) { - $page->fillPolygon($pts, $fr, $fg, $fb); + 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) { $line = $pts; @@ -795,31 +851,56 @@ 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 - // 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]), @@ -827,23 +908,6 @@ private static function renderPathXY(\SimpleXMLElement $el, Page $page, callable ]; } } - - if ($hasFill && $hasStroke) { - $mode = 'fillstroke'; - } elseif ($hasFill) { - $mode = 'fill'; - } elseif ($hasStroke) { - $mode = 'stroke'; - } else { - return; - } - $page->emitPath( - $commands, - $mode, - $hasFill ? ['r' => $fr, 'g' => $fg, 'b' => $fb] : null, - $hasStroke ? ['r' => $sr, 'g' => $sg, 'b' => $sb] : null, - $sw * $scaleX, - ); } /** @@ -943,15 +1007,67 @@ 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. */ 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]); @@ -975,22 +1091,17 @@ private static function renderRect(\SimpleXMLElement $el, Page $page, callable $ $w = (float) ($el['width'] ?? 0); $h = (float) ($el['height'] ?? 0); - // Detect fill="url(#id)" → use shading pattern. - $fillAttr = (string) ($el['fill'] ?? '#000'); - $patternName = null; - if (preg_match('@^url\(#([^)]+)\)$@', trim($fillAttr), $m)) { - $gradId = $m[1]; - if (isset(self::$currentGradients[$gradId])) { - $patternName = self::createPatternFromGradient( - $page, self::$currentGradients[$gradId], - $tx($x), $ty($y + $h), $w * $scaleX, $h * $scaleY, - ); - } - } + // fill="url(#id)" naming a gradient → shading pattern. + $fillAttr = (string) (self::inheritedProperty($el, 'fill') ?? '#000'); + $gradient = self::gradientFor($el); + $patternName = $gradient === null ? null : self::createPatternFromGradient( + $page, $gradient, + $tx($x), $ty($y + $h), $w * $scaleX, $h * $scaleY, + ); [$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); @@ -1022,6 +1133,224 @@ 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; + } + if ($commands === []) { + return true; // Nothing to fill: no pattern left unused in the page's resources. + } + $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; + } + + /** + * The points that bound a path tightly, as SVG's objectBoundingBox + * takes it: every end point, and where a cubic curve turns in x or y. + * Control points are left out; a curve rarely reaches them. + * + * @param list $commands + * @return list + */ + private static function commandPoints(array $commands): array + { + $points = []; + $x = $y = $startX = $startY = 0.0; + foreach ($commands as $cmd) { + if (! is_array($cmd)) { + [$x, $y] = [$startX, $startY]; // Z returns to the subpath's start. + + continue; + } + if ($cmd[0] === 'C' && count($cmd) >= 7) { + $xs = [$x, (float) $cmd[1], (float) $cmd[3], (float) $cmd[5]]; + $ys = [$y, (float) $cmd[2], (float) $cmd[4], (float) $cmd[6]]; + foreach ([...self::cubicTurns($xs), ...self::cubicTurns($ys)] as $t) { + $points[] = [self::cubicAt($xs, $t), self::cubicAt($ys, $t)]; + } + [$x, $y] = [$xs[3], $ys[3]]; + } else { + [$x, $y] = [(float) $cmd[1], (float) $cmd[2]]; + if ($cmd[0] === 'M') { + [$startX, $startY] = [$x, $y]; + } + } + $points[] = [$x, $y]; + } + + return $points; + } + + /** + * The parameters in (0, 1) where one coordinate of a cubic Bézier + * turns: the roots of its derivative, a quadratic. + * + * @param array{0: float, 1: float, 2: float, 3: float} $p + * @return list + */ + private static function cubicTurns(array $p): array + { + $a = -$p[0] + 3 * $p[1] - 3 * $p[2] + $p[3]; + $b = 2 * ($p[0] - 2 * $p[1] + $p[2]); + $c = $p[1] - $p[0]; + if (abs($a) < 1e-12) { + $roots = abs($b) < 1e-12 ? [] : [-$c / $b]; + } else { + $disc = $b * $b - 4 * $a * $c; + $roots = $disc < 0 ? [] : [(-$b + sqrt($disc)) / (2 * $a), (-$b - sqrt($disc)) / (2 * $a)]; + } + + return array_values(array_filter($roots, static fn (float $t): bool => $t > 0 && $t < 1)); + } + + /** + * @param array{0: float, 1: float, 2: float, 3: float} $p + */ + private static function cubicAt(array $p, float $t): float + { + $u = 1 - $t; + + return $u * $u * $u * $p[0] + 3 * $u * $u * $t * $p[1] + 3 * $u * $t * $t * $p[2] + $t * $t * $t * $p[3]; + } + + /** + * 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. * @@ -1055,34 +1384,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, @@ -1105,8 +1407,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); } @@ -1136,40 +1438,72 @@ private static function renderEllipse(\SimpleXMLElement $el, Page $page, callabl } /** - * Ellipse → polygon approximation (36 segments). + * Ellipse with its opacity; drawn by drawEllipse(). * * @param callable(float): float $tx * @param callable(float): float $ty */ 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 = []; - for ($i = 0; $i < $segments; $i++) { - $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); + $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 ($page, $hasFill, $hasStroke, $points, $fr, $fg, $fb, $sr, $sg, $sb, $sw, $scaleX): void { - if ($hasFill) { - $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); + + 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 @@ -1181,17 +1515,19 @@ 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); + $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); $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 ($page, $closed, $hasFill, $hasStroke, $points, $fr, $fg, $fb, $sr, $sg, $sb, $sw, $scaleX): void { - if ($closed && $hasFill) { - $page->fillPolygon($points, $fr, $fg, $fb); + $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) { $line = $points; @@ -1238,23 +1574,26 @@ 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); - - $commands = self::parsePathD($d, $tx, $ty); - if ($commands === []) { - return; - } - - // Determine fill/stroke mode. - if ($hasFill && $hasStroke) { - $mode = 'fillstroke'; - } elseif ($hasFill) { - $mode = 'fill'; - } elseif ($hasStroke) { - $mode = 'stroke'; + [$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); + + // 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) { return; // Nothing to draw. } @@ -1276,16 +1615,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; @@ -1295,9 +1634,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 = []; @@ -1313,14 +1654,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; @@ -1331,7 +1672,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; @@ -1341,7 +1682,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; @@ -1351,7 +1692,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; @@ -1366,7 +1707,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; @@ -1387,7 +1728,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; @@ -1406,7 +1747,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; @@ -1428,7 +1769,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; @@ -1437,7 +1778,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; @@ -1457,7 +1798,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]), @@ -1471,8 +1812,18 @@ 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); } /** diff --git a/tests/Pdf/ContentStreamTest.php b/tests/Pdf/ContentStreamTest.php index 348af42..5785f24 100644 --- a/tests/Pdf/ContentStreamTest.php +++ b/tests/Pdf/ContentStreamTest.php @@ -66,6 +66,70 @@ 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()); + } + + #[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 + * 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 { 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(); + } +} diff --git a/tests/Svg/SvgDefsUseTest.php b/tests/Svg/SvgDefsUseTest.php index 2f557cd..222bb55 100644 --- a/tests/Svg/SvgDefsUseTest.php +++ b/tests/Svg/SvgDefsUseTest.php @@ -93,4 +93,59 @@ 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_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 + { + $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")); + } + + #[Test] + public function many_uses_of_a_group_over_the_limit_are_refused_at_once(): void + { + // Each of the oversized group is refused; counting its + // elements again for every one of them took seconds. + $big = ''.str_repeat('', \Dskripchenko\PhpPdf\Svg\SvgRenderer::MAX_USE_COPIES + 10_000).''; + $svg = ''.$big.'' + .str_repeat('', 20_000).''; + $page = \Dskripchenko\PhpPdf\Pdf\Document::new()->addPage(customDimensionsPt: [100, 100]); + + $start = microtime(true); + \Dskripchenko\PhpPdf\Svg\SvgRenderer::render($svg, $page, 0, 0, 100, 100); + $elapsed = microtime(true) - $start; + + self::assertSame(1, substr_count($page->rawContentStream()->toString(), "1 0 0 rg\n")); + self::assertLessThan(1.0, $elapsed, sprintf('%.2fs', $elapsed)); + } } 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)); + } +} diff --git a/tests/Svg/SvgGradientShapesTest.php b/tests/Svg/SvgGradientShapesTest.php new file mode 100644 index 0000000..00dfa52 --- /dev/null +++ b/tests/Svg/SvgGradientShapesTest.php @@ -0,0 +1,158 @@ +: 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 */ + #[Test] + public function the_bounding_box_hugs_a_curve_not_its_control_points(): void + { + // The curve's control points reach y = 10, the curve itself only y = 20: + // the box is 80 x 30 from (10, 20), not 80 x 40 from (10, 10). + [, $bytes] = self::render(''.self::STOPS.''.''); + + self::assertStringContainsString('/Matrix [80 0 0 -30 10 80]', $bytes); + } + + #[Test] + public function a_quadratic_curve_and_an_arc_bound_tightly_too(): void + { + // Q's control point is at y = 10; the curve peaks at y = 30. + [, $quad] = self::render(''.self::STOPS.''.''); + self::assertStringContainsString('/Matrix [80 0 0 -20 10 70]', $quad); + + // A half circle of radius 40 above y = 50. + [, $arc] = self::render(''.self::STOPS.''.''); + self::assertStringContainsString('/Matrix [80 0 0 -40 10 90]', $arc); + } + + #[Test] + public function a_path_with_no_commands_registers_no_pattern(): void + { + // userSpaceOnUse: no bounding box to find empty first. + [$stream, $bytes] = self::render(''.self::STOPS.'' + .''); + + self::assertStringNotContainsString('/Pattern', $stream); + self::assertStringNotContainsString('/PatternType', $bytes); + } + + 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()]; + } +} diff --git a/tests/Svg/SvgGradientTest.php b/tests/Svg/SvgGradientTest.php index 8f66e32..6e68339 100644 --- a/tests/Svg/SvgGradientTest.php +++ b/tests/Svg/SvgGradientTest.php @@ -120,4 +120,19 @@ public function two_gradients_emit_two_patterns(): void self::assertStringContainsString('/P1 scn', $bytes); self::assertStringContainsString('/P2 scn', $bytes); } + + #[Test] + public function a_quoted_gradient_reference_fills_a_plain_rect(): void + { + foreach (["url('#g1')", 'url("#g1")', 'url( #g1 )'] as $fill) { + $svg = '' + .'' + .''; + $bytes = (new Document(new Section([new SvgElement($svg)]))) + ->toBytes(new Engine(compressStreams: false)); + + self::assertStringContainsString('/P1 scn', $bytes, $fill); + self::assertStringNotContainsString("0 0 0 rg\n", $bytes, $fill); + } + } } diff --git a/tests/Svg/SvgGroupsTest.php b/tests/Svg/SvgGroupsTest.php new file mode 100644 index 0000000..ed1c592 --- /dev/null +++ b/tests/Svg/SvgGroupsTest.php @@ -0,0 +1,138 @@ +'; + + #[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); + } + + #[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()); + } + + #[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); + } + + #[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]); + SvgRenderer::render(''.$body.'', $page, 0, 0, 100, 100); + + return $page->rawContentStream()->toString(); + } +} 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()); + } +} diff --git a/tests/Svg/SvgOpacityTest.php b/tests/Svg/SvgOpacityTest.php index c496f54..dbce878 100644 --- a/tests/Svg/SvgOpacityTest.php +++ b/tests/Svg/SvgOpacityTest.php @@ -96,4 +96,34 @@ public function out_of_range_opacity_clamped(): void self::assertStringNotContainsString('/Type /ExtGState', $bytes); } + + #[Test] + public function transformed_shapes_and_paths_take_their_opacity(): void + { + $shapes = [ + '', + '', + '', + '', + '', + '', + ]; + foreach ($shapes as $shape) { + $bytes = (new Document(new Section([new SvgElement(''.$shape.'')]))) + ->toBytes(new Engine(compressStreams: false)); + + self::assertMatchesRegularExpression('@/(ca|CA) 0\.5@', $bytes, $shape); + self::assertMatchesRegularExpression('@/Gs\d+ gs@', $bytes, $shape); + } + } + + #[Test] + public function opaque_transformed_shapes_add_no_extgstate(): void + { + $svg = ''; + $bytes = (new Document(new Section([new SvgElement($svg)]))) + ->toBytes(new Engine(compressStreams: false)); + + self::assertStringNotContainsString('/Type /ExtGState', $bytes); + } }