1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* Copyright (C) 2020-2022 Jan Böhmer |
4
|
|
|
* |
5
|
|
|
* This program is free software: you can redistribute it and/or modify |
6
|
|
|
* it under the terms of the GNU Affero General Public License as published |
7
|
|
|
* by the Free Software Foundation, either version 3 of the License, or |
8
|
|
|
* (at your option) any later version. |
9
|
|
|
* |
10
|
|
|
* This program is distributed in the hope that it will be useful, |
11
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
12
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
13
|
|
|
* GNU Affero General Public License for more details. |
14
|
|
|
* |
15
|
|
|
* You should have received a copy of the GNU Affero General Public License |
16
|
|
|
* along with this program. If not, see <https://www.gnu.org/licenses/>. |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
namespace App\Services\PDF; |
20
|
|
|
|
21
|
|
|
use Dompdf\Dompdf; |
22
|
|
|
use Dompdf\Options; |
23
|
|
|
use Symfony\Component\HttpKernel\KernelInterface; |
24
|
|
|
use Twig\Environment; |
25
|
|
|
|
26
|
|
|
class TwigPDFRenderer |
27
|
|
|
{ |
28
|
|
|
private $twig; |
29
|
|
|
private $cacheDir; |
30
|
|
|
|
31
|
|
|
public function __construct(Environment $twig, KernelInterface $kernel) |
32
|
|
|
{ |
33
|
|
|
$this->twig = $twig; |
34
|
|
|
$this->cacheDir = $kernel->getCacheDir(); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param string $template The path of the template to render |
39
|
|
|
* @param array $context The twig context (variables) |
40
|
|
|
* @param string $orientation The paper orientation |
41
|
|
|
* @return string The PDF data stream |
42
|
|
|
*/ |
43
|
|
|
public function renderTemplate(string $template, array $context, string $orientation = 'portrait'): string |
44
|
|
|
{ |
45
|
|
|
$html = $this->twig->render($template, $context); |
46
|
|
|
return $this->renderHTML($html, $orientation); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param string $html The HTML to render |
51
|
|
|
* @param string $orientation The paper orientation to use |
52
|
|
|
* @return string The PDF data stream |
53
|
|
|
*/ |
54
|
|
|
public function renderHTML(string $html, string $orientation = 'portrait'): string |
55
|
|
|
{ |
56
|
|
|
$dompdf = new Dompdf(); |
57
|
|
|
|
58
|
|
|
$dompdf->loadHtml($html); |
59
|
|
|
$dompdf->getOptions()->setIsRemoteEnabled(false); |
60
|
|
|
$dompdf->getOptions()->setFontCache($this->cacheDir); |
61
|
|
|
$dompdf->getOptions()->setTempDir($this->cacheDir); |
62
|
|
|
|
63
|
|
|
$dompdf->setPaper('A4', $orientation); |
64
|
|
|
|
65
|
|
|
$dompdf->render(); |
66
|
|
|
return $dompdf->output(); |
67
|
|
|
} |
68
|
|
|
} |