Projet

Général

Profil

Paste
Télécharger (21,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / print / print_pdf / print_pdf.pages.inc @ 74f6bef0

1
<?php
2

    
3
/**
4
 * @file
5
 * Generates the PDF versions of the pages
6
 *
7
 * This file is included by the print_pdf module and includes the
8
 * functions that interface with the PDF generation packages.
9
 *
10
 * @ingroup print
11
 */
12

    
13
module_load_include('inc', 'print', 'print.pages');
14

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

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

    
30
  // Handle the query
31
  $query = $_GET;
32
  unset($query['q']);
33

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

    
45
    $pdf_filename = variable_get('print_pdf_filename', PRINT_PDF_FILENAME_DEFAULT);
46
    if (!empty($pdf_filename) && !empty($node)) {
47
      $pdf_filename = token_replace($pdf_filename, array('node' => $node));
48
    }
49
    else {
50
      $pdf_filename = token_replace($pdf_filename, array('site'));
51
      if (empty($pdf_filename) || count(token_scan($pdf_filename))) {
52
        // If there are still tokens, use a fallback solution
53
        $pdf_filename = str_replace('/', '_', $path);
54
      }
55
    }
56
  }
57
  else {
58
    $pdf_filename = 'page';
59
  }
60

    
61
  if (function_exists('transliteration_clean_filename')) {
62
    $pdf_filename = transliteration_clean_filename($pdf_filename, language_default('language'));
63
  }
64

    
65
  drupal_alter('print_pdf_filename', $pdf_filename, $path);
66

    
67
  $pdf = print_pdf_generate_path($path, $query, $cid, $pdf_filename . '.pdf');
68
  if ($pdf == NULL) {
69
    drupal_goto($path);
70
    exit;
71
  }
72

    
73
  $nodepath = (isset($node->path) && is_string($node->path)) ? drupal_get_normal_path($node->path) : 'node/' . $path;
74
  db_merge('print_pdf_page_counter')
75
    ->key(array('path' => $nodepath))
76
    ->fields(array(
77
        'totalcount' => 1,
78
        'timestamp' => REQUEST_TIME,
79
    ))
80
    ->expression('totalcount', 'totalcount + 1')
81
    ->execute();
82

    
83
  drupal_exit();
84
}
85

    
86
function print_pdf_generate_path($path, $query = NULL, $cid = NULL, $pdf_filename = NULL) {
87
  global $base_url;
88

    
89
  $print = print_controller($path, $query, $cid, PRINT_PDF_FORMAT);
90
  if ($print === FALSE) {
91
    return;
92
  }
93

    
94
  // Img elements must be set to absolute
95
  $pattern = '!<(img\s[^>]*?)>!is';
96
  $print['content'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['content']);
97
  $print['logo'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['logo']);
98
  $print['footer_message'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['footer_message']);
99

    
100
  // Send to printer option causes problems with PDF
101
  $print['sendtoprinter'] = '';
102

    
103
  $node = $print['node'];
104
  $html = theme('print', array('print' => $print, 'type' => PRINT_PDF_FORMAT, 'node' => $node));
105

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

    
112
  return print_pdf_generate_html($print, $html, $pdf_filename);
113
}
114

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

    
118
  if (basename($print_pdf_pdf_tool) == 'dompdf_config.inc.php') {
119
    return _print_pdf_dompdf($print, $html, $filename);
120
  }
121
  elseif (basename($print_pdf_pdf_tool) == 'tcpdf.php') {
122
    return _print_pdf_tcpdf($print, $html, $filename);
123
  }
124
  elseif (drupal_substr(basename($print_pdf_pdf_tool, '.exe'), 0, 11) == 'wkhtmltopdf') {
125
    return _print_pdf_wkhtmltopdf($print, $html, $filename);
126
  }
127
  elseif ($filename) {
128
    return drupal_not_found();
129
  }
130
  return NULL;
131
}
132

    
133
/**
134
 * Convert image paths to the file:// protocol
135
 *
136
 * In some Drupal setups, the use of the 'private' filesystem or Apache's
137
 * configuration prevent access to the images of the page. This function
138
 * tries to circumnvent those problems by accessing files in the local
139
 * filesystem.
140
 *
141
 * @param $html
142
 *   contents of the post-processed template already with the node data
143
 * @see print_pdf_controller()
144
 */
