From cb375e4568965d79a0e297446e96163bd8903cf1 Mon Sep 17 00:00:00 2001 From: Denis Skripchenko Date: Sun, 8 Nov 2026 23:35:28 +0300 Subject: [PATCH] feat(svg): stroke-dasharray and stroke-dashoffset Dashed strokes in SVG printed solid: the renderer never read the dash properties. Every stroked shape (line, polyline, polygon, path, rect, circle, ellipse) now gets its dash pattern, in plain and transformed groups alike, scaled as its stroke width. The properties resolve like the other presentation properties: element, style, style sheet, group. `none`, negative or non-absolute lengths and an all-zero list stroke solid; an odd list is repeated once; the offset becomes the PDF phase, wrapped into one period. The pattern is set inside a graphics state of its own (Page::withLineDashPattern(), on a new ContentStream::pushGraphicsState()), so it never reaches the next shape or the page outside the SVG. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 18 +++ docs/de/USAGE.md | 4 + docs/en/USAGE.md | 3 + docs/ru/USAGE.md | 4 + docs/zh/USAGE.md | 3 + src/Pdf/ContentStream.php | 8 ++ src/Pdf/Page.php | 26 ++++ src/Svg/SvgRenderer.php | 132 ++++++++++++++++---- tests/Svg/SvgStrokeDashTest.php | 215 ++++++++++++++++++++++++++++++++ 9 files changed, 392 insertions(+), 21 deletions(-) create mode 100644 tests/Svg/SvgStrokeDashTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 8efd775..43d4d2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ 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::withLineDashPattern()` draws inside a graphics state of its own + with a dash pattern, so the pattern ends with the drawing; + `ContentStream::pushGraphicsState()` saves the state without an + ExtGState. + +### Fixed +- SVG ignored `stroke-dasharray` and `stroke-dashoffset`, so dashed lines — + a chart's guide line, say — printed solid. Lines, polylines, polygons, + paths, rectangles, circles and ellipses now stroke with dashes, under + transforms too, scaled as their stroke width. The properties are read + from the element, its `style`, a style sheet or a group, as SVG resolves + them. `none`, a negative length, a list of zeros or a length in a + relative unit (`%`, `em`) strokes solid; a list of odd length is + repeated once. The pattern does not reach the next shape. + ## [1.26.0] — 2026-10-27 ### Added diff --git a/docs/de/USAGE.md b/docs/de/USAGE.md index ba156f9..b0f533e 100644 --- a/docs/de/USAGE.md +++ b/docs/de/USAGE.md @@ -729,6 +729,10 @@ 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. +Gestrichelte Konturen: `stroke-dasharray` und `stroke-dashoffset`, ebenso +gelesen, stricheln jede konturierte Form und skalieren mit ihr wie +`stroke-width`; `none` oder eine ungültige Liste ergibt eine durchgezogene +Linie, eine Liste ungerader Länge wird einmal wiederholt. `` 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 8121b9f..2103154 100644 --- a/docs/en/USAGE.md +++ b/docs/en/USAGE.md @@ -701,6 +701,9 @@ 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. +Dashed strokes: `stroke-dasharray` and `stroke-dashoffset`, read the same +way, dash every stroked shape and scale with it like `stroke-width`; `none` +or an invalid list strokes solid, and a list of odd length is repeated once. `` 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 295466a..e5c3dd8 100644 --- a/docs/ru/USAGE.md +++ b/docs/ru/USAGE.md @@ -720,6 +720,10 @@ CSS-классы. нарисованное в ту же сторону, что и контур (кольцо, буква O), остаётся пустым. Градиенты заливают любую фигуру в обоих `gradientUnits`; `fill`, `stroke` и их прозрачность наследуются от групп, вложенные преобразования складываются. +Пунктирная обводка: `stroke-dasharray` и `stroke-dashoffset` читаются так же и +делают пунктир у любой обведённой фигуры, масштабируясь вместе с ней, как +`stroke-width`; `none` или некорректный список дают сплошную линию, список +нечётной длины повторяется ещё раз. `` набирается шрифтами документа — той же цепочкой семейств, запасными шрифтами и начертаниями, что и абзац, — поэтому кириллица и другие diff --git a/docs/zh/USAGE.md b/docs/zh/USAGE.md index 7e6ee2a..18d950e 100644 --- a/docs/zh/USAGE.md +++ b/docs/zh/USAGE.md @@ -669,6 +669,9 @@ DocumentBuilder::new() 填充 path 与多边形:与外轮廓同向绘制的孔(圆环、字母 O)保持镂空。 渐变可填充任意图形,支持两种 `gradientUnits`;`fill`、`stroke` 及其不透明度 从分组继承,嵌套的变换会依次叠加。 +虚线描边:`stroke-dasharray` 与 `stroke-dashoffset` 以同样方式读取, +作用于所有带描边的图形,并像 `stroke-width` 一样随图形缩放;`none` +或无效的列表按实线描边,奇数个值的列表会重复一次。 `` 使用文档的字体排版 —— 与段落相同的字体族链、后备字体以及粗体/斜体 字形 —— 因此西里尔字母及其他非拉丁文字的显示与正文一致;没有嵌入字体时, diff --git a/src/Pdf/ContentStream.php b/src/Pdf/ContentStream.php index 3728f25..b2f9e33 100644 --- a/src/Pdf/ContentStream.php +++ b/src/Pdf/ContentStream.php @@ -848,6 +848,14 @@ public function pushGraphicsStateWithGs(string $gsName): self return $this; } + /** Saves the graphics state (q); pair with popGraphicsState(). */ + public function pushGraphicsState(): self + { + $this->body .= "q\n"; + + return $this; + } + public function popGraphicsState(): self { $this->body .= "Q\n"; diff --git a/src/Pdf/Page.php b/src/Pdf/Page.php index 1396bff..5454cd4 100644 --- a/src/Pdf/Page.php +++ b/src/Pdf/Page.php @@ -633,6 +633,32 @@ public function resetLineDashPattern(): self return $this; } + /** + * Runs `$draw` with a dash pattern inside its own graphics state + * (q … Q), so the pattern ends with it. An empty pattern draws solid + * and adds nothing to the content stream. + * + * @param list $pattern alternating on/off lengths + * @param callable(): mixed $draw + */ + public function withLineDashPattern(array $pattern, float $phase, callable $draw): self + { + if ($pattern === []) { + $draw(); + + return $this; + } + $this->stream->pushGraphicsState(); + $this->stream->setLineDashPattern($pattern, $phase); + try { + $draw(); + } finally { + $this->stream->popGraphicsState(); + } + + return $this; + } + /** Set line cap (0=butt, 1=round, 2=projecting square). */ public function setLineCap(int $cap): self { diff --git a/src/Svg/SvgRenderer.php b/src/Svg/SvgRenderer.php index c0aac0f..e0e5ee0 100644 --- a/src/Svg/SvgRenderer.php +++ b/src/Svg/SvgRenderer.php @@ -517,13 +517,13 @@ 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::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::withShapeOpacity($child, $page, static fn () => self::renderPath($child, $page, $elTx, $elTy, $scaleX)), + 'rect' => self::withDash($child, $page, $scaleX, static fn () => self::renderRect($child, $page, $elTx, $elTy, $scaleX, $scaleY)), + 'line' => self::withDash($child, $page, $scaleX, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderLine($child, $page, $elTx, $elTy, $scaleX))), + 'circle' => self::withDash($child, $page, $scaleX, static fn () => self::renderCircle($child, $page, $elTx, $elTy, $scaleX, $scaleY)), + 'ellipse' => self::withDash($child, $page, $scaleX, static fn () => self::renderEllipse($child, $page, $elTx, $elTy, $scaleX, $scaleY)), + 'polygon' => self::withDash($child, $page, $scaleX, static fn () => self::renderPolygon($child, $page, $elTx, $elTy, true, $scaleX)), + 'polyline' => self::withDash($child, $page, $scaleX, static fn () => self::renderPolygon($child, $page, $elTx, $elTy, false, $scaleX)), + 'path' => self::withDash($child, $page, $scaleX, static fn () => 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. @@ -579,13 +579,13 @@ private static function walkChildTransformed( $tag = $el->getName(); match ($tag) { - '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)), + 'rect' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderRectXY($el, $page, $px, $py, $effScale, $scaleY))), + 'line' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderLineXY($el, $page, $px, $py, $effScale))), + 'circle' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderEllipseXY($el, $page, $px, $py, $effScale, true))), + 'ellipse' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderEllipseXY($el, $page, $px, $py, $effScale, false))), + 'polygon' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderPolygonXY($el, $page, $px, $py, true, $effScale))), + 'polyline' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderPolygonXY($el, $page, $px, $py, false, $effScale))), + 'path' => self::withDash($el, $page, $effScale, static fn () => self::withShapeOpacity($el, $page, static fn () => self::renderPathXY($el, $page, $px, $py, $effScale))), 'text' => self::renderTextXY($el, $page, $px, $py, $effScale), 'g' => self::walkElementXY($el, $page, $px, $py, $effScale, $scaleY), default => null, @@ -608,6 +608,96 @@ private static function withShapeOpacity(\SimpleXMLElement $el, Page $page, \Clo ); } + /** + * Draws a shape with its `stroke-dasharray` and `stroke-dashoffset`, + * scaled to the page as its stroke width is. The pattern lives in its + * own graphics state, so it never reaches the next shape. A shape + * without a stroke, or with a solid one, is drawn as it is. + * + * @param \Closure(): mixed $draw + */ + private static function withDash(\SimpleXMLElement $el, Page $page, float $scale, \Closure $draw): void + { + $dash = self::dashPattern($el, $scale); + if ($dash === null) { + $draw(); + + return; + } + // A line strokes black by default here; other shapes only when asked. + $stroke = self::inheritedProperty($el, 'stroke') ?? ($el->getName() === 'line' ? '#000' : null); + if (! self::parseColor($stroke)[3]) { + $draw(); + + return; + } + $page->withLineDashPattern($dash[0], $dash[1], $draw); + } + + /** + * The dash pattern of an element's stroke in page units, with its + * phase — or null for a solid stroke. As SVG defines: `none`, an + * invalid list (a negative length, a length that is not one) and a + * list of zeros are solid; a list of odd length is repeated once. + * + * @return array{0: list, 1: float}|null + */ + private static function dashPattern(\SimpleXMLElement $el, float $scale): ?array + { + $raw = trim((string) self::inheritedProperty($el, 'stroke-dasharray')); + if ($raw === '' || strtolower($raw) === 'none') { + return null; + } + $tokens = preg_split('@\s*,\s*|\s+@', $raw) ?: []; + $lengths = []; + foreach ($tokens as $token) { + $length = self::dashLength($token); + if ($length === null || $length < 0) { + return null; + } + $lengths[] = $length; + } + if ($lengths === [] || array_sum($lengths) <= 0) { + return null; + } + if (count($lengths) % 2 === 1) { + $lengths = [...$lengths, ...$lengths]; + } + $pattern = array_map(static fn (float $l): float => $l * $scale, $lengths); + + // The offset may be negative or longer than the pattern; the PDF + // phase is the same point within one period. + $offset = self::dashLength(trim((string) self::inheritedProperty($el, 'stroke-dashoffset'))) ?? 0.0; + $period = array_sum($pattern); + $phase = fmod($offset * $scale, $period); + if ($phase < 0) { + $phase += $period; + } + + return [$pattern, $phase]; + } + + /** + * A dash length in user units: a number, bare or in px, or in an + * absolute unit (pt, pc, mm, cm, in). Null for anything else. + */ + private static function dashLength(string $token): ?float + { + if (preg_match('@^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(px|pt|pc|mm|cm|in)?$@i', $token, $m) !== 1) { + return null; + } + $factor = match (strtolower($m[2] ?? '')) { + 'pt' => 4 / 3, + 'pc' => 16.0, + 'mm' => 96 / 25.4, + 'cm' => 96 / 2.54, + 'in' => 96.0, + default => 1.0, + }; + + return (float) $m[1] * $factor; + } + /** * Walk children with (px, py) cross-coupled point transformers. * @@ -630,13 +720,13 @@ private static function walkElementXY(\SimpleXMLElement $el, Page $page, callabl } $tag = $child->getName(); match ($tag) { - '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)), + 'rect' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderRectXY($child, $page, $cpx, $cpy, $cScale, $scaleY))), + 'line' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderLineXY($child, $page, $cpx, $cpy, $cScale))), + 'circle' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderEllipseXY($child, $page, $cpx, $cpy, $cScale, true))), + 'ellipse' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderEllipseXY($child, $page, $cpx, $cpy, $cScale, false))), + 'polygon' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderPolygonXY($child, $page, $cpx, $cpy, true, $cScale))), + 'polyline' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderPolygonXY($child, $page, $cpx, $cpy, false, $cScale))), + 'path' => self::withDash($child, $page, $cScale, static fn () => self::withShapeOpacity($child, $page, static fn () => self::renderPathXY($child, $page, $cpx, $cpy, $cScale))), 'text' => self::renderTextXY($child, $page, $cpx, $cpy, $cScale), 'g' => self::walkElementXY($child, $page, $cpx, $cpy, $cScale, $scaleY), default => null, diff --git a/tests/Svg/SvgStrokeDashTest.php b/tests/Svg/SvgStrokeDashTest.php new file mode 100644 index 0000000..aad676b --- /dev/null +++ b/tests/Svg/SvgStrokeDashTest.php @@ -0,0 +1,215 @@ +'); + + self::assertMatchesRegularExpression('@q\n\[4 4\] 0 d\n.*?\nS\nQ\nQ\n@s', $bytes); + } + + #[Test] + public function the_pattern_does_not_reach_the_next_shape(): void + { + $bytes = self::render( + '' + .'', + ); + + self::assertSame(1, substr_count($bytes, ' d'."\n")); + // The dashed line's state is closed before the solid line opens. + self::assertMatchesRegularExpression('@\[4 4\] 0 d\n(?:(?!\nq\n).)*?S\nQ\nQ\nq\n[^\n]+ w\n1 0 0 RG@s', $bytes); + self::assertStatesBalanced($bytes); + } + + #[Test] + public function the_pattern_is_scaled_as_the_stroke_width(): void + { + // A 50-unit viewBox in the 100-unit box: everything doubles. + $bytes = self::render( + '', + '0 0 50 50', + ); + + self::assertStringContainsString("[8 4] 2 d\n", $bytes); + self::assertStringContainsString("\n2 w\n", $bytes); + } + + #[Test] + public function dasharray_is_inherited_from_a_group(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("[5 3] 0 d\n", $bytes); + } + + #[Test] + public function the_element_overrides_its_group(): void + { + $bytes = self::render(''); + + self::assertStringNotContainsString(' d'."\n", $bytes); + } + + #[Test] + public function dasharray_from_a_style_attribute(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("[6 2] 3 d\n", $bytes); + } + + #[Test] + public function dasharray_from_a_style_sheet(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("[4 4] 0 d\n", $bytes); + } + + #[Test] + public function an_odd_count_is_repeated_once(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("[5 3 2 5 3 2] 0 d\n", $bytes); + } + + #[Test] + public function a_single_length_is_on_and_off(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("[3 3] 0 d\n", $bytes); + } + + #[Test] + #[DataProvider('solidValues')] + public function none_and_invalid_values_stroke_solid(string $value): void + { + $bytes = self::render(''); + + self::assertStringNotContainsString(' d'."\n", $bytes); + self::assertStringContainsString("\nS\n", $bytes); + } + + /** @return iterable */ + public static function solidValues(): iterable + { + yield 'none' => ['none']; + yield 'empty' => ['']; + yield 'negative' => ['4 -2']; + yield 'all zero' => ['0 0']; + yield 'not a length' => ['4 abc']; + yield 'relative unit' => ['4 10%']; + } + + #[Test] + public function the_offset_becomes_the_phase(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("[4 4] 2 d\n", $bytes); + } + + #[Test] + public function a_negative_offset_wraps_into_the_period(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("[4 4] 5 d\n", $bytes); + } + + #[Test] + public function dashes_apply_to_rect_circle_ellipse_and_polygon(): void + { + $bytes = self::render( + '' + .'' + .'' + .'' + .'', + ); + + foreach (['1 1', '2 2', '3 3', '4 4', '5 5'] as $pattern) { + self::assertStringContainsString('['.$pattern."] 0 d\n", $bytes); + } + self::assertStatesBalanced($bytes); + } + + #[Test] + public function a_shape_without_a_stroke_gets_no_pattern(): void + { + $bytes = self::render(''); + + self::assertStringNotContainsString(' d'."\n", $bytes); + } + + #[Test] + public function dashes_apply_inside_a_transformed_group(): void + { + // scale(2) doubles the stroke width and the dashes alike. + $bytes = self::render( + '' + .'' + .'' + .'' + .'' + .'', + ); + + self::assertSame(3, substr_count($bytes, "[8 4] 2 d\n")); + self::assertSame(3, substr_count($bytes, ' d'."\n")); + self::assertStatesBalanced($bytes); + } + + #[Test] + public function a_transformed_shape_scales_its_own_dashes(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("[3 6] 0 d\n", $bytes); + } + + #[Test] + public function absolute_units_are_converted_to_user_units(): void + { + $bytes = self::render(''); + + self::assertStringContainsString("[4 4] 0 d\n", $bytes); + } + + private static function assertStatesBalanced(string $bytes): void + { + self::assertSame(preg_match_all('@^q$@m', $bytes), preg_match_all('@^Q$@m', $bytes)); + } + + private static function render(string $body, string $viewBox = '0 0 100 100'): string + { + $svg = ''.$body.''; + $doc = new Document(new Section([new SvgElement($svg, widthPt: 100, heightPt: 100)])); + + return $doc->toBytes(new Engine(compressStreams: false)); + } +}