feat: convert uploaded contracts and invoices to pdf

This commit is contained in:
Björn Fromme
2025-03-04 14:13:09 +01:00
parent ab6d350045
commit 917640183f
9 changed files with 164 additions and 8 deletions
+9 -2
View File
@@ -8,12 +8,19 @@ use Symfony\Component\Filesystem\Filesystem;
class InvoiceApprover extends AbstractPdfRenderer
{
/**
* @throws \InvalidArgumentException
*/
public function render(Disposition $disposition): Pdf
{
$teamer = $disposition->getTeamer();
$assignment = $disposition->getAssignment();
$invoice = $disposition->getDocumentByType(Upload::TYPE_INVOICE);
$originalPdfFilename = $invoice->getFilename();
$originalFilename = $invoice->getFilename();
if ('application/pdf' !== $invoice->getMimeType()) {
throw new \InvalidArgumentException('Expected PDF but got '.$invoice->getMimeType());
}
$pdf = new Pdf();
@@ -21,7 +28,7 @@ class InvoiceApprover extends AbstractPdfRenderer
$pdf->SetCreator($teamer->getFullName(), true);
// Load template
$filepath = sprintf('%s/uploads/invoice/%s', $this->config['project_dir'], $originalPdfFilename);
$filepath = sprintf('%s/uploads/invoice/%s', $this->config['project_dir'], $originalFilename);
$pdf->appendPdf($filepath);
$pdf->setPage(1);
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace App\Service\Pdf;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
class Sanitizer
{
public function __construct(
private readonly string $binGs,
private readonly string $binConvert,
private readonly string $tempDir,
) {
}
/**
* @throws \InvalidArgumentException
*/
public function sanitizeFile(string $inputFilepath, ?string $targetFilepath = null, bool $backup = true): string
{
$filesystem = new Filesystem();
if (true === $backup) {
$filesystem->copy($inputFilepath, $inputFilepath.'.bak');
}
$tempFilename = sha1($inputFilepath);
$outputFilepath = $this->tempDir.'/'.$tempFilename;
$pdfFilepath = null;
if (null === $targetFilepath) {
$targetFilepath = $inputFilepath.'.pdf';
}
if ('pdf' !== pathinfo($inputFilepath, PATHINFO_EXTENSION)) {
$pdfFilepath = $outputFilepath.'.pdf';
$command = [
$this->binConvert,
$inputFilepath,
$pdfFilepath,
];
$process = new Process($command);
$process->run();
if (false === $process->isSuccessful()) {
throw new \InvalidArgumentException('File could not be sanitized: '.$process->getErrorOutput());
}
$inputFilepath = $pdfFilepath;
}
$command = [
$this->binGs,
'-dNOPAUSE',
'-dQUIET',
'-dBATCH',
'-sDEVICE=pdfwrite',
'-dCompatibilityLevel=1.4',
'-sOutputFile='.$outputFilepath,
'-f',
$inputFilepath,
];
$process = new Process($command);
$process->run();
if (false === $process->isSuccessful()) {
throw new \InvalidArgumentException('File could not be sanitized: '.$process->getErrorOutput());
}
$filesystem->rename($outputFilepath, $targetFilepath, true);
if (null !== $pdfFilepath) {
$filesystem->remove($pdfFilepath);
}
return $targetFilepath;
}
}