Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docs/de/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

`<text>` wird in den Schriften des Dokuments gesetzt — dieselbe
Familienkette, dieselben Ersatzschriften und Fett-/Kursivschnitte wie ein
Expand Down
3 changes: 3 additions & 0 deletions docs/en/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

`<text>` 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
Expand Down
4 changes: 4 additions & 0 deletions docs/ru/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,10 @@ CSS-классы.
нарисованное в ту же сторону, что и контур (кольцо, буква O), остаётся пустым.
Градиенты заливают любую фигуру в обоих `gradientUnits`; `fill`, `stroke` и их
прозрачность наследуются от групп, вложенные преобразования складываются.
Пунктирная обводка: `stroke-dasharray` и `stroke-dashoffset` читаются так же и
делают пунктир у любой обведённой фигуры, масштабируясь вместе с ней, как
`stroke-width`; `none` или некорректный список дают сплошную линию, список
нечётной длины повторяется ещё раз.

`<text>` набирается шрифтами документа — той же цепочкой семейств,
запасными шрифтами и начертаниями, что и абзац, — поэтому кириллица и другие
Expand Down
3 changes: 3 additions & 0 deletions docs/zh/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,9 @@ DocumentBuilder::new()
填充 path 与多边形:与外轮廓同向绘制的孔(圆环、字母 O)保持镂空。
渐变可填充任意图形,支持两种 `gradientUnits`;`fill`、`stroke` 及其不透明度
从分组继承,嵌套的变换会依次叠加。
虚线描边:`stroke-dasharray` 与 `stroke-dashoffset` 以同样方式读取,
作用于所有带描边的图形,并像 `stroke-width` 一样随图形缩放;`none`
或无效的列表按实线描边,奇数个值的列表会重复一次。

`<text>` 使用文档的字体排版 —— 与段落相同的字体族链、后备字体以及粗体/斜体
字形 —— 因此西里尔字母及其他非拉丁文字的显示与正文一致;没有嵌入字体时,
Expand Down
8 changes: 8 additions & 0 deletions src/Pdf/ContentStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
26 changes: 26 additions & 0 deletions src/Pdf/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<float> $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
{
Expand Down
132 changes: 111 additions & 21 deletions src/Svg/SvgRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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, // <defs> children referenced by <use>, not rendered directly.
Expand Down Expand Up @@ -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,
Expand All @@ -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<float>, 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.
*
Expand All @@ -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,
Expand Down
Loading
Loading