Projet

Général

Profil

Paste
Télécharger (32,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / views_pdf / views_pdf_template.php @ 11b63505

1
<?php
2

    
3
/**
4
 * @file
5
 * PDF Class to generate PDFs with native PHP. This class based on FPDF and FPDI.
6
 *
7
 * A direct include of this class is not realy possible. The basic functions of drupal must be
8
 * present.
9
 *
10
 */
11

    
12

    
13
/**
14
 * Get the depending classes.
15
 */
16
require_once views_pdf_get_library('tcpdf') . '/tcpdf.php';
17

    
18
if (file_exists(views_pdf_get_library('fpdi') . '/fpdi_bridge.php')) {
19
  require_once views_pdf_get_library('fpdi') . '/fpdi_bridge.php';
20
}
21
else {
22
  require_once views_pdf_get_library('fpdi') . '/fpdi2tcpdf_bridge.php';
23
}
24

    
25
require_once views_pdf_get_library('fpdi') . '/fpdi.php';
26

    
27

    
28
/**
29
 * The main class to generate the PDF.
30
 */
31
class PdfTemplate extends FPDI {
32
  protected static $fontList = NULL;
33
  protected static $fontListClean = NULL;
34
  protected static $templateList = NULL;
35
  protected static $hyphenatePatterns = NULL;
36
  protected $defaultFontStyle = '';
37
  protected $defaultFontFamily = 'helvetica';
38
  protected $defaultFontSize = '11';
39
  protected $defaultTextAlign = 'L';
40
  protected $defaultFontColor = '000000';
41
  protected $defaultPageTemplateFiles = array();
42
  protected $mainContentPageNumber = 0;
43
  protected $rowContentPageNumber = 0;
44
  protected $defaultOrientation = 'P';
45
  protected $defaultFormat = 'A4';
46
  protected $addNewPageBeforeNextContent = FALSE;
47
  protected $elements = array();
48
  protected $headerFooterData = array();
49
  protected $views_header = '';
50
  protected $view = NULL;
51
  protected $views_footer = '';
52
  protected $headerFooterOptions = array();
53
  protected $lastWritingPage = 1;
54
  protected $lastWritingPositions;
55

    
56
  protected static $defaultFontList = array(
57
    'almohanad' => 'AlMohanad',
58
    'arialunicid0' => 'ArialUnicodeMS',
59
    'courier' => 'Courier',
60
    'courierb' => 'Courier Bold',
61
    'courierbi' => 'Courier Bold Italic',
62
    'courieri' => 'Courier Italic',
63
    'dejavusans' => 'DejaVuSans',
64
    'dejavusansb' => 'DejaVuSans-Bold',
65
    'dejavusansbi' => 'DejaVuSans-BoldOblique',
66
    'dejavusansi' => 'DejaVuSans-Oblique',
67
    'dejavusanscondensed' => 'DejaVuSansCondensed',
68
    'dejavusanscondensedb' => 'DejaVuSansCondensed-Bold',
69
    'dejavusanscondensedbi' => 'DejaVuSansCondensed-BoldOblique',
70
    'dejavusanscondensedi' => 'DejaVuSansCondensed-Oblique',
71
    'dejavusansmono' => 'DejaVuSansMono',
72
    'dejavusansmonob' => 'DejaVuSansMono-Bold',
73
    'dejavusansmonobi' => 'DejaVuSansMono-BoldOblique',
74
    'dejavusansmonoi' => 'DejaVuSansMono-Oblique',
75
    'dejavuserif' => 'DejaVuSerif',
76
    'dejavuserifb' => 'DejaVuSerif-Bold',
77
    'dejavuserifbi' => 'DejaVuSerif-BoldItalic',
78
    'dejavuserifi' => 'DejaVuSerif-Italic',
79
    'dejavuserifcondensed' => 'DejaVuSerifCondensed',
80
    'dejavuserifcondensedb' => 'DejaVuSerifCondensed-Bold',
81
    'dejavuserifcondensedbi' => 'DejaVuSerifCondensed-BoldItalic',
82
    'dejavuserifcondensedi' => 'DejaVuSerifCondensed-Italic',
83
    'freemono' => 'FreeMono',
84
    'freemonob' => 'FreeMonoBold',
85
    'freemonobi' => 'FreeMonoBoldOblique',
86
    'freemonoi' => 'FreeMonoOblique',
87
    'freesans' => 'FreeSans',
88
    'freesansb' => 'FreeSansBold',
89
    'freesansbi' => 'FreeSansBoldOblique',
90
    'freesansi' => 'FreeSansOblique',
91
    'freeserif' => 'FreeSerif',
92
    'freeserifb' => 'FreeSerifBold',
93
    'freeserifbi' => 'FreeSerifBoldItalic',
94
    'freeserifi' => 'FreeSerifItalic',
95
    'hysmyeongjostdmedium' => 'HYSMyeongJoStd-Medium-Acro',
96
    'helvetica' => 'Helvetica',
97
    'helveticab' => 'Helvetica Bold',
98
    'helveticabi' => 'Helvetica Bold Italic',
99
    'helveticai' => 'Helvetica Italic',
100
    'kozgopromedium' => 'KozGoPro-Medium-Acro',
101
    'kozminproregular' => 'KozMinPro-Regular-Acro',
102
    'msungstdlight' => 'MSungStd-Light-Acro',
103
    'stsongstdlight' => 'STSongStd-Light-Acro',
104
    'symbol' => 'Symbol',
105
    'times' => 'Times New Roman',
106
    'timesb' => 'Times New Roman Bold',
107
    'timesbi' => 'Times New Roman Bold Italic',
108
    'timesi' => 'Times New Roman Italic',
109
    'zapfdingbats' => 'Zapf Dingbats',
110
    'zarbold' => 'ZarBold'
111
  );
112

    
113
  /**
114
   * This method overrides the parent constructor method.
115
   * this is need to reset the default values.
116
   */
117
  public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=TRUE, $encoding='UTF-8', $diskcache=FALSE) {
118
    parent::__construct($orientation, $unit, $format, $unicode, $encoding, $diskcache);
119
    $this->defaultOrientation = $orientation;
120
    $this->defaultFormat = $format;
121
  }
122

    
123
  public function setDefaultFontSize($size) {
124
    $this->defaultFontSize = $size;
125
  }
126

    
127
  public function setDefaultFontFamily($family) {
128
    $this->defaultFontFamily = $family;
129
  }
130

    
131
  public function setDefaultFontStyle($style) {
132
    $this->defaultFontStyle = $style;
133
  }
134

    
135
  public function setDefaultTextAlign($style) {
136
    $this->defaultTextAlign = $style;
137
  }
138

    
139
  public function setDefaultFontColor($color) {
140
    $this->defaultFontColor = $color;
141
  }
142

    
143
  public function setDefaultPageTemplate($path, $key, $pageNumbering = 'main') {
144
    $this->defaultPageTemplateFiles[$key] = array(
145
      'path' => $path,
146
      'numbering' => $pageNumbering
147
    );
148
  }
149

    
150
  public function setViewsHeader($header) {
151
    $this->views_header = $header;
152
  }
153
  /**
154
   * This method must be overriden, in the other case, some
155
   * output is printed to the header.
156
   */
157
  function Header() {
158
    if (!empty($this->views_header)) {
159
      $this->writeHTML($this->views_header);
160
    }
161
  }
162

    
163
  public function setViewsFooter($footer) {
164
    $this->views_footer = $footer;
165
   }
166

    
167
  /**
168
   * This method must be overriden, in the other case, some
169
   * output is printed to the footer.
170
   */
171
  function Footer() {
172
    $this->SetY(-$this->bMargin);
173
    if (!empty($this->views_footer)) {
174
      $this->writeHTML($this->views_footer);
175
    }
176
  }
177

    
178
  /**
179
   * Converts a hex color into an array with RGB colors.
180
   */
181
  public function convertHexColorToArray($hex) {
182
    if (drupal_strlen($hex) == 6) {
183
      $r = drupal_substr($hex, 0, 2);
184
      $g = drupal_substr($hex, 2, 2);
185
      $b = drupal_substr($hex, 4, 2);
186
      return array(hexdec($r), hexdec($g), hexdec($b));
187

    
188
    }
189
    elseif (drupal_strlen($hex) == 3) {
190
      $r = drupal_substr($hex, 0, 1);
191
      $g = drupal_substr($hex, 1, 1);
192
      $b = drupal_substr($hex, 2, 1);
193
      return array(hexdec($r), hexdec($g), hexdec($b));
194

    
195
    }
196
    else {
197
      return array();
198
    }
199
  }
200

    
201
  /**
202
   * Parse color input into an array.
203
   *
204
   * @param string $color
205
   *   Color entered by the user
206
   *
207
   * @return array
208
   *   Color as an array
209
   */
210
  public function parseColor($color) {
211
    $color = trim($color, ', ');
212
    $components = explode(',', $color);
213
    if (count($components) == 1) {
214
      return $this->convertHexColorToArray($color);
215
    }
216
    else {
217
      // Remove white spaces from comonents:
218
      foreach ($components as $id => $component) {
219
        $components[$id] = trim($component);
220
      }
221
      return $components;
222
    }
223
  }
224

    
225
  /**
226
   * This method draws a field on the PDF.
227
   */
228
  public function drawContent($row, $options, &$view = NULL, $key = NULL, $printLabels = TRUE) {
229

    
230
    if (!is_array($options)) {
231
      $options = array();
232
    }
233

    
234
    // Set defaults:
235
    $options += array(
236
      'position' => array(),
237
      'text' => array(),
238
      'render' => array(),
239
    );
240

    
241
    $options['position'] += array(
242
      'corner' => 'top_left',
243
      'x' => 0,
244
      'y' => 0,
245
      'object' => 'last_position',
246
      'width' => 0,
247
      'height' => 0,
248
    );
249

    
250
    $options['text'] += array(
251
      'font_family' => 'default',
252
      'font_style' => '',
253
    );
254

    
255
    $options['render'] += array(
256
      'eval_before' => '',
257
      'eval_after' => '',
258
      'bypass_eval_before' => FALSE,
259
      'bypass_eval_after' => FALSE,
260
    );
261

    
262
    $x = $y = 0;
263

    
264

    
265
    // Get the page dimensions
266
    $pageDim = $this->getPageDimensions();
267

    
268
    // Check if there is a minimum space defined. If so, then ensure
269
    // that we have enough space left on this page. If not force adding
270
    // a new one.
271
    if (isset($options['render']['minimal_space'])) {
272
      $enoughtSpace = ($this->y + $this->bMargin + $options['render']['minimal_space']) < $pageDim['hk'];
273
    }
274
    else {
275
      $enoughtSpace = TRUE;
276
    }
277

    
278

    
279
    // Check if there is a page, if not add it:
280
    if (!$enoughtSpace OR $this->getPage() == 0 OR $this->addNewPageBeforeNextContent == TRUE) {
281
      $this->addNewPageBeforeNextContent = FALSE;
282
      $this->addPage();
283
    }
284

    
285
    // Get the page dimenstions again, because it can be that a new
286
    // page was added with new dimensions.
287
    $pageDim = $this->getPageDimensions();
288

    
289
    // Determine the last writting y coordinate, if we are on a new
290
    // page we need to reset it back to the top margin.
291
    if ($this->lastWritingPage != $this->getPage() OR ($this->y + $this->bMargin) > $pageDim['hk']) {
292
      $last_writing_y_position = $this->tMargin;
293
    }
294
    else {
295
      $last_writing_y_position = $this->y;
296
    }
297

    
298
    // Determin the x and y coordinates
299
    if ($options['position']['object'] == 'last_position') {
300
      $x = $this->x + $options['position']['x'];
301
      $y = $this->y + $options['position']['y'];
302
    }
303
    elseif ($options['position']['object'] == 'page') {
304
      switch ($options['position']['corner']) {
305
        default:
306
        case 'top_left':
307
          $x = $options['position']['x']+$this->lMargin;
308
          $y = $options['position']['y']+$this->tMargin;
309
          break;
310

    
311
        case 'top_right':
312
          $x = $options['position']['x'] + $pageDim['wk'] - $this->rMargin;
313
          $y = $options['position']['y'] + $this->tMargin;
314
          break;
315

    
316
        case 'bottom_left':
317
          $x = $options['position']['x'] + $this->rMargin;
318
          $y = $options['position']['y'] + $pageDim['hk'] - $this->bMargin;
319

    
320
          break;
321

    
322
        case 'bottom_right':
323
          $x = $options['position']['x'] + $pageDim['wk'] - $this->rMargin;
324
          $y = $options['position']['y'] + $pageDim['hk'] - $this->bMargin;
325

    
326
          break;
327
      }
328
    }
329
    elseif (
330
      $options['position']['object'] == 'self' or
331
      //$options['position']['object'] == 'last' or
332
      preg_match('/field\_(.*)/', $options['position']['object'], $rs)
333
    ) {
334
      if ($options['position']['object'] == 'last') {
335
        $relative_to_element = $this->lastWritingElement;
336
      }
337
      elseif ($options['position']['object'] == 'self') {
338
        $relative_to_element = $key;
339
      }
340
      else {
341
        $relative_to_element = $rs[1];
342
      }
343

    
344
      if (isset($this->elements[$relative_to_element])) {
345

    
346
        switch ($options['position']['corner']) {
347
          default:
348
          case 'top_left':
349
            $x = $options['position']['x'] + $this->elements[$relative_to_element]['x'];
350
            $y = $options['position']['y'] + $this->elements[$relative_to_element]['y'];
351
            break;
352

    
353
          case 'top_right':
354
            $x = $options['position']['x'] + $this->elements[$relative_to_element]['x'] + $this->elements[$relative_to_element]['width'];
355
            $y = $options['position']['y'] + $this->elements[$relative_to_element]['y'];
356
            break;
357

    
358
          case 'bottom_left':
359
            $x = $options['position']['x'] + $this->elements[$relative_to_element]['x'];
360
            $y = $options['position']['y'] + $this->elements[$relative_to_element]['y'] + $this->elements[$relative_to_element]['height'];
361

    
362
            break;
363

    
364
          case 'bottom_right':
365
            $x = $options['position']['x'] + $this->elements[$relative_to_element]['x'] + $this->elements[$relative_to_element]['width'];
366
            $y = $options['position']['y'] + $this->elements[$relative_to_element]['y'] + $this->elements[$relative_to_element]['height'];
367

    
368
            break;
369
        }
370

    
371
        // Handle if the relative element is on another page. So using the
372
        // the last writing position instead for y.
373
        if ($this->getPage() != $this->elements[$relative_to_element]['page'] && $options['position']['object'] != 'self') {
374
          $this->setPage($this->elements[$relative_to_element]['page']);
375
        }
376
        elseif ($this->getPage() != $this->elements[$relative_to_element]['page'] && $options['position']['object'] == 'self') {
377
          $y = $y - $this->elements[$relative_to_element]['y'] + $last_writing_y_position;
378
          $this->SetPage($this->lastWritingPage);
379
        }
380

    
381
      }
382
      else {
383
        $x = $this->x;
384
        $y = $last_writing_y_position;
385
      }
386

    
387
    }
388

    
389
    // No position match (for example header/footer)
390
    else {
391
      // Render or return
392
      if (is_object($view) && $key != NULL ) {
393
        $content = $view->field[$key]->theme($row);
394
      }
395
      else{
396
        return;
397
      }
398

    
399
    }
400

    
401
    if ($key !== NULL && $view->field[$key]->theme($row) || !empty($row)) {
402
      $this->SetX($x);
403
      $this->SetY($y);
404
      $this->renderRow($x, $y, $row, $options, $view, $key, $printLabels);
405
    }
406
  }
407

    
408
  protected function renderRow($x, $y, $row, $options, &$view = NULL, $key = NULL, $printLabels = TRUE) {
409

    
410
    $pageDim = $this->getPageDimensions();
411

    
412
    // Render the content if it is not already:
413
    if (is_object($view) && $key != NULL && isset($view->field[$key]) && is_object($view->field[$key]) && !is_string($row)) {
414
      $content = $view->field[$key]->theme($row);
415
    }
416
    elseif (is_string($row)) {
417
      $content = $row;
418
    }
419
    else {
420
      // We got bad data. So return.
421
      return;
422
    }
423

    
424
    if (empty($key) || !empty($view->field[$key]->options['exclude']) || (empty($content) && $view->field[$key]->options['hide_empty'])) {
425
      return '';
426
    }
427

    
428
    // Apply the hyphenation patterns to the content:
429
    if (!isset($options['text']['hyphenate']) && is_object($view) && is_object($view->display_handler)) {
430
      $options['text']['hyphenate'] = $view->display_handler->get_option('default_text_hyphenate');
431
    }
432

    
433
    if (isset($options['text']['hyphenate']) && $options['text']['hyphenate'] != 'none') {
434
      $patternFile = $options['text']['hyphenate'];
435
      if ($options['text']['hyphenate'] == 'auto' && is_object($row)) {
436

    
437
        // Workaround:
438
        // Since "$nodeLanguage = $row->node_language;" does not work anymore,
439
        // we using this:
440
        if (isset($row->_field_data['nid']['entity']->language)) {
441
          $nodeLanguage = $row->_field_data['nid']['entity']->language;
442

    
443
          foreach (self::getAvailableHyphenatePatterns() as $file => $pattern) {
444
            if (stristr($pattern, $nodeLanguage) !== FALSE) {
445
              $patternFile = $file;
446
              break;
447
            }
448
          }
449
        }
450
      }
451

    
452
      $patternFile = views_pdf_get_library('tcpdf') . '/hyphenate_patterns/' . $patternFile;
453

    
454
      if (file_exists($patternFile)) {
455
        if (method_exists('TCPDF_STATIC', 'getHyphenPatternsFromTEX')) {
456
          $hyphen_patterns = TCPDF_STATIC::getHyphenPatternsFromTEX($patternFile);
457
        }
458
        else {
459
          $hyphen_patterns = $this->getHyphenPatternsFromTEX($patternFile);
460
        }
461

    
462
        // Bugfix if you like to print some html code to the PDF, we
463
        // need to prevent the replacement of this tags.
464
        $content = str_replace('&gt;', '&amp;gt;', $content);
465
        $content = str_replace('&lt;', '&amp;lt;', $content);
466
        $content = $this->hyphenateText($content, $hyphen_patterns);
467

    
468
      }
469
    }
470

    
471
    // Set css variable
472
    if (is_object($view) && is_object($view->display_handler)) {
473
      $css_file = $view->display_handler->get_option('css_file');
474
    }
475

    
476
    // Render Labels
477
    $prefix = '';
478
    if ($printLabels && !empty($view->field[$key]->options['label'])) {
479
      $prefix = $view->field[$key]->options['label'];
480
      if ($view->field[$key]->options['element_label_colon']) {
481
        $prefix .= ':';
482
      }
483
      $prefix .= ' ';
484
    }
485

    
486
    $font_size = empty($options['text']['font_size']) ? $this->defaultFontSize : $options['text']['font_size'] ;
487
    $font_family = ($options['text']['font_family'] == 'default' || empty($options['text']['font_family'])) ? $this->defaultFontFamily : $options['text']['font_family'];
488
    $font_style = is_array($options['text']['font_style']) ? $options['text']['font_style'] : $this->defaultFontStyle;
489
    $textColor = !empty($options['text']['color']) ? $this->parseColor($options['text']['color']) : $this->parseColor($this->defaultFontColor);
490

    
491

    
492
    $w = $options['position']['width'];
493
    $h = $options['position']['height'];
494
    $border = 0;
495
    $align = isset($options['text']['align']) ? $options['text']['align'] : $this->defaultTextAlign;
496
    $fill = 0;
497
    $ln = 1;
498
    $reseth = TRUE;
499
    $stretch = 0;
500
    $ishtml = isset($options['render']['is_html']) ? $options['render']['is_html'] : 1;
501
    $stripHTML = !$ishtml;
502
    $autopadding = TRUE;
503
    $maxh = 0;
504
    $valign = 'T';
505
    $fitcell = FALSE;
506

    
507
    // Run eval before.
508
    if (!empty($options['render']['bypass_eval_before']) && !empty($options['render']['eval_before'])) {
509
      eval($options['render']['eval_before']);
510
    }
511
    elseif (!empty($options['render']['eval_before']))  {
512
      $content = php_eval($options['render']['eval_before']);
513
    }
514

    
515
    // Add css if there is a css file set and stripHTML is not active.
516
    if (!empty($css_file) && is_string($css_file) && !$stripHTML && $ishtml && !empty($content)) {
517
      $content = '<link type="text/css" rel="stylesheet" media="all" href="' . $css_file . '" />' . PHP_EOL . $content;
518
    }
519

    
520
    // Set Text Color.
521
    $this->SetTextColorArray($textColor);
522

    
523
    // Set font.
524
    $this->SetFont($font_family, implode('', $font_style), $font_size);
525

    
526
    // Save the last page before starting writing, this
527
    // is needed to dected if we write over a page. Then we need
528
    // to reset the y coordinate for the 'last_writing' position option.
529
    $this->lastWritingPage = $this->getPage();
530

    
531
    if ($stripHTML) {
532
      $content = strip_tags($content);
533
    }
534

    
535
    // Write the content of a field to the pdf file:
536
    if (!empty($content)) {
537
      $this->MultiCell($w, $h, $prefix . $content, $border, $align, $fill, $ln, $x, $y, $reseth, $stretch, $ishtml, $autopadding, $maxh, $valign, $fitcell);
538
    }
539
    else {
540
      $this->MultiCell($w, $h, $prefix, $border, $align, $fill, $ln, $x, $y, $reseth, $stretch, $ishtml, $autopadding, $maxh, $valign, $fitcell);
541
    }
542

    
543
    // Reset font to default.
544
    $this->SetFont($this->defaultFontFamily, implode('', $this->defaultFontStyle), $this->defaultFontSize);
545

    
546
    // Run eval after.
547
    if (!empty($options['render']['bypass_eval_after']) && !empty($options['render']['eval_after'])) {
548
      eval($options['render']['eval_after']);
549
    }
550
    elseif (!empty($options['render']['eval_after'])) {
551
      $content = php_eval($options['render']['eval_after']);
552
    }
553

    
554
    // Write Coordinates of element.
555
    $this->elements[$key] = array(
556
      'x' => $x,
557
      'y' => $y,
558
      'width' => empty($w) ? ($pageDim['wk'] - $this->rMargin-$x) : $w,
559
      'height' => $this->y - $y,
560
      'page' => $this->lastWritingPage,
561
    );
562

    
563
    $this->lastWritingElement = $key;
564
  }
565

    
566
  /**
567
   * This method draws a table on the PDF.
568
   */
569
  public function drawTable(&$view, $options) {
570

    
571
    $rows = $view->result;
572
    $columns = $view->field;
573
    $pageDim = $this->getPageDimensions();
574

    
575
    // Set draw point to the indicated position:
576
    if (empty($options['position']['x'])) {
577
      $options['position']['x'] = 0;
578
    }
579

    
580
    if (empty($options['position']['y'])) {
581
      $options['position']['y'] = 0;
582
    }
583

    
584
    if (isset($options['position']['last_writing_position']) && $options['position']['last_writing_position']) {
585
      $y = $options['position']['y'] + $this->y;
586
      $x = $options['position']['x'] + $this->x;
587
    }
588
    else {
589
      $y = $options['position']['y'];
590
      $x = $options['position']['x'];
591
    }
592

    
593
    if (isset($options['position']['width']) && !empty($options['position']['width'])) {
594
      $width = $options['position']['width'];
595
    }
596
    else {
597
      $width = $pageDim['wk'] - $this->rMargin - $x;
598
    }
599

    
600
    $sumWidth = 0;
601
    $numberOfColumnsWithoutWidth = 0;
602

    
603
    // Set the definitiv width of a column
604
    foreach ($columns as $id => $columnName) {
605
      if (isset($options['info'][$id]['position']['width']) && !empty($options['info'][$id]['position']['width'])) {
606
        $sumWidth += $options['info'][$id]['position']['width'];
607
      }
608
      else {
609
        $numberOfColumnsWithoutWidth++;
610
      }
611
    }
612
    if ($numberOfColumnsWithoutWidth > 0) {
613
      $defaultColumnWidth = ($width - $sumWidth) / $numberOfColumnsWithoutWidth;
614
    }
615
    else {
616
      $defaultColumnWidth = 0;
617
    }
618

    
619
    // Print header:
620
    $rowX = $x;
621
    $page = $this->getPage();
622
    if ($page == 0) {
623
      $this->addPage();
624
      $page = $this->getPage();
625
    }
626

    
627
    if (!isset($options['position']['row_height']) || empty($options['position']['row_height'])) {
628
      $options['position']['row_height'] = 0;
629
    }
630

    
631
    foreach ($columns as $id => $column) {
632

    
633
      if (!empty($column->options['exclude'])) {
634
        continue;
635
      }
636

    
637
      if (!is_array($options['info'][$id])) {
638
        $options['info'][$id] = array();
639
      }
640

    
641
      $options['info'][$id] += array(
642
        'header_style' => array(),
643
        'body_style' => array(),
644
      );
645

    
646
      $options['info'][$id]['header_style'] += array(
647
        'position' => array(),
648
        'text' => array(),
649
        'render' => array(),
650
      );
651

    
652
      $options['info'][$id]['header_style']['position'] += array(
653
        'corner' => 'top_left',
654
        'x' => NULL,
655
        'y' => NULL,
656
        'object' => '',
657
        'width' => NULL,
658
        'height' => NULL,
659
      );
660

    
661
      $options['info'][$id]['header_style']['text'] += array(
662
        'font_family' => 'default',
663
        'font_style' => '',
664
      );
665

    
666
      $options['info'][$id]['header_style']['text'] += array(
667
        'eval_before' => '',
668
        'eval_after' => '',
669
      );
670

    
671
      $options['info'][$id]['body_style'] += array(
672
        'position' => array(),
673
        'text' => array(),
674
        'render' => array(),
675
      );
676

    
677
      $options['info'][$id]['body_style']['position'] += array(
678
        'corner' => 'top_left',
679
        'x' => NULL,
680
        'y' => NULL,
681
        'object' => '',
682
        'width' => NULL,
683
        'height' => NULL,
684
      );
685

    
686
      $options['info'][$id]['body_style']['text'] += array(
687
        'font_family' => 'default',
688
        'font_style' => '',
689
      );
690

    
691
      $options['info'][$id]['body_style']['text'] += array(
692
        'eval_before' => '',
693
        'eval_after' => '',
694
      );
695

    
696
      $headerOptions = $options['info'][$id]['header_style'];
697

    
698
      if (isset($options['info'][$id]['position']['width']) && !empty($options['info'][$id]['position']['width'])) {
699
        $headerOptions['position']['width'] = $options['info'][$id]['position']['width'];
700
      }
701
      else {
702
        $headerOptions['position']['width'] = $defaultColumnWidth;
703
      }
704
      $headerOptions['position']['object'] = 'last_position_without_reset';
705

    
706
      $this->SetY($y);
707
      $this->SetX($x);
708
      $this->setPage($page);
709

    
710
      $this->renderRow($x, $y, $column->options['label'], $headerOptions, $view, $id, FALSE);
711
      $x += $headerOptions['position']['width'];
712
    }
713

    
714
    $rowY = $this->y;
715

    
716
    if (!isset($options['position']['row_height']) || empty($options['position']['row_height'])) {
717
      $options['position']['row_height'] = 0;
718
    }
719

    
720
    foreach ($rows as $row) {
721
      $x = $rowX;
722

    
723
       // Get the page dimensions
724
      $pageDim = $this->getPageDimensions();
725

    
726
      if (($rowY + $this->bMargin + $options['position']['row_height']) > $pageDim['hk']) {
727
        $rowY = $this->tMargin;
728
        $this->addPage();
729
      }
730

    
731
      if ($this->lastWritingPage != $this->getPage()) {
732
        $rowY = $this->y; // $rowY - $pageDim['hk']
733
      }
734

    
735
      $y = $rowY;
736
      $page = $this->getPage();
737
      foreach ($columns as $id => $column) {
738

    
739
        if (!empty($column->options['exclude']) && is_object($view->field[$id])) {
740
          // Render the element, but dont print the output. This
741
          // is required to allow the use of tokens in other fields.
742
          $view->field[$id]->theme($row);
743
          continue;
744
        }
745

    
746
        $bodyOptions = $options['info'][$id]['body_style'];
747

    
748
        if (isset($options['info'][$id]['position']['width']) && !empty($options['info'][$id]['position']['width'])) {
749
          $bodyOptions['position']['width'] = $options['info'][$id]['position']['width'];
750
        }
751
        else {
752
          $bodyOptions['position']['width'] = $defaultColumnWidth;
753
        }
754
        $bodyOptions['position']['object'] = 'last_position';
755

    
756
        $this->setPage($page);
757
        $this->SetY($y);
758
        $this->SetX($x);
759

    
760
        $bodyOptions['position']['height'] = 0;
761

    
762
        $this->renderRow($x, $y, $row, $bodyOptions, $view, $id, FALSE);
763

    
764
        $x += $bodyOptions['position']['width'];
765

    
766
        // If the cell is writting over the row, we need to adjust the
767
        // row y position.
768
        if (($rowY + $options['position']['row_height']) < $this->y) {
769
          $rowY = $this->y - $options['position']['row_height'];
770
        }
771

    
772
      }
773

    
774
      $rowY += $options['position']['row_height'];
775

    
776
    }
777

    
778
    $this->SetY($rowY + $options['position']['row_height']);
779
  }
780

    
781
  /**
782
   * This method adds a existing PDF document to the current document. If
783
   * the file does not exists this method will return 0. In all other cases
784
   * it will returns the number of the added pages.
785
   *
786
   * @param $path string Path to the file
787
   * @return integer Number of added pages
788
   */
789
  public function addPdfDocument($path) {
790
    if (empty($path) || !file_exists($path)) {
791
      return 0;
792
    }
793

    
794
    $numberOfPages = $this->setSourceFile($path);
795
    for ($i = 1; $i <= $numberOfPages; $i++) {
796

    
797
      $dim = $this->getTemplateSize($i);
798
      $format[0] = $dim['w'];
799
      $format[1] = $dim['h'];
800

    
801
      if ($dim['w'] > $dim['h']) {
802
        $orientation = 'L';
803
      }
804
      else {
805
        $orientation = 'P';
806
      }
807
      $this->setPageFormat($format, $orientation);
808
      parent::addPage();
809

    
810
      // Ensure that all new content is printed to a new page
811
      $this->y = 0;
812

    
813
      $page = $this->importPage($i);
814
      $this->useTemplate($page, 0, 0);
815
      $this->addNewPageBeforeNextContent = TRUE;
816
    }
817

    
818
    return $numberOfPages;
819

    
820
  }
821

    
822
  /**
823
   * This method resets the page number. This is useful if you want to start
824
   * the numbering by zero.
825
   */
826
  public function resetRowPageNumber() {
827
    $this->rowContentPageNumber = 0;
828
  }
829

    
830
  /**
831
   * This method adds a new page to the PDF.
832
   */
833
  public function addPage($orientation = '', $format = '', $keepmargins = false, $tocpage = false, $path = NULL, $reset = FALSE, $numbering = 'main') {
834

    
835
    // Do not add any new page, if we are writing
836
    // in the footer or header.
837
    if ($this->InFooter) {
838
      return;
839
    }
840

    
841
    $this->mainContentPageNumber++;
842
    $this->rowContentPageNumber++;
843

    
844
    // Prevent a reset without any template
845
    if ($reset == TRUE && (empty($path) || !file_exists($path))) {
846
      parent::addPage();
847
      $this->setPageFormat($this->defaultFormat, $this->defaultOrientation);
848
      return;
849
    }
850

    
851
    $files = $this->defaultPageTemplateFiles;
852

    
853
    // Reset with new template
854
    if ($reset) {
855
      $files = array();
856
    }
857

    
858
    if ($path != NULL) {
859
      $files[] = array('path' => $path, 'numbering' => $numbering);
860
    }
861
    $format = FALSE;
862
    foreach ($files as $file) {
863
      if (!empty($file['path']) && file_exists($file['path'])) {
864
        $path = realpath($file['path']);
865

    
866
        $numberOfPages = $this->setSourceFile($path);
867
        if ($file['numbering'] == 'row')  {
868
          $index = min($this->rowContentPageNumber, $numberOfPages);
869
        }
870
        else {
871
          $index = min($this->mainContentPageNumber, $numberOfPages);
872
        }
873

    
874

    
875
        $page = $this->importPage($index);
876

    
877
        // ajust the page format (only for the first template)
878
        if ($format == FALSE) {
879

    
880
          $dim = $this->getTemplateSize($index);
881
          $format[0] = $dim['w'];
882
          $format[1] = $dim['h'];
883
          //$this->setPageFormat($format);
884
          if ($dim['w'] > $dim['h']) {
885
            $orientation = 'L';
886
          }
887
          else {
888
            $orientation = 'P';
889
          }
890
          $this->setPageFormat($format, $orientation);
891
          parent::addPage();
892
        }
893

    
894
        // Apply the template
895
        $this->useTemplate($page, 0, 0);
896
      }
897
    }
898

    
899
    // if all paths were empty, ensure that at least the page is added
900
    if ($format == FALSE) {
901
      parent::addPage();
902
      $this->setPageFormat($this->defaultFormat, $this->defaultOrientation);
903
    }
904

    
905
  }
906

    
907
  /**
908
   * Sets the current header and footer of the page.
909
   */
910
  public function setHeaderFooter($record, $options, $view) {
911
    //if ($this->getPage() > 0 && !isset($this->headerFooterData[$this->getPage()])) {
912
      $this->headerFooterData[$this->getPage()] = $record;
913
    //}
914
    $this->headerFooterOptions = $options;
915
    $this->view =& $view;
916
  }
917

    
918
  /**
919
   * Close the document. This is called automatically by
920
   * TCPDF::Output().
921
   */
922
  public function Close() {
923
    // Print the Header & Footer
924
    for ($page = 1; $page <= $this->getNumPages(); $page++) {
925
      $this->setPage($page);
926

    
927
      if (isset($this->headerFooterData[$page])) {
928
        $record = $this->headerFooterData[$page];
929
        if (is_array($this->headerFooterOptions['formats'])) {
930
          foreach ($this->headerFooterOptions['formats'] as $id => $options) {
931
            if ($options['position']['object'] == 'header_footer') {
932
              $fieldOptions = $options;
933
              $fieldOptions['position']['object'] = 'page';
934
              $this->InFooter = TRUE;
935

    
936
              // backup margins
937
              $ml = $this->lMargin;
938
              $mr = $this->rMargin;
939
              $mt = $this->tMargin;
940
              $this->SetMargins(0, 0, 0);
941

    
942
              $this->drawContent($record, $fieldOptions, $this->view, $id);
943
              $this->InFooter = FALSE;
944

    
945
              // restore margins
946
              $this->SetMargins($ml, $mt, $mr);
947
            }
948
          }
949
        }
950
      }
951
    }
952

    
953
    // call parent:
954
    parent::Close();
955

    
956
  }
957

    
958
  /**
959
   * This method returns a list of current uploaded files.
960
   */
961
  public static function getAvailableTemplates() {
962
    if (self::$templateList != NULL) {
963
      return self::$templateList;
964
    }
965

    
966
    $files_path = drupal_realpath('public://');
967
    $template_dir = variable_get('views_pdf_template_path', 'views_pdf_templates');
968
    $dir = $files_path . '/' . $template_dir;
969
    $templatesFiles = file_scan_directory($dir, '/.pdf$/', array('nomask' => '/(\.\.?|CVS)$/'), 1);
970

    
971
    $templates = array();
972

    
973
    foreach ($templatesFiles as $file) {
974
      $templates[$file->filename] = $file->name;
975
    }
976

    
977
    self::$templateList = $templates;
978

    
979
    return $templates;
980

    
981
  }
982

    
983
  /**
984
   * This method returns the path to a specific template.
985
   */
986
  public static function getTemplatePath($template, $row = NULL, $view = NULL) {
987
    if (empty($template)) {
988
      return '';
989
    }
990

    
991
    if ($row != NULL && $view != NULL && !preg_match('/\.pdf/', $template)) {
992
      return drupal_realpath($row->field_data_field_file_node_values[0]['uri']);
993
    }
994

    
995
    $template_dir = variable_get('views_pdf_template_stream', 'public://views_pdf_templates');
996
    return drupal_realpath($template_dir . '/' . $template);
997
  }
998

    
999
  /**
1000
   * This method returns a list of available fonts.
1001
   */
1002
  public static function getAvailableFonts() {
1003
    if (self::$fontList != NULL) {
1004
      return self::$fontList;
1005
    }
1006

    
1007
    // Get all pdf files with the font list: K_PATH_FONTS
1008
    $fonts = file_scan_directory(K_PATH_FONTS, '/.php$/', array('nomask' => '/(\.\.?|CVS)$/', 'recurse' => FALSE), 1);
1009
    $cache = cache_get('views_pdf_cached_fonts');
1010

    
1011
    $cached_font_mapping = NULL;
1012

    
1013
    if (is_object($cache)) {
1014
      $cached_font_mapping = $cache->data;
1015
    }
1016

    
1017
    if (is_array($cached_font_mapping)) {
1018
      $font_mapping = array_merge(self::$defaultFontList, $cached_font_mapping);
1019
    }
1020
    else {
1021
      $font_mapping = self::$defaultFontList;
1022
    }
1023

    
1024
    foreach ($fonts as $font) {
1025
        $name = self::getFontNameByFileName($font->uri);
1026
        if (isset($name)) {
1027
          $font_mapping[$font->name] = $name;
1028
        }
1029
    }
1030

    
1031
    asort($font_mapping);
1032

    
1033
    cache_set('views_pdf_cached_fonts', $font_mapping);
1034

    
1035
    // Remove all fonts without name
1036
    foreach ($font_mapping as $key => $font) {
1037
      if (empty($font)) {
1038
        unset($font_mapping[$key]);
1039
      }
1040

    
1041
    }
1042

    
1043
    self::$fontList = $font_mapping;
1044

    
1045
    return $font_mapping;
1046
  }
1047

    
1048
  /**
1049
   * This method returns a cleaned up version of the font list.
1050
   */
1051
  public static function getAvailableFontsCleanList() {
1052
    if (self::$fontListClean != NULL) {
1053
      return self::$fontListClean;
1054
    }
1055

    
1056
    $clean = self::getAvailableFonts();
1057

    
1058
    foreach ($clean as $key => $font) {
1059

    
1060
      // Unset bold, italic, italic/bold fonts
1061
      unset($clean[ ($key . 'b') ]);
1062
      unset($clean[ ($key . 'bi') ]);
1063
      unset($clean[ ($key . 'i') ]);
1064

    
1065
    }
1066

    
1067
    self::$fontListClean = $clean;
1068

    
1069
    return $clean;
1070
  }
1071

    
1072
  /**
1073
   * This method returns a list of hyphenation patterns, that are
1074
   * available.
1075
   */
1076
  public static function getAvailableHyphenatePatterns() {
1077
    if (self::$hyphenatePatterns != NULL) {
1078
      return self::$hyphenatePatterns;
1079
    }
1080

    
1081
    self::$hyphenatePatterns = array();
1082

    
1083
    $files = file_scan_directory(views_pdf_get_library('tcpdf') . '/hyphenate_patterns', '/.tex$/', array('nomask' => '/(\.\.?|CVS)$/'), 1);
1084

    
1085
    foreach ($files as $file) {
1086
      self::$hyphenatePatterns[basename($file->uri)] = str_replace('hyph-', '', $file->name);
1087
    }
1088

    
1089

    
1090
    return self::$hyphenatePatterns;
1091
  }
1092

    
1093
  /**
1094
   * This method returns the name of a given font.
1095
   */
1096
  protected static function getFontNameByFileName($path) {
1097
    include $path;
1098
    if (isset($name)) {
1099
      return $name;
1100
    }
1101
    else {
1102
      return NULL;
1103
    }
1104
  }
1105
}