print_pdf.pages.inc 20.5 KB
Newer Older
jcnventura's avatar
jcnventura committed
1
<?php
jcnventura's avatar
jcnventura committed
2 3 4 5 6 7 8

/**
 * @file
 * Generates the PDF versions of the pages
 *
 * This file is included by the print_pdf module and includes the
 * functions that interface with the PDF generation packages.
9 10
 *
 * @ingroup print
jcnventura's avatar
jcnventura committed
11
 */
jcnventura's avatar
jcnventura committed
12

13
module_load_include('inc', 'print', 'print.pages');
jcnventura's avatar
jcnventura committed
14

15 16 17 18 19 20 21
/**
 * Generate a PDF version of the printer-friendly page
 *
 * @see print_controller()
 * @see _print_pdf_dompdf()
 * @see _print_pdf_tcpdf()
 */
jcnventura's avatar
jcnventura committed
22
function print_pdf_controller() {
23 24 25
  // Disable caching for generated PDFs, as Drupal doesn't ouput the proper headers from the cache
  $GLOBALS['conf']['cache'] = FALSE;

26 27
  $args = func_get_args();
  $path = implode('/', $args);
28
  $cid = isset($_GET['comment']) ? (int)$_GET['comment'] : NULL;
jcnventura's avatar
jcnventura committed
29

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
  if (!empty($path)) {
    if ($alias = drupal_lookup_path('source', $path)) {
      // Alias
      $path_arr = explode('/', $alias);
      $node = node_load($path_arr[1]);
    }
    elseif (ctype_digit($args[0])) {
      // normal nid
      $node = node_load($args[0]);
    }

    $pdf_filename = variable_get('print_pdf_filename', PRINT_PDF_FILENAME_DEFAULT);
    if (!empty($pdf_filename) && !empty($node)) {
      $pdf_filename = token_replace($pdf_filename, array('node' => $node)) . '.pdf';
    }
    else {
      $pdf_filename = str_replace('/', '_', $path) . '.pdf';
    }
48 49
  }
  else {
50
    $pdf_filename = 'page.pdf';
51 52 53 54 55 56 57 58 59 60
  }
  if (function_exists('transliteration_clean_filename')) {
    $pdf_filename = transliteration_clean_filename($pdf_filename, language_default('language'));
  }

  $pdf = print_pdf_generate_path($path, $cid, $pdf_filename);
  if ($pdf == NULL) {
    drupal_goto($print['url']);
    exit;
  }
jcnventura's avatar
jcnventura committed
61

62
  $nodepath = (isset($node->path) && is_string($node->path)) ? drupal_get_normal_path($node->path) : 'node/' . $path;
63 64 65 66 67 68
  db_merge('print_pdf_page_counter')
    ->key(array('path' => $nodepath))
    ->fields(array(
        'totalcount' => 1,
        'timestamp' => REQUEST_TIME,
    ))
69
    ->expression('totalcount', 'totalcount + 1')
70 71 72 73
    ->execute();
}

function print_pdf_generate_path($path, $cid = NULL, $pdf_filename = NULL) {
74 75
  global $base_url;

jcnventura's avatar
jcnventura committed
76
  $print = print_controller($path, $cid, PRINT_PDF_FORMAT);
77 78 79 80
  if ($print === FALSE) {
    return;
  }

jcnventura's avatar
jcnventura committed
81
  // Img elements must be set to absolute
82 83 84 85
  $pattern = '!<(img\s[^>]*?)>!is';
  $print['content'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['content']);
  $print['logo'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['logo']);
  $print['footer_message'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['footer_message']);
86

87 88
  // Send to printer option causes problems with PDF
  $print['sendtoprinter'] = '';
jcnventura's avatar
jcnventura committed
89

90
  $node = $print['node'];
91
  $html = theme('print', array('print' => $print, 'type' => PRINT_PDF_FORMAT, 'node' => $node));
92

93
  // Convert the a href elements, to make sure no relative links remain
94 95
  $pattern = '!<(a\s[^>]*?)>!is';
  $html = preg_replace_callback($pattern, '_print_rewrite_urls', $html);
96
  // And make anchor links relative again, to permit in-PDF navigation
97
  $html = preg_replace("!${base_url}/" . PRINTPDF_PATH . '/.*?#!', '#', $html);
98

99 100 101 102 103
  return print_pdf_generate_html($print, $html, $pdf_filename);
}

