PageMode = ''; } public function Header() { // The first page has the accent band, as an invoice does if ($this->getPage() <= 1) { $this->SetFillColor(13, 110, 253); $this->Rect(0, 0, $this->getPageWidth(), 2.5, 'F'); return; } $margins = $this->getMargins(); $width = $this->getPageWidth() - $margins['left'] - $margins['right']; $this->SetY(9); $this->SetFont('dejavusans', '', 7.5); $this->SetTextColor(108, 117, 125); $this->Cell($width * 0.4, 4, $this->running_left, 0, 0, 'L', false, '', 1); $this->Cell($width * 0.6, 4, $this->running_right, 0, 1, 'R', false, '', 1); $this->SetDrawColor(222, 226, 230); $this->SetLineWidth(0.2); $this->Line($margins['left'], 14, $this->getPageWidth() - $margins['right'], 14); } public function Footer() { $margins = $this->getMargins(); $width = $this->getPageWidth() - $margins['left'] - $margins['right']; $this->SetY(-14); $this->SetDrawColor(222, 226, 230); $this->SetLineWidth(0.2); $this->Line($margins['left'], $this->GetY() - 1.5, $this->getPageWidth() - $margins['right'], $this->GetY() - 1.5); $this->SetFont('dejavusans', '', 7); $this->SetTextColor(108, 117, 125); $this->Cell($width * 0.75, 4, $this->footer_label, 0, 0, 'L'); $this->Cell($width * 0.25, 4, 'Page ' . $this->getAliasNumPage() . ' of ' . $this->getAliasNbPages(), 0, 0, 'R'); } public function Error($msg) { throw new Exception('TCPDF: ' . $msg); } } /** What goes in a document's PDF - for documentPdfRender(), from documentForHandler()'s row. */ function documentPdfDocument(array $row) { global $mysqli; $client_id = intval($row['document_client_id']); $client = mysqli_fetch_row(mysqli_query($mysqli, "SELECT client_name FROM clients WHERE client_id = $client_id")); $tree = folderTree($client_id); $folder_id = intval($row['document_folder_id']); $by_id = intval($row['document_updated_by']) ?: intval($row['document_created_by']); $by = $by_id ? mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_name FROM users WHERE user_id = $by_id")) : null; return [ 'kind' => 'document', 'id' => intval($row['document_id']), 'title' => (string) $row['document_name'], 'description' => (string) $row['document_description'], 'html' => (string) $row['document_content'], 'client' => (string) ($client[0] ?? ''), 'place' => isset($tree[$folder_id]) ? implode(' / ', array_column(folderPath($tree, $folder_id), 'folder_name')) : '', 'updated' => $row['document_updated_at'] ?: $row['document_created_at'], 'by' => (string) ($by[0] ?? ''), ]; } /** What goes in a Knowledge Base article's PDF - for documentPdfRender(), from kbArticleRow(). */ function documentPdfKbArticle(array $row) { return [ 'kind' => 'kb', 'id' => intval($row['kb_article_id']), 'title' => (string) $row['kb_article_title'], 'description' => trim((string) $row['kb_article_summary']), 'html' => (string) $row['kb_article_content'], 'client' => '', 'place' => (string) ($row['category_name'] ?? ''), 'updated' => $row['kb_article_updated_at'] ?: $row['kb_article_created_at'], 'by' => (string) (($row['kb_article_updated_at'] ? $row['updated_by_name'] : $row['created_by_name']) ?? ''), ]; } /** How what it says looks in the PDF - TCPDF reads a style block with each piece it draws. */ function documentPdfStyle() { return ''; } /* * What it says, ready for TCPDF and split at its headings into [heading's * text, bookmark level, HTML] - so each heading can be a bookmark where it * falls. Only headings at the top of the document (or of the one wrapper a * Markdown document has) split it; one inside a table or a list stays where * it is. Two or more headings are needed - with fewer, or HTML that won't * parse, it is one piece with no heading. * * TCPDF takes some looks only from an element's own style, not the style * block: a table's lines and header cells (unless it was made without * lines, border="0"), and code's typeface and shading. */ function documentPdfParts($html) { $whole = [['', 0, $html]]; if (trim($html) === '') { return $whole; } $dom = new DOMDocument(); $errors = libxml_use_internal_errors(true); $loaded = $dom->loadHTML('
' . $html . '
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_PARSEHUGE | LIBXML_NONET); libxml_clear_errors(); libxml_use_internal_errors($errors); $root = $loaded ? $dom->getElementsByTagName('div')->item(0) : null; if (!$root) { return $whole; } $style = function (DOMElement $element, $css) { $element->setAttribute('style', $css . $element->getAttribute('style')); }; foreach (iterator_to_array($dom->getElementsByTagName('table')) as $table) { // Its own rows - not those of a table inside one - each kept whole on a page $rows = []; foreach ($table->childNodes as $child) { $name = strtolower($child->nodeName); if ($name === 'tr') { $rows[] = $child; } elseif (in_array($name, ['thead', 'tbody', 'tfoot'], true)) { foreach ($child->childNodes as $row) { if (strtolower($row->nodeName) === 'tr') { $rows[] = $row; } } } } foreach ($rows as $row) { $row->setAttribute('nobr', 'true'); } $border = trim($table->getAttribute('border')); if ($border !== '' && intval($border) === 0 && strpos(' ' . $table->getAttribute('class') . ' ', ' table-bordered ') === false) { continue; } $table->removeAttribute('border'); $table->setAttribute('cellspacing', '0'); if (!$table->hasAttribute('cellpadding')) { $table->setAttribute('cellpadding', '4'); } foreach ($rows as $row) { foreach ($row->childNodes as $cell) { $name = strtolower($cell->nodeName); if ($name === 'td' || $name === 'th') { $style($cell, 'border:0.3px solid #adb5bd;' . ($name === 'th' ? 'background-color:#f1f3f5;font-weight:bold;' : '')); } } } } foreach (iterator_to_array($dom->getElementsByTagName('pre')) as $pre) { $style($pre, 'font-family:dejavusansmono;font-size:8pt;background-color:#f1f3f5;'); // Without the line break a Markdown code block ends with, drawn as an empty line $last = $pre->lastChild; while ($last && $last->nodeType === XML_ELEMENT_NODE && $last->lastChild) { $last = $last->lastChild; } if ($last && $last->nodeType === XML_TEXT_NODE) { $last->nodeValue = rtrim($last->nodeValue, "\r\n"); } } foreach (iterator_to_array($dom->getElementsByTagName('code')) as $code) { $style($code, 'font-family:dejavusansmono;font-size:8.5pt;'); } // A task list without bullets as well as its boxes foreach (iterator_to_array($dom->getElementsByTagName('ul')) as $list) { $items = 0; $tasks = 0; foreach ($list->childNodes as $item) { if (strtolower($item->nodeName) === 'li') { $items++; $first = $item->firstChild; while ($first && $first->nodeType === XML_TEXT_NODE && trim($first->nodeValue) === '') { $first = $first->nextSibling; } $tasks += $first && $first->nodeType === XML_ELEMENT_NODE && strpos(' ' . $first->getAttribute('class') . ' ', ' itflow-task ') !== false ? 1 : 0; } } if ($items && $tasks === $items) { $style($list, 'list-style-type:none;'); } } // The line breaks between blocks - Markdown's - which TCPDF draws as space $blocks = '/^(address|blockquote|dd|div|dl|dt|h[1-6]|hr|li|ol|p|pre|table|tbody|td|tfoot|th|thead|tr|ul)$/'; foreach (iterator_to_array((new DOMXPath($dom))->query('//text()[normalize-space(.) = ""]')) as $space) { $parent = strtolower($space->parentNode->nodeName); $near = [$space->previousSibling, $space->nextSibling]; $by_block = false; foreach ($near as $node) { $by_block = $by_block || ($node && $node->nodeType === XML_ELEMENT_NODE && preg_match($blocks, strtolower($node->nodeName))); } if ($parent !== 'pre' && ($by_block || preg_match($blocks, $parent) && !$space->previousSibling || preg_match($blocks, $parent) && !$space->nextSibling)) { $space->parentNode->removeChild($space); } } // Into a lone wrapper - a Markdown document's
while (true) { $elements = []; $text = ''; foreach ($root->childNodes as $node) { if ($node->nodeType === XML_ELEMENT_NODE) { $elements[] = $node; } else { $text .= $node->textContent; } } if (count($elements) !== 1 || strtolower($elements[0]->nodeName) !== 'div' || trim($text) !== '') { break; } $root = $elements[0]; } $parts = []; $levels = []; $current = ['', 0, '']; foreach ($root->childNodes as $node) { $tag = $node->nodeType === XML_ELEMENT_NODE ? strtolower($node->nodeName) : ''; $heading = preg_match('/^h([1-6])$/', $tag, $m) ? trim(preg_replace('/\s+/u', ' ', $node->textContent)) : ''; if ($heading !== '') { if ($current[2] !== '' || $current[0] !== '') { $parts[] = $current; } $current = [$heading, intval($m[1]), '']; $levels[] = intval($m[1]); } $current[2] .= $dom->saveHTML($node); } $parts[] = $current; if (count($levels) < 2) { // One piece, with the looks above return [['', 0, implode('', array_column($parts, 2))]]; } // Under the title, at 1: the document's biggest heading, and each smaller one a level further in $top = min($levels); foreach ($parts as &$part) { $part[1] = $part[0] !== '' ? 1 + $part[1] - $top : 0; } return $parts; } /** Draw a document or an article (documentPdfDocument(), documentPdfKbArticle()) - ['name' => file name, 'data' => the PDF]. */ function documentPdfRender(array $item) { $company = billingCompany(); $kb = $item['kind'] === 'kb'; $e = function ($value) { return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); }; $grey = '#6c757d'; $title = (string) $item['title']; // Letter for North America, A4 everywhere else $format = in_array($company['company_country'] ?? '', ['United States', 'USA', 'US', 'Canada'], true) ? 'LETTER' : 'A4'; $pdf = new DocumentPdf('P', 'mm', $format, true, 'UTF-8', false); $pdf->SetCreator('ITFlow'); $pdf->SetAuthor((string) ($company['company_name'] ?? '')); $pdf->SetTitle($title); $pdf->SetSubject($kb ? 'Knowledge Base' : (string) $item['client']); $pdf->SetMargins(16, 20, 16); $pdf->SetHeaderMargin(8); $pdf->SetFooterMargin(12); $pdf->SetAutoPageBreak(true, 20); $pdf->setFontSubsetting(true); $pdf->setImageScale(1.6); $pdf->running_left = $kb ? 'Knowledge Base' : (string) $item['client']; $pdf->running_right = mb_strimwidth($title, 0, 90, '…', 'UTF-8'); $pdf->footer_label = implode(' · ', array_filter([(string) ($company['company_name'] ?? ''), $kb ? 'Knowledge Base' : 'Confidential', date('M j, Y')])); $margins = $pdf->getMargins(); $width = $pdf->getPageWidth() - $margins['left'] - $margins['right']; // By reference: a rolled-back document swaps the object out from under it $write = function ($html) use (&$pdf) { $pdf->SetFont('dejavusans', '', 9); $pdf->SetTextColor(33, 37, 41); $pdf->writeHTML(documentPdfStyle() . $html, true, false, true, false, ''); }; $pdf->AddPage(); $pdf->SetY(12); // Who it is from $from_lines = array_filter([ formatAddress($company['company_address'] ?? '', $company['company_city'] ?? '', $company['company_state'] ?? '', $company['company_zip'] ?? '', $company['company_country'] ?? '', ', '), implode(' · ', array_filter([$company['company_email'] ?? '', $company['phone_display'] ?? '', $company['company_website'] ?? ''])), ]); $logo = !empty($company['logo_path']) && @getimagesize($company['logo_path']) ? '
' : ''; $letterhead = function ($logo) use (&$pdf, $company, $from_lines, $kb, $e, $grey) { $pdf->SetFont('dejavusans', '', 8.5); $pdf->SetTextColor(33, 37, 41); $pdf->writeHTML('
' . $logo . '' . $e($company['company_name'] ?? '') . '
' . nl2br($e(implode("\n", $from_lines))) . '
' . ($kb ? 'KNOWLEDGE BASE' : 'DOCUMENT') . '
' . $e(date('M j, Y')) . '
', true, false, true, false, ''); }; // A logo TCPDF cannot read leaves it without one $pdf->startTransaction(); try { $letterhead($logo); $pdf->commitTransaction(); } catch (Throwable $error) { $pdf = $pdf->rollbackTransaction(); $letterhead(''); } $pdf->Ln(6); // The title, where it is kept and when it was last updated $parts = documentPdfParts(documentHtmlPurify((string) $item['html'])); $bookmarks = count($parts) > 1; if ($bookmarks) { $pdf->Bookmark($title, 0, -1, '', 'B', [33, 37, 41]); } // Lined up with the letterhead and the text, without a cell's padding $padding = $pdf->getCellPaddings(); $pdf->setCellPaddings(0, 0, 0, 0); $pdf->SetFont('dejavusans', 'B', 17); $pdf->SetTextColor(33, 37, 41); $pdf->MultiCell($width, 8, $title, 0, 'L', false, 1); $pdf->SetDrawColor(13, 110, 253); $pdf->SetLineWidth(0.6); $pdf->Line($pdf->GetX(), $pdf->GetY() + 0.5, $pdf->GetX() + 18, $pdf->GetY() + 0.5); $pdf->Ln(2.5); $updated = $item['updated'] ? 'Updated ' . date('M j, Y', strtotime($item['updated'])) . ($item['by'] !== '' ? ' by ' . $item['by'] : '') : ''; $about = implode(' · ', array_filter([(string) $item['client'], (string) $item['place'], $updated])); if ($about !== '') { $pdf->SetFont('dejavusans', '', 8); $pdf->SetTextColor(108, 117, 125); $pdf->MultiCell($width, 4, $about, 0, 'L', false, 1); } if ($item['description'] !== '') { $pdf->Ln(1); $pdf->SetFont('dejavusans', 'I', 9); $pdf->SetTextColor(73, 80, 87); $pdf->MultiCell($width, 4.5, $item['description'], 0, 'L', false, 1); } $pdf->setCellPaddings($padding['L'], $padding['T'], $padding['R'], $padding['B']); $pdf->Ln(3); // What it says, a bookmark at each heading - as plain text when TCPDF can't draw it $pdf->startTransaction(); try { foreach ($parts as [$heading, $level, $html]) { if ($heading !== '') { // A heading near the foot of a page goes over to the next with what follows it, // and otherwise - but at the top of a page - has room above it, as TCPDF gives // none to the first thing it draws if ($pdf->GetY() > $pdf->getPageHeight() - 50) { $pdf->AddPage(); } elseif ($pdf->GetY() > $margins['top'] + 12) { $pdf->Ln($level > 1 ? 2 : 3.5); } if ($bookmarks) { $pdf->Bookmark($heading, $level, -1, '', '', [33, 37, 41]); } } $write(clientExportPdfImages($html, $item['id'], $kb ? 'kb' : 'documents')); } $pdf->commitTransaction(); } catch (Throwable $error) { $pdf = $pdf->rollbackTransaction(); $write('

This ' . ($kb ? 'article' : 'document') . ' has formatting the PDF cannot show, so here is its text.

' . nl2br($e(clientExportText((string) $item['html'])))); } $name = trim(preg_replace('/[^A-Za-z0-9 ._-]/', '', $title)); return ['name' => ($name !== '' ? $name : ($kb ? 'Article' : 'Document')) . '.pdf', 'data' => $pdf->Output('', 'S')]; }