Skip to content
Closed
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
48 changes: 48 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,54 @@ All notable changes to `dskripchenko/php-pdf` are documented in this file.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added
- `Page::emitPath()` and `ContentStream::emitPath()` take the modes
`'fill-evenodd'` (`f*`) and `'fillstroke-evenodd'` (`B*`), which fill by
the even-odd rule: a subpath inside another is a hole whichever way round
it is drawn.
- `Page::fillPathWithPattern()` and `ContentStream::fillPathWithPattern()`
fill any path with a registered shading pattern.
- `emitPath()` and `fillPathWithPattern()` take any iterable of commands,
so a generator is written as it is read.
- SVG gradients fill paths, polygons, circles, ellipses and transformed
rectangles, not only plain rectangles, and honour
`gradientUnits="userSpaceOnUse"`. The pattern follows the shape's
transforms, its bounding box and `gradientTransform`. Before, those
shapes printed black.

### Fixed
- SVG ignored `fill-rule`, so every path and polygon filled by the nonzero
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.

## [1.25.0] — 2026-10-19

### Fixed
Expand Down
8 changes: 8 additions & 0 deletions docs/de/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,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 @@ -637,6 +637,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 @@ -655,6 +655,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 @@ -611,6 +611,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
87 changes: 71 additions & 16 deletions src/Pdf/ContentStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,39 +253,103 @@ 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.
*
* @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.
*
* @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 +375,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
26 changes: 24 additions & 2 deletions src/Pdf/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -989,15 +989,37 @@ public function strokePolyline(
return $this;
}

/**
* Fills a path with a shading pattern from registerShadingPattern(), by
* the nonzero or (with $evenOdd) the even-odd rule. The pattern's
* matrix maps its space onto the page's default coordinates.
*
* @param 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.
*
* @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