3 namespace BookStack\Entities\Tools;
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 BookStack\Util\CspService;
11 use BookStack\Util\HtmlDocument;
18 public function __construct(
19 protected ImageService $imageService,
20 protected PdfGenerator $pdfGenerator,
21 protected CspService $cspService
26 * Convert a page to a self-contained HTML file.
27 * Includes required CSS & image content. Images are base64 encoded into the HTML.
31 public function pageToContainedHtml(Page $page): string
33 $page->html = (new PageContent($page))->render();
34 $pageHtml = view('exports.page', [
37 'cspContent' => $this->cspService->getCspMetaTagValue(),
38 'locale' => user()->getLocale(),
41 return $this->containHtml($pageHtml);
45 * Convert a chapter to a self-contained HTML file.
49 public function chapterToContainedHtml(Chapter $chapter): string
51 $pages = $chapter->getVisiblePages();
52 $pages->each(function ($page) {
53 $page->html = (new PageContent($page))->render();
55 $html = view('exports.chapter', [
56 'chapter' => $chapter,
59 'cspContent' => $this->cspService->getCspMetaTagValue(),
60 'locale' => user()->getLocale(),
63 return $this->containHtml($html);
67 * Convert a book to a self-contained HTML file.
71 public function bookToContainedHtml(Book $book): string
73 $bookTree = (new BookContents($book))->getTree(false, true);
74 $html = view('exports.book', [
76 'bookChildren' => $bookTree,
78 'cspContent' => $this->cspService->getCspMetaTagValue(),
79 'locale' => user()->getLocale(),
82 return $this->containHtml($html);
86 * Convert a page to a PDF file.
90 public function pageToPdf(Page $page): string
92 $page->html = (new PageContent($page))->render();
93 $html = view('exports.page', [
96 'engine' => $this->pdfGenerator->getActiveEngine(),
97 'locale' => user()->getLocale(),
100 return $this->htmlToPdf($html);
104 * Convert a chapter to a PDF file.
108 public function chapterToPdf(Chapter $chapter): string
110 $pages = $chapter->getVisiblePages();
111 $pages->each(function ($page) {
112 $page->html = (new PageContent($page))->render();
115 $html = view('exports.chapter', [
116 'chapter' => $chapter,
119 'engine' => $this->pdfGenerator->getActiveEngine(),
120 'locale' => user()->getLocale(),
123 return $this->htmlToPdf($html);
127 * Convert a book to a PDF file.
131 public function bookToPdf(Book $book): string
133 $bookTree = (new BookContents($book))->getTree(false, true);
134 $html = view('exports.book', [
136 'bookChildren' => $bookTree,
138 'engine' => $this->pdfGenerator->getActiveEngine(),
139 'locale' => user()->getLocale(),
142 return $this->htmlToPdf($html);
146 * Convert normal web-page HTML to a PDF.
150 protected function htmlToPdf(string $html): string
152 $html = $this->containHtml($html);
153 $doc = new HtmlDocument();
154 $doc->loadCompleteHtml($html);
156 $this->replaceIframesWithLinks($doc);
157 $this->openDetailElements($doc);
158 $cleanedHtml = $doc->getHtml();
160 return $this->pdfGenerator->fromHtml($cleanedHtml);
164 * Within the given HTML content, Open any detail blocks.
166 protected function openDetailElements(HtmlDocument $doc): void
168 $details = $doc->queryXPath('//details');
169 /** @var DOMElement $detail */
170 foreach ($details as $detail) {
171 $detail->setAttribute('open', 'open');
176 * Within the given HTML document, replace any iframe elements
177 * with anchor links within paragraph blocks.
179 protected function replaceIframesWithLinks(HtmlDocument $doc): void
181 $iframes = $doc->queryXPath('//iframe');
183 /** @var DOMElement $iframe */
184 foreach ($iframes as $iframe) {
185 $link = $iframe->getAttribute('src');
186 if (str_starts_with($link, '//')) {
187 $link = 'https:' . $link;
190 $anchor = $doc->createElement('a', $link);
191 $anchor->setAttribute('href', $link);
192 $paragraph = $doc->createElement('p');
193 $paragraph->appendChild($anchor);
194 $iframe->parentNode->replaceChild($paragraph, $iframe);
199 * Bundle of the contents of a html file to be self-contained.
203 protected function containHtml(string $htmlContent): string
205 $imageTagsOutput = [];
206 preg_match_all("/\<img.*?src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput);
208 // Replace image src with base64 encoded image strings
209 if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) {
210 foreach ($imageTagsOutput[0] as $index => $imgMatch) {
211 $oldImgTagString = $imgMatch;
212 $srcString = $imageTagsOutput[2][$index];
213 $imageEncoded = $this->imageService->imageUrlToBase64($srcString);
214 if ($imageEncoded === null) {
215 $imageEncoded = $srcString;
217 $newImgTagString = str_replace($srcString, $imageEncoded, $oldImgTagString);
218 $htmlContent = str_replace($oldImgTagString, $newImgTagString, $htmlContent);
223 preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $linksOutput);
225 // Update relative links to be absolute, with instance url
226 if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) {
227 foreach ($linksOutput[0] as $index => $linkMatch) {
228 $oldLinkString = $linkMatch;
229 $srcString = $linksOutput[2][$index];
230 if (!str_starts_with(trim($srcString), 'http')) {
231 $newSrcString = url($srcString);
232 $newLinkString = str_replace($srcString, $newSrcString, $oldLinkString);
233 $htmlContent = str_replace($oldLinkString, $newLinkString, $htmlContent);
242 * Converts the page contents into simple plain text.
243 * This method filters any bad looking content to provide a nice final output.
245 public function pageToPlainText(Page $page, bool $pageRendered = false, bool $fromParent = false): string
247 $html = $pageRendered ? $page->html : (new PageContent($page))->render();
248 // Add proceeding spaces before tags so spaces remain between
249 // text within elements after stripping tags.
250 $html = str_replace('<', " <", $html);
251 $text = trim(strip_tags($html));
252 // Replace multiple spaces with single spaces
253 $text = preg_replace('/ {2,}/', ' ', $text);
254 // Reduce multiple horrid whitespace characters.
255 $text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text);
256 $text = html_entity_decode($text);
258 $text = $page->name . ($fromParent ? "\n" : "\n\n") . $text;
264 * Convert a chapter into a plain text string.
266 public function chapterToPlainText(Chapter $chapter): string
268 $text = $chapter->name . "\n" . $chapter->description;
269 $text = trim($text) . "\n\n";
272 foreach ($chapter->getVisiblePages() as $page) {
273 $parts[] = $this->pageToPlainText($page, false, true);
276 return $text . implode("\n\n", $parts);
280 * Convert a book into a plain text string.
282 public function bookToPlainText(Book $book): string
284 $bookTree = (new BookContents($book))->getTree(false, true);
285 $text = $book->name . "\n" . $book->description;
286 $text = rtrim($text) . "\n\n";
289 foreach ($bookTree as $bookChild) {
290 if ($bookChild->isA('chapter')) {
291 $parts[] = $this->chapterToPlainText($bookChild);
293 $parts[] = $this->pageToPlainText($bookChild, true, true);
297 return $text . implode("\n\n", $parts);
301 * Convert a page to a Markdown file.
303 public function pageToMarkdown(Page $page): string
305 if ($page->markdown) {
306 return '# ' . $page->name . "\n\n" . $page->markdown;
309 return '# ' . $page->name . "\n\n" . (new HtmlToMarkdown($page->html))->convert();
313 * Convert a chapter to a Markdown file.
315 public function chapterToMarkdown(Chapter $chapter): string
317 $text = '# ' . $chapter->name . "\n\n";
318 $text .= $chapter->description . "\n\n";
319 foreach ($chapter->pages as $page) {
320 $text .= $this->pageToMarkdown($page) . "\n\n";
327 * Convert a book into a plain text string.
329 public function bookToMarkdown(Book $book): string
331 $bookTree = (new BookContents($book))->getTree(false, true);
332 $text = '# ' . $book->name . "\n\n";
333 foreach ($bookTree as $bookChild) {
334 if ($bookChild instanceof Chapter) {
335 $text .= $this->chapterToMarkdown($bookChild) . "\n\n";
337 $text .= $this->pageToMarkdown($bookChild) . "\n\n";