Files
laraundfelix/app/Domain/Catalog/PdfFlow.php
T

623 lines
23 KiB
PHP

<?php
namespace App\Domain\Catalog;
use App\Domain\Commerce\Receipt\PdfDocument;
use Closure;
use Transliterator;
/**
* Satz für gedruckte Ausgaben (Übung, Dokument): Überschriften, Absätze mit fett und kursiv, Listen, Tabellen und Bilder
* aus den Blöcken von {@see FormattedText::blocks()}. Übung und Dokument setzen mit demselben Baustein; so sehen
* Tabellen und Bilder in beiden gleich aus.
*
* Der Satz kennt weder Seitenkopf noch Fußzeile: Passt etwas nicht mehr auf die Seite, ruft er `$breakPage` auf. Diese
* Funktion schließt die Seite und öffnet die nächste; danach beginnt der Satz wieder am oberen Rand.
*/
final class PdfFlow
{
public float $y;
/** Schachtelungstiefe beim Setzen einer Tabelle (Zelleninhalt setzt nie wieder eine Tabelle). */
private int $depth = 0;
/**
* @param Closure(): void $breakPage
* @param (Closure(int): ?array{jpeg?: string, width?: int, height?: int, note?: string})|null $images Löst ein Bild auf: JPEG mit Maßen,
* ein Hinweistext oder null (entfällt)
*/
public function __construct(
private readonly PdfDocument $pdf,
private readonly float $left,
private readonly float $right,
private readonly float $top,
private readonly float $bottom,
private readonly Closure $breakPage,
private readonly ?Closure $images = null,
) {
$this->y = $top;
}
/**
* Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere
* lateinische Buchstaben); sonst bleibt „?“.
*/
public static function printable(string $text): string
{
$text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']);
$latin = Transliterator::create('Any-Latin; Latin-ASCII');
$out = '';
foreach (mb_str_split($text) as $char) {
$encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8');
$out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char;
}
return $out;
}
/** Beginn einer neuen Seite: der Satz steht wieder am oberen Rand. */
public function restart(): void
{
$this->y = $this->top;
}
public function room(float $needed): void
{
if ($this->y - $needed < $this->bottom) {
($this->breakPage)();
$this->y = $this->top;
}
}
/** Eine Überschrift oder ein kurzer Text in Zeilen nach {@see PdfDocument::wrap()}. `$keep` hält Platz für folgenden Text frei. */
public function write(string $text, float $size, bool $bold, float $after, float $keep = 0, ?float $x = null): void
{
$x ??= $this->left;
$lines = PdfDocument::wrap($text, $this->right - $x, $size, $bold);
if ($keep > 0 && $lines !== []) {
$this->room(count($lines) * ($size + 4) + $keep);
}
foreach ($lines as $line) {
$this->room($size + 4);
$this->pdf->text($x, $this->y, $line, $size, $bold);
$this->y -= $size + 4;
}
$this->y -= $after;
}
/**
* Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat, Listen, Tabelle und Bild.
*
* @param list<array<string, mixed>> $blocks
*/
public function formatted(array $blocks, ?float $x = null, float $size = 10.5): void
{
$x ??= $this->left;
foreach ($blocks as $block) {
match ($block['type']) {
'heading' => $this->headingBlock($block, $x, $size),
'quote' => $this->runs($block['runs'], $x + 14, $size, italic: true, after: 5),
'bullets' => $this->listItems($block['items'], fn (int $n): string => '•', $x, $size),
'numbered' => $this->listItems($block['items'], fn (int $n): string => $n.'.', $x, $size),
'table' => $this->table($block['rows'], $x),
'image' => $this->image($block, $x),
default => $this->runs($block['runs'] ?? [], $x, $size, after: 5),
};
}
}
/**
* @param array<string, mixed> $block
*/
private function headingBlock(array $block, float $x, float $size): void
{
// Eine Zwischenüberschrift bleibt bei ihrem Text: mindestens zwei Zeilen müssen mit auf die Seite.
$this->room(($size + 0.5) + 4 + 2 * ($size + 4));
$this->runs($block['runs'], $x, $size + 0.5, bold: true, after: 4);
}
/**
* @param list<list<array{text: string, bold: bool, italic: bool, href: ?string}>> $items
* @param callable(int): string $marker
*/
public function listItems(array $items, callable $marker, ?float $x = null, float $size = 10.5): void
{
$x ??= $this->left;
foreach ($items as $index => $item) {
$this->room(14);
$this->pdf->text($x + 4, $this->y, $marker($index + 1), $size);
$this->runs($item, $x + 18, $size, after: 1);
}
$this->y -= 3;
}
/**
* Setzt Textabschnitte mit fett und kursiv in Zeilen um und zeichnet sie. Links erscheinen mit ausgeschriebener
* Adresse, weil sie auf Papier sonst verloren gehen.
*
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
*/
public function runs(array $runs, float $x, float $size, bool $bold = false, bool $italic = false, float $after = 0): void
{
foreach ($this->lines($runs, $this->right - $x, $size, $bold, $italic) as $row) {
$this->room($size + 4);
$cursor = $x;
foreach ($row as [$text, $isBold, $isItalic]) {
$this->pdf->text($cursor, $this->y, $text, $size, $isBold, $isItalic);
$cursor += PdfDocument::exactWidth($text, $size, $isBold);
}
$this->y -= $size + 4;
}
$this->y -= $after;
}
/**
* Zeilen aus Textabschnitten für eine Breite. Die Breite kommt aus den Schriftbreiten der Helvetica
* ({@see PdfDocument::exactWidth()}), damit verschiedene Schnitte in einer Zeile ohne Lücken aneinanderstoßen.
*
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
* @return list<list<array{0: string, 1: bool, 2: bool}>>
*/
public function lines(array $runs, float $maxWidth, float $size, bool $bold = false, bool $italic = false): array
{
$lines = [];
$line = [];
$width = 0.0;
$pendingSpace = false;
$count = count($runs);
$flush = function () use (&$lines, &$line, &$width, &$pendingSpace): void {
if ($line !== []) {
$lines[] = $line;
}
$line = [];
$width = 0.0;
$pendingSpace = false;
};
$place = function (string $word, bool $isBold, bool $isItalic) use (&$line, &$width, &$pendingSpace, $maxWidth, $size, $flush): void {
$space = $pendingSpace && $line !== [] ? ' ' : '';
$need = PdfDocument::exactWidth($space.$word, $size, $isBold);
if ($line !== [] && $width + $need > $maxWidth) {
$flush();
$space = '';
$need = PdfDocument::exactWidth($word, $size, $isBold);
}
while ($need > $maxWidth && mb_strlen($word) > 1) {
$cut = mb_strlen($word) - 1;
while ($cut > 1 && PdfDocument::exactWidth(mb_substr($word, 0, $cut), $size, $isBold) > $maxWidth) {
$cut--;
}
$line[] = [mb_substr($word, 0, $cut), $isBold, $isItalic];
$flush();
$word = mb_substr($word, $cut);
$need = PdfDocument::exactWidth($word, $size, $isBold);
}
$last = $line === [] ? null : $line[array_key_last($line)];
if ($last !== null && $last[1] === $isBold && $last[2] === $isItalic) {
$line[array_key_last($line)][0] .= $space.$word;
} else {
$line[] = [$space.$word, $isBold, $isItalic];
}
$width += $need;
$pendingSpace = false;
};
foreach ($runs as $index => $run) {
$isBold = $bold || $run['bold'];
$isItalic = $italic || $run['italic'];
foreach (preg_split('/(\s+)/u', self::printable($run['text']), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) ?: [] as $token) {
if (trim($token) !== '') {
$place($token, $isBold, $isItalic);
continue;
}
if (str_contains($token, "\n")) {
$flush();
continue;
}
$pendingSpace = true;
}
$nextHref = $index + 1 < $count ? $runs[$index + 1]['href'] : null;
if ($run['href'] !== null && $nextHref !== $run['href'] && ! str_contains($run['text'], $run['href'])) {
$pendingSpace = true;
$place('('.self::printable($run['href']).')', false, false);
}
}
$flush();
return $lines;
}
/**
* Ein Bild in Breite der Spalte, höchstens 320 Punkt hoch. Ein Bild lässt sich nicht teilen: Es steht ganz auf einer
* Seite. Kann das Bild nicht gezeigt werden, steht an seiner Stelle der Hinweis.
*
* @param array<string, mixed> $block
*/
private function image(array $block, float $x): void
{
$found = $this->images === null ? null : ($this->images)((int) $block['id']);
if ($found === null) {
return;
}
if (! isset($found['jpeg'])) {
$this->runs([['text' => '['.($found['note'] ?? 'Bild nicht verfügbar').']', 'bold' => false, 'italic' => true, 'href' => null]], $x, 9.5, after: 5);
return;
}
$available = $this->right - $x;
$scale = min(1.0, $available / max(1, $found['width']), 320.0 / max(1, $found['height']));
$width = max(1.0, $found['width'] * $scale);
$height = max(1.0, $found['height'] * $scale);
$this->room($height + 16);
$this->pdf->image($x, $this->y + 4 - $height, $width, $height, $found['jpeg'], $found['width'], $found['height']);
$this->y -= $height + 16;
}
/**
* Eine Tabelle mit Rahmen. Die Spaltenbreiten folgen dem Inhalt (Spalten mit kurzem Text bleiben schmal), Verbindungen
* über Spalten und Zeilen werden gesetzt. Eine Zeile bleibt zusammen; auf jeder Folgeseite stehen die Kopfzeilen
* erneut. Ist eine einzelne Zeile höher als eine Seite, erscheint ihr Inhalt als Fließtext.
*
* @param list<list<array<string, mixed>>> $rows
*/
private function table(array $rows, float $x): void
{
if ($this->depth > 0 || $rows === []) {
// Tabellen in Tabellen kennt der Editor nicht; sicherheitshalber als Fließtext.
foreach ($rows as $row) {
foreach ($row as $cell) {
$this->formatted($cell['blocks'], $x);
}
}
return;
}
$size = 9.5;
$pad = 3.5;
$lineHeight = $size + 3;
$grid = $this->grid($rows);
$columns = $grid['columns'];
$widths = $this->columnWidths($grid['cells'], $columns, $this->right - $x, $size, $pad);
$headRows = 0;
foreach ($rows as $row) {
if ($row !== [] && count(array_filter($row, fn (array $cell): bool => $cell['header'])) === count($row)) {
$headRows++;
continue;
}
break;
}
$headRows = $headRows === count($rows) ? 0 : $headRows;
$prepared = [];
foreach ($grid['cells'] as $cell) {
$inner = array_sum(array_slice($widths, $cell['column'], $cell['colspan'])) - 2 * $pad;
$this->depth++;
$cell['lines'] = $this->cellLines($cell['blocks'], max(10.0, $inner), $size, $cell['header']);
$this->depth--;
$cell['height'] = max($lineHeight, array_sum(array_column($cell['lines'], 'height'))) + 2 * $pad;
$prepared[] = $cell;
}
$rowCount = count($rows);
$heights = array_fill(0, $rowCount, $lineHeight + 2 * $pad);
foreach ($prepared as $cell) {
if ($cell['rowspan'] === 1) {
$heights[$cell['row']] = max($heights[$cell['row']], $cell['height']);
}
}
foreach ($prepared as $cell) {
if ($cell['rowspan'] > 1) {
$last = min($rowCount - 1, $cell['row'] + $cell['rowspan'] - 1);
$have = array_sum(array_slice($heights, $cell['row'], $last - $cell['row'] + 1));
$heights[$last] += max(0.0, $cell['height'] - $have);
}
}
$pageHeight = $this->top - $this->bottom;
if (max($heights) > $pageHeight - 8) {
foreach ($rows as $row) {
foreach ($row as $cell) {
$this->formatted($cell['blocks'], $x);
}
}
return;
}
$drawRows = function (int $from, int $to) use ($prepared, $widths, $heights, $x, $size, $pad): void {
$y = $this->y;
for ($r = $from; $r <= $to; $r++) {
foreach ($prepared as $cell) {
if ($cell['row'] !== $r) {
continue;
}
$cellLeft = $x + array_sum(array_slice($widths, 0, $cell['column']));
$cellWidth = array_sum(array_slice($widths, $cell['column'], $cell['colspan']));
$cellHeight = array_sum(array_slice($heights, $r, $cell['rowspan']));
$this->frame($cellLeft, $y - $cellHeight, $cellWidth, $cellHeight, $cell['header']);
$textY = $y - $pad - $size;
foreach ($cell['lines'] as $line) {
if (isset($line['image'])) {
$this->pdf->image($cellLeft + $pad, $textY + $size - $line['image']['height'], $line['image']['width'], $line['image']['height'], $line['image']['jpeg'], $line['image']['pixelWidth'], $line['image']['pixelHeight']);
$textY -= $line['height'];
continue;
}
if ($line['marker'] !== null) {
$this->pdf->text($cellLeft + $pad + $line['indent'] - 12, $textY, $line['marker'], $size, $cell['header']);
}
$cursor = $cellLeft + $pad + $line['indent'];
foreach ($line['segments'] as [$text, $isBold, $isItalic]) {
$this->pdf->text($cursor, $textY, $text, $size, $isBold || $cell['header'], $isItalic);
$cursor += PdfDocument::exactWidth($text, $size, $isBold || $cell['header']);
}
$textY -= $line['height'];
}
}
$y -= $heights[$r];
}
$this->y = $y;
};
$this->room($heights[0] + ($rowCount > 1 ? min($heights[1], 40.0) : 0));
for ($r = 0; $r < $rowCount; $r++) {
// Zeilen, die eine Verbindung über Zeilen zusammenhält, werden gemeinsam gesetzt.
$end = $r;
do {
$before = $end;
foreach ($prepared as $cell) {
if ($cell['row'] <= $end && $end < $cell['row'] + $cell['rowspan'] - 1) {
$end = min($rowCount - 1, $cell['row'] + $cell['rowspan'] - 1);
}
}
} while ($end !== $before);
$span = $end - $r + 1;
$need = array_sum(array_slice($heights, $r, $span));
if ($this->y - $need < $this->bottom) {
($this->breakPage)();
$this->y = $this->top;
if ($headRows > 0 && $r >= $headRows) {
$drawRows(0, $headRows - 1);
}
}
$drawRows($r, $r + $span - 1);
$r += $span - 1;
}
$this->y -= 14;
}
private function frame(float $x, float $y, float $w, float $h, bool $header): void
{
if ($header) {
$this->pdf->fillRect($x, $y, $w, $h, 0.92);
}
$this->pdf->line($x, $y, $x + $w, $y, 0.4);
$this->pdf->line($x, $y + $h, $x + $w, $y + $h, 0.4);
$this->pdf->line($x, $y, $x, $y + $h, 0.4);
$this->pdf->line($x + $w, $y, $x + $w, $y + $h, 0.4);
}
/**
* Weist jeder Zelle ihre Spalte zu; Verbindungen über Zeilen belegen die Spalte in den Folgezeilen mit.
*
* @param list<list<array<string, mixed>>> $rows
* @return array{columns: int, cells: list<array<string, mixed>>}
*/
private function grid(array $rows): array
{
$occupied = [];
$cells = [];
$columns = 0;
foreach ($rows as $r => $row) {
$column = 0;
foreach ($row as $cell) {
while (isset($occupied[$r][$column])) {
$column++;
}
$colspan = max(1, (int) $cell['colspan']);
$rowspan = max(1, (int) $cell['rowspan']);
for ($dr = 0; $dr < $rowspan; $dr++) {
for ($dc = 0; $dc < $colspan; $dc++) {
$occupied[$r + $dr][$column + $dc] = true;
}
}
$cells[] = $cell + ['row' => $r, 'column' => $column] + ['colspan' => $colspan, 'rowspan' => $rowspan];
$column += $colspan;
$columns = max($columns, $column);
}
}
return ['columns' => max(1, $columns), 'cells' => $cells];
}
/**
* Spaltenbreiten nach Inhalt: Jede Spalte braucht mindestens ihr längstes Wort und wünscht sich die Breite ihres
* längsten Zelltexts. Reicht der Platz, wird der Rest gleichmäßig verteilt; sonst teilt sich der Mangel nach Wunsch auf.
*
* @param list<array<string, mixed>> $cells
* @return list<float>
*/
private function columnWidths(array $cells, int $columns, float $available, float $size, float $pad): array
{
$min = array_fill(0, $columns, 24.0);
$want = array_fill(0, $columns, 24.0);
foreach ($cells as $cell) {
if ($cell['colspan'] !== 1) {
continue;
}
$text = self::printable($this->cellText($cell['blocks']));
$widest = 0.0;
foreach (preg_split('/\s+/u', $text) ?: [] as $word) {
$widest = max($widest, PdfDocument::exactWidth($word, $size, (bool) $cell['header']));
}
$c = $cell['column'];
$min[$c] = max($min[$c], $widest + 2 * $pad + 1);
$want[$c] = max($want[$c], PdfDocument::exactWidth($text, $size, (bool) $cell['header']) + 2 * $pad + 1);
}
$want = array_map(fn (float $w, float $m): float => max($w, $m), $want, $min);
if (array_sum($min) >= $available) {
$scale = $available / array_sum($min);
return array_map(fn (float $w): float => $w * $scale, $min);
}
if (array_sum($want) <= $available) {
$extra = ($available - array_sum($want)) / $columns;
return array_map(fn (float $w): float => $w + $extra, $want);
}
// Der Platz über dem Mindestmaß wird gleichmäßig verteilt, aber keine Spalte bekommt mehr, als sie sich wünscht:
// Schmale Spalten behalten ihren Text in einer Zeile, die breite nimmt den Rest.
$widths = $min;
$room = $available - array_sum($min);
$open = array_keys($min);
usort($open, fn (int $a, int $b): int => ($want[$a] - $min[$a]) <=> ($want[$b] - $min[$b]));
foreach ($open as $position => $c) {
$share = $room / (count($open) - $position);
$give = min($want[$c] - $min[$c], $share);
$widths[$c] += $give;
$room -= $give;
}
return $widths;
}
/**
* @param list<array<string, mixed>> $blocks
*/
private function cellText(array $blocks): string
{
$out = [];
foreach ($blocks as $block) {
$out[] = match ($block['type']) {
'bullets', 'numbered' => implode(' ', array_map(fn (array $item): string => implode('', array_column($item, 'text')), $block['items'])),
'table', 'image' => '',
default => implode('', array_column($block['runs'] ?? [], 'text')),
};
}
return trim((string) preg_replace('/\s+/u', ' ', implode(' ', $out)));
}
/**
* Zeilen einer Tabellenzelle: Absätze, Aufzählungen, Zwischenüberschriften und Bilder (höchstens 110 Punkt hoch, in
* Breite der Zelle). Jeder Eintrag trägt seine Höhe.
*
* @param list<array<string, mixed>> $blocks
* @return list<array<string, mixed>>
*/
private function cellLines(array $blocks, float $width, float $size, bool $header): array
{
$out = [];
$lineHeight = $size + 3;
foreach ($blocks as $block) {
if (in_array($block['type'], ['bullets', 'numbered'], true)) {
foreach ($block['items'] as $index => $item) {
foreach ($this->lines($item, $width - 12, $size, $header) as $i => $segments) {
$out[] = ['segments' => $segments, 'indent' => 12.0, 'marker' => $i === 0 ? ($block['type'] === 'bullets' ? '•' : ($index + 1).'.') : null, 'height' => $lineHeight];
}
}
continue;
}
if ($block['type'] === 'image') {
$found = $this->images === null ? null : ($this->images)((int) $block['id']);
if ($found !== null && isset($found['jpeg'])) {
$scale = min(1.0, $width / max(1, $found['width']), 110.0 / max(1, $found['height']));
$w = max(1.0, $found['width'] * $scale);
$h = max(1.0, $found['height'] * $scale);
$out[] = ['image' => ['jpeg' => $found['jpeg'], 'width' => $w, 'height' => $h, 'pixelWidth' => $found['width'], 'pixelHeight' => $found['height']], 'height' => $h + 4];
} elseif ($found !== null) {
$out[] = ['segments' => [['['.($found['note'] ?? 'Bild nicht verfügbar').']', false, true]], 'indent' => 0.0, 'marker' => null, 'height' => $lineHeight];
}
continue;
}
if (! isset($block['runs'])) {
continue;
}
foreach ($this->lines($block['runs'], $width, $size, $header || $block['type'] === 'heading', $block['type'] === 'quote') as $segments) {
$out[] = ['segments' => $segments, 'indent' => 0.0, 'marker' => null, 'height' => $lineHeight];
}
}
return $out;
}
}