]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PdfGenerator.php
PDF: Started new command option, merged options, simplified dompdf
[bookstack] / app / Entities / Tools / PdfGenerator.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use Barryvdh\Snappy\Facades\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             $pdf = SnappyPDF::loadHTML($html);
23             $pdf->setOption('print-media-type', true);
24             return $pdf->output();
25         } else if ($engine === self::ENGINE_COMMAND) {
26             // TODO - Support PDF command
27             return '';
28         }
29
30         return $this->renderUsingDomPdf($html);
31     }
32
33     /**
34      * Get the currently active PDF engine.
35      * Returns the value of an `ENGINE_` const on this class.
36      */
37     public function getActiveEngine(): string
38     {
39         $wkhtmlBinaryPath = config('snappy.pdf.binary');
40         if (file_exists(base_path('wkhtmltopdf'))) {
41             $wkhtmlBinaryPath = base_path('wkhtmltopdf');
42         }
43
44         if (is_string($wkhtmlBinaryPath) && config('app.allow_untrusted_server_fetching') === true) {
45             return self::ENGINE_WKHTML;
46         }
47
48         return self::ENGINE_DOMPDF;
49     }
50
51     protected function renderUsingDomPdf(string $html): string
52     {
53         $options = config('exports.dompdf');
54         $domPdf = new Dompdf($options);
55         $domPdf->setBasePath(base_path('public'));
56
57         $domPdf->loadHTML($this->convertEntities($html));
58         $domPdf->render();
59
60         return (string) $domPdf->output();
61     }
62
63     /**
64      * Taken from https://github.com/barryvdh/laravel-dompdf/blob/v2.1.1/src/PDF.php
65      * Copyright (c) 2021 barryvdh, MIT License
66      * https://github.com/barryvdh/laravel-dompdf/blob/v2.1.1/LICENSE
67      */
68     protected function convertEntities(string $subject): string
69     {
70         $entities = [
71             '€' => '&euro;',
72             '£' => '&pound;',
73         ];
74
75         foreach ($entities as $search => $replace) {
76             $subject = str_replace($search, $replace, $subject);
77         }
78         return $subject;
79     }
80 }