]> BookStack Code Mirror - bookstack/blobdiff - app/Entities/Tools/PdfGenerator.php
PDF: Started new command option, merged options, simplified dompdf
[bookstack] / app / Entities / Tools / PdfGenerator.php
index 17a7da9f30536f8bd6d39d5800cb41327e230775..7502c10ff43243488c01e7cea82028def07c740f 100644 (file)
@@ -2,27 +2,32 @@
 
 namespace BookStack\Entities\Tools;
 
-use Barryvdh\DomPDF\Facade as DomPDF;
 use Barryvdh\Snappy\Facades\SnappyPdf;
+use Dompdf\Dompdf;
 
 class PdfGenerator
 {
     const ENGINE_DOMPDF = 'dompdf';
     const ENGINE_WKHTML = 'wkhtml';
+    const ENGINE_COMMAND = 'command';
 
     /**
      * Generate PDF content from the given HTML content.
      */
     public function fromHtml(string $html): string
     {
-        if ($this->getActiveEngine() === self::ENGINE_WKHTML) {
+        $engine = $this->getActiveEngine();
+
+        if ($engine === self::ENGINE_WKHTML) {
             $pdf = SnappyPDF::loadHTML($html);
             $pdf->setOption('print-media-type', true);
-        } else {
-            $pdf = DomPDF::loadHTML($html);
+            return $pdf->output();
+        } else if ($engine === self::ENGINE_COMMAND) {
+            // TODO - Support PDF command
+            return '';
         }
 
-        return $pdf->output();
+        return $this->renderUsingDomPdf($html);
     }
 
     /**
@@ -31,8 +36,45 @@ class PdfGenerator
      */
     public function getActiveEngine(): string
     {
-        $useWKHTML = config('snappy.pdf.binary') !== false && config('app.allow_untrusted_server_fetching') === true;
+        $wkhtmlBinaryPath = config('snappy.pdf.binary');
+        if (file_exists(base_path('wkhtmltopdf'))) {
+            $wkhtmlBinaryPath = base_path('wkhtmltopdf');
+        }
+
+        if (is_string($wkhtmlBinaryPath) && config('app.allow_untrusted_server_fetching') === true) {
+            return self::ENGINE_WKHTML;
+        }
+
+        return self::ENGINE_DOMPDF;
+    }
+
+    protected function renderUsingDomPdf(string $html): string
+    {
+        $options = config('exports.dompdf');
+        $domPdf = new Dompdf($options);
+        $domPdf->setBasePath(base_path('public'));
 
-        return $useWKHTML ? self::ENGINE_WKHTML : self::ENGINE_DOMPDF;
+        $domPdf->loadHTML($this->convertEntities($html));
+        $domPdf->render();
+
+        return (string) $domPdf->output();
+    }
+
+    /**
+     * Taken from https://github.com/barryvdh/laravel-dompdf/blob/v2.1.1/src/PDF.php
+     * Copyright (c) 2021 barryvdh, MIT License
+     * https://github.com/barryvdh/laravel-dompdf/blob/v2.1.1/LICENSE
+     */
+    protected function convertEntities(string $subject): string
+    {
+        $entities = [
+            '€' => '€',
+            '£' => '£',
+        ];
+
+        foreach ($entities as $search => $replace) {
+            $subject = str_replace($search, $replace, $subject);
+        }
+        return $subject;
     }
 }