rpg-westreiche/westreiche_website/app/pdf.php

303 lines
9.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
/**
* Westreiche – PDF-Export des Charakterbogens.
*
* Bewusst ohne Fremdbibliothek: ein kleiner PDF-1.4-Writer mit den
* Standard-Schriften (Helvetica/Times), Windows-1252-Kodierung und A4-Seiten.
* Dadurch läuft der Export auf jedem Shared Hosting ohne Composer, GD oder
* Python. Umlaute und ß sind in CP1252 enthalten; alles andere wird
* transliteriert.
*/
final class WsPdf
{
private const PAGE_W = 595.28;
private const PAGE_H = 841.89;
private const FONTS = [
'F1' => 'Helvetica',
'F2' => 'Helvetica-Bold',
'F3' => 'Times-Roman',
'F4' => 'Times-Bold',
'F5' => 'Times-Italic',
];
/** Grobe Zeichenbreite relativ zur Schriftgröße (reicht für Zeilenumbrüche). */
private const WIDTH_FACTOR = ['F1' => 0.52, 'F2' => 0.57, 'F3' => 0.47, 'F4' => 0.52, 'F5' => 0.46];
/** @var list<array{bytes: string, w: int, h: int, name: string, object: int}> */
private array $images = [];
/** @var list<string> */
private array $pages = [];
private string $buffer = '';
private int $pageCount = 0;
public function __construct()
{
$this->addPage();
}
public static function width(): float
{
return self::PAGE_W;
}
public static function height(): float
{
return self::PAGE_H;
}
public function currentPage(): int
{
return $this->pageCount;
}
public function addPage(): void
{
if ($this->buffer !== '') {
$this->pages[] = $this->buffer;
}
$this->buffer = '';
$this->pageCount++;
}
private static function encode(string $text): string
{
$converted = @iconv('UTF-8', 'CP1252//TRANSLIT', $text);
if ($converted === false) {
$converted = preg_replace('/[^\x20-\x7e]/', '?', $text) ?? '';
}
return str_replace(['\\', '(', ')', "\r"], ['\\\\', '\\(', '\\)', ''], $converted);
}
private static function color(array $rgb): string
{
return sprintf('%.3F %.3F %.3F', $rgb[0], $rgb[1], $rgb[2]);
}
/** @param array{0:float,1:float,2:float} $rgb */
public function text(float $x, float $yTop, float $size, string $font, array $rgb, string $text): void
{
if ($text === '') {
return;
}
$this->buffer .= sprintf(
"BT /%s %.2F Tf %s rg 1 0 0 1 %.2F %.2F Tm (%s) Tj ET\n",
$font,
$size,
self::color($rgb),
$x,
self::PAGE_H - $yTop,
self::encode($text)
);
}
public function textRight(float $xRight, float $yTop, float $size, string $font, array $rgb, string $text): void
{
$this->text($xRight - self::textWidth($text, $size, $font), $yTop, $size, $font, $rgb, $text);
}
public function textCenter(float $centerX, float $yTop, float $size, string $font, array $rgb, string $text): void
{
$this->text($centerX - self::textWidth($text, $size, $font) / 2, $yTop, $size, $font, $rgb, $text);
}
public static function textWidth(string $text, float $size, string $font = 'F3'): float
{
return mb_strlen($text, 'UTF-8') * $size * (self::WIDTH_FACTOR[$font] ?? 0.5);
}
/** @param array{0:float,1:float,2:float} $rgb */
public function line(float $x1, float $y1Top, float $x2, float $y2Top, array $rgb, float $lw = 0.6): void
{
$this->buffer .= sprintf(
"q %s RG %.2F w %.2F %.2F m %.2F %.2F l S Q\n",
self::color($rgb),
$lw,
$x1,
self::PAGE_H - $y1Top,
$x2,
self::PAGE_H - $y2Top
);
}
/**
* @param array{0:float,1:float,2:float}|null $fill
* @param array{0:float,1:float,2:float}|null $stroke
*/
public function rect(float $x, float $yTop, float $w, float $h, ?array $fill = null, ?array $stroke = null, float $lw = 0.6): void
{
$op = '';
if ($fill !== null) {
$op .= self::color($fill) . ' rg ';
}
if ($stroke !== null) {
$op .= self::color($stroke) . ' RG ' . sprintf('%.2F w ', $lw);
}
$mode = ($fill !== null && $stroke !== null) ? 'B' : ($fill !== null ? 'f' : 'S');
$this->buffer .= sprintf(
"q %s%.2F %.2F %.2F %.2F re %s Q\n",
$op,
$x,
self::PAGE_H - $yTop - $h,
$w,
$h,
$mode
);
}
/** Zeilenumbruch nach geschätzter Breite. @return list<string> */
public static function wrap(string $text, float $size, string $font, float $maxWidth): array
{
$text = trim(preg_replace('/\s+/u', ' ', $text) ?? '');
if ($text === '') {
return [];
}
$lines = [];
$current = '';
foreach (explode(' ', $text) as $word) {
$candidate = $current === '' ? $word : $current . ' ' . $word;
if (self::textWidth($candidate, $size, $font) <= $maxWidth || $current === '') {
$current = $candidate;
continue;
}
$lines[] = $current;
$current = $word;
}
if ($current !== '') {
$lines[] = $current;
}
return $lines;
}
/**
* Bettet ein JPEG ein (DCTDecode, keine Neukodierung nötig).
*
* @param string $source Dateipfad oder JPEG-Bytes
*/
public function imageJpeg(string $source, float $x, float $yTop, float $w, float $h, bool $isBytes = false): bool
{
$bytes = $isBytes ? $source : (is_file($source) ? (string) file_get_contents($source) : '');
if ($bytes === '' || strncmp($bytes, "\xFF\xD8", 2) !== 0) {
return false;
}
$size = getimagesizefromstring($bytes);
if ($size === false) {
return false;
}
$name = 'Im' . (count($this->images) + 1);
$this->images[] = ['bytes' => $bytes, 'w' => (int) $size[0], 'h' => (int) $size[1], 'name' => $name, 'object' => 0];
$this->buffer .= sprintf(
"q %.2F 0 0 %.2F %.2F %.2F cm /%s Do Q\n",
$w,
$h,
$x,
self::PAGE_H - $yTop - $h,
$name
);
return true;
}
public function output(): string
{
$pages = $this->pages;
$pages[] = $this->buffer;
$objects = [];
$fontIds = [];
$nextFontObj = 3;
foreach (self::FONTS as $key => $baseFont) {
$fontIds[$key] = $nextFontObj++;
$objects[$fontIds[$key]] = sprintf(
'<< /Type /Font /Subtype /Type1 /BaseFont /%s /Encoding /WinAnsiEncoding >>',
$baseFont
);
}
// Bilder als XObjects (JPEG, DCTDecode) – IDs nach den Schriften.
$nextImageObj = $nextFontObj;
foreach ($this->images as $index => $image) {
$objectId = $nextImageObj + $index;
$this->images[$index]['object'] = $objectId;
$objects[$objectId] = sprintf(
"<< /Type /XObject /Subtype /Image /Width %d /Height %d /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length %d >>\nstream\n%s\nendstream",
$image['w'],
$image['h'],
strlen($image['bytes']),
$image['bytes']
);
}
$nextFontObj = $nextImageObj + count($this->images);
$imageRefs = '';
foreach ($this->images as $image) {
$imageRefs .= sprintf('/%s %d 0 R ', $image['name'], $image['object']);
}
$pageObjStart = $nextFontObj;
$pageIds = [];
$pageCount = count($pages);
for ($i = 0; $i < $pageCount; $i++) {
$pageIds[] = $pageObjStart + $i * 2;
}
$fontRefs = '';
foreach ($fontIds as $key => $id) {
$fontRefs .= sprintf('/%s %d 0 R ', $key, $id);
}
foreach ($pages as $i => $content) {
$pageId = $pageIds[$i];
$contentId = $pageId + 1;
$xObject = $imageRefs !== '' ? '/XObject << ' . $imageRefs . '>> ' : '';
$objects[$pageId] = sprintf(
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %.2F %.2F] /Resources << /Font << %s>> %s>> /Contents %d 0 R >>',
self::PAGE_W,
self::PAGE_H,
$fontRefs,
$xObject,
$contentId
);
$objects[$contentId] = sprintf(
"<< /Length %d >>\nstream\n%s\nendstream",
strlen($content) + 1,
$content
);
}
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
$objects[2] = sprintf(
'<< /Type /Pages /Count %d /Kids [%s] >>',
$pageCount,
implode(' ', array_map(static fn ($id) => $id . ' 0 R', $pageIds))
);
ksort($objects);
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
$offsets = [];
foreach ($objects as $id => $body) {
$offsets[$id] = strlen($pdf);
$pdf .= sprintf("%d 0 obj\n%s\nendobj\n", $id, $body);
}
$xrefPos = strlen($pdf);
$maxObj = max(array_keys($objects));
$pdf .= sprintf("xref\n0 %d\n", $maxObj + 1);
$pdf .= "0000000000 65535 f \n";
for ($id = 1; $id <= $maxObj; $id++) {
$pdf .= isset($offsets[$id])
? sprintf("%010d 00000 n \n", $offsets[$id])
: "0000000000 65535 f \n";
}
$pdf .= sprintf(
"trailer\n<< /Size %d /Root 1 0 R /Info << /Producer (Westreiche Charakterbogen) >> >>\nstartxref\n%d\n%%%%EOF\n",
$maxObj + 1,
$xrefPos
);
return $pdf;
}
}