]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PdfGenerator.php
PDF: Removed barryvdh snappy to use snappy direct
[bookstack] / app / Entities / Tools / PdfGenerator.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use Knp\Snappy\Pdf as SnappyPdf;
6 use Dompdf\Dompdf;
7
8 class PdfGenerator
9 {
10     const ENGINE_DOMPDF = 'dompdf';
11     const ENGINE_WKHTML = 'wkhtml';
12     const ENGINE_COMMAND = 'command';
13
14     /**
15      * Generate PDF content from the given HTML content.
16      */
17     public function fromHtml(string $html): string
18     {
19         $engine = $this->getActiveEngine();
20
21         if ($engine === self::ENGINE_WKHTML) {
22             return $this->renderUsingWkhtml($html);
23         } else if ($engine === self::ENGINE_COMMAND) {
24             // TODO - Support PDF command
25             return '';
26         }
27
28         return $this->renderUsingDomPdf($html);
29     }
30
31     /**
32      * Get the currently active PDF engine.
33      * Returns the value of an `ENGINE_` const on this class.
34      */
35     public function getActiveEngine(): string
36     {
37         if ($this->getWkhtmlBinaryPath() && config('app.allow_untrusted_server_fetching') === true) {
38             return self::ENGINE_WKHTML;
39         }
40
41         return self::ENGINE_DOMPDF;
42     }
43
44     protected function getWkhtmlBinaryPath(): string
45     {
46         $wkhtmlBinaryPath = config('exports.snappy.pdf_binary');
47         if (file_exists(base_path('wkhtmltopdf'))) {
48             $wkhtmlBinaryPath = base_path('wkhtmltopdf');
49         }
50
51         return $wkhtmlBinaryPath ?: '';
52     }
53
54     protected function renderUsingDomPdf(string $html): string
55     {
56         $options = config('exports.dompdf');
57         $domPdf = new Dompdf($options);
58         $domPdf->setBasePath(base_path('public'));
59
60         $domPdf->loadHTML($this->convertEntities($html));
61         $domPdf->render();
62
63         return (string) $domPdf->output();
64     }
65
66     protected function renderUsingWkhtml(string $html): string
67     {
68         $snappy = new SnappyPdf($this->getWkhtmlBinaryPath());
69         $options = config('exports.snappy.options');
70         return $snappy->getOutputFromHtml($html, $options);
71     }
72
73     /**
74      * Taken from https://github.com/barryvdh/laravel-dompdf/blob/v2.1.1/src/PDF.php
75      * Copyright (c) 2021 barryvdh, MIT License
76      * https://github.com/barryvdh/laravel-dompdf/blob/v2.1.1/LICENSE
77      */
78     protected function convertEntities(string $subject): string
79     {
80         $entities = [
81             '€' => '&euro;',
82             '£' => '&pound;',
83         ];
84
85         foreach ($entities as $search => $replace) {
86             $subject = str_replace($search, $replace, $subject);
87         }
88         return $subject;
89     }
90 }