5 * Generates the PDF versions of the pages
7 * This file is included by the print_pdf module and includes the
8 * functions that interface with the PDF generation packages.
13 require_once(DRUPAL_ROOT .
'/' .
drupal_get_path('module', 'print') .
'/print.pages.inc');
16 * Generate a PDF version of the printer-friendly page
18 * @see print_controller()
19 * @see _print_pdf_dompdf()
20 * @see _print_pdf_tcpdf()
22 function print_pdf_controller() {
25 // Disable caching for generated PDFs, as Drupal doesn't ouput the proper headers from the cache
26 $GLOBALS['conf']['cache'] = FALSE
;
28 $args = func_get_args();
29 $path = implode('/', $args);
30 $cid = isset($_GET['comment']) ?
(int)$_GET['comment'] : NULL
;
32 $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT
);
34 $print = print_controller($path, $cid, PRINT_PDF_FORMAT
);
35 if ($print === FALSE
) {
39 // Img elements must be set to absolute
40 $pattern = '!<(img\s[^>]*?)>!is';
41 $print['content'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['content']);
42 $print['logo'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['logo']);
43 $print['footer_message'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['footer_message']);
45 // Send to printer option causes problems with PDF
46 $print['sendtoprinter'] = '';
48 $node = $print['node'];
49 $html = theme('print', array('print' => $print, 'type' => PRINT_PDF_FORMAT
, 'node' => $node));
51 // Convert the a href elements, to make sure no relative links remain
52 $pattern = '!<(a\s[^>]*?)>!is';
53 $html = preg_replace_callback($pattern, '_print_rewrite_urls', $html);
54 // And make anchor links relative again, to permit in-PDF navigation
55 $html = preg_replace("!${base_url}/" . PRINTPDF_PATH .
"/.*?%2523!", '#', $html);
57 $pdf_filename = variable_get('print_pdf_filename', PRINT_PDF_FILENAME_DEFAULT
);
58 if (!empty($pdf_filename)) {
59 $pdf_filename = token_replace($pdf_filename, array('node' => $node)) .
'.pdf';
62 $pdf_filename = str_replace('/', '_', $path) .
'.pdf';
64 if (function_exists('transliteration_clean_filename')) {
65 $pdf_filename = transliteration_clean_filename($pdf_filename, language_default('language'));
68 if (basename($print_pdf_pdf_tool) == 'dompdf_config.inc.php') {
69 _print_pdf_dompdf($print, $html, $pdf_filename);
71 elseif (basename($print_pdf_pdf_tool) == 'tcpdf.php') {
72 _print_pdf_tcpdf($print, $html, $pdf_filename);
74 elseif (substr(basename($print_pdf_pdf_tool, '.exe'), 0, 11) == 'wkhtmltopdf') {
75 _print_pdf_wkhtmltopdf($print, $html, $pdf_filename);
78 return drupal_not_found();
81 $nodepath = (isset($node->path
)) ?
drupal_get_normal_path($node->path
) : 'node/' .
$path;
82 db_merge('print_pdf_page_counter')
83 ->key(array('path' => $nodepath))
86 'timestamp' => REQUEST_TIME
,
88 ->expression('totalcount', 'totalcount + :inc', array(':inc' => 1))
93 * Convert image paths to the file:// protocol
95 * In some Drupal setups, the use of the 'private' filesystem or Apache's
96 * configuration prevent access to the images of the page. This function
97 * tries to circumnvent those problems by accessing files in the local
101 * contents of the post-processed template already with the node data
102 * @see print_pdf_controller()
104 function _print_pdf_file_access_images($html) {
105 global $base_url, $language;
107 // And converted from private to public paths
108 switch (variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE
)) {
109 case LANGUAGE_NEGOTIATION_PATH_DEFAULT
:
110 case LANGUAGE_NEGOTIATION_PATH
:
111 $lang = $language->language
;
117 $file_downloads = variable_get('file_default_scheme', 'public');
118 if ($file_downloads == 'private') {
119 $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?)${base_url}/(?:(?:index.php)?\?q=)?(?:${lang}/)?system/files/([^>]*?>)!is";
120 $replacement = '$1file://' .
realpath(file_directory_path()) .
'/$2';
121 $html = preg_replace($pattern, $replacement, $html);
123 $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?)${base_url}/(?:(?:index.php)?\?q=)?(?:${lang}/)?([^>]*?>)!is";
124 $replacement = '$1file://' .
dirname($_SERVER['SCRIPT_FILENAME']) .
'/$2';
125 $html = preg_replace($pattern, $replacement, $html);
131 * Generate the PDF file using the dompdf library
134 * array containing the configured data
136 * contents of the post-processed template already with the node data
138 * name of the PDF file to be generated
139 * @see print_pdf_controller()
141 function _print_pdf_dompdf($print, $html, $filename) {
142 $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT
);
143 $print_pdf_paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT
);
144 $print_pdf_page_orientation = variable_get('print_pdf_page_orientation', PRINT_PDF_PAGE_ORIENTATION_DEFAULT
);
145 $print_pdf_content_disposition = variable_get('print_pdf_content_disposition', PRINT_PDF_CONTENT_DISPOSITION_DEFAULT
);
147 if (variable_get('print_pdf_autoconfig', PRINT_PDF_AUTOCONFIG_DEFAULT
)) {
148 define("DOMPDF_ENABLE_PHP", FALSE
);
149 define("DOMPDF_ENABLE_REMOTE", TRUE
);
150 define("DOMPDF_TEMP_DIR", file_directory_temp());
151 define("DOMPDF_UNICODE_ENABLED", variable_get('print_pdf_dompdf_unicode', PRINT_PDF_DOMPDF_UNICODE_DEFAULT
));
154 require_once(DRUPAL_ROOT .
'/' .
$print_pdf_pdf_tool);
155 spl_autoload_register('DOMPDF_autoload');
157 // Try to use local file access for image files
158 $html = _print_pdf_file_access_images($html);
160 // dompdf seems to have problems with something in system.css so let's not use it
161 $html = preg_replace('!<link.*?modules/system/system.css.*?/>!', '', $html);
163 $url_array = parse_url($print['url']);
165 $protocol = $url_array['scheme'] .
'://';
166 $host = $url_array['host'];
167 $path = dirname($url_array['path']) .
'/';
169 $dompdf = new
DOMPDF();
170 $dompdf->set_base_path($path);
171 $dompdf->set_host($host);
172 $dompdf->set_paper(drupal_strtolower($print_pdf_paper_size), $print_pdf_page_orientation);
173 $dompdf->set_protocol($protocol);
175 // dompdf can't handle footers cleanly, so disable the following
176 // $html = theme('print_pdf_dompdf_footer', array('html' => $html));
178 // If dompdf Unicode support is disabled, try to convert to ISO-8859-1 and then to HTML entities
179 if (!variable_get('print_pdf_dompdf_unicode', PRINT_PDF_DOMPDF_UNICODE_DEFAULT
)) {
180 // Convert the euro sign to an HTML entity
181 $html = str_replace('€', '€', $html);
183 // Convert from UTF-8 to ISO 8859-1 and then to HTML entities
184 if (function_exists('utf8_decode')) {
185 $html = utf8_decode($html);
187 // iconv fails silently when it encounters something that it doesn't know, so don't use it
188 // else if (function_exists('iconv')) {
189 // $html = iconv('UTF-8', 'ISO-8859-1', $html);
191 elseif (function_exists('mb_convert_encoding')) {
192 $html = mb_convert_encoding($html, 'ISO-8859-1', 'UTF-8');
194 elseif (function_exists('recode_string')) {
195 $html = recode_string('UTF-8..ISO_8859-1', $html);
197 $html = htmlspecialchars_decode(htmlentities($html, ENT_NOQUOTES
, 'ISO-8859-1'), ENT_NOQUOTES
);
200 //must get rid of tbody (dompdf goes into recursion)
201 $html = preg_replace('!<tbody[^>]*?>|</tbody>!i', '', $html);
203 $dompdf->load_html($html);
206 $dompdf->stream($filename, array('Attachment' => ($print_pdf_content_disposition == 2)));
210 * Generate the PDF file using the TCPDF library
213 * array containing the configured data
215 * contents of the post-processed template already with the node data
217 * name of the PDF file to be generated
218 * @see print_pdf_controller()
220 function _print_pdf_tcpdf($print, $html, $filename) {
221 global $base_url, $language;
223 $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT
);
224 $print_pdf_paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT
);
225 $print_pdf_page_orientation = variable_get('print_pdf_page_orientation', PRINT_PDF_PAGE_ORIENTATION_DEFAULT
);
226 $print_pdf_content_disposition = variable_get('print_pdf_content_disposition', PRINT_PDF_CONTENT_DISPOSITION_DEFAULT
);
228 $pdf_tool_path = realpath(dirname($print_pdf_pdf_tool));
230 if (variable_get('print_pdf_autoconfig', PRINT_PDF_AUTOCONFIG_DEFAULT
)) {
231 define('K_TCPDF_EXTERNAL_CONFIG', TRUE
);
232 define('K_PATH_MAIN', dirname($_SERVER['SCRIPT_FILENAME']));
233 define('K_PATH_URL', $base_url);
234 define('K_PATH_FONTS', $pdf_tool_path .
'/fonts/');
235 define('K_PATH_CACHE', $pdf_tool_path .
'/cache/');
236 define('K_PATH_IMAGES', '');
237 define('K_BLANK_IMAGE', $pdf_tool_path .
'/images/_blank.png');
238 define('K_CELL_HEIGHT_RATIO', 1.25);
239 define('K_SMALL_RATIO', 2/3);
242 // Try to use local file access for image files
243 $html = _print_pdf_file_access_images($html);
245 // Decode HTML entities in image filenames
246 $pattern = "!<img\s[^>]*?src\s*?=\s*?['\"]?{$base_url}[^>]*?>!is";
247 $html = preg_replace_callback($pattern, create_function('$matches', 'return html_entity_decode($matches[0], ENT_QUOTES);'), $html);
248 // Remove queries from the image URL
249 $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?{$base_url}[^>]*?)(?:%3F|\?)[\w=&]+([^>]*?>)!is";
250 $html = preg_replace($pattern, '$1$2', $html);
252 require_once(DRUPAL_ROOT .
'/' .
$print_pdf_pdf_tool);
253 if (strpos(PDF_PRODUCER
, 'PHP4') === FALSE
) {
254 require_once(DRUPAL_ROOT .
'/' .
drupal_get_path('module', 'print_pdf') .
'/print_pdf.class.inc');
257 drupal_set_message(t("The PHP4 version of TCPDF is not supported. Please upgrade it."), 'error', FALSE
);
258 drupal_goto($_GET['q']);
262 check_plain(variable_get('print_pdf_font_family', PRINT_PDF_FONT_FAMILY_DEFAULT
)),
264 check_plain(variable_get('print_pdf_font_size', PRINT_PDF_FONT_SIZE_DEFAULT
)),
266 $orientation = drupal_strtoupper($print_pdf_page_orientation[0]);
268 // create new PDF document
269 $pdf = new
PrintTCPDF($orientation , 'mm', $print_pdf_paper_size, TRUE
);
271 // set document information
272 $pdf->SetAuthor(strip_tags($print['submitted']));
273 $pdf->SetCreator(variable_get('site_name', 'Drupal'));
274 $pdf->SetTitle(html_entity_decode($print['title'], ENT_QUOTES
, 'UTF-8'));
275 $keys = implode(' ', explode("\n", trim(strip_tags($print['taxonomy']))));
276 $pdf->SetKeywords($keys);
277 $pdf->setPDFVersion('1.6');
279 if ($language->direction
== LANGUAGE_RTL
) {
283 $pdf = theme('print_pdf_tcpdf_header', array('pdf' => $pdf, 'html' => $html, 'font' => $font));
284 $pdf = theme('print_pdf_tcpdf_footer', array('pdf' => $pdf, 'html' => $html, 'font' => $font));
285 $pdf = theme('print_pdf_tcpdf_page', array('pdf' => $pdf));
287 //initialize document
288 $pdf->AliasNbPages();
293 $pdf = theme('print_pdf_tcpdf_content', array('pdf' => $pdf, 'html' => $html, 'font' => $font));
295 // reset pointer to the last page
298 // try to recover from any warning/error
301 //Close and output PDF document
302 $output_dest = ($print_pdf_content_disposition == 2) ?
'D' : 'I';
303 $pdf->Output($filename, $output_dest);
307 * Generate the PDF file using wkhtmltopdf
310 * array containing the configured data
312 * contents of the post-processed template already with the node data
314 * name of the PDF file to be generated
315 * @see print_pdf_controller()
317 function _print_pdf_wkhtmltopdf($print, $html, $filename) {
318 $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT
);
319 $print_pdf_paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT
);
320 $print_pdf_page_orientation = variable_get('print_pdf_page_orientation', PRINT_PDF_PAGE_ORIENTATION_DEFAULT
);
321 $print_pdf_content_disposition = variable_get('print_pdf_content_disposition', PRINT_PDF_CONTENT_DISPOSITION_DEFAULT
);
322 $print_pdf_wkhtmltopdf_options = variable_get('print_pdf_wkhtmltopdf_options', PRINT_PDF_WKHTMLTOPDF_OPTIONS
);
326 if (!empty($print_pdf_wkhtmltopdf_options)) {
327 $print_pdf_wkhtmltopdf_options = token_replace($print_pdf_wkhtmltopdf_options, array('node' => $print['node']));
330 $version = _print_pdf_wkhtmltopdf_version();
332 // 0.10.0 beta2 identifies itself as 0.9.9
333 if (version_compare($version, '0.9.9', '>=')) {
334 $print_pdf_wkhtmltopdf_options = '--disable-local-file-access ' .
$print_pdf_wkhtmltopdf_options;
336 elseif (version_compare($version, '0.9.6', '>=')) {
337 $print_pdf_wkhtmltopdf_options = '--disallow-local-file-access ' .
$print_pdf_wkhtmltopdf_options;
340 drupal_goto($print['url']);
344 $descriptor = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
345 $cmd = realpath($print_pdf_pdf_tool) .
" --page-size $print_pdf_paper_size --orientation $print_pdf_page_orientation --dpi $dpi $print_pdf_wkhtmltopdf_options - -";
347 $process = proc_open($cmd, $descriptor, $pipes, NULL
, NULL
);
349 if (is_resource($process)) {
350 fwrite($pipes[0], $html);
353 $pdf = stream_get_contents($pipes[1]);
356 stream_set_blocking($pipes[2], 0);
357 $error = stream_get_contents($pipes[2]);
358 if (!empty($error)) {
359 watchdog('print_pdf', 'wkhtmltopdf: ' .
$error);
363 $retval = proc_terminate($process);
367 if (headers_sent()) {
368 die("Unable to stream pdf: headers already sent");
370 header("Cache-Control: private");
371 header("Content-Type: application/pdf");
373 $attachment = ($print_pdf_content_disposition == 2) ?
"attachment" : "inline";
375 header("Content-Disposition: $attachment; filename=\"$filename\"");
381 drupal_goto($print['url']);
387 * Format the dompdf footer contents
390 * contents of the body of the HTML from the original node
391 * @see theme_print_pdf_tcpdf_footer()
393 function theme_print_pdf_dompdf_footer($vars) {
394 preg_match('!<div class="print-footer">(.*?)</div>!si', $vars['html'], $tpl_footer);
395 $html = str_replace($tpl_footer[0], '', $vars['html']);
397 $text = '<script type="text/php">
399 $font = Font_Metrics::get_font("verdana");;
401 $color = array(0,0,0);
402 $text_height = Font_Metrics::get_font_height($font, $size);
404 $w = $pdf->get_width();
405 $h = $pdf->get_height();
407 $footer = $pdf->open_object();
409 // Draw a line along the bottom
411 $pdf->line(15, $y, $w - 15, $y, $color, 1);
413 $y += $text_height / 2;
414 $pdf->page_text(15, $y, \'' .
addslashes(strip_tags($tpl_footer[1])) .
'\', $font, $size, $color);
416 $pdf->close_object();
417 $pdf->add_object($footer, "all");
420 $width = Font_Metrics::get_text_width("Page 1 of 2", $font, $size);
421 $pagenumtxt = t("Page !n of !total", array("!n" => "{PAGE_NUM}", "!total" => "{PAGE_COUNT}"));
422 $pdf->page_text($w - 15 - $width, $y, $pagenumtxt, $font, $size, $color);
426 return str_replace("<body>", "<body>" .
$text, $html);
430 * Format the TCPDF header
433 * current TCPDF object
435 * contents of the body of the HTML from the original node
437 * array with the font definition (font name, styles and size)
438 * @see theme_print_pdf_tcpdf_header()
440 function theme_print_pdf_tcpdf_header($vars) {
442 preg_match('!<div class="print-logo">(.*?)</div>!si', $vars['html'], $tpl_logo);
443 preg_match('!<h1 class="print-title">(.*?)</h1>!si', $vars['html'], $tpl_title);
444 preg_match('!<div class="print-site_name">(.*?)</div>!si', $vars['html'], $tpl_site_name);
448 $logo_ret = preg_match('!src\s*=\s*(\'.*?\'|".*?"|[^\s]*)!i', $tpl_logo[1], $matches);
450 $logo = trim($matches[1], '\'"');
451 $size = getimagesize($logo);
452 $ratio = $size ?
($size[0] / $size[1]) : 0;
456 $pdf->setHeaderFont($vars['font']);
458 $pdf->SetHeaderMargin(5);
460 $pdf->SetHeaderData($logo, 10 * $ratio, html_entity_decode($tpl_title[1], ENT_QUOTES
, 'UTF-8'), strip_tags($tpl_site_name[1]));
466 * Format the TCPDF page settings (margins, etc)
469 * current TCPDF object
470 * @see theme_print_pdf_tcpdf_page()
472 function theme_print_pdf_tcpdf_page($vars) {
475 $pdf->SetMargins(15, 20, 15);
476 // set auto page breaks
477 $pdf->SetAutoPageBreak(TRUE
, 15);
478 // set image scale factor
479 sscanf(PDF_PRODUCER
, "TCPDF %d.%d.%d", $major, $minor, $build);
480 $imagescale = (($major >= 4) && ($minor >= 6) && ($build >= 2)) ?
1 : 4;
481 $pdf->setImageScale($imagescale);
482 // set image compression quality
483 $pdf->setJPEGQuality(100);
489 * Format the TCPDF page content
492 * current TCPDF object
494 * contents of the body of the HTML from the original node
496 * array with the font definition (font name, styles and size)
497 * @see theme_print_pdf_tcpdf_content()
499 function theme_print_pdf_tcpdf_content($vars) {
502 $pdf->setFont($vars['font'][0], $vars['font'][1], $vars['font'][2]);
504 preg_match('!<body.*?>(.*)</body>!sim', $vars['html'], $matches);
505 $pattern = '!(?:<div class="print-(?:logo|site_name|breadcrumb|footer)">.*?</div>|<hr class="print-hr" />)!si';
506 $matches[1] = preg_replace($pattern, '', $matches[1]);
508 // Make CCK fields look better
509 $matches[1] = preg_replace('!(<div class="field.*?>)\s*!sm', '$1', $matches[1]);
510 $matches[1] = preg_replace('!(<div class="field.*?>.*?</div>)\s*!sm', '$1', $matches[1]);
511 $matches[1] = preg_replace('!<div( class="field-label.*?>.*?)</div>!sm', '<strong$1</strong>', $matches[1]);
513 // Since TCPDF's writeHTML is so bad with <p>, do everything possible to make it look nice
514 $matches[1] = preg_replace('!<(?:p(|\s+.*?)/?|/p)>!i', '<br$1 />', $matches[1]);
515 $matches[1] = str_replace(array('<div', 'div>'), array('<span', 'span><br />'), $matches[1]);
518 $matches[1] = preg_replace('!(</span>)<br />(\s*?</span><br />)!s', '$1$2', $matches[1]);
519 } while ($prev != $matches[1]);
521 @
$pdf->writeHTML($matches[1]);
527 * Format the TCPDF footer contents
530 * current TCPDF object
532 * contents of the body of the HTML from the original node
534 * array with the font definition (font name, styles and size)
535 * @see theme_print_pdf_tcpdf_footer()
537 function theme_print_pdf_tcpdf_footer($vars) {
539 preg_match('!<div class="print-footer">(.*?)</div>!si', $vars['html'], $tpl_footer);
540 $footer = trim(preg_replace('!</?div[^>]*?>!i', '', $tpl_footer[1]));
543 $vars['font'][2] *= 0.8;
544 $pdf->setFooterFont($vars['font']);
546 $pdf->SetFooterMargin(10);
548 $pdf->SetFooterData($footer);
554 * Format the TCPDF footer layout
557 * current TCPDF object
558 * @see theme_print_pdf_tcpdf_footer2()
560 function theme_print_pdf_tcpdf_footer2($vars) {
562 //Position at 1.5 cm from bottom
563 $pdf->writeHTMLCell(0, 15, 15, -10, $pdf->footer
, 0, 0, 0, TRUE
, '');
565 $ormargins = $pdf->getOriginalMargins();
566 $pagenumtxt = t('Page !n of !total', array('!n' => $pdf->PageNo(), '!total' => $pdf->getAliasNbPages()));
568 if ($pdf->getRTL()) {
569 $pdf->SetX($ormargins['right']);
570 $pdf->Cell(0, 10, $pagenumtxt, 'T', 0, 'L');
573 $pdf->SetX($ormargins['left']);
574 $pdf->Cell(0, 10, $pagenumtxt, 'T', 0, 'R');