3 namespace BookStack\Entities\Tools;
5 use Knp\Snappy\Pdf as SnappyPdf;
10 const ENGINE_DOMPDF = 'dompdf';
11 const ENGINE_WKHTML = 'wkhtml';
12 const ENGINE_COMMAND = 'command';
15 * Generate PDF content from the given HTML content.
17 public function fromHtml(string $html): string
19 $engine = $this->getActiveEngine();
21 if ($engine === self::ENGINE_WKHTML) {
22 return $this->renderUsingWkhtml($html);
23 } else if ($engine === self::ENGINE_COMMAND) {
24 // TODO - Support PDF command
28 return $this->renderUsingDomPdf($html);
32 * Get the currently active PDF engine.
33 * Returns the value of an `ENGINE_` const on this class.
35 public function getActiveEngine(): string
37 if ($this->getWkhtmlBinaryPath() && config('app.allow_untrusted_server_fetching') === true) {
38 return self::ENGINE_WKHTML;
41 return self::ENGINE_DOMPDF;
44 protected function getWkhtmlBinaryPath(): string
46 $wkhtmlBinaryPath = config('exports.snappy.pdf_binary');
47 if (file_exists(base_path('wkhtmltopdf'))) {
48 $wkhtmlBinaryPath = base_path('wkhtmltopdf');
51 return $wkhtmlBinaryPath ?: '';
54 protected function renderUsingDomPdf(string $html): string
56 $options = config('exports.dompdf');
57 $domPdf = new Dompdf($options);
58 $domPdf->setBasePath(base_path('public'));
60 $domPdf->loadHTML($this->convertEntities($html));
63 return (string) $domPdf->output();
66 protected function renderUsingWkhtml(string $html): string
68 $snappy = new SnappyPdf($this->getWkhtmlBinaryPath());
69 $options = config('exports.snappy.options');
70 return $snappy->getOutputFromHtml($html, $options);
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
78 protected function convertEntities(string $subject): string
85 foreach ($entities as $search => $replace) {
86 $subject = str_replace($search, $replace, $subject);