145
function _print_pdf_file_access_images($html) {
146
  global $base_url, $language;
147
  $print_pdf_images_via_file = variable_get('print_pdf_images_via_file', PRINT_PDF_IMAGES_VIA_FILE_DEFAULT);
148

    
149
  $lang = (function_exists('language_negotiation_get_any') && language_negotiation_get_any('locale-url')) ? $language->language : '';
150

    
151
  // Always convert private to local paths
152
  $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?)${base_url}/(?:(?:index.php)?\?q=)?(?:${lang}/)?system/files/([^>]*?>)!is";
153
  $replacement = '$1file://' . realpath(variable_get('file_private_path', '')) . '/$2';
154
  $html = preg_replace($pattern, $replacement, $html);
155
  if ($print_pdf_images_via_file) {
156
    $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?)${base_url}/(?:(?:index.php)?\?q=)?(?:${lang}/)?([^>]*?>)!is";
157
    $replacement = '$1file://' . dirname($_SERVER['SCRIPT_FILENAME']) . '/$2';
158
    $html = preg_replace($pattern, $replacement, $html);
159
  }
160

    
161
  return $html;
162
}
163

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

    
181
  if (variable_get('print_pdf_autoconfig', PRINT_PDF_AUTOCONFIG_DEFAULT)) {
182
    define("DOMPDF_ENABLE_PHP", FALSE);
183
    define("DOMPDF_ENABLE_REMOTE", TRUE);
184
    define("DOMPDF_TEMP_DIR", file_directory_temp());
185
    define("DOMPDF_UNICODE_ENABLED", variable_get('print_pdf_dompdf_unicode', PRINT_PDF_DOMPDF_UNICODE_DEFAULT));
186
    define("DOMPDF_FONT_CACHE", drupal_realpath('public://' . PRINT_PDF_DOMPDF_CACHE_DIR_DEFAULT . '/fonts/'));
187
  }
188

    
189
  require_once(DRUPAL_ROOT . '/' . $print_pdf_pdf_tool);
190
  spl_autoload_register('DOMPDF_autoload');
191

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

    
195
  // Spaces in img URLs must be replaced with %20
196
  $pattern = '!<(img\s[^>]*?)>!is';
197
  $html = preg_replace_callback($pattern, '_print_replace_spaces', $html);
198

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

    
202
  $url_array  = parse_url($print['url']);
203

    
204
  $protocol = $url_array['scheme'] . '://';
205
  $host = $url_array['host'];
206
  $path = dirname($url_array['path']) . '/';
207

    
208
  $dompdf = new DOMPDF();
209
  $dompdf->set_base_path($path);
210
  $dompdf->set_host($host);
211
  $dompdf->set_paper(drupal_strtolower($print_pdf_paper_size), $print_pdf_page_orientation);
212
  $dompdf->set_protocol($protocol);
213

    
214
// dompdf can't handle footers cleanly, so disable the following
215
//  $html = theme('print_pdf_dompdf_footer', array('html' => $html));
216

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

    
222
  // Convert from UTF-8 to ISO 8859-1 and then to HTML entities
223
  if (function_exists('utf8_decode')) {
224
    $html = utf8_decode($html);
225
  }
226
// iconv fails silently when it encounters something that it doesn't know, so don't use it
227
//  else if (function_exists('iconv')) {
228
//    $html = iconv('UTF-8', 'ISO-8859-1', $html);
229
//  }
230
  elseif (function_exists('mb_convert_encoding')) {
231
    $html = mb_convert_encoding($html, 'ISO-8859-1', 'UTF-8');
232
  }
233
  elseif (function_exists('recode_string')) {
234
    $html = recode_string('UTF-8..ISO_8859-1', $html);
235
  }
236
  $html = htmlspecialchars_decode(htmlentities($html, ENT_NOQUOTES, 'ISO-8859-1'), ENT_NOQUOTES);
237
  }
238

    
239
  // Must get rid of tbody (dompdf goes into recursion)
240
  $html = preg_replace('!<tbody[^>]*?>|</tbody>!i', '', $html);
241

    
242
  $dompdf->load_html($html);
243

    
244
  $dompdf->render();
245
  if ($filename) {
246
    $dompdf->stream($filename, array('Attachment' => ($print_pdf_content_disposition == 2)));
247
    return TRUE;
248
  }
249
  else {
250
    return $dompdf->output();
251
  }
252
}
253

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

    
268
  $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT);
269
  $print_pdf_paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT);
270
  $print_pdf_page_orientation = variable_get('print_pdf_page_orientation', PRINT_PDF_PAGE_ORIENTATION_DEFAULT);
271
  $print_pdf_content_disposition = variable_get('print_pdf_content_disposition', PRINT_PDF_CONTENT_DISPOSITION_DEFAULT);
