Files
laraundfelix/app/Domain/Catalog/DocumentPdf.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

368 lines
14 KiB
PHP

<?php
namespace App\Domain\Catalog;
use App\Domain\Commerce\Receipt\PdfDocument;
use App\Domain\Media\PdfImage;
use Closure;
use Transliterator;
/**
* Druckbare Ausgabe eines Dokuments (DIN A4) aus demselben Ergebnis wie die Ansicht ({@see DocumentGuide}): anklickbares
* Inhaltsverzeichnis samt Seitenzahlen, jedes Kapitel der ersten Ebene beginnt auf einer neuen Seite, Lesezeichen für die
* Gliederung des PDF-Betrachters. Fußzeile mit Lizenznehmer, Lizenzkopie und „Seite n von m“ auf jeder Seite (K2), die Kennung
* in den Metadaten (K1). Die Datei wird bei jedem Abruf neu erzeugt und nie abgelegt.
*
* Vorlage (ADR-51, Nachtrag): Ist dem Dokument eine {@see PdfTemplate} zugeordnet, steht der Titel allein auf einer eigenen
* Titelseite (mit Untertitel, Ausgabe, Veröffentlichungsdatum, Herausgeber und Copyright-Vermerk), und Kopf und Fuß aller
* weiteren Seiten tragen die gewählten Grafiken. Die Angaben kommen aus der Dokumentfassung ({@see DocumentMeta}). Ohne Vorlage
* beginnt das Inhaltsverzeichnis wie bisher unter dem Titel auf der ersten Seite.
*
* Seitenzahlen stehen erst nach dem Satz fest. Der Satz läuft deshalb so oft, bis Inhaltsverzeichnis, Kapitelanfänge und
* Seitenzahl sich nicht mehr ändern (in der Regel zweimal).
*/
class DocumentPdf
{
private const LEFT = 56.0;
private const RIGHT = 539.0;
private const PAGE_HEIGHT = 842.0;
private PdfDocument $pdf;
private PdfFlow $flow;
private int $page = 0;
private string $footer = '';
private int $total = 0;
private bool $onCover = false;
/** Obere und untere Grenze des Textes, abhängig von den Grafiken der Vorlage. */
private float $top = 790.0;
private float $bottom = 72.0;
/** Höhe der Fußlinie über dem Seitenrand. */
private float $footerLine = 54.0;
/** @var array{header: ?array<string, mixed>, footer: ?array<string, mixed>, cover: ?array<string, mixed>} */
private array $bands = ['header' => null, 'footer' => null, 'cover' => null];
/** @var array<string, array{page: int, top: float}> */
private array $starts = [];
/**
* @param array<string, mixed> $guide Ergebnis von {@see DocumentGuide::build}; `pdf_template` und `meta` sind optional
*/
public function render(array $guide, string $licensee, string $copyId, ?PdfImages $images = null): string
{
$template = ($guide['pdf_template'] ?? null) instanceof PdfTemplate ? $guide['pdf_template'] : null;
$this->prepareLayout($template);
$starts = [];
$total = 0;
$bytes = '';
for ($pass = 0; $pass < 5; $pass++) {
$bytes = $this->pass($guide, $template, $licensee, $copyId, $images, $starts, $total);
if ($this->starts === $starts && $this->total === $total) {
break;
}
$starts = $this->starts;
$total = $this->total;
}
return $bytes;
}
/**
* Bereitet die Grafiken der Vorlage auf und legt Ränder fest: Kopf und Fuß in voller Seitenbreite (höchstens 140 Punkt hoch),
* der Text beginnt unter dem Kopf und endet über dem Fuß.
*/
private function prepareLayout(?PdfTemplate $template): void
{
$this->bands = [
'header' => $this->band($template?->target('header'), 140.0),
'footer' => $this->band($template?->target('footer'), 140.0),
'cover' => $template !== null && $template->show_cover ? $this->band($template->target('cover'), self::PAGE_HEIGHT * 0.4) : null,
];
$header = (float) ($this->bands['header']['height'] ?? 0);
$footer = (float) ($this->bands['footer']['height'] ?? 0);
$this->top = $header > 0 ? min(790.0, self::PAGE_HEIGHT - $header - 26.0) : 790.0;
$this->footerLine = max(54.0, $footer + 24.0);
$this->bottom = $this->footerLine + 18.0;
}
/**
* Eine Grafik in Seitenbreite, bei zu großer Höhe verkleinert und zentriert.
*
* @return array{jpeg: string, pixelWidth: int, pixelHeight: int, width: float, height: float, x: float}|null
*/
private function band(?string $target, float $maxHeight): ?array
{
$bytes = TemplateImage::bytes($target);
$image = $bytes === null ? null : PdfImage::fromBytes($bytes);
if ($image === null) {
return null;
}
$width = (float) PdfDocument::WIDTH;
$height = $width * $image['height'] / max(1, $image['width']);
if ($height > $maxHeight) {
$height = $maxHeight;
$width = $height * $image['width'] / max(1, $image['height']);
}
return ['jpeg' => $image['jpeg'], 'pixelWidth' => $image['width'], 'pixelHeight' => $image['height'], 'width' => $width, 'height' => $height, 'x' => (PdfDocument::WIDTH - $width) / 2];
}
/**
* @param array<string, mixed> $guide
* @param array<string, array{page: int, top: float}> $known Kapitelanfänge aus dem vorigen Durchgang
*/
private function pass(array $guide, ?PdfTemplate $template, string $licensee, string $copyId, ?PdfImages $images, array $known, int $total): string
{
$this->pdf = new PdfDocument;
$this->page = 0;
$this->starts = [];
$this->onCover = false;
$this->footer = PdfFlow::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId);
$this->flow = new PdfFlow($this->pdf, self::LEFT, self::RIGHT, $this->top, $this->bottom, function (): void {
$this->closePage();
$this->newPage();
}, $images === null ? null : Closure::fromCallable($images));
$this->flow->onHeading = function (array $block, float $top): void {
$this->starts[$block['anchor']] = ['page' => $this->page, 'top' => $top];
$this->pdf->bookmark((string) $block['text'], $this->page - 1, $top, (int) $block['level'] - 1);
};
$this->total = $total;
$withCover = $template !== null && $template->show_cover;
if ($withCover) {
$this->onCover = true;
$this->newPage();
$this->cover($guide, $template);
$this->closePage();
$this->onCover = false;
$this->newPage();
} else {
$this->newPage();
$this->flow->write(PdfFlow::printable((string) $guide['title']), 24, true, 10);
}
$this->flow->write('Inhaltsverzeichnis', 14, true, 8, keep: 40);
foreach ($this->contents($guide) as $entry) {
$this->contentsLine($entry, $known[$entry['anchor']] ?? ['page' => 1, 'top' => $this->top]);
}
foreach ($guide['chapters'] as $chapter) {
$this->chapter($chapter);
}
$this->closePage();
$total = $this->page;
$starts = $this->starts;
$bytes = $this->pdf->output($this->asciiTitle((string) $guide['title']), 'Lizenzkopie '.$copyId);
$this->total = $total;
$this->starts = $starts;
return $bytes;
}
/**
* Titelseite: Bild (falls gewählt), Titel allein, Untertitel, dann Ausgabe, Veröffentlichung und Herausgeber, unten der
* Copyright-Vermerk. Die Vermerke der Fassung gehen dem Standard der Vorlage vor.
*
* @param array<string, mixed> $guide
*/
private function cover(array $guide, PdfTemplate $template): void
{
$meta = is_array($guide['meta'] ?? null) ? $guide['meta'] : [];
$y = self::PAGE_HEIGHT - 150.0;
if ($this->bands['cover'] !== null) {
$cover = $this->bands['cover'];
$this->pdf->image($cover['x'], self::PAGE_HEIGHT - $cover['height'], $cover['width'], $cover['height'], $cover['jpeg'], $cover['pixelWidth'], $cover['pixelHeight']);
$y = self::PAGE_HEIGHT - $cover['height'] - 90.0;
}
$this->coverText(PdfFlow::printable((string) $guide['title']), 30.0, true, $y, 12.0);
if (filled($meta['subtitle'] ?? null)) {
$this->coverText(PdfFlow::printable((string) $meta['subtitle']), 15.0, false, $y, 8.0);
}
$y -= 26.0;
$facts = array_filter([
filled($meta['edition'] ?? null) ? $meta['edition'] : null,
DocumentMeta::publishedLabel($meta) !== '' ? 'Veröffentlicht am '.DocumentMeta::publishedLabel($meta) : null,
filled($template->publisher) ? 'Herausgeber: '.$template->publisher : null,
]);
foreach ($facts as $fact) {
$this->coverText(PdfFlow::printable((string) $fact), 11.0, false, $y, 4.0);
}
$copyright = trim((string) ($meta['copyright'] ?? '')) !== '' ? (string) $meta['copyright'] : (string) $template->copyright;
if (trim($copyright) !== '') {
$lines = PdfDocument::wrap(PdfFlow::printable($copyright), self::RIGHT - self::LEFT, 8.5, false);
$at = $this->footerLine + 24.0 + (count($lines) - 1) * 12.0;
foreach ($lines as $line) {
$this->pdf->text(self::LEFT, $at, $line, 8.5);
$at -= 12.0;
}
}
}
private function coverText(string $text, float $size, bool $bold, float &$y, float $after): void
{
foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) {
$this->pdf->text(self::LEFT, $y, $line, $size, $bold);
$y -= $size + 6.0;
}
$y -= $after;
}
/**
* Die Einträge des Inhaltsverzeichnisses in der Reihenfolge des Dokuments: Kapitel und Unterkapitel mit Nummer, darunter
* ihre Zwischenüberschriften (h3 bis h6), eingerückt nach Stufe.
*
* @param array<string, mixed> $guide
* @return list<array{anchor: string, label: string, size: float, indent: float, bold: bool}>
*/
private function contents(array $guide): array
{
$entries = [];
foreach ($guide['chapters'] as $chapter) {
$entries[] = [
'anchor' => $chapter['anchor'],
'label' => $chapter['number'].' '.$chapter['title'],
'size' => $chapter['level'] === 1 ? 11.0 : 10.0,
'indent' => $chapter['level'] === 1 ? 0.0 : 18.0,
'bold' => $chapter['level'] === 1,
];
foreach ($chapter['headings'] ?? [] as $heading) {
$entries[] = ['anchor' => $heading['anchor'], 'label' => $heading['text'], 'size' => 9.5, 'indent' => 18.0 + ($heading['level'] - 3) * 12.0, 'bold' => false];
}
}
return $entries;
}
/**
* Eine Zeile des Inhaltsverzeichnisses: Titel, Punktlinie, Seitenzahl; die ganze Zeile springt zum Eintrag.
*
* @param array{anchor: string, label: string, size: float, indent: float, bold: bool} $entry
* @param array{page: int, top: float} $target
*/
private function contentsLine(array $entry, array $target): void
{
$size = $entry['size'];
$indent = $entry['indent'];
$bold = $entry['bold'];
$label = PdfFlow::printable($entry['label']);
$pageText = (string) $target['page'];
$numberWidth = PdfDocument::exactWidth($pageText, $size, false);
$lines = PdfDocument::wrap($label, self::RIGHT - self::LEFT - $indent - $numberWidth - 14, $size, $bold);
$x = self::LEFT + $indent;
$this->flow->room(count($lines) * ($size + 4) + 2);
$top = $this->flow->y;
foreach ($lines as $index => $line) {
$this->pdf->text($x, $this->flow->y, $line, $size, $bold);
if ($index === count($lines) - 1) {
$used = PdfDocument::exactWidth($line, $size, $bold) + 4;
$room = self::RIGHT - $numberWidth - 4 - ($x + $used);
$dots = (int) floor($room / PdfDocument::exactWidth('.', 8, false));
if ($dots > 2) {
$this->pdf->text($x + $used, $this->flow->y, str_repeat('.', $dots), 8);
}
$this->pdf->textRight(self::RIGHT, $this->flow->y, $pageText, $size);
}
$this->flow->y -= $size + 4;
}
$this->pdf->link(self::LEFT, $this->flow->y + 2, self::RIGHT - self::LEFT, $top - $this->flow->y, max(0, $target['page'] - 1), $target['top']);
$this->flow->y -= 2;
}
/**
* @param array<string, mixed> $chapter
*/
private function chapter(array $chapter): void
{
$level = $chapter['level'];
if ($level === 1) {
$this->closePage();
$this->newPage();
}
$size = $level === 1 ? 18.0 : 13.5;
$title = PdfFlow::printable($chapter['number'].' '.$chapter['title']);
$this->flow->room(($size + 4) + 60);
$top = $this->flow->y + $size;
$this->starts[$chapter['anchor']] = ['page' => $this->page, 'top' => $top];
$this->pdf->bookmark($chapter['number'].' '.$chapter['title'], $this->page - 1, $top, $level);
$this->flow->y -= $level === 1 ? 0 : 6;
$this->flow->write($title, $size, true, $level === 1 ? 10 : 5, keep: 40);
if (! $chapter['allowed']) {
$this->flow->write('Dieses Kapitel ist derzeit nicht verfügbar.', 10.5, false, 6);
return;
}
$this->flow->formatted($chapter['blocks'] ?? []);
$this->flow->y -= 4;
}
private function newPage(): void
{
$this->pdf->addPage();
$this->page++;
$this->flow->restart();
if (! $this->onCover && $this->bands['header'] !== null) {
$band = $this->bands['header'];
$this->pdf->image($band['x'], self::PAGE_HEIGHT - $band['height'], $band['width'], $band['height'], $band['jpeg'], $band['pixelWidth'], $band['pixelHeight']);
}
}
private function closePage(): void
{
if (! $this->onCover && $this->bands['footer'] !== null) {
$band = $this->bands['footer'];
$this->pdf->image($band['x'], 0, $band['width'], $band['height'], $band['jpeg'], $band['pixelWidth'], $band['pixelHeight']);
}
$this->pdf->line(self::LEFT, $this->footerLine, self::RIGHT, $this->footerLine, 0.4);
$this->pdf->text(self::LEFT, $this->footerLine - 14.0, $this->footer, 8);
$this->pdf->textRight(self::RIGHT, $this->footerLine - 14.0, 'Seite '.$this->page.($this->total > 0 ? ' von '.$this->total : ''), 8);
}
private function asciiTitle(string $title): string
{
$ascii = Transliterator::create('Any-Latin; Latin-ASCII');
return $ascii?->transliterate($title) ?: 'Dokument';
}
}