3 namespace BookStack\Entities\Tools;
5 use Barryvdh\Snappy\Facades\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 $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
30 return $this->renderUsingDomPdf($html);
34 * Get the currently active PDF engine.
35 * Returns the value of an `ENGINE_` const on this class.
37 public function getActiveEngine(): string
39 $wkhtmlBinaryPath = config('snappy.pdf.binary');
40 if (file_exists(base_path('wkhtmltopdf'))) {
41 $wkhtmlBinaryPath = base_path('wkhtmltopdf');
44 if (is_string($wkhtmlBinaryPath) && config('app.allow_untrusted_server_fetching') === true) {
45 return self::ENGINE_WKHTML;
48 return self::ENGINE_DOMPDF;
51 protected function renderUsingDomPdf(string $html): string
53 $options = config('exports.dompdf');
54 $domPdf = new Dompdf($options);
55 $domPdf->setBasePath(base_path('public'));
57 $domPdf->loadHTML($this->convertEntities($html));
60 return (string) $domPdf->output();
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
68 protected function convertEntities(string $subject): string
75 foreach ($entities as $search => $replace) {
76 $subject = str_replace($search, $replace, $subject);