Kufrik/app/Model/Faktura/PdfSestava.php

96 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Model\Faktura;
use Mpdf\Config\ConfigVariables;
use Mpdf\Config\FontVariables;
use Mpdf\Mpdf;
use Mpdf\Output\Destination;
use Nette\Bridges\ApplicationLatte\LatteFactory;
use Nette\Utils\FileSystem;
/**
* Společné PDF pro sestavy: písmo, stránka a zápatí na každé straně.
*/
final class PdfSestava
{
public function __construct(
private LatteFactory $latteFactory,
private string $tempDir,
) {
}
/**
* @param array<string, mixed> $params
*/
public function render(
string $templateFile,
array $params,
string $title,
bool $autoPrint = false,
string $orientation = 'P',
): string {
$html = $this->latteFactory->create()->renderToString($templateFile, $params);
$mpdf = $this->create($orientation === 'L');
$mpdf->SetHTMLFooter($this->footer());
$mpdf->SetTitle($title);
$mpdf->SetAuthor('Kufřík');
if ($autoPrint) {
$mpdf->SetJS('this.print();');
}
$mpdf->WriteHTML($html);
return $mpdf->Output('', Destination::STRING_RETURN);
}
private function create(bool $landscape): Mpdf
{
$tempDir = $this->tempDir . DIRECTORY_SEPARATOR . 'mpdf';
FileSystem::createDir($tempDir);
$fontDir = dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'fonts';
$config = (new ConfigVariables())->getDefaults();
$fontData = (new FontVariables())->getDefaults();
return new Mpdf([
'mode' => 'utf-8',
'format' => 'A4',
'orientation' => $landscape ? 'L' : 'P',
'margin_left' => $landscape ? 14 : 18,
'margin_right' => $landscape ? 14 : 16,
'margin_top' => $landscape ? 14 : 16,
'margin_bottom' => $landscape ? 16 : 18,
'margin_footer' => 8,
'default_font' => 'sourcesans3',
'default_font_size' => 9,
'tempDir' => $tempDir,
'shrink_tables_to_fit' => 0,
'fontDir' => array_merge($config['fontDir'], [$fontDir]),
'fontdata' => $fontData['fontdata'] + [
'sourcesans3' => [
'R' => 'SourceSans3-Regular.ttf',
'B' => 'SourceSans3-Bold.ttf',
'I' => 'SourceSans3-It.ttf',
'BI' => 'SourceSans3-BoldIt.ttf',
],
],
]);
}
private function footer(): string
{
$datum = htmlspecialchars((new \DateTimeImmutable('today'))->format('d.m.Y'), ENT_QUOTES, 'UTF-8');
return '<table width="100%" style="font-size: 8pt; color: #444; border-top: 0.2mm solid #ccc;">
<tr>
<td width="33%">Vytvořeno aplikací Kufřík</td>
<td width="34%" align="center">Vytištěno dne: ' . $datum . '.</td>
<td width="33%" align="right">Strana {PAGENO}/{nbpg}</td>
</tr>
</table>';
}
}