1 <?php namespace BookStack\Services;
10 * Convert a page to a self-contained HTML file.
11 * Includes required CSS & image content. Images are base64 encoded into the HTML.
13 * @return mixed|string
15 public function pageToContainedHtml(Page $page)
17 $cssContent = file_get_contents(public_path('/css/export-styles.css'));
18 $pageHtml = view('pages/export', ['page' => $page, 'css' => $cssContent])->render();
19 return $this->containHtml($pageHtml);
23 * Convert a page to a pdf file.
25 * @return mixed|string
27 public function pageToPdf(Page $page)
29 $cssContent = file_get_contents(public_path('/css/export-styles.css'));
30 $pageHtml = view('pages/pdf', ['page' => $page, 'css' => $cssContent])->render();
31 $containedHtml = $this->containHtml($pageHtml);
32 $pdf = \PDF::loadHTML($containedHtml);
33 return $pdf->output();
37 * Bundle of the contents of a html file to be self-contained.
39 * @return mixed|string
41 protected function containHtml($htmlContent)
43 $imageTagsOutput = [];
44 preg_match_all("/\<img.*src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput);
46 // Replace image src with base64 encoded image strings
47 if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) {
48 foreach ($imageTagsOutput[0] as $index => $imgMatch) {
49 $oldImgString = $imgMatch;
50 $srcString = $imageTagsOutput[2][$index];
51 $isLocal = strpos(trim($srcString), 'http') !== 0;
53 $pathString = public_path(trim($srcString, '/'));
55 $pathString = $srcString;
57 if ($isLocal && !file_exists($pathString)) continue;
58 $imageContent = file_get_contents($pathString);
59 $imageEncoded = 'data:image/' . pathinfo($pathString, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageContent);
60 $newImageString = str_replace($srcString, $imageEncoded, $oldImgString);
61 $htmlContent = str_replace($oldImgString, $newImageString, $htmlContent);
66 preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $linksOutput);
68 // Replace image src with base64 encoded image strings
69 if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) {
70 foreach ($linksOutput[0] as $index => $linkMatch) {
71 $oldLinkString = $linkMatch;
72 $srcString = $linksOutput[2][$index];
73 if (strpos(trim($srcString), 'http') !== 0) {
74 $newSrcString = url($srcString);
75 $newLinkString = str_replace($srcString, $newSrcString, $oldLinkString);
76 $htmlContent = str_replace($oldLinkString, $newLinkString, $htmlContent);
81 // Replace any relative links with system domain
86 * Converts the page contents into simple plain text.
87 * This method filters any bad looking content to
88 * provide a nice final output.
92 public function pageToPlainText(Page $page)
95 // Replace multiple spaces with single spaces
96 $text = preg_replace('/\ {2,}/', ' ', $text);
97 // Reduce multiple horrid whitespace characters.
98 $text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text);
99 $text = html_entity_decode($text);
101 $text = $page->name . "\n\n" . $text;