272

    
273
  $pdf_tool_path = realpath(dirname($print_pdf_pdf_tool));
274

    
275
  if (variable_get('print_pdf_autoconfig', PRINT_PDF_AUTOCONFIG_DEFAULT)) {
276
    define('K_TCPDF_EXTERNAL_CONFIG', TRUE);
277
    define('K_PATH_MAIN', dirname($_SERVER['SCRIPT_FILENAME']));
278
    define('K_PATH_URL', $base_url);
279
    define('K_PATH_FONTS', $pdf_tool_path . '/fonts/');
280
    define('K_PATH_CACHE', drupal_realpath('public://' . PRINT_PDF_TCPDF_CACHE_DIR_DEFAULT . '/cache/'));
281
    define('K_PATH_IMAGES', '');
282
    define('K_BLANK_IMAGE', $pdf_tool_path . '/images/_blank.png');
283
    define('K_CELL_HEIGHT_RATIO', 1.25);
284
    define('K_SMALL_RATIO', 2/3);
285
  }
286

    
287
  // Try to use local file access for image files
288
  $html = _print_pdf_file_access_images($html);
289

    
290
  // Decode HTML entities in image filenames
291
  $pattern = "!<img\s[^>]*?src\s*?=\s*?['\"]?{$base_url}[^>]*?>!is";
292
  $html = preg_replace_callback($pattern, create_function('$matches', 'return html_entity_decode($matches[0], ENT_QUOTES);'), $html);
293
  // Remove queries from the image URL
294
  $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?{$base_url}[^>]*?)(?:%3F|\?)[\w=&]+([^>]*?>)!is";
295
  $html = preg_replace($pattern, '$1$2', $html);
296

    
297
  require_once(DRUPAL_ROOT . '/' . $print_pdf_pdf_tool);
298
  module_load_include('inc', 'print_pdf', 'print_pdf.class');
299

    
300
  $font = Array(
301
    check_plain(variable_get('print_pdf_font_family', PRINT_PDF_FONT_FAMILY_DEFAULT)),
302
    '',
303
    check_plain(variable_get('print_pdf_font_size', PRINT_PDF_FONT_SIZE_DEFAULT)),
304
  );
305
  $orientation = drupal_strtoupper($print_pdf_page_orientation[0]);
306

    
307
  // create new PDF document
308
  $pdf = new PrintTCPDF($orientation , 'mm', $print_pdf_paper_size, TRUE);
309

    
310
  // set document information
311
  if (property_exists($print['node'], 'name')) {
312
    $pdf->SetAuthor(strip_tags($print['node']->name));
313
  }
314
  $pdf->SetCreator(variable_get('site_name', 'Drupal'));
315
  $pdf->SetTitle(html_entity_decode($print['title'], ENT_QUOTES, 'UTF-8'));
316
  $pdf->setPDFVersion('1.6');
317
  $pdf->setFontSubsetting(variable_get('print_pdf_font_subsetting', PRINT_PDF_FONT_SUBSETTING_DEFAULT));
318

    
319
  if ($language->direction == LANGUAGE_RTL) {
320
    $pdf->setRTL(TRUE);
321
  }
322

    
323
  $pdf = theme('print_pdf_tcpdf_header', array('pdf' => $pdf, 'html' => $html, 'font' => $font));
324
  $pdf = theme('print_pdf_tcpdf_footer', array('pdf' => $pdf, 'html' => $html, 'font' => $font));
325
  $pdf = theme('print_pdf_tcpdf_page', array('pdf' => $pdf));
326

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

    
330
  $pdf = theme('print_pdf_tcpdf_content', array('pdf' => $pdf, 'html' => $html, 'font' => $font));
331

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

    
335
  // try to recover from any warning/error
336
  ob_clean();
337

    
338
  if ($filename) {
339
    // Close and output PDF document
340
    $output_dest = ($print_pdf_content_disposition == 2) ? 'D' : 'I';
341
    $pdf->Output($filename, $output_dest);
342
    return TRUE;
343
  }
344
  else {
345
    return $pdf = $pdf->Output('', 'S');
346
  }
347
}
348

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

    
367
  $dpi = 96;
368

    
369
  if (!empty($print_pdf_wkhtmltopdf_options)) {
370
    $print_pdf_wkhtmltopdf_options = token_replace($print_pdf_wkhtmltopdf_options, array('node' => $print['node']));
371
  }
372

    
373
  $version = _print_pdf_wkhtmltopdf_version();