function print_pdf_generate_html($print, $html, $filename = NULL) {
  $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT);
104

105
  if (basename($print_pdf_pdf_tool) == 'dompdf_config.inc.php') {
106
    return _print_pdf_dompdf($print, $html, $filename);
jcnventura's avatar
jcnventura committed
107
  }
108
  elseif (basename($print_pdf_pdf_tool) == 'tcpdf.php') {
109
    return _print_pdf_tcpdf($print, $html, $filename);
jcnventura's avatar
jcnventura committed
110
  }
jcnventura's avatar
jcnventura committed
111
  elseif (drupal_substr(basename($print_pdf_pdf_tool, '.exe'), 0, 11) == 'wkhtmltopdf') {
112
    return _print_pdf_wkhtmltopdf($print, $html, $filename);
113
  }
114
  elseif ($filename) {
jcnventura's avatar
jcnventura committed
115 116
    return drupal_not_found();
  }
117
  return NULL;
jcnventura's avatar
jcnventura committed
118 119
}

120 121 122 123 124 125 126 127 128 129 130 131 132 133
/**
 * Convert image paths to the file:// protocol
 *
 * In some Drupal setups, the use of the 'private' filesystem or Apache's
 * configuration prevent access to the images of the page. This function
 * tries to circumnvent those problems by accessing files in the local
 * filesystem.
 *
 * @param $html
 *   contents of the post-processed template already with the node data
 * @see print_pdf_controller()
 */
function _print_pdf_file_access_images($html) {
  global $base_url, $language;
134
  $print_pdf_images_via_file = variable_get('print_pdf_images_via_file', PRINT_PDF_IMAGES_VIA_FILE_DEFAULT);
135

136
  // TODO: This needs to be rewritten from scratch for Drupal 7
137
  $lang = '';
138
/*
jcnventura's avatar
jcnventura committed
139
  TODO
140 141 142 143 144 145 146 147 148
  switch (variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE)) {
    case LANGUAGE_NEGOTIATION_PATH_DEFAULT:
    case LANGUAGE_NEGOTIATION_PATH:
      $lang = $language->language;
      break;
    default:
      $lang = '';
      break;
  }
149
*/
150
  // Always convert private to local paths
151 152 153 154
  $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?)${base_url}/(?:(?:index.php)?\?q=)?(?:${lang}/)?system/files/([^>]*?>)!is";
  $replacement = '$1file://' . realpath(variable_get('file_private_path', '')) . '/$2';
  $html = preg_replace($pattern, $replacement, $html);
  if ($print_pdf_images_via_file) {
155 156 157 158
    $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?)${base_url}/(?:(?:index.php)?\?q=)?(?:${lang}/)?([^>]*?>)!is";
    $replacement = '$1file://' . dirname($_SERVER['SCRIPT_FILENAME']) . '/$2';
    $html = preg_replace($pattern, $replacement, $html);
  }
159

160 161 162
  return $html;
}

163 164 165 166 167 168 169 170 171 172 173
/**
 * Generate the PDF file using the dompdf library
 *
 * @param $print
 *   array containing the configured data
 * @param $html
 *   contents of the post-processed template already with the node data
 * @param $filename
 *   name of the PDF file to be generated
 * @see print_pdf_controller()
 */
174
function _print_pdf_dompdf($print, $html, $filename = NULL) {
175 176 177 178
  $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT);
  $print_pdf_paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT);
  $print_pdf_page_orientation = variable_get('print_pdf_page_orientation', PRINT_PDF_PAGE_ORIENTATION_DEFAULT);
  $print_pdf_content_disposition = variable_get('print_pdf_content_disposition', PRINT_PDF_CONTENT_DISPOSITION_DEFAULT);
179 180 181 182 183

  if (variable_get('print_pdf_autoconfig', PRINT_PDF_AUTOCONFIG_DEFAULT)) {
    define("DOMPDF_ENABLE_PHP", FALSE);
    define("DOMPDF_ENABLE_REMOTE", TRUE);
    define("DOMPDF_TEMP_DIR", file_directory_temp());
184
    define("DOMPDF_UNICODE_ENABLED", variable_get('print_pdf_dompdf_unicode', PRINT_PDF_DOMPDF_UNICODE_DEFAULT));
185 186
  }

