From 18650ba7ad03821205b19f18f7cca0bb8921f033 Mon Sep 17 00:00:00 2001 From: Philipp Lang Date: Wed, 29 Nov 2023 23:01:01 +0100 Subject: [PATCH] Add merge --- src/BaseCompiler.php | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/BaseCompiler.php b/src/BaseCompiler.php index 379ae6c..68def13 100644 --- a/src/BaseCompiler.php +++ b/src/BaseCompiler.php @@ -10,7 +10,14 @@ use Log; abstract class BaseCompiler implements Responsable { - protected File $file; + public function __construct(protected ?File $file = null) + { + } + + public static function fromFile(string $file): static + { + return new static(new File($file, false)); + } public function compile(Document $document): self { @@ -41,6 +48,32 @@ abstract class BaseCompiler implements Responsable return $this; } + /** + * @param array $documents + */ + public function merge(array $documents): self + { + $outfile = '/tmp/' . Str::uuid()->toString() . '.pdf'; + $paths = array_map(fn ($document) => static::compile($document)->getPath(), $documents); + $command = collect([ + 'pdfjam --nup 1x1 --outfile ' . $outfile, + ...array_map(fn ($path) => escapeshellarg($path), $paths), + ])->implode(' '); + + exec($command, $output, $returnVar); + + foreach ($paths as $path) { + @unlink($path); + } + + if (0 !== $returnVar) { + Log::error('Merging failed', ['output' => $output]); + throw (new CompilerException('Compilation failed.'))->setOutput($output); + } + + return static::fromFile($outfile); + } + public function storeAs(string $directory, string $name, string $disk): string { $contents = $this->file->getContent();