|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Traincase\HtmlToPdfTinker\Drivers; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use League\Flysystem\Filesystem; |
|
7
|
|
|
use mikehaertl\wkhtmlto\Pdf; |
|
8
|
|
|
use Traincase\HtmlToPdfTinker\DTO\PdfToGenerateDTO; |
|
9
|
|
|
use Traincase\HtmlToPdfTinker\Exceptions\PdfCouldNotBeCreatedException; |
|
10
|
|
|
|
|
11
|
|
|
class WkhtmltopdfDriver extends Driver |
|
12
|
|
|
{ |
|
13
|
|
|
private Pdf $wkhtmltopdf; |
|
14
|
|
|
|
|
15
|
3 |
|
public function __construct(Pdf $wkhtmltopdf) |
|
16
|
|
|
{ |
|
17
|
3 |
|
$this->wkhtmltopdf = $wkhtmltopdf; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Create the PDF and return it in string format. |
|
22
|
|
|
* |
|
23
|
|
|
* @param Filesystem $filesystem Filesystem used for storing the PDF |
|
24
|
|
|
* @param PdfToGenerateDTO $dto Data needed to generate the PDF file |
|
25
|
|
|
* @return string Filepath to the generated PDF file |
|
26
|
|
|
* @throws PdfCouldNotBeCreatedException |
|
27
|
|
|
*/ |
|
28
|
3 |
|
public function storeOnFilesystem(Filesystem $filesystem, PdfToGenerateDTO $dto): string |
|
29
|
|
|
{ |
|
30
|
|
|
try { |
|
31
|
3 |
|
$options = array_merge([ |
|
32
|
3 |
|
'orientation' => $dto->orientation |
|
33
|
3 |
|
], $dto->options); |
|
34
|
|
|
|
|
35
|
3 |
|
$pdf = $this->generatePdf($dto->html, $options); |
|
36
|
|
|
|
|
37
|
3 |
|
if (!$pdf) { |
|
38
|
1 |
|
throw new \Exception('Wkhtmltopdf could not create PDF'); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
2 |
|
$fullPath = $this->getFullPath($dto->path, $dto->filename); |
|
42
|
|
|
|
|
43
|
2 |
|
$filesystem->write($fullPath, $pdf); |
|
44
|
|
|
|
|
45
|
1 |
|
return $fullPath; |
|
46
|
2 |
|
} catch (\Exception $e) { |
|
47
|
2 |
|
throw new PdfCouldNotBeCreatedException('Wkhtmltopdf could not create PDF', $e->getCode(), $e); |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param string $html |
|
53
|
|
|
* @param array $options |
|
54
|
|
|
* @return string |
|
55
|
|
|
* @throws Exception |
|
56
|
|
|
*/ |
|
57
|
3 |
|
protected function generatePdf(string $html, array $options): string |
|
58
|
|
|
{ |
|
59
|
|
|
// Cloning the wkhtmltopdf class, since we're not able to reset/flush it. |
|
60
|
|
|
// If we generate multiple pdfs with the same driver we don't want |
|
61
|
|
|
// pages of the first PDF showing up in the second and nth... |
|
62
|
3 |
|
$wk = clone $this->wkhtmltopdf; |
|
63
|
|
|
|
|
64
|
3 |
|
$wk->setOptions($options); |
|
65
|
|
|
|
|
66
|
3 |
|
$wk->addPage($html); |
|
67
|
|
|
|
|
68
|
3 |
|
$pdf = $wk->toString(); |
|
69
|
|
|
|
|
70
|
3 |
|
return (string) $pdf; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|