374

    
375
  // 0.10.0 beta2 identifies itself as 0.9.9
376
  if (version_compare($version, '0.9.9', '>=')) {
377
    $print_pdf_wkhtmltopdf_options = '--disable-local-file-access ' . $print_pdf_wkhtmltopdf_options;
378
  }
379
  elseif (version_compare($version, '0.9.6', '>=')) {
380
    $print_pdf_wkhtmltopdf_options = '--disallow-local-file-access ' . $print_pdf_wkhtmltopdf_options;
381
  }
382
  else {
383
    drupal_goto($print['url']);
384
    exit;
385
  }
386

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

    
390
  $process = proc_open($cmd, $descriptor, $pipes, NULL, NULL);
391

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

    
396
    $pdf = stream_get_contents($pipes[1]);
397
    fclose($pipes[1]);
398

    
399
    stream_set_blocking($pipes[2], 0);
400
    $error = stream_get_contents($pipes[2]);
401
    fclose($pipes[2]);
402

    
403
    $retval = proc_close($process);
404
    if (!empty($error) || ($retval != 0)) {
405
      if (empty($error)) {
406
        $error = 'No stderr output available.';
407
      }
408
      watchdog('print_pdf', "wkhtmltopdf (returned $retval): $error");
409
    }
410
  }
411

    
412
  if (!empty($pdf)) {
413
    if ($filename) {
414
      if (headers_sent()) {
415
        exit("Unable to stream pdf: headers already sent");
416
      }
417
      header("Cache-Control: private");
418
      header("Content-Type: application/pdf");
419

    
420
      $attachment =  ($print_pdf_content_disposition == 2) ?  "attachment" :  "inline";
421

    
422
      header("Content-Disposition: $attachment; filename=\"$filename\"");
423

    
424
      echo $pdf;
425
      flush();
426
      return TRUE;
427
    }
428
    else {
429
      return $pdf;
430
    }
431
  }
432
  else {
433
    drupal_set_message(t('Unable to generate PDF file.'), 'error');
434
    drupal_goto($meta['url']);
435
    return NULL;
436
  }
437
}
438

    
439
/**
440
 * Format the dompdf footer contents
441
 *
442
 * @param $html
443
 *   contents of the body of the HTML from the original node
444
 * @see theme_print_pdf_tcpdf_footer()
445
 */
