Files
laraundfelix/app/Domain/Catalog/DocumentPdf.php
T
LarsandClaude Sonnet 5.5 58b68b768c
Deploy Test / test (push) Successful in 3m18s
Deploy Test / deploy (push) Successful in 29s
Erlaube in PDF-Vorlagen jedes Bild des Medienmanagers, auch ohne Inhaltsfassung
Kopf-, Fuß- und Titelbild einer PDF-Vorlage sind Gestaltung und brauchen keine
Inhaltsfassung. Der Picker bietet auch Präsentationsmedien und für die Website
freigegebene Bilder an (Spalten *_element_id, Klasse TemplateImage); gedruckt wird
die Website-Datei, sonst die Präsentationsdatei. Abgelehnt werden nur gesperrte
oder archivierte Bilder, fehlende Dateien und Nicht-Bilder. Bilder im Text eines
Dokuments bleiben an freigegebene Bildfassungen gebunden.

Die öffentliche Eigenschaft heißt bilder, weil slots mit Livewires internem
Slot-Mechanismus kollidiert.

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

336 lines
13 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->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 ($guide['chapters'] as $chapter) {
$this->contentsLine($chapter, $known[$chapter['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;
}
/**
* Eine Zeile des Inhaltsverzeichnisses: Nummer und Titel, Punktlinie, Seitenzahl; die ganze Zeile springt zum Kapitel.
*
* @param array<string, mixed> $chapter
* @param array{page: int, top: float} $target
*/
private function contentsLine(array $chapter, array $target): void
{
$level = $chapter['level'];
$size = $level === 1 ? 11.0 : 10.0;
$indent = $level === 1 ? 0.0 : 18.0;
$label = PdfFlow::printable($chapter['number'].' '.$chapter['title']);
$pageText = (string) $target['page'];
$numberWidth = PdfDocument::exactWidth($pageText, $size, false);
$lines = PdfDocument::wrap($label, self::RIGHT - self::LEFT - $indent - $numberWidth - 14, $size, $level === 1);
$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, $level === 1);
if ($index === count($lines) - 1) {
$used = PdfDocument::exactWidth($line, $size, $level === 1) + 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';
}
}