jcnventura's avatar
jcnventura committed
187
  require_once(DRUPAL_ROOT . '/' . $print_pdf_pdf_tool);
188
  spl_autoload_register('DOMPDF_autoload');
jcnventura's avatar
jcnventura committed
189

190 191 192
  // Try to use local file access for image files
  $html = _print_pdf_file_access_images($html);

193 194 195
  // dompdf seems to have problems with something in system.css so let's not use it
  $html = preg_replace('!<link.*?modules/system/system.css.*?/>!', '', $html);

196 197
  $url_array  = parse_url($print['url']);

jcnventura's avatar
jcnventura committed
198
  $protocol = $url_array['scheme'] . '://';
199
  $host = $url_array['host'];
jcnventura's avatar
jcnventura committed
200
  $path = dirname($url_array['path']) . '/';
jcnventura's avatar
jcnventura committed
201 202

  $dompdf = new DOMPDF();
203 204
  $dompdf->set_base_path($path);
  $dompdf->set_host($host);
205
  $dompdf->set_paper(drupal_strtolower($print_pdf_paper_size), $print_pdf_page_orientation);
206 207
  $dompdf->set_protocol($protocol);

jcnventura's avatar
jcnventura committed
208
// dompdf can't handle footers cleanly, so disable the following
209
//  $html = theme('print_pdf_dompdf_footer', array('html' => $html));
210

211 212
  // If dompdf Unicode support is disabled, try to convert to ISO-8859-1 and then to HTML entities
  if (!variable_get('print_pdf_dompdf_unicode', PRINT_PDF_DOMPDF_UNICODE_DEFAULT)) {
213 214 215
  // Convert the euro sign to an HTML entity
  $html = str_replace('€', '&#0128;', $html);

216 217 218 219 220 221 222 223
  // Convert from UTF-8 to ISO 8859-1 and then to HTML entities
  if (function_exists('utf8_decode')) {
    $html = utf8_decode($html);
  }
// iconv fails silently when it encounters something that it doesn't know, so don't use it
//  else if (function_exists('iconv')) {
//    $html = iconv('UTF-8', 'ISO-8859-1', $html);
//  }
jcnventura's avatar
jcnventura committed
224
  elseif (function_exists('mb_convert_encoding')) {
225 226
    $html = mb_convert_encoding($html, 'ISO-8859-1', 'UTF-8');
  }
jcnventura's avatar
jcnventura committed
227
  elseif (function_exists('recode_string')) {
228 229 230
    $html = recode_string('UTF-8..ISO_8859-1', $html);
  }
  $html = htmlspecialchars_decode(htmlentities($html, ENT_NOQUOTES, 'ISO-8859-1'), ENT_NOQUOTES);
231
  }
232

233
  //must get rid of tbody (dompdf goes into recursion)
234
  $html = preg_replace('!<tbody[^>]*?>|</tbody>!i', '', $html);
235

236
  $dompdf->load_html($html);
jcnventura's avatar
jcnventura committed
237

jcnventura's avatar
jcnventura committed
238
  $dompdf->render();
239 240 241 242 243 244 245
  if ($filename) {
    $dompdf->stream($filename, array('Attachment' => ($print_pdf_content_disposition == 2)));
    return TRUE;
  }
  else {
    return $dompdf->output();
  }
jcnventura's avatar
jcnventura committed
246 247
}

248 249 250 251 252 253 254 255 256 257 258
/**
 * Generate the PDF file using the TCPDF library
 *
 * @param $print
 *   array containing the configured data
 * @param $html
 *   contents of the post-processed template already with the node data
 * @param $filename
 *   name of the PDF file to be generated
 * @see print_pdf_controller()
 */
259
function _print_pdf_tcpdf($print, $html, $filename = NULL) {
260 261
  global $base_url, $language;

262 263 264 265 266
  $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT);
  $print_pdf_paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT);
  $print_pdf_page_orientation = variable_get('print_pdf_page_orientation', PRINT_PDF_PAGE_ORIENTATION_DEFAULT);
  $print_pdf_content_disposition = variable_get('print_pdf_content_disposition', PRINT_PDF_CONTENT_DISPOSITION_DEFAULT);

267 268
  $pdf_tool_path = realpath(dirname($print_pdf_pdf_tool));

269 270 271 272 273 274 275 276 277 278 279
  if (variable_get('print_pdf_autoconfig', PRINT_PDF_AUTOCONFIG_DEFAULT)) {
    define('K_TCPDF_EXTERNAL_CONFIG', TRUE);
    define('K_PATH_MAIN', dirname($_SERVER['SCRIPT_FILENAME']));
    define('K_PATH_URL', $base_url);
    define('K_PATH_FONTS', $pdf_tool_path . '/fonts/');
    define('K_PATH_CACHE', $pdf_tool_path . '/cache/');
    define('K_PATH_IMAGES', '');
    define('K_BLANK_IMAGE', $pdf_tool_path . '/images/_blank.png');
    define('K_CELL_HEIGHT_RATIO', 1.25);
    define('K_SMALL_RATIO', 2/3);
  }
280

281 282 283
  // Try to use local file access for image files
  $html = _print_pdf_file_access_images($html);

284
  // Decode HTML entities in image filenames
285
  $pattern = "!<img\s[^>]*?src\s*?=\s*?['\"]?{$base_url}[^>]*?>!is";
jcnventura's avatar
jcnventura committed
286
  $html = preg_replace_callback($pattern, create_function('$matches', 'return html_entity_decode($matches[0], ENT_QUOTES);'), $html);
jcnventura's avatar
jcnventura committed
287
  // Remove queries from the image URL
288
  $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?{$base_url}[^>]*?)(?:%3F|\?)[\w=&]+([^>]*?>)!is";
289
  $html = preg_replace($pattern, '$1$2', $html);
290

jcnventura's avatar
jcnventura committed
291
  require_once(DRUPAL_ROOT . '/' . $print_pdf_pdf_tool);
292
  module_load_include('inc', 'print_pdf', 'print_pdf.class');
293

294
  $font = Array(
295
    check_plain(variable_get('print_pdf_font_family', PRINT_PDF_FONT_FAMILY_DEFAULT)),
296
    '',
297
    check_plain(variable_get('print_pdf_font_size', PRINT_PDF_FONT_SIZE_DEFAULT)),
298
  );
299
  $orientation = drupal_strtoupper($print_pdf_page_orientation[0]);
300 301

  // create new PDF document
302
  $pdf = new PrintTCPDF($orientation , 'mm', $print_pdf_paper_size, TRUE);
jcnventura's avatar
jcnventura committed
303

304
  // set document information
305 306 307
  if (property_exists($print['node'], 'name')) {
    $pdf->SetAuthor(strip_tags($print['node']->name));
  }
308
  $pdf->SetCreator(variable_get('site_name', 'Drupal'));
309
  $pdf->SetTitle(html_entity_decode($print['title'], ENT_QUOTES, 'UTF-8'));
310
  $pdf->setPDFVersion('1.6');
jcnventura's avatar
jcnventura committed
311
  $pdf->setFontSubsetting(variable_get('print_pdf_font_subsetting', FALSE));
312

313
  if ($language->direction == LANGUAGE_RTL) {
314 315 316
    $pdf->setRTL(TRUE);
  }

317 318 319
  $pdf = theme('print_pdf_tcpdf_header', array('pdf' => $pdf, 'html' => $html, 'font' => $font));
  $pdf = theme('print_pdf_tcpdf_footer', array('pdf' => $pdf, 'html' => $html, 'font' => $font));
  $pdf = theme('print_pdf_tcpdf_page', array('pdf' => $pdf));
320 321 322 323

  // add a page
  $pdf->AddPage();

324
  $pdf = theme('print_pdf_tcpdf_content', array('pdf' => $pdf, 'html' => $html, 'font' => $font));
325 326 327 328

  // reset pointer to the last page
  $pdf->lastPage();

329 330 331
  // try to recover from any warning/error
  ob_clean();

332 333 334 335 336 337 338 339 340
  if ($filename) {
    //Close and output PDF document
    $output_dest = ($print_pdf_content_disposition == 2) ? 'D' : 'I';
    $pdf->Output($filename, $output_dest);
    return TRUE;
  }
  else {
    return $pdf = $pdf->Output('', 'S');
  }
341 342
}

343 344 345 346 347 348 349 350 351 352 353
/**
 * Generate the PDF file using wkhtmltopdf
 *
 * @param $print
 *   array containing the configured data
 * @param $html
 *   contents of the post-processed template already with the node data
 * @param $filename
 *   name of the PDF file to be generated
 * @see print_pdf_controller()
 */
354
function _print_pdf_wkhtmltopdf($print, $html, $filename = NULL) {
355
  $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT);
356
  $print_pdf_paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT);
357 358
  $print_pdf_page_orientation = variable_get('print_pdf_page_orientation', PRINT_PDF_PAGE_ORIENTATION_DEFAULT);
  $print_pdf_content_disposition = variable_get('print_pdf_content_disposition', PRINT_PDF_CONTENT_DISPOSITION_DEFAULT);
359
  $print_pdf_wkhtmltopdf_options = variable_get('print_pdf_wkhtmltopdf_options', PRINT_PDF_WKHTMLTOPDF_OPTIONS);
360

361
  $dpi = 96;
362

363
  if (!empty($print_pdf_wkhtmltopdf_options)) {
jcnventura's avatar
jcnventura committed
364
    $print_pdf_wkhtmltopdf_options = token_replace($print_pdf_wkhtmltopdf_options, array('node' => $print['node']));
365 366
  }

367 368 369 370
  $version = _print_pdf_wkhtmltopdf_version();

  // 0.10.0 beta2 identifies itself as 0.9.9
  if (version_compare($version, '0.9.9', '>=')) {
jcnventura's avatar
jcnventura committed
371
    $print_pdf_wkhtmltopdf_options = '--disable-local-file-access ' . $print_pdf_wkhtmltopdf_options;
372 373
  }
  elseif (version_compare($version, '0.9.6', '>=')) {
jcnventura's avatar
jcnventura committed
374
    $print_pdf_wkhtmltopdf_options = '--disallow-local-file-access ' . $print_pdf_wkhtmltopdf_options;
375 376 377 378 379 380
  }
  else {
    drupal_goto($print['url']);
    exit;
  }

381
  $descriptor = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
382
  $cmd = '"' . realpath($print_pdf_pdf_tool) . "\" --page-size $print_pdf_paper_size --orientation $print_pdf_page_orientation --dpi $dpi $print_pdf_wkhtmltopdf_options - -";
383

jcnventura's avatar
jcnventura committed
384
  $process = proc_open($cmd, $descriptor, $pipes, NULL, NULL);
385 386 387 388 389

  if (is_resource($process)) {
    fwrite($pipes[0], $html);
    fclose($pipes[0]);

390
    $pdf = stream_get_contents($pipes[1]);
391 392
    fclose($pipes[1]);

393
    stream_set_blocking($pipes[2], 0);
394 395 396
    $error = stream_get_contents($pipes[2]);
    if (!empty($error)) {
      watchdog('print_pdf', 'wkhtmltopdf: ' . $error);
397
    }
398
    fclose($pipes[2]);
399

400
    $retval = proc_terminate($process);
401 402
  }

403
  if (!empty($pdf)) {
404 405 406 407 408 409
    if ($filename) {
      if (headers_sent()) {
        die("Unable to stream pdf: headers already sent");
      }
      header("Cache-Control: private");
      header("Content-Type: application/pdf");
410

411
      $attachment =  ($print_pdf_content_disposition == 2) ?  "attachment" :  "inline";
412

413
      header("Content-Disposition: $attachment; filename=\"$filename\"");
414

415 416 417 418 419 420 421
      echo $pdf;
      flush();
      return TRUE;
    }
    else {
      return $pdf;
    }
422
  }
423
  else {
424
    return NULL;
425
  }
426 427
}

428 429 430 431 432 433 434
/**
 * Format the dompdf footer contents
 *
 * @param $html
 *   contents of the body of the HTML from the original node
 * @see theme_print_pdf_tcpdf_footer()
 */
435 436 437
function theme_print_pdf_dompdf_footer($vars) {
  preg_match('!<div class="print-footer">(.*?)</div>!si', $vars['html'], $tpl_footer);
  $html = str_replace($tpl_footer[0], '', $vars['html']);
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

  $text = '<script type="text/php">
    if (isset($pdf)) {
      $font = Font_Metrics::get_font("verdana");;
      $size = 10;
      $color = array(0,0,0);
      $text_height = Font_Metrics::get_font_height($font, $size);

      $w = $pdf->get_width();
      $h = $pdf->get_height();

      $footer = $pdf->open_object();

      // Draw a line along the bottom
      $y = $h - 25;
      $pdf->line(15, $y, $w - 15, $y, $color, 1);

      $y += $text_height / 2;
jcnventura's avatar
jcnventura committed
456
      $pdf->page_text(15, $y, \'' . addslashes(strip_tags($tpl_footer[1])) . '\', $font, $size, $color);
457 458 459 460 461 462 463 464 465 466 467 468 469 470

      $pdf->close_object();
      $pdf->add_object($footer, "all");

      // Center the text
      $width = Font_Metrics::get_text_width("Page 1 of 2", $font, $size);
      $pagenumtxt = t("Page !n of !total", array("!n" => "{PAGE_NUM}", "!total" => "{PAGE_COUNT}"));
      $pdf->page_text($w - 15 - $width, $y, $pagenumtxt, $font, $size, $color);
    }
  </script>';

  return str_replace("<body>", "<body>" . $text, $html);
}

471 472 473 474 475 476 477 478 479 480 481
/**
 * Format the TCPDF header
 *
 * @param $pdf
 *   current TCPDF object
 * @param $html
 *   contents of the body of the HTML from the original node
 * @param $font
 *   array with the font definition (font name, styles and size)
 * @see theme_print_pdf_tcpdf_header()
 */
482 483 484
function theme_print_pdf_tcpdf_header($vars) {
  $pdf = $vars['pdf'];
  preg_match('!<div class="print-logo">(.*?)</div>!si', $vars['html'], $tpl_logo);
485
  preg_match('!<title>(.*?)</title>!si', $vars['html'], $tpl_title);
486
  preg_match('!<div class="print-site_name">(.*?)</div>!si', $vars['html'], $tpl_site_name);
487

488
  $ratio = 0;
489
  $logo = '';
490 491
  if (preg_match('!src\s*=\s*(?:\'(.*?)\'|"(.*?)"|([^\s]*))!i', $tpl_logo[1], $logo_url)) {
    $logo = $logo_url[1];
492
    $size = getimagesize($logo);
493
    $ratio = $size ? ($size[0] / $size[1]) : 0;
494 495
  }

496
  // set header font
497
  $pdf->setHeaderFont($vars['font']);
498
  // set header margin
499
  $pdf->setHeaderMargin(5);
500
  // set header data
501
  $pdf->setHeaderData($logo, 10 * $ratio, html_entity_decode($tpl_title[1], ENT_QUOTES, 'UTF-8'), html_entity_decode(strip_tags($tpl_site_name[1]), ENT_QUOTES, 'UTF-8'));
502 503

  return $pdf;
504
}
505

506 507 508 509 510 511 512
/**
 * Format the TCPDF page settings (margins, etc)
 *
 * @param $pdf
 *   current TCPDF object
 * @see theme_print_pdf_tcpdf_page()
 */
513 514
function theme_print_pdf_tcpdf_page($vars) {
  $pdf = $vars['pdf'];
jcnventura's avatar
jcnventura committed
515
  // set margins
516
  $pdf->SetMargins(15, 20, 15);
517
  // set auto page breaks
518
  $pdf->SetAutoPageBreak(TRUE, 15);
jcnventura's avatar
jcnventura committed
519
  // set image scale factor
520
  $pdf->setImageScale(1);
521 522
  // set image compression quality
  $pdf->setJPEGQuality(100);
523 524

  return $pdf;
525
}
526

527 528 529 530 531 532 533 534 535 536 537
/**
 * Format the TCPDF page content
 *
 * @param $pdf
 *   current TCPDF object
 * @param $html
 *   contents of the body of the HTML from the original node
 * @param $font
 *   array with the font definition (font name, styles and size)
 * @see theme_print_pdf_tcpdf_content()
 */
538 539
function theme_print_pdf_tcpdf_content($vars) {
  $pdf = $vars['pdf'];
540
  // set content font
541
  $pdf->setFont($vars['font'][0], $vars['font'][1], $vars['font'][2]);
jcnventura's avatar
jcnventura committed
542

543
  preg_match('!<body.*?>(.*)</body>!sim', $vars['html'], $matches);
544
  $pattern = '!(?:<div class="print-(?:logo|site_name|breadcrumb|footer)">.*?</div>|<hr class="print-hr" />)!si';
545 546
  $matches[1] = preg_replace($pattern, '', $matches[1]);

547 548 549 550 551
  // Make CCK fields look better
  $matches[1] = preg_replace('!(<div class="field.*?>)\s*!sm', '$1', $matches[1]);
  $matches[1] = preg_replace('!(<div class="field.*?>.*?</div>)\s*!sm', '$1', $matches[1]);
  $matches[1] = preg_replace('!<div( class="field-label.*?>.*?)</div>!sm', '<strong$1</strong>', $matches[1]);

552
  // Since TCPDF's writeHTML is so bad with <p>, do everything possible to make it look nice
553
  $matches[1] = preg_replace('!<(?:p(|\s+.*?)/?|/p)>!i', '<br$1 />', $matches[1]);
554
  $matches[1] = str_replace(array('<div', 'div>'), array('<span', 'span><br />'), $matches[1]);
555 556 557 558
  do {
    $prev = $matches[1];
    $matches[1] = preg_replace('!(</span>)<br />(\s*?</span><br />)!s', '$1$2', $matches[1]);
  } while ($prev != $matches[1]);
559

560
  @$pdf->writeHTML($matches[1]);
561 562

  return $pdf;
563
}
jcnventura's avatar
jcnventura committed
564

565 566 567 568 569 570 571 572 573 574 575
/**
 * Format the TCPDF footer contents
 *
 * @param $pdf
 *   current TCPDF object
 * @param $html
 *   contents of the body of the HTML from the original node
 * @param $font
 *   array with the font definition (font name, styles and size)
 * @see theme_print_pdf_tcpdf_footer()
 */
576 577 578
function theme_print_pdf_tcpdf_footer($vars) {
  $pdf = $vars['pdf'];
  preg_match('!<div class="print-footer">(.*?)</div>!si', $vars['html'], $tpl_footer);
579
  $footer = trim(preg_replace('!</?div[^>]*?>!i', '', $tpl_footer[1]));
580

581
  // set footer font
582 583
  $vars['font'][2] *= 0.8;
  $pdf->setFooterFont($vars['font']);
584 585 586
  // set footer margin
  $pdf->SetFooterMargin(10);
  // set footer data
587
  $pdf->SetFooterData($footer);
588 589

  return $pdf;
jcnventura's avatar
jcnventura committed
590
}
591 592 593 594 595 596 597 598

/**
 * Format the TCPDF footer layout
 *
 * @param $pdf
 *   current TCPDF object
 * @see theme_print_pdf_tcpdf_footer2()
 */
599 600
function theme_print_pdf_tcpdf_footer2($vars) {
  $pdf = $vars['pdf'];
601
  //Position at 1.5 cm from bottom
jcnventura's avatar
jcnventura committed
602
  $pdf->writeHTMLCell(0, 15, 15, $pdf->getPageHeight()-15, $pdf->footer);
603 604

  $ormargins = $pdf->getOriginalMargins();
605
  $pagenumtxt = t('Page !n of !total', array('!n' => $pdf->PageNo(), '!total' => $pdf->getAliasNbPages()));
606 607 608 609 610 611 612 613 614
  //Print page number
  if ($pdf->getRTL()) {
    $pdf->SetX($ormargins['right']);
    $pdf->Cell(0, 10, $pagenumtxt, 'T', 0, 'L');
  }
  else {
    $pdf->SetX($ormargins['left']);
    $pdf->Cell(0, 10, $pagenumtxt, 'T', 0, 'R');
  }
615 616

  return $pdf;
617
}