Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
1b50038
feat(pdf): even-odd fill modes for emitPath
serpentblade Oct 20, 2026
4280c32
fix(svg): honour fill-rule="evenodd" on paths and polygons
serpentblade Oct 20, 2026
892ab1e
fix(svg): gradients fill rects inside groups
serpentblade Oct 20, 2026
273d661
fix(svg): shapes inherit fill and stroke from their groups
serpentblade Oct 20, 2026
c719016
fix(svg): nested transforms compose
serpentblade Oct 20, 2026
45ec0d0
feat(svg): gradient fills on every shape
serpentblade Oct 20, 2026
107e8ee
fix(svg): cap the elements <use> may copy
serpentblade Oct 20, 2026
8003706
test(svg): a group that uses itself stays within the <use> cap
serpentblade Oct 20, 2026
84d7e79
perf(svg): stream path data instead of holding it in arrays
serpentblade Oct 20, 2026
9393825
perf(svg): circles and ellipses as four Bézier curves
serpentblade Oct 20, 2026
5db367e
perf(svg): find a shape's ancestors once, not per property
serpentblade Oct 20, 2026
0a1e2b9
fix(svg): refuse an oversized <use> target once, not per reference
dskripchenko Oct 27, 2026
fa3fea4
fix(svg): plain rects read the gradient like every other shape
dskripchenko Oct 27, 2026
c0b5c02
fix(svg): bound gradient-filled curves tightly, not by their control …
dskripchenko Oct 27, 2026
1b5adf2
chore(svg): no unused pattern for an empty path; note one-shot genera…
dskripchenko Oct 27, 2026
2cc9134
fix(svg): opacity on transformed shapes, paths and lines
dskripchenko Oct 27, 2026
8749622
docs(changelog): note the review fixes for SVG fills and gradients
dskripchenko Oct 27, 2026
be71e56
Merge remote-tracking branch 'origin/main' into feat/svg-fill-rules-a…
dskripchenko Oct 27, 2026
425d668
Merge remote-tracking branch 'origin/main' into feat/svg-fill-rules-a…
dskripchenko Oct 27, 2026
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
50 changes: 50 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 `<rect>` inside a `<g>` 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
`<g fill="#f00">` 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: `<g transform="scale(2)"><g transform="translate(2,2)">`, 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.
- `<use>` copies are capped at `SvgRenderer::MAX_USE_COPIES` (50,000)
elements per document. `<use>` elements that refer to groups of
`<use>` elements, or a group with `<use>` references to itself, could
make a small file expand into millions of shapes and take minutes to
draw. A `<use>` that would pass the cap is left out, and later
references to the same element are refused without counting it again,
so thousands of `<use>` 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 `<rect>` black.
- `opacity`, `fill-opacity` and `stroke-opacity` were applied only to
untransformed rectangles, circles, ellipses and polygons: shapes under a
`transform`, and every `<path>` and `<line>`, 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
Expand Down
8 changes: 8 additions & 0 deletions docs/de/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,14 @@ Bézierkurven), Formen (`<rect>`, `<circle>`, `<ellipse>`, `<line>`,
Transformationen (`translate`, `scale`, `rotate`, `skewX`, `skewY`,
`matrix`), `<use>` / `<defs>`, 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.

`<text>` 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
Expand Down
6 changes: 6 additions & 0 deletions docs/en/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,12 @@ shapes (`<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polyline>`,
(`translate`, `scale`, `rotate`, `skewX`, `skewY`, `matrix`),
`<use>` / `<defs>`, 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.

`<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
prints as it does in the body; without an embedded font it falls back to a
Expand Down
6 changes: 6 additions & 0 deletions docs/ru/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,12 @@ DocumentBuilder::new()
`skewX`, `skewY`, `matrix`), `<use>` / `<defs>`, стилизация через
CSS-классы.

`fill-rule="evenodd"` — на элементе, в его `style`, в таблице стилей или на
группе — заливает пути и многоугольники по правилу чёт-нечет: отверстие,
нарисованное в ту же сторону, что и контур (кольцо, буква O), остаётся пустым.
Градиенты заливают любую фигуру в обоих `gradientUnits`; `fill`, `stroke` и их
прозрачность наследуются от групп, вложенные преобразования складываются.

`<text>` набирается шрифтами документа — той же цепочкой семейств,
запасными шрифтами и начертаниями, что и абзац, — поэтому кириллица и другие
нелатинские письменности печатаются как в тексте; без встроенного шрифта
Expand Down
5 changes: 5 additions & 0 deletions docs/zh/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,11 @@ DocumentBuilder::new()
(`translate`、`scale`、`rotate`、`skewX`、`skewY`、`matrix`)、
`<use>` / `<defs>`、CSS 类样式。

`fill-rule="evenodd"`(写在元素上、其 `style` 中、样式表中或分组上)按奇偶规则
填充 path 与多边形:与外轮廓同向绘制的孔(圆环、字母 O)保持镂空。
渐变可填充任意图形,支持两种 `gradientUnits`;`fill`、`stroke` 及其不透明度
从分组继承,嵌套的变换会依次叠加。

`<text>` 使用文档的字体排版 —— 与段落相同的字体族链、后备字体以及粗体/斜体
字形 —— 因此西里尔字母及其他非拉丁文字的显示与正文一致;没有嵌入字体时,
会退回到只含拉丁字形的 base-14 字体。`font-family`、`font-weight`、
Expand Down
89 changes: 73 additions & 16 deletions src/Pdf/ContentStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,39 +253,105 @@ 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<array{0: string, 1: float, 2: float, 3?: float, 4?: float, 5?: float, 6?: float}|string> $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<array{0: string, 1: float, 2: float, 3?: float, 4?: float, 5?: float, 6?: float}|string> $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']),
$this->formatNumber($strokeRgb['g']),
$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<array{0: string, 1: float, 2: float, 3?: float, 4?: float, 5?: float, 6?: float}|string> $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<array{0: string, 1: float, 2: float, 3?: float, 4?: float, 5?: float, 6?: float}|string> $commands
* @return \Iterator<array{0: string, 1: float, 2: float, 3?: float, 4?: float, 5?: float, 6?: float}|string>|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<array{0: string, 1: float, 2: float, 3?: float, 4?: float, 5?: float, 6?: float}|string> $commands already started
*/
private function appendPathCommands(\Iterator $commands): void
{
for (; $commands->valid(); $commands->next()) {
$cmd = $commands->current();
if ($cmd === 'Z') {
$this->body .= "h\n";

Expand All @@ -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;
}

/**
Expand Down
27 changes: 25 additions & 2 deletions src/Pdf/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<array{0: string, 1: float, 2: float, 3?: float, 4?: float, 5?: float, 6?: float}|string> $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<array{0: string, 1: float, 2: float, 3?: float, 4?: float, 5?: float, 6?: float}|string> $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<array{0: string, 1: float, 2: float, 3?: float, 4?: float, 5?: float, 6?: float}|string> $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,
Expand Down
Loading
Loading