]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/ExportFormatter.php
Added option to configure PDF export paper size
[bookstack] / app / Entities / Tools / ExportFormatter.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Entities\Tools\Markdown\HtmlToMarkdown;
9 use BookStack\Uploads\ImageService;
10 use DOMDocument;
11 use DOMElement;
12 use DOMXPath;
13 use Exception;
14 use Throwable;
15
16 class ExportFormatter
17 {
18     protected $imageService;
19     protected $pdfGenerator;
20
21     /**
22      * ExportService constructor.
23      */
24     public function __construct(ImageService $imageService, PdfGenerator $pdfGenerator)
25     {
26         $this->imageService = $imageService;
27         $this->pdfGenerator = $pdfGenerator;
28     }
29
30     /**
31      * Convert a page to a self-contained HTML file.
32      * Includes required CSS & image content. Images are base64 encoded into the HTML.
33      *
34      * @throws Throwable
35      */
36     public function pageToContainedHtml(Page $page)
37     {
38         $page->html = (new PageContent($page))->render();
39         $pageHtml = view('pages.export', [
40             'page'   => $page,
41             'format' => 'html',
42         ])->render();
43
44         return $this->containHtml($pageHtml);
45     }
46
47     /**
48      * Convert a chapter to a self-contained HTML file.
49      *
50      * @throws Throwable
51      */
52     public function chapterToContainedHtml(Chapter $chapter)
53     {
54         $pages = $chapter->getVisiblePages();
55         $pages->each(function ($page) {
56             $page->html = (new PageContent($page))->render();
57         });
58         $html = view('chapters.export', [
59             'chapter' => $chapter,
60             'pages'   => $pages,
61             'format'  => 'html',
62         ])->render();
63
64         return $this->containHtml($html);
65     }
66
67     /**
68      * Convert a book to a self-contained HTML file.
69      *
70      * @throws Throwable
71      */
72     public function bookToContainedHtml(Book $book)
73     {
74         $bookTree = (new BookContents($book))->getTree(false, true);
75         $html = view('books.export', [
76             'book'         => $book,
77             'bookChildren' => $bookTree,
78             'format'       => 'html',
79         ])->render();
80
81         return $this->containHtml($html);
82     }
83
84     /**
85      * Convert a page to a PDF file.
86      *
87      * @throws Throwable
88      */
89     public function pageToPdf(Page $page)
90     {
91         $page->html = (new PageContent($page))->render();
92         $html = view('pages.export', [
93             'page'   => $page,
94             'format' => 'pdf',
95             'engine' => $this->pdfGenerator->getActiveEngine(),
96         ])->render();
97
98         return $this->htmlToPdf($html);
99     }
100
101     /**
102      * Convert a chapter to a PDF file.
103      *
104      * @throws Throwable
105      */
106     public function chapterToPdf(Chapter $chapter)
107     {
108         $pages = $chapter->getVisiblePages();
109         $pages->each(function ($page) {
110             $page->html = (new PageContent($page))->render();
111         });
112
113         $html = view('chapters.export', [
114             'chapter' => $chapter,
115             'pages'   => $pages,
116             'format'  => 'pdf',
117             'engine'  => $this->pdfGenerator->getActiveEngine(),
118         ])->render();
119
120         return $this->htmlToPdf($html);
121     }
122
123     /**
124      * Convert a book to a PDF file.
125      *
126      * @throws Throwable
127      */
128     public function bookToPdf(Book $book)
129     {
130         $bookTree = (new BookContents($book))->getTree(false, true);
131         $html = view('books.export', [
132             'book'         => $book,
133             'bookChildren' => $bookTree,
134             'format'       => 'pdf',
135             'engine'       => $this->pdfGenerator->getActiveEngine(),
136         ])->render();
137
138         return $this->htmlToPdf($html);
139     }
140
141     /**
142      * Convert normal web-page HTML to a PDF.
143      *
144      * @throws Exception
145      */
146     protected function htmlToPdf(string $html): string
147     {
148         $html = $this->containHtml($html);
149         $html = $this->replaceIframesWithLinks($html);
150
151         return $this->pdfGenerator->fromHtml($html);
152     }
153
154     /**
155      * Within the given HTML content, replace any iframe elements
156      * with anchor links within paragraph blocks.
157      */
158     protected function replaceIframesWithLinks(string $html): string
159     {
160         libxml_use_internal_errors(true);
161
162         $doc = new DOMDocument();
163         $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
164         $xPath = new DOMXPath($doc);
165
166         $iframes = $xPath->query('//iframe');
167         /** @var DOMElement $iframe */
168         foreach ($iframes as $iframe) {
169             $link = $iframe->getAttribute('src');
170             if (strpos($link, '//') === 0) {
171                 $link = 'https:' . $link;
172             }
173
174             $anchor = $doc->createElement('a', $link);
175             $anchor->setAttribute('href', $link);
176             $paragraph = $doc->createElement('p');
177             $paragraph->appendChild($anchor);
178             $iframe->parentNode->replaceChild($paragraph, $iframe);
179         }
180
181         return $doc->saveHTML();
182     }
183
184     /**
185      * Bundle of the contents of a html file to be self-contained.
186      *
187      * @throws Exception
188      */
189     protected function containHtml(string $htmlContent): string
190     {
191         $imageTagsOutput = [];
192         preg_match_all("/\<img.*?src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput);
193
194         // Replace image src with base64 encoded image strings
195         if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) {
196             foreach ($imageTagsOutput[0] as $index => $imgMatch) {
197                 $oldImgTagString = $imgMatch;
198                 $srcString = $imageTagsOutput[2][$index];
199                 $imageEncoded = $this->imageService->imageUriToBase64($srcString);
200                 if ($imageEncoded === null) {
201                     $imageEncoded = $srcString;
202                 }
203                 $newImgTagString = str_replace($srcString, $imageEncoded, $oldImgTagString);
204                 $htmlContent = str_replace($oldImgTagString, $newImgTagString, $htmlContent);
205             }
206         }
207
208         $linksOutput = [];
209         preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $linksOutput);
210
211         // Replace image src with base64 encoded image strings
212         if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) {
213             foreach ($linksOutput[0] as $index => $linkMatch) {
214                 $oldLinkString = $linkMatch;
215                 $srcString = $linksOutput[2][$index];
216                 if (strpos(trim($srcString), 'http') !== 0) {
217                     $newSrcString = url($srcString);
218                     $newLinkString = str_replace($srcString, $newSrcString, $oldLinkString);
219                     $htmlContent = str_replace($oldLinkString, $newLinkString, $htmlContent);
220                 }
221             }
222         }
223
224         // Replace any relative links with system domain
225         return $htmlContent;
226     }
227
228     /**
229      * Converts the page contents into simple plain text.
230      * This method filters any bad looking content to provide a nice final output.
231      */
232     public function pageToPlainText(Page $page): string
233     {
234         $html = (new PageContent($page))->render();
235         $text = strip_tags($html);
236         // Replace multiple spaces with single spaces
237         $text = preg_replace('/\ {2,}/', ' ', $text);
238         // Reduce multiple horrid whitespace characters.
239         $text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text);
240         $text = html_entity_decode($text);
241         // Add title
242         $text = $page->name . "\n\n" . $text;
243
244         return $text;
245     }
246
247     /**
248      * Convert a chapter into a plain text string.
249      */
250     public function chapterToPlainText(Chapter $chapter): string
251     {
252         $text = $chapter->name . "\n\n";
253         $text .= $chapter->description . "\n\n";
254         foreach ($chapter->getVisiblePages() as $page) {
255             $text .= $this->pageToPlainText($page);
256         }
257
258         return $text;
259     }
260
261     /**
262      * Convert a book into a plain text string.
263      */
264     public function bookToPlainText(Book $book): string
265     {
266         $bookTree = (new BookContents($book))->getTree(false, false);
267         $text = $book->name . "\n\n";
268         foreach ($bookTree as $bookChild) {
269             if ($bookChild->isA('chapter')) {
270                 $text .= $this->chapterToPlainText($bookChild);
271             } else {
272                 $text .= $this->pageToPlainText($bookChild);
273             }
274         }
275
276         return $text;
277     }
278
279     /**
280      * Convert a page to a Markdown file.
281      */
282     public function pageToMarkdown(Page $page): string
283     {
284         if ($page->markdown) {
285             return '# ' . $page->name . "\n\n" . $page->markdown;
286         }
287
288         return '# ' . $page->name . "\n\n" . (new HtmlToMarkdown($page->html))->convert();
289     }
290
291     /**
292      * Convert a chapter to a Markdown file.
293      */
294     public function chapterToMarkdown(Chapter $chapter): string
295     {
296         $text = '# ' . $chapter->name . "\n\n";
297         $text .= $chapter->description . "\n\n";
298         foreach ($chapter->pages as $page) {
299             $text .= $this->pageToMarkdown($page) . "\n\n";
300         }
301
302         return $text;
303     }
304
305     /**
306      * Convert a book into a plain text string.
307      */
308     public function bookToMarkdown(Book $book): string
309     {
310         $bookTree = (new BookContents($book))->getTree(false, true);
311         $text = '# ' . $book->name . "\n\n";
312         foreach ($bookTree as $bookChild) {
313             if ($bookChild instanceof Chapter) {
314                 $text .= $this->chapterToMarkdown($bookChild);
315             } else {
316                 $text .= $this->pageToMarkdown($bookChild);
317             }
318         }
319
320         return $text;
321     }
322 }