1 | <?php |
||
2 | |||
3 | namespace ProtoneMedia\LaravelMixins\Pdf; |
||
4 | |||
5 | use Symfony\Component\Process\Process; |
||
6 | |||
7 | class Ghostscript implements CanRegeneratePDF |
||
8 | { |
||
9 | /** |
||
10 | * Ghostscript binary path. |
||
11 | */ |
||
12 | private string $bin; |
||
13 | |||
14 | public function __construct(string $bin = 'ghostscript') |
||
15 | { |
||
16 | $this->bin = $bin; |
||
17 | } |
||
18 | |||
19 | /** |
||
20 | * Generates a temporary filename for a PDF file. |
||
21 | * |
||
22 | * @return string |
||
23 | */ |
||
24 | private static function tempFile(): string |
||
25 | { |
||
26 | return tempnam(sys_get_temp_dir(), 'ghostscript') . '.pdf'; |
||
27 | } |
||
28 | |||
29 | /** |
||
30 | * {@inheritdoc} |
||
31 | */ |
||
32 | public function regeneratePdf(string $pdfContents): string |
||
33 | { |
||
34 | file_put_contents($input = static::tempFile(), $pdfContents); |
||
35 | |||
36 | (new Process([ |
||
37 | $this->bin, |
||
38 | '-sDEVICE=pdfwrite', |
||
39 | '-dPDFSETTINGS=/prepress', |
||
40 | '-sOutputFile=' . $destination = static::tempFile(), |
||
41 | $input, |
||
42 | ]))->run(); |
||
43 | |||
44 | return tap(@file_get_contents($destination), function () use ($input, $destination) { |
||
45 | @unlink($input); |
||
0 ignored issues
–
show
|
|||
46 | @unlink($destination); |
||
47 | }); |
||
48 | } |
||
49 | } |
||
50 |
If you suppress an error, we recommend checking for the error condition explicitly: