Projet

Général

Profil

Paste
Télécharger (33,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / views_pdf / views_pdf_template.php @ e9f59ce0

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
      if ($options['position']['object'] !== 'header_footer') {
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 (VIEWS_PDF_PHP) {
509
          if (!empty($options['render']['bypass_eval_before']) && !empty($options['render']['eval_before'])) {
510
            eval($options['render']['eval_before']);
511
          }
512
          elseif (!empty($options['render']['eval_before']))  {
513
            $content = php_eval($options['render']['eval_before']);
514
          }
515
        }
516

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

    
522
        // Set Text Color.
523
        $this->SetTextColorArray($textColor);
524

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

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

    
533
        if ($stripHTML) {
534
          $content = strip_tags($content);
535
        }
536

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

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

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

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

    
567
        $this->lastWritingElement = $key;
568
      }
569

    
570
  }
571

    
572
  /**
573
   * This method draws a table on the PDF.
574
   */
575
  public function drawTable(&$view, $options) {
576

    
577
    $rows = $view->result;
578
    $columns = $view->field;
579
    $pageDim = $this->getPageDimensions();
580

    
581
    // Set draw point to the indicated position:
582
    if (empty($options['position']['x'])) {
583
      $options['position']['x'] = 0;
584
    }
585

    
586
    if (empty($options['position']['y'])) {
587
      $options['position']['y'] = 0;
588
    }
589

    
590
    if (isset($options['position']['last_writing_position']) && $options['position']['last_writing_position']) {
591
      $y = $options['position']['y'] + $this->y;
592
      $x = $options['position']['x'] + $this->x;
593
    }
594
    else {
595
      $y = $options['position']['y'];
596
      $x = $options['position']['x'];
597
    }
598

    
599
    if (isset($options['position']['width']) && !empty($options['position']['width'])) {
600
      $width = $options['position']['width'];
601
    }
602
    else {
603
      $width = $pageDim['wk'] - $this->rMargin - $x;
604
    }
605

    
606
    $sumWidth = 0;
607
    $numberOfColumnsWithoutWidth = 0;
608

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

    
625
    // Print header:
626
    $rowX = $x;
627
    $page = $this->getPage();
628
    if ($page == 0) {
629
      $this->addPage();
630
      $page = $this->getPage();
631
    }
632

    
633
    if (!isset($options['position']['row_height']) || empty($options['position']['row_height'])) {
634
      $options['position']['row_height'] = 0;
635
    }
636

    
637
    foreach ($columns as $id => $column) {
638

    
639
      if (!empty($column->options['exclude'])) {
640
        continue;
641
      }
642

    
643
      if (!is_array($options['info'][$id])) {
644
        $options['info'][$id] = array();
645
      }
646

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

    
652
      $options['info'][$id]['header_style'] += array(
653
        'position' => array(),
654
        'text' => array(),
655
        'render' => array(),
656
      );
657

    
658
      $options['info'][$id]['header_style']['position'] += array(
659
        'corner' => 'top_left',
660
        'x' => NULL,
661
        'y' => NULL,
662
        'object' => '',
663
        'width' => NULL,
664
        'height' => NULL,
665
      );
666

    
667
      $options['info'][$id]['header_style']['text'] += array(
668
        'font_family' => 'default',
669
        'font_style' => '',
670
      );
671

    
672
      $options['info'][$id]['header_style']['text'] += array(
673
        'eval_before' => '',
674
        'eval_after' => '',
675
      );
676

    
677
      $options['info'][$id]['body_style'] += array(
678
        'position' => array(),
679
        'text' => array(),
680
        'render' => array(),
681
      );
682

    
683
      $options['info'][$id]['body_style']['position'] += array(
684
        'corner' => 'top_left',
685
        'x' => NULL,
686
        'y' => NULL,
687
        'object' => '',
688
        'width' => NULL,
689
        'height' => NULL,
690
      );
691

    
692
      $options['info'][$id]['body_style']['text'] += array(
693
        'font_family' => 'default',
694
        'font_style' => '',
695
      );
696

    
697
      $options['info'][$id]['body_style']['text'] += array(
698
        'eval_before' => '',
699
        'eval_after' => '',
700
      );
701

    
702
      $headerOptions = $options['info'][$id]['header_style'];
703

    
704
      if (isset($options['info'][$id]['position']['width']) && !empty($options['info'][$id]['position']['width'])) {
705
        $headerOptions['position']['width'] = $options['info'][$id]['position']['width'];
706
      }
707
      else {
708
        $headerOptions['position']['width'] = $defaultColumnWidth;
709
      }
710
      $headerOptions['position']['object'] = 'last_position_without_reset';
711

    
712
      $this->SetY($y);
713
      $this->SetX($x);
714
      $this->setPage($page);
715

    
716
      $this->renderRow($x, $y, $column->options['label'], $headerOptions, $view, $id, FALSE);
717
      $x += $headerOptions['position']['width'];
718
    }
719

    
720
    $rowY = $this->y;
721

    
722
    if (!isset($options['position']['row_height']) || empty($options['position']['row_height'])) {
723
      $options['position']['row_height'] = 0;
724
    }
725

    
726
    foreach ($rows as $row) {
727
      $x = $rowX;
728

    
729
       // Get the page dimensions
730
      $pageDim = $this->getPageDimensions();
731

    
732
      if (($rowY + $this->bMargin + $options['position']['row_height']) > $pageDim['hk']) {
733
        $rowY = $this->tMargin;
734
        $this->addPage();
735
      }
736

    
737
      if ($this->lastWritingPage != $this->getPage()) {
738
        $rowY = $this->y; // $rowY - $pageDim['hk']
739
      }
740

    
741
      $y = $rowY;
742
      $page = $this->getPage();
743
      foreach ($columns as $id => $column) {
744

    
745
        if (!empty($column->options['exclude']) && is_object($view->field[$id])) {
746
          // Render the element, but dont print the output. This
747
          // is required to allow the use of tokens in other fields.
748
          $view->field[$id]->theme($row);
749
          continue;
750
        }
751

    
752
        $bodyOptions = $options['info'][$id]['body_style'];
753

    
754
        if (isset($options['info'][$id]['position']['width']) && !empty($options['info'][$id]['position']['width'])) {
755
          $bodyOptions['position']['width'] = $options['info'][$id]['position']['width'];
756
        }
757
        else {
758
          $bodyOptions['position']['width'] = $defaultColumnWidth;
759
        }
760
        $bodyOptions['position']['object'] = 'last_position';
761

    
762
        $this->setPage($page);
763
        $this->SetY($y);
764
        $this->SetX($x);
765

    
766
        $bodyOptions['position']['height'] = 0;
767

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

    
770
        $x += $bodyOptions['position']['width'];
771

    
772
        // If the cell is writting over the row, we need to adjust the
773
        // row y position.
774
        if (($rowY + $options['position']['row_height']) < $this->y) {
775
          $rowY = $this->y - $options['position']['row_height'];
776
        }
777

    
778
      }
779

    
780
      $rowY += $options['position']['row_height'];
781

    
782
      $view->row_index++;
783
    }
784

    
785
    $this->SetY($rowY + $options['position']['row_height']);
786
  }
787

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

    
801
    $numberOfPages = $this->setSourceFile($path);
802
    for ($i = 1; $i <= $numberOfPages; $i++) {
803

    
804
      $dim = $this->getTemplateSize($i);
805
      $format[0] = $dim['w'];
806
      $format[1] = $dim['h'];
807

    
808
      if ($dim['w'] > $dim['h']) {
809
        $orientation = 'L';
810
      }
811
      else {
812
        $orientation = 'P';
813
      }
814
      $this->setPageFormat($format, $orientation);
815
      parent::addPage();
816

    
817
      // Ensure that all new content is printed to a new page
818
      $this->y = 0;
819

    
820
      $page = $this->importPage($i);
821
      $this->useTemplate($page, 0, 0);
822
      $this->addNewPageBeforeNextContent = TRUE;
823
    }
824

    
825
    return $numberOfPages;
826

    
827
  }
828

    
829
  /**
830
   * This method resets the page number. This is useful if you want to start
831
   * the numbering by zero.
832
   */
833
  public function resetRowPageNumber() {
834
    $this->rowContentPageNumber = 0;
835
  }
836

    
837
  /**
838
   * This method adds a new page to the PDF.
839
   */
840
  public function addPage($orientation = '', $format = '', $keepmargins = false, $tocpage = false, $path = NULL, $reset = FALSE, $numbering = 'main') {
841

    
842
    // Do not add any new page, if we are writing
843
    // in the footer or header.
844
    if ($this->InFooter) {
845
      return;
846
    }
847

    
848
    $this->mainContentPageNumber++;
849
    $this->rowContentPageNumber++;
850

    
851
    // Prevent a reset without any template
852
    if ($reset == TRUE && (empty($path) || !file_exists($path))) {
853
      parent::addPage();
854
      $this->setPageFormat($this->defaultFormat, $this->defaultOrientation);
855
      return;
856
    }
857

    
858
    $files = $this->defaultPageTemplateFiles;
859

    
860
    // Reset with new template
861
    if ($reset) {
862
      $files = array();
863
    }
864

    
865
    if ($path != NULL) {
866
      $files[] = array('path' => $path, 'numbering' => $numbering);
867
    }
868
    $format = FALSE;
869
    foreach ($files as $file) {
870
      if (!empty($file['path']) && file_exists($file['path'])) {
871
        $path = realpath($file['path']);
872

    
873
        $numberOfPages = $this->setSourceFile($path);
874
        if ($file['numbering'] == 'row')  {
875
          $index = min($this->rowContentPageNumber, $numberOfPages);
876
        }
877
        else {
878
          $index = min($this->mainContentPageNumber, $numberOfPages);
879
        }
880

    
881

    
882
        $page = $this->importPage($index);
883

    
884
        // ajust the page format (only for the first template)
885
        if ($format == FALSE) {
886

    
887
          $dim = $this->getTemplateSize($index);
888
          $format[0] = $dim['w'];
889
          $format[1] = $dim['h'];
890
          //$this->setPageFormat($format);
891
          if ($dim['w'] > $dim['h']) {
892
            $orientation = 'L';
893
          }
894
          else {
895
            $orientation = 'P';
896
          }
897
          $this->setPageFormat($format, $orientation);
898
          parent::addPage();
899
        }
900

    
901
        // Apply the template
902
        $this->useTemplate($page, 0, 0);
903
      }
904
    }
905

    
906
    // if all paths were empty, ensure that at least the page is added
907
    if ($format == FALSE) {
908
      parent::addPage();
909
      $this->setPageFormat($this->defaultFormat, $this->defaultOrientation);
910
    }
911

    
912
  }
913

    
914
  /**
915
   * Sets the current header and footer of the page.
916
   */
917
  public function setHeaderFooter($record, $options, $view) {
918
    //if ($this->getPage() > 0 && !isset($this->headerFooterData[$this->getPage()])) {
919
      $this->headerFooterData[$this->getPage()] = $record;
920
    //}
921
    $this->headerFooterOptions = $options;
922
    $this->view =& $view;
923
  }
924

    
925
  /**
926
   * Close the document. This is called automatically by
927
   * TCPDF::Output().
928
   */
929
  public function Close() {
930
    // Print the Header & Footer
931
    for ($page = 1; $page <= $this->getNumPages(); $page++) {
932
      $this->setPage($page);
933

    
934
      if (isset($this->headerFooterData[$page])) {
935
        $record = $this->headerFooterData[$page];
936
        if (is_array($this->headerFooterOptions['formats'])) {
937
          foreach ($this->headerFooterOptions['formats'] as $id => $options) {
938
            if ($options['position']['object'] == 'header_footer') {
939
              $fieldOptions = $options;
940
              $fieldOptions['position']['object'] = 'page';
941
              $this->InFooter = TRUE;
942

    
943
              // backup margins
944
              $ml = $this->lMargin;
945
              $mr = $this->rMargin;
946
              $mt = $this->tMargin;
947
              $this->SetMargins(0, 0, 0);
948

    
949
              $this->drawContent($record, $fieldOptions, $this->view, $id);
950
              $this->InFooter = FALSE;
951

    
952
              // restore margins
953
              $this->SetMargins($ml, $mt, $mr);
954
            }
955
          }
956
        }
957
      }
958
    }
959

    
960
    // call parent:
961
    parent::Close();
962

    
963
  }
964

    
965
  /**
966
   * This method returns a list of current uploaded files.
967
   */
968
  public static function getAvailableTemplates() {
969
    if (self::$templateList != NULL) {
970
      return self::$templateList;
971
    }
972

    
973
    $files_path = drupal_realpath('public://');
974
    $template_dir = variable_get('views_pdf_template_path', 'views_pdf_templates');
975
    $dir = $files_path . '/' . $template_dir;
976
    $templatesFiles = file_scan_directory($dir, '/.pdf$/', array('nomask' => '/(\.\.?|CVS)$/'), 1);
977

    
978
    $templates = array();
979

    
980
    foreach ($templatesFiles as $file) {
981
      $templates[$file->filename] = $file->name;
982
    }
983

    
984
    self::$templateList = $templates;
985

    
986
    return $templates;
987

    
988
  }
989

    
990
  /**
991
   * This method returns the path to a specific template.
992
   */
993
  public static function getTemplatePath($template, $row = NULL, $view = NULL) {
994
    if (empty($template)) {
995
      return '';
996
    }
997

    
998
    if ($row != NULL && $view != NULL && !preg_match('/\.pdf/', $template)) {
999
      return drupal_realpath($row->field_data_field_file_node_values[0]['uri']);
1000
    }
1001

    
1002
    $template_dir = variable_get('views_pdf_template_stream', 'public://views_pdf_templates');
1003
    return drupal_realpath($template_dir . '/' . $template);
1004
  }
1005

    
1006
  /**
1007
   * This method returns a list of available fonts.
1008
   */
1009
  public static function getAvailableFonts() {
1010
    if (self::$fontList != NULL) {
1011
      return self::$fontList;
1012
    }
1013

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

    
1018
    $cached_font_mapping = NULL;
1019

    
1020
    if (is_object($cache)) {
1021
      $cached_font_mapping = $cache->data;
1022
    }
1023

    
1024
    if (is_array($cached_font_mapping)) {
1025
      $font_mapping = array_merge(self::$defaultFontList, $cached_font_mapping);
1026
    }
1027
    else {
1028
      $font_mapping = self::$defaultFontList;
1029
    }
1030

    
1031
    foreach ($fonts as $font) {
1032
        $name = self::getFontNameByFileName($font->uri);
1033
        if (isset($name)) {
1034
          $font_mapping[$font->name] = $name;
1035
        }
1036
    }
1037

    
1038
    asort($font_mapping);
1039

    
1040
    cache_set('views_pdf_cached_fonts', $font_mapping);
1041

    
1042
    // Remove all fonts without name
1043
    foreach ($font_mapping as $key => $font) {
1044
      if (empty($font)) {
1045
        unset($font_mapping[$key]);
1046
      }
1047

    
1048
    }
1049

    
1050
    self::$fontList = $font_mapping;
1051

    
1052
    return $font_mapping;
1053
  }
1054

    
1055
  /**
1056
   * This method returns a cleaned up version of the font list.
1057
   */
1058
  public static function getAvailableFontsCleanList() {
1059
    if (self::$fontListClean != NULL) {
1060
      return self::$fontListClean;
1061
    }
1062

    
1063
    $clean = self::getAvailableFonts();
1064

    
1065
    foreach ($clean as $key => $font) {
1066

    
1067
      // Unset bold, italic, italic/bold fonts
1068
      unset($clean[ ($key . 'b') ]);
1069
      unset($clean[ ($key . 'bi') ]);
1070
      unset($clean[ ($key . 'i') ]);
1071

    
1072
    }
1073

    
1074
    self::$fontListClean = $clean;
1075

    
1076
    return $clean;
1077
  }
1078

    
1079
  /**
1080
   * This method returns a list of hyphenation patterns, that are
1081
   * available.
1082
   */
1083
  public static function getAvailableHyphenatePatterns() {
1084
    if (self::$hyphenatePatterns != NULL) {
1085
      return self::$hyphenatePatterns;
1086
    }
1087

    
1088
    self::$hyphenatePatterns = array();
1089

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

    
1092
    foreach ($files as $file) {
1093
      self::$hyphenatePatterns[basename($file->uri)] = str_replace('hyph-', '', $file->name);
1094
    }
1095

    
1096

    
1097
    return self::$hyphenatePatterns;
1098
  }
1099

    
1100
  /**
1101
   * This method returns the name of a given font.
1102
   */
1103
  protected static function getFontNameByFileName($path) {
1104
    include $path;
1105
    if (isset($name)) {
1106
      return $name;
1107
    }
1108
    else {
1109
      return NULL;
1110
    }
1111
  }
1112
}