446
function theme_print_pdf_dompdf_footer($vars) {
447
  preg_match('!<div class="print-footer">(.*?)</div>!si', $vars['html'], $tpl_footer);
448
  $html = str_replace($tpl_footer[0], '', $vars['html']);
449

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

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

    
460
      $footer = $pdf->open_object();
461

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

    
466
      $y += $text_height / 2;
467
      $pdf->page_text(15, $y, \'' . addslashes(strip_tags($tpl_footer[1])) . '\', $font, $size, $color);
468

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

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

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

    
482
/**
483
 * Format the TCPDF header
484
 *
485
 * @param $pdf
486
 *   current TCPDF object
487
 * @param $html
488
 *   contents of the body of the HTML from the original node
489
 * @param $font
490
 *   array with the font definition (font name, styles and size)
491
 * @see theme_print_pdf_tcpdf_header()
492
 */
493
function theme_print_pdf_tcpdf_header($vars) {
494
  $pdf = $vars['pdf'];
495
  preg_match('!<div class="print-logo">(.*?)</div>!si', $vars['html'], $tpl_logo);
496
  preg_match('!<title>(.*?)</title>!si', $vars['html'], $tpl_title);
497
  preg_match('!<div class="print-site_name">(.*?)</div>!si', $vars['html'], $tpl_site_name);
498

    
499
  $ratio = 0;
500
  $logo = '';
501
  if (isset($tpl_logo[1]) && preg_match('!src\s*=\s*(?:"(.*?)"|\'(.*?)\'|([^\s]*))!i', $tpl_logo[1], $logo_url)) {
502
    $logo = $logo_url[1];
503
    if (!empty($logo)) {
504
      $size = getimagesize($logo);
505
      $ratio = $size ? ($size[0] / $size[1]) : 0;
506
    }
507
  }
508

    
509
  // set header font
510
  $pdf->setHeaderFont($vars['font']);
511
  // set header margin
512
  $pdf->setHeaderMargin(5);
513
  // set header data
514
  $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'));
515

    
516
  return $pdf;
517
}
518

    
519
/**
520
 * Format the TCPDF page settings (margins, etc)
521
 *
522
 * @param $pdf
523
 *   current TCPDF object
524
 * @see theme_print_pdf_tcpdf_page()
525
 */
526
function theme_print_pdf_tcpdf_page($vars) {
527
  $pdf = $vars['pdf'];
528
  // set margins
529
  $pdf->SetMargins(15, 20, 15);
530
  // set auto page breaks
531
  $pdf->SetAutoPageBreak(TRUE, 15);
532
  // set image scale factor
533
  $pdf->setImageScale(1);
534
  // set image compression quality
535
  $pdf->setJPEGQuality(100);
536

    
537
  return $pdf;
538
}
539

    
540
/**
541
 * Format the TCPDF page content
542
 *
543
 * @param $pdf
544
 *   current TCPDF object
545
 * @param $html
546
 *   contents of the body of the HTML from the original node
547
 * @param $font
548
 *   array with the font definition (font name, styles and size)
549
 * @see theme_print_pdf_tcpdf_content()
550
 */
551
function theme_print_pdf_tcpdf_content($vars) {
552
  $pdf = $vars['pdf'];
553
  // set content font
554
  $pdf->setFont($vars['font'][0], $vars['font'][1], $vars['font'][2]);
555

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

    
560
  // Make CCK fields look better
561
  $matches[1] = preg_replace('!(<div class="field.*?>)\s*!sm', '$1', $matches[1]);
562
  $matches[1] = preg_replace('!(<div class="field.*?>.*?</div>)\s*!sm', '$1', $matches[1]);
563
  $matches[1] = preg_replace('!<div( class="field-label.*?>.*?)</div>!sm', '<strong$1</strong>', $matches[1]);
564

    
565
  // Since TCPDF's writeHTML is so bad with <p>, do everything possible to make it look nice
566
  $matches[1] = preg_replace('!<(?:p(|\s+.*?)/?|/p)>!i', '<br$1 />', $matches[1]);
567
  $matches[1] = str_replace(array('<div', 'div>'), array('<span', 'span><br />'), $matches[1]);
568
  do {
569
    $prev = $matches[1];
570
    $matches[1] = preg_replace('!(</span>)<br />(\s*?</span><br />)!s', '$1$2', $matches[1]);
571
  } while ($prev != $matches[1]);
572

    
573
  @$pdf->writeHTML($matches[1]);
574

    
575
  return $pdf;
576
}
577

    
578
/**
579
 * Format the TCPDF footer contents
580
 *
581
 * @param $pdf
582
 *   current TCPDF object
583
 * @param $html
584
 *   contents of the body of the HTML from the original node
585
 * @param $font
586
 *   array with the font definition (font name, styles and size)
587
 * @see theme_print_pdf_tcpdf_footer()
588
 */
589
function theme_print_pdf_tcpdf_footer($vars) {
590
  $pdf = $vars['pdf'];
591
  preg_match('!<div class="print-footer">(.*?)</div>!si', $vars['html'], $tpl_footer);
592
  $footer = trim(preg_replace('!</?div[^>]*?>!i', '', $tpl_footer[1]));
593

    
594
  // set footer font
595
  $vars['font'][2] *= 0.8;
596
  $pdf->setFooterFont($vars['font']);
597
  // set footer margin
598
  $pdf->SetFooterMargin(10);
599
  // set footer data
600
  $pdf->SetFooterData($footer);
601

    
602
  return $pdf;
603
}
604

    
605
/**
606
 * Format the TCPDF footer layout
607
 *
608
 * @param $pdf
609
 *   current TCPDF object
610
 * @see theme_print_pdf_tcpdf_footer2()
611
 */
612
function theme_print_pdf_tcpdf_footer2($vars) {
613
  $pdf = $vars['pdf'];
614
  // Position at 1.5 cm from bottom
615
  $pdf->writeHTMLCell(0, 15, 15, $pdf->getPageHeight()-15, $pdf->footer);
616

    
617
  $ormargins = $pdf->getOriginalMargins();
618
  $pagenumtxt = t('Page !n of !total', array('!n' => $pdf->PageNo(), '!total' => $pdf->getAliasNbPages()));
619
  // Print page number
620
  if ($pdf->getRTL()) {
621
    $pdf->SetX($ormargins['right']);
622
    $pdf->Cell(0, 10, $pagenumtxt, 'T', 0, 'L');
623
  }
624
  else {
625
    $pdf->SetX($ormargins['left']);
626
    $pdf->Cell(0, 10, $pagenumtxt, 'T', 0, 'R');
627
  }
628

    
629
  return $pdf;
630
}