drink-it-cold/app/pdf.php

521 lines
18 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
/**
* Kleiner PDF-Erzeuger ohne externe Abhängigkeiten.
*
* Auf dem Hosting steht keine Composer-Bibliothek (mPDF/TCPDF) zur Verfügung,
* deshalb erzeugt diese Klasse PDF 1.4 selbst: Helvetica als Kernschrift,
* Text in CP1252 (deckt deutsche Umlaute ab), Linien, Rechtecke sowie
* eingebettete Bilder – JPEG (z. B. die Unterschrift vom Tablet) und PNG
* (Logo, inklusive Transparenz über /SMask).
*
* Koordinaten werden in Punkten von links oben angegeben; die Umrechnung ins
* PDF-Koordinatensystem (Ursprung links unten) passiert intern.
*/
final class PdfDoc
{
public const A4_W = 595.28;
public const A4_H = 841.89;
/** Zeichenbreiten Helvetica (Einheiten/1000) für ASCII 32–126. */
private const W_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,
];
/** Zeichenbreiten Helvetica-Bold (Einheiten/1000) für ASCII 32–126. */
private const W_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,
];
private float $width;
private float $height;
/** @var list<string> */
private array $pages = [];
private string $stream = '';
/** @var array<string, array{data: string, w: int, h: int, gray: bool, filter: string, smask: ?string}> */
private array $images = [];
public function __construct(float $width = self::A4_W, float $height = self::A4_H)
{
$this->width = $width;
$this->height = $height;
}
public function pageWidth(): float
{
return $this->width;
}
public function pageHeight(): float
{
return $this->height;
}
/** Nummer der aktuell offenen Seite (1-basiert). */
public function pageNo(): int
{
return count($this->pages) + 1;
}
public function newPage(): void
{
$this->pages[] = $this->stream;
$this->stream = '';
}
/**
* Schreibt Text. $top ist der Abstand der Grundlinie vom oberen Rand.
* $align: left|right|center – bezogen auf $boxWidth ab Position $x.
*/
public function text(
float $x,
float $top,
float $size,
string $text,
bool $bold = false,
string $align = 'left',
?float $boxWidth = null
): void {
if ($text === '') {
return;
}
$encoded = self::encode($text);
if ($align !== 'left' && $boxWidth !== null) {
$w = $this->measure($text, $size, $bold);
$x += $align === 'right' ? $boxWidth - $w : ($boxWidth - $w) / 2;
}
$y = $this->height - $top;
$font = $bold ? 'F2' : 'F1';
$this->stream .= sprintf(
"BT /%s %.2F Tf 1 0 0 1 %.2F %.2F Tm (%s) Tj ET\n",
$font,
$size,
$x,
$y,
self::escape($encoded)
);
}
public function measure(string $text, float $size, bool $bold = false): float
{
$encoded = self::encode($text);
$table = $bold ? self::W_BOLD : self::W_REGULAR;
$total = 0;
$len = strlen($encoded);
for ($i = 0; $i < $len; $i++) {
$code = ord($encoded[$i]);
$total += ($code >= 32 && $code <= 126) ? $table[$code - 32] : ($bold ? 611 : 556);
}
return $total * $size / 1000;
}
/**
* Bricht Text auf die angegebene Breite um (Wortgrenzen, harte Umbrüche).
*
* @return list<string>
*/
public function wrap(string $text, float $size, float $maxWidth, bool $bold = false): array
{
$limit = $maxWidth * 0.985;
$lines = [];
foreach (preg_split('/\R/', $text) ?: [] as $rawLine) {
$words = preg_split('/\s+/', trim($rawLine)) ?: [];
if ($words === []) {
$lines[] = '';
continue;
}
$current = '';
foreach ($words as $word) {
$candidate = $current === '' ? $word : $current . ' ' . $word;
if ($current !== '' && $this->measure($candidate, $size, $bold) > $limit) {
$lines[] = $current;
$current = $word;
continue;
}
$current = $candidate;
}
$lines[] = $current;
}
return $lines;
}
/**
* Schreibt umbrochenen Text ab $top und liefert die nächste freie Grundlinie.
*/
public function paragraph(
float $x,
float $top,
float $maxWidth,
float $size,
string $text,
bool $bold = false,
float $lineHeight = 0.0
): float {
$leading = $lineHeight > 0 ? $lineHeight : $size * 1.42;
$y = $top;
foreach ($this->wrap($text, $size, $maxWidth, $bold) as $line) {
$this->text($x, $y, $size, $line, $bold);
$y += $leading;
}
return $y;
}
public function line(float $x1, float $top1, float $x2, float $top2, float $lw = 0.6): void
{
$this->stream .= sprintf(
"%.2F w %.2F %.2F m %.2F %.2F l S\n",
$lw,
$x1,
$this->height - $top1,
$x2,
$this->height - $top2
);
}
public function rect(float $x, float $top, float $w, float $h, bool $fill = false, float $lw = 0.6): void
{
$y = $this->height - $top - $h;
$this->stream .= $fill
? sprintf("0.94 0.96 0.98 rg %.2F %.2F %.2F %.2F re f 0 0 0 rg\n", $x, $y, $w, $h)
: sprintf("%.2F w %.2F %.2F %.2F %.2F re S\n", $lw, $x, $y, $w, $h);
}
/**
* Bettet ein Bild ein: JPEG (Unterschrift vom Tablet) oder PNG (Logo,
* auch mit Alphakanal). Liefert false, wenn das Format nicht unterstützt wird.
*/
public function image(string $file, float $x, float $top, float $w, float $h): bool
{
$data = @file_get_contents($file);
if (!is_string($data)) {
return false;
}
$name = 'Im' . (count($this->images) + 1);
if (strncmp($data, "\xFF\xD8", 2) === 0) {
$size = self::jpeg_size($data);
if ($size === null) {
return false;
}
$this->images[$name] = [
'data' => $data,
'w' => $size[0],
'h' => $size[1],
'gray' => $size[2] === 1,
'filter' => 'DCTDecode',
'smask' => null,
];
} elseif (strncmp($data, "\x89PNG\r\n\x1a\n", 8) === 0) {
$png = self::png_decode($data);
if ($png === null) {
return false;
}
$this->images[$name] = [
'data' => gzcompress($png['rgb'], 6),
'w' => $png['w'],
'h' => $png['h'],
'gray' => false,
'filter' => 'FlateDecode',
'smask' => null,
];
if ($png['alpha'] !== null) {
$alphaName = $name . 'A';
$this->images[$alphaName] = [
'data' => gzcompress($png['alpha'], 6),
'w' => $png['w'],
'h' => $png['h'],
'gray' => true,
'filter' => 'FlateDecode',
'smask' => null,
];
$this->images[$name]['smask'] = $alphaName;
}
} else {
return false;
}
$this->stream .= sprintf(
"q %.2F 0 0 %.2F %.2F %.2F cm /%s Do Q\n",
$w,
$h,
$x,
$this->height - $top - $h,
$name
);
return true;
}
public function output(): string
{
$pages = $this->pages;
if (trim($this->stream) !== '' || $pages === []) {
$pages[] = $this->stream;
}
$objects = [];
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
$objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
$objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
$next = 5;
$imageRefs = [];
foreach ($this->images as $name => $_) {
$imageRefs[$name] = $next++;
}
foreach ($this->images as $name => $image) {
$smask = $image['smask'] !== null && isset($imageRefs[$image['smask']])
? ' /SMask ' . $imageRefs[$image['smask']] . ' 0 R'
: '';
$objects[$imageRefs[$name]] = '<< /Type /XObject /Subtype /Image'
. ' /Width ' . $image['w'] . ' /Height ' . $image['h']
. ' /ColorSpace /' . ($image['gray'] ? 'DeviceGray' : 'DeviceRGB')
. ' /BitsPerComponent 8 /Filter /' . $image['filter']
. $smask
. ' /Length ' . strlen($image['data']) . " >>\nstream\n"
. $image['data'] . "\nendstream";
}
$xobjects = '';
foreach ($imageRefs as $name => $id) {
$xobjects .= '/' . $name . ' ' . $id . ' 0 R ';
}
$kids = [];
foreach ($pages as $content) {
$compressed = gzcompress($content, 6);
$contentId = $next++;
$objects[$contentId] = '<< /Filter /FlateDecode /Length ' . strlen($compressed) . " >>\nstream\n"
. $compressed . "\nendstream";
$pageId = $next++;
$objects[$pageId] = '<< /Type /Page /Parent 2 0 R'
. sprintf(' /MediaBox [0 0 %.2F %.2F]', $this->width, $this->height)
. ' /Resources << /Font << /F1 3 0 R /F2 4 0 R >> /XObject << ' . $xobjects . '>> >>'
. ' /Contents ' . $contentId . ' 0 R >>';
$kids[] = $pageId . ' 0 R';
}
$objects[2] = '<< /Type /Pages /Kids [' . implode(' ', $kids) . '] /Count ' . count($kids) . ' >>';
ksort($objects);
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
$offsets = [];
foreach ($objects as $id => $body) {
$offsets[$id] = strlen($pdf);
$pdf .= $id . " 0 obj\n" . $body . "\nendobj\n";
}
$xref = strlen($pdf);
$maxId = max(array_keys($objects));
$pdf .= "xref\n0 " . ($maxId + 1) . "\n0000000000 65535 f \n";
for ($id = 1; $id <= $maxId; $id++) {
$pdf .= isset($offsets[$id]) ? sprintf("%010d 00000 n \n", $offsets[$id]) : "0000000000 65535 f \n";
}
$pdf .= "trailer\n<< /Size " . ($maxId + 1) . " /Root 1 0 R >>\nstartxref\n" . $xref . "\n%%EOF\n";
return $pdf;
}
private static function encode(string $text): string
{
if ($text === '') {
return '';
}
$out = @iconv('UTF-8', 'CP1252//TRANSLIT', $text);
if ($out === false) {
$out = (string) preg_replace('/[^\x20-\x7E]/', '?', $text);
}
return $out;
}
private static function escape(string $encoded): string
{
return str_replace(['\\', '(', ')', "\r", "\n"], ['\\\\', '\\(', '\\)', '', ''], $encoded);
}
/**
* Entpackt ein PNG (8 Bit, nicht interlaced, ohne Palette) zu RGB und
* optional Alpha. Die Zeilenfilter nach PNG-Spezifikation (0–4) werden
* dabei rückgängig gemacht.
*
* @return array{w: int, h: int, rgb: string, alpha: ?string}|null
*/
private static function png_decode(string $data): ?array
{
$len = strlen($data);
if ($len < 8 + 25 || strncmp($data, "\x89PNG\r\n\x1a\n", 8) !== 0 || !function_exists('gzuncompress')) {
return null;
}
$pos = 8;
$width = $height = $bitDepth = $colorType = 0;
$interlace = 0;
$idat = '';
$seenHeader = false;
while ($pos + 8 <= $len) {
$chunkLength = unpack('N', substr($data, $pos, 4))[1];
$type = substr($data, $pos + 4, 4);
$body = substr($data, $pos + 8, $chunkLength);
$pos += 12 + $chunkLength;
if ($type === 'IHDR') {
if (strlen($body) < 13) {
return null;
}
$header = unpack('Nw/Nh/Cbit/Ccolor/Ccomp/Cfilter/Cinterlace', substr($body, 0, 13));
$width = (int) $header['w'];
$height = (int) $header['h'];
$bitDepth = (int) $header['bit'];
$colorType = (int) $header['color'];
$interlace = (int) $header['interlace'];
$seenHeader = true;
continue;
}
if ($type === 'IDAT') {
$idat .= $body;
continue;
}
if ($type === 'IEND') {
break;
}
}
if (!$seenHeader || $width < 1 || $height < 1 || $bitDepth !== 8) {
return null;
}
if ($height > 20000 || $width > 20000) {
return null;
}
$channels = match ($colorType) {
0 => 1,
2 => 3,
4 => 2,
6 => 4,
default => 0,
};
if ($channels === 0 || $interlace !== 0 || $idat === '') {
return null;
}
$raw = @gzuncompress($idat);
if (!is_string($raw)) {
return null;
}
$stride = $width * $channels;
if (strlen($raw) < ($stride + 1) * $height) {
return null;
}
$rgb = '';
$alpha = $channels === 2 || $channels === 4 ? '' : null;
$previous = str_repeat("\0", $stride);
$offset = 0;
for ($row = 0; $row < $height; $row++) {
$filter = ord($raw[$offset]);
$line = substr($raw, $offset + 1, $stride);
$offset += $stride + 1;
$pixels = '';
for ($i = 0; $i < $stride; $i++) {
$left = $i >= $channels ? ord($pixels[$i - $channels]) : 0;
$up = ord($previous[$i]);
$upLeft = $i >= $channels ? ord($previous[$i - $channels]) : 0;
$value = ord($line[$i]);
$value = match ($filter) {
0 => $value,
1 => $value + $left,
2 => $value + $up,
3 => $value + (($left + $up) >> 1),
4 => $value + self::paeth($left, $up, $upLeft),
default => $value,
};
$pixels .= chr($value & 0xFF);
}
$previous = $pixels;
for ($x = 0; $x < $width; $x++) {
$base = $x * $channels;
if ($channels === 1 || $channels === 2) {
$gray = $pixels[$base];
$rgb .= $gray . $gray . $gray;
if ($alpha !== null) {
$alpha .= $pixels[$base + 1];
}
continue;
}
$rgb .= $pixels[$base] . $pixels[$base + 1] . $pixels[$base + 2];
if ($alpha !== null) {
$alpha .= $pixels[$base + 3];
}
}
}
return ['w' => $width, 'h' => $height, 'rgb' => $rgb, 'alpha' => $alpha];
}
private static function paeth(int $left, int $up, int $upLeft): int
{
$estimate = $left + $up - $upLeft;
$distanceLeft = abs($estimate - $left);
$distanceUp = abs($estimate - $up);
$distanceUpLeft = abs($estimate - $upLeft);
if ($distanceLeft <= $distanceUp && $distanceLeft <= $distanceUpLeft) {
return $left;
}
return $distanceUp <= $distanceUpLeft ? $up : $upLeft;
}
/**
* Liest Breite, Höhe und Farbkanäle eines JPEG aus dem SOF-Segment.
*
* @return array{0: int, 1: int, 2: int}|null
*
* @return array{0: int, 1: int, 2: int}|null
*/
private static function jpeg_size(string $data): ?array
{
$len = strlen($data);
$i = 2;
while ($i + 3 < $len) {
if ($data[$i] !== "\xFF") {
$i++;
continue;
}
$marker = ord($data[$i + 1]);
if ($marker === 0xD8 || $marker === 0x01 || ($marker >= 0xD0 && $marker <= 0xD7)) {
$i += 2;
continue;
}
if ($i + 4 >= $len) {
return null;
}
$length = (ord($data[$i + 2]) << 8) | ord($data[$i + 3]);
$isSof = $marker >= 0xC0 && $marker <= 0xCF && !in_array($marker, [0xC4, 0xC8, 0xCC], true);
if ($isSof) {
if ($i + 9 >= $len) {
return null;
}
$height = (ord($data[$i + 5]) << 8) | ord($data[$i + 6]);
$width = (ord($data[$i + 7]) << 8) | ord($data[$i + 8]);
$channels = ord($data[$i + 9]);
if ($width < 1 || $height < 1) {
return null;
}
return [$width, $height, $channels];
}
$i += 2 + $length;
}
return null;
}
}