Files
laraundfelix/app/Domain/Commerce/Receipt/PdfDocument.php
T
LarsandClaude Sonnet 5.5 b942b5331a Biete Überschriften h3 bis h6 an und nimm sie ins Inhaltsverzeichnis auf
Ein Dokument gliedert sich vor allem durch Kapitel der ersten Ebene und
Überschriften im Text. Der Editor bietet h3 bis h6; h1 und h2 aus eingefügtem
Text werden h3. Alle Überschriften des Kapiteltexts stehen automatisch im
Inhaltsverzeichnis der Seite und des PDF (eingerückt, ohne Nummer), mit
Sprungmarken, im PDF mit Seitenzahl, Verweis und verschachtelten Lesezeichen.
Die PDF-Gliederung kennt jetzt bis zu sechs Ebenen und zählt alle Nachkommen.
Unter einem Unterkapitel rücken die Überschriften eine Stufe tiefer (höchstens h6).

Der bestehende Test erwartete h4 für eine Zwischenüberschrift im Kapitel; das gilt
bewusst nicht mehr (h3 bleibt h3 und trägt eine Sprungmarke). Keine Migration,
der Änderungsnachweis bleibt unverändert.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 16:23:29 +01:00

388 lines
17 KiB
PHP

<?php
namespace App\Domain\Commerce\Receipt;
/**
* Minimaler PDF-Schreiber für einseitige bis wenige Seiten Text (DIN A4, Standardschriften Helvetica, Kodierung
* WinAnsi). Absichtlich ohne Abhängigkeit: Ein Zahlungsbeleg ist ein Text mit Linien. Der Inhalt ist unkomprimiert und
* enthält keinen Zeitstempel, damit dasselbe Dokument bei jedem Abruf byte-gleich ist und Tests den Text prüfen können.
* Zeichen außerhalb von Windows-1252 werden durch „?“ ersetzt (das Minuszeichen U+2212 durch „-“).
*
* Für längere Dokumente (Handbuch) kann der Schreiber zusätzlich Flächen, JPEG-Bilder, Verweise innerhalb des Dokuments
* (Inhaltsverzeichnis) und Lesezeichen setzen. Wer sie nicht nutzt, erhält dieselben Bytes wie zuvor: Die zusätzlichen
* Objekte entstehen nur bei Bedarf und nach allen bisherigen.
*/
final class PdfDocument
{
public const WIDTH = 595;
public const HEIGHT = 842;
/** @var list<string> */
private array $pages = [];
/** Schräge Schnitte werden nur eingebunden, wenn das Dokument sie braucht (Belege bleiben unverändert). */
private bool $usesItalic = false;
/** @var list<array{bytes: string, width: int, height: int}> */
private array $images = [];
/** @var array<string, int> Prüfsumme der Bilddatei => Index in {@see self::$images} */
private array $imageIndex = [];
/** @var array<int, array<int, true>> Seite => Bilder, die sie zeigt */
private array $pageImages = [];
/** @var array<int, list<array{x: float, y: float, w: float, h: float, page: int, top: float}>> */
private array $links = [];
/** @var list<array{title: string, page: int, top: float, level: int}> */
private array $outline = [];
/** Breiten der Helvetica (Tausendstel der Schrifthöhe) für Zeichen 32 bis 126; schräg wie aufrecht. */
private const REGULAR = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584];
/** Breiten der Helvetica-Bold für Zeichen 32 bis 126; schräg wie aufrecht. */
private const BOLD = [278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584];
public function addPage(): void
{
$this->pages[] = '';
}
/** Anzahl der bisher angelegten Seiten. */
public function pageCount(): int
{
return count($this->pages);
}
/** Gefüllte Fläche in einem Grauwert (0 schwarz, 1 weiß), zum Beispiel für Tabellenköpfe. */
public function fillRect(float $x, float $y, float $w, float $h, float $gray): void
{
$this->append(sprintf("q %s g %s %s %s %s re f Q\n", $this->n($gray), $this->n($x), $this->n($y), $this->n($w), $this->n($h)));
}
/**
* Setzt ein JPEG (RGB, aus `imagejpeg`) mit seiner linken unteren Ecke bei `$x`/`$y`. Dasselbe Bild wird nur einmal
* im Dokument abgelegt.
*/
public function image(float $x, float $y, float $w, float $h, string $jpeg, int $pixelWidth, int $pixelHeight): void
{
$key = md5($jpeg);
if (! isset($this->imageIndex[$key])) {
$this->imageIndex[$key] = count($this->images);
$this->images[] = ['bytes' => $jpeg, 'width' => $pixelWidth, 'height' => $pixelHeight];
}
$index = $this->imageIndex[$key];
if ($this->pages === []) {
$this->addPage();
}
$this->pageImages[array_key_last($this->pages)][$index] = true;
$this->append(sprintf("q %s 0 0 %s %s %s cm /Im%d Do Q\n", $this->n($w), $this->n($h), $this->n($x), $this->n($y), $index + 1));
}
/**
* Anklickbarer Bereich auf der aktuellen Seite, der zu einer Stelle im Dokument springt (Seitenindex ab 0, `$top` ist
* die Höhe des Ziels auf der Zielseite).
*/
public function link(float $x, float $y, float $w, float $h, int $page, float $top): void
{
if ($this->pages === []) {
$this->addPage();
}
$this->links[array_key_last($this->pages)][] = ['x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'page' => $page, 'top' => $top];
}
/** Lesezeichen (Ebene 1 bis 6) für die Gliederung in PDF-Betrachtern. */
public function bookmark(string $title, int $page, float $top, int $level = 1): void
{
$this->outline[] = ['title' => $title, 'page' => $page, 'top' => $top, 'level' => max(1, min(6, $level))];
}
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false, bool $italic = false): void
{
$font = $italic ? ($bold ? 'F4' : 'F3') : ($bold ? 'F2' : 'F1');
$this->usesItalic = $this->usesItalic || $italic;
$this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $font, $this->n($size), $this->n($x), $this->n($y), self::escape($text)));
}
/**
* Genaue Breite in Punkt nach den Schriftbreiten der Helvetica, damit Textabschnitte mit verschiedenen Schnitten in
* einer Zeile ohne Lücken aneinanderstoßen. Umlaute zählen wie ihr Grundbuchstabe, das ß wie ein kleines b, jedes
* andere Zeichen außerhalb von ASCII wie eine Ziffer.
*/
public static function exactWidth(string $text, float $size = 10, bool $bold = false): float
{
$table = $bold ? self::BOLD : self::REGULAR;
$units = 0;
$text = strtr($text, ['ä' => 'a', 'ö' => 'o', 'ü' => 'u', 'Ä' => 'A', 'Ö' => 'O', 'Ü' => 'U', 'ß' => 'b', "\u{2019}" => "'", "\u{2026}" => '...', "\u{00A0}" => ' ']);
foreach (mb_str_split($text) as $char) {
$code = strlen($char) === 1 ? ord($char) : 0;
$units += $code >= 32 && $code <= 126 ? $table[$code - 32] : 556;
}
return $units / 1000 * $size;
}
public function textRight(float $xRight, float $y, string $text, float $size = 10, bool $bold = false): void
{
$this->text($xRight - self::width($text, $size, $bold), $y, $text, $size, $bold);
}
public function line(float $x1, float $y1, float $x2, float $y2, float $width = 0.5): void
{
$this->append(sprintf("%s w %s %s m %s %s l S\n", $this->n($width), $this->n($x1), $this->n($y1), $this->n($x2), $this->n($y2)));
}
/**
* Zeilenumbruch nach Wörtern. Die Breite ist eine bewusst großzügige Schätzung der Helvetica-Breiten, damit nichts
* über den Rand läuft; ein einzelnes zu langes Wort wird hart getrennt.
*
* @return list<string>
*/
public static function wrap(string $text, float $maxWidth, float $size = 10, bool $bold = false): array
{
$lines = [];
foreach (preg_split('/\R/u', trim($text)) ?: [''] as $paragraph) {
$current = '';
foreach (preg_split('/\s+/u', trim($paragraph)) ?: [] as $word) {
while (mb_strlen($word) > 1 && self::width($word, $size, $bold) > $maxWidth) {
$cut = mb_strlen($word) - 1;
while ($cut > 1 && self::width(mb_substr($word, 0, $cut), $size, $bold) > $maxWidth) {
$cut--;
}
if ($current !== '') {
$lines[] = $current;
$current = '';
}
$lines[] = mb_substr($word, 0, $cut);
$word = mb_substr($word, $cut);
}
$candidate = $current === '' ? $word : $current.' '.$word;
if ($current !== '' && self::width($candidate, $size, $bold) > $maxWidth) {
$lines[] = $current;
$current = $word;
} else {
$current = $candidate;
}
}
$lines[] = $current;
}
return $lines;
}
/** Geschätzte Textbreite in Punkt (Helvetica; Ziffern und Währung exakt, Buchstaben großzügig). */
public static function width(string $text, float $size = 10, bool $bold = false): float
{
$units = 0.0;
foreach (mb_str_split($text) as $char) {
$width = match (true) {
$char === ' ', $char === ',', $char === '.', $char === ':', $char === ';', $char === "'", $char === '|', $char === 'i', $char === 'l', $char === 'I', $char === 'j', $char === 't', $char === 'f' => 0.3,
$char === '-', $char === '(', $char === ')', $char === '/', $char === 'r' => 0.35,
ctype_digit($char), $char === '€' => 0.556,
mb_strtoupper($char) === $char && $char !== mb_strtolower($char) => 0.75,
$char === 'm', $char === 'w', $char === 'M', $char === 'W' => 0.85,
default => 0.57,
};
// Fette Ziffern, Währung und Satzzeichen sind in Helvetica so breit wie normale; nur Buchstaben werden breiter.
$units += $bold && ctype_alpha($char) ? $width * 1.08 : $width;
}
return $units * $size;
}
/**
* @param string $title Nur ASCII (Dokumenttitel)
*/
public function output(string $title, ?string $keywords = null): string
{
$pages = $this->pages === [] ? [''] : $this->pages;
$objects = [];
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
$kids = [];
$next = 6;
// Nummern der zusätzlichen Objekte: nach den Seiten und Schriften, in fester Reihenfolge (Verweise, Bilder, Gliederung).
$cursor = 6 + 2 * count($pages) + ($this->usesItalic ? 2 : 0);
$annotations = [];
foreach ($this->links as $pageIndex => $links) {
foreach ($links as $link) {
$annotations[$pageIndex][] = ['number' => $cursor++] + $link;
}
}
$imageNumbers = [];
foreach (array_keys($this->images) as $index) {
$imageNumbers[$index] = $cursor++;
}
$outlineRoot = $this->outline === [] ? null : $cursor++;
$outlineNumbers = [];
foreach (array_keys($this->outline) as $index) {
$outlineNumbers[$index] = $cursor++;
}
foreach ($pages as $pageIndex => $stream) {
$kids[] = $next.' 0 R';
$xobjects = '';
foreach (array_keys($this->pageImages[$pageIndex] ?? []) as $index) {
$xobjects .= ' /Im'.($index + 1).' '.$imageNumbers[$index].' 0 R';
}
$annots = isset($annotations[$pageIndex]) ? ' /Annots ['.implode(' ', array_map(fn (array $link): string => $link['number'].' 0 R', $annotations[$pageIndex])).']' : '';
$objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R'.($this->usesItalic ? ' /F3 %ITALIC% 0 R /F4 %BOLDITALIC% 0 R' : '').' >>'.($xobjects === '' ? '' : ' /XObject <<'.$xobjects.' >>').' >> /Contents '.($next + 1).' 0 R'.$annots.' >>';
$objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream';
$next += 2;
}
if ($this->usesItalic) {
$objects[$next] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>';
$objects[$next + 1] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-BoldOblique /Encoding /WinAnsiEncoding >>';
foreach ($objects as $number => $body) {
$objects[$number] = str_replace(['%ITALIC%', '%BOLDITALIC%'], [(string) $next, (string) ($next + 1)], $body);
}
}
foreach ($annotations as $links) {
foreach ($links as $link) {
$objects[$link['number']] = sprintf(
'<< /Type /Annot /Subtype /Link /Rect [%s %s %s %s] /Border [0 0 0] /Dest [%d 0 R /XYZ 0 %s null] >>',
$this->n($link['x']),
$this->n($link['y']),
$this->n($link['x'] + $link['w']),
$this->n($link['y'] + $link['h']),
6 + 2 * min($link['page'], count($pages) - 1),
$this->n($link['top']),
);
}
}
foreach ($this->images as $index => $image) {
$objects[$imageNumbers[$index]] = '<< /Type /XObject /Subtype /Image /Width '.$image['width'].' /Height '.$image['height'].' /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length '.strlen($image['bytes'])." >>\nstream\n".$image['bytes']."\nendstream";
}
if ($outlineRoot !== null) {
$objects[1] = '<< /Type /Catalog /Pages 2 0 R /Outlines '.$outlineRoot.' 0 R /PageMode /UseOutlines >>';
foreach ($this->outlineObjects($outlineRoot, $outlineNumbers, count($pages)) as $number => $body) {
$objects[$number] = $body;
}
}
$objects[2] = '<< /Type /Pages /Kids ['.implode(' ', $kids).'] /Count '.count($pages).' >>';
$objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
$objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
$ascii = fn (string $value): string => (string) preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $value));
$objects[5] = '<< /Title ('.$ascii($title).')'.($keywords === null ? '' : ' /Keywords ('.$ascii($keywords).')').' /Producer (Lara und Felix) >>';
ksort($objects);
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
$offsets = [];
foreach ($objects as $number => $body) {
$offsets[$number] = strlen($pdf);
$pdf .= $number." 0 obj\n".$body."\nendobj\n";
}
$xref = strlen($pdf);
$pdf .= 'xref'."\n0 ".(count($objects) + 1)."\n0000000000 65535 f \n";
foreach ($offsets as $offset) {
$pdf .= sprintf("%010d 00000 n \n", $offset);
}
return $pdf.'trailer'."\n<< /Size ".(count($objects) + 1).' /Root 1 0 R /Info 5 0 R >>'."\nstartxref\n".$xref."\n%%EOF\n";
}
/**
* Gliederung (Lesezeichen): Ebene 1 unter der Wurzel, Ebene 2 unter dem vorangehenden Eintrag der Ebene 1.
*
* @param array<int, int> $numbers Objektnummer je Eintrag
* @return array<int, string>
*/
private function outlineObjects(int $root, array $numbers, int $pageCount): array
{
$parentOf = [];
$childrenOf = [];
$descendants = [];
$path = [];
// Ein Eintrag gehört zum nächsten davor mit kleinerer Ebene; ohne einen solchen steht er oben.
foreach ($this->outline as $index => $item) {
while ($path !== [] && $this->outline[$path[array_key_last($path)]]['level'] >= $item['level']) {
array_pop($path);
}
$parentOf[$index] = $path === [] ? null : $path[array_key_last($path)];
$childrenOf[$parentOf[$index] ?? -1][] = $index;
foreach ($path as $ancestor) {
$descendants[$ancestor] = ($descendants[$ancestor] ?? 0) + 1;
}
$path[] = $index;
}
$top = $childrenOf[-1];
$objects = [$root => '<< /Type /Outlines /First '.$numbers[$top[0]].' 0 R /Last '.$numbers[$top[array_key_last($top)]].' 0 R /Count '.count($this->outline).' >>'];
foreach ($this->outline as $index => $item) {
$siblings = $childrenOf[$parentOf[$index] ?? -1];
$position = (int) array_search($index, $siblings, true);
$kids = $childrenOf[$index] ?? [];
$objects[$numbers[$index]] = '<< /Title ('.self::escape($item['title']).') /Parent '.($parentOf[$index] === null ? $root : $numbers[$parentOf[$index]]).' 0 R'
.($position > 0 ? ' /Prev '.$numbers[$siblings[$position - 1]].' 0 R' : '')
.($position < count($siblings) - 1 ? ' /Next '.$numbers[$siblings[$position + 1]].' 0 R' : '')
.($kids === [] ? '' : ' /First '.$numbers[$kids[0]].' 0 R /Last '.$numbers[$kids[array_key_last($kids)]].' 0 R /Count '.($descendants[$index] ?? 0))
.' /Dest ['.(6 + 2 * min($item['page'], $pageCount - 1)).' 0 R /XYZ 0 '.$this->n($item['top']).' null] >>';
}
return $objects;
}
private function append(string $operators): void
{
if ($this->pages === []) {
$this->addPage();
}
$this->pages[array_key_last($this->pages)] .= $operators;
}
private function n(float $value): string
{
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.') ?: '0';
}
/** Windows-1252, geklammert für PDF-Zeichenketten. */
private static function escape(string $text): string
{
$text = strtr($text, ["\u{2212}" => '-', "\u{2019}" => "'", "\u{2026}" => '...', "\u{00A0}" => ' ', "\u{202F}" => ' ']);
$text = (string) preg_replace('/[\x00-\x08\x0B-\x1F\x7F]/u', '', $text);
$encoded = mb_convert_encoding($text, 'Windows-1252', 'UTF-8');
return str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $encoded);
}
}