source: trunk/filemanager/tp/dompdf/include/cpdf_adapter.cls.php @ 7673

Revision 7673, 29.0 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

Line 
1<?php
2/**
3 * DOMPDF - PHP5 HTML to PDF renderer
4 *
5 * File: $RCSfile: cpdf_adapter.cls.php,v $
6 * Created on: 2004-08-04
7 * Modified on: 2008-01-05
8 *
9 * Copyright (c) 2004 - Benj Carson <benjcarson@digitaljunkies.ca>
10 * Portions copyright (c) 2008 - Orion Richardson <orionr@yahoo.com>
11 *
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
16 *
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 * Lesser General Public License for more details.
21 *
22 * You should have received a copy of the GNU Lesser General Public License
23 * along with this library in the file LICENSE.LGPL; if not, write to the
24 * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
25 * 02111-1307 USA
26 *
27 * Alternatively, you may distribute this software under the terms of the
28 * PHP License, version 3.0 or later.  A copy of this license should have
29 * been distributed with this file in the file LICENSE.PHP .  If this is not
30 * the case, you can obtain a copy at http://www.php.net/license/3_0.txt.
31 *
32 * The latest version of DOMPDF might be available at:
33 * http://www.digitaljunkies.ca/dompdf
34 *
35 * @link http://www.digitaljunkies.ca/dompdf
36 * @copyright 2004 Benj Carson
37 * @author Benj Carson <benjcarson@digitaljunkies.ca>
38 * @contributor Orion Richardson <orionr@yahoo.com>
39 * @contributor Helmut Tischer <htischer@weihenstephan.org>
40 * @package dompdf
41 * @version 0.5.1
42 *
43 * Changes
44 * @contributor Helmut Tischer <htischer@weihenstephan.org>
45 * @version 0.5.1.htischer.20090507
46 * - On gif to png conversion tmp file creation, clarify tmp name and add to tmp deletion list only on success
47 * - On gif to png conversion, when available add direct from gd without tmp file, skip image load if already cached.
48 *   to safe CPU time and memory
49 * @contributor Helmut Tischer <htischer@weihenstephan.org>
50 * @version dompdf_trunk_with_helmut_mods.20090524
51 * - Pass temp and fontcache folders to Cpdf, to making Cpdf independent from dompdf
52 * @version dompdf_trunk_with_helmut_mods.20090528
53 * - fix text position according to glyph baseline to match background rectangle
54 */
55
56/* $Id: cpdf_adapter.cls.php 186 2009-10-19 22:42:06Z eclecticgeek@gmail.com $ */
57
58// FIXME: Need to sanity check inputs to this class
59require_once(DOMPDF_LIB_DIR . "/class.pdf.php");
60
61/**
62 * PDF rendering interface
63 *
64 * CPDF_Adapter provides a simple stateless interface to the stateful one
65 * provided by the Cpdf class.
66 *
67 * Unless otherwise mentioned, all dimensions are in points (1/72 in).  The
68 * coordinate origin is in the top left corner, and y values increase
69 * downwards.
70 *
71 * See {@link http://www.ros.co.nz/pdf/} for more complete documentation
72 * on the underlying {@link Cpdf} class.
73 *
74 * @package dompdf
75 */
76class CPDF_Adapter implements Canvas {
77
78  /**
79   * Dimensions of paper sizes in points
80   *
81   * @var array;
82   */
83  static $PAPER_SIZES = array("4a0" => array(0,0,4767.87,6740.79),
84                              "2a0" => array(0,0,3370.39,4767.87),
85                              "a0" => array(0,0,2383.94,3370.39),
86                              "a1" => array(0,0,1683.78,2383.94),
87                              "a2" => array(0,0,1190.55,1683.78),
88                              "a3" => array(0,0,841.89,1190.55),
89                              "a4" => array(0,0,595.28,841.89),
90                              "a5" => array(0,0,419.53,595.28),
91                              "a6" => array(0,0,297.64,419.53),
92                              "a7" => array(0,0,209.76,297.64),
93                              "a8" => array(0,0,147.40,209.76),
94                              "a9" => array(0,0,104.88,147.40),
95                              "a10" => array(0,0,73.70,104.88),
96                              "b0" => array(0,0,2834.65,4008.19),
97                              "b1" => array(0,0,2004.09,2834.65),
98                              "b2" => array(0,0,1417.32,2004.09),
99                              "b3" => array(0,0,1000.63,1417.32),
100                              "b4" => array(0,0,708.66,1000.63),
101                              "b5" => array(0,0,498.90,708.66),
102                              "b6" => array(0,0,354.33,498.90),
103                              "b7" => array(0,0,249.45,354.33),
104                              "b8" => array(0,0,175.75,249.45),
105                              "b9" => array(0,0,124.72,175.75),
106                              "b10" => array(0,0,87.87,124.72),
107                              "c0" => array(0,0,2599.37,3676.54),
108                              "c1" => array(0,0,1836.85,2599.37),
109                              "c2" => array(0,0,1298.27,1836.85),
110                              "c3" => array(0,0,918.43,1298.27),
111                              "c4" => array(0,0,649.13,918.43),
112                              "c5" => array(0,0,459.21,649.13),
113                              "c6" => array(0,0,323.15,459.21),
114                              "c7" => array(0,0,229.61,323.15),
115                              "c8" => array(0,0,161.57,229.61),
116                              "c9" => array(0,0,113.39,161.57),
117                              "c10" => array(0,0,79.37,113.39),
118                              "ra0" => array(0,0,2437.80,3458.27),
119                              "ra1" => array(0,0,1729.13,2437.80),
120                              "ra2" => array(0,0,1218.90,1729.13),
121                              "ra3" => array(0,0,864.57,1218.90),
122                              "ra4" => array(0,0,609.45,864.57),
123                              "sra0" => array(0,0,2551.18,3628.35),
124                              "sra1" => array(0,0,1814.17,2551.18),
125                              "sra2" => array(0,0,1275.59,1814.17),
126                              "sra3" => array(0,0,907.09,1275.59),
127                              "sra4" => array(0,0,637.80,907.09),
128                              "letter" => array(0,0,612.00,792.00),
129                              "legal" => array(0,0,612.00,1008.00),
130                              "ledger" => array(0,0,1224.00, 792.00),
131                              "tabloid" => array(0,0,792.00, 1224.00),
132                              "executive" => array(0,0,521.86,756.00),
133                              "folio" => array(0,0,612.00,936.00),
134                              "commerical #10 envelope" => array(0,0,684,297),
135                              "catalog #10 1/2 envelope" => array(0,0,648,864),
136                              "8.5x11" => array(0,0,612.00,792.00),
137                              "8.5x14" => array(0,0,612.00,1008.0),
138                              "11x17"  => array(0,0,792.00, 1224.00));
139
140
141  /**
142   * Instance of Cpdf class
143   *
144   * @var Cpdf
145   */
146  private $_pdf;
147
148  /**
149   * PDF width, in points
150   *
151   * @var float
152   */
153  private $_width;
154
155  /**
156   * PDF height, in points
157   *
158   * @var float;
159   */
160  private $_height;
161
162  /**
163   * Current page number
164   *
165   * @var int
166   */
167  private $_page_number;
168
169  /**
170   * Total number of pages
171   *
172   * @var int
173   */
174  private $_page_count;
175
176  /**
177   * Text to display on every page
178   *
179   * @var array
180   */
181  private $_page_text;
182
183  /**
184   * Array of pages for accesing after rendering is initially complete
185   *
186   * @var array
187   */
188  private $_pages;
189
190  /**
191   * Array of temporary cached images to be deleted when processing is complete
192   *
193   * @var array
194   */
195  private $_image_cache;
196 
197  /**
198   * Class constructor
199   *
200   * @param mixed  $paper  The size of paper to use in this PDF ({@link CPDF_Adapter::$PAPER_SIZES})
201   * @param string $orientation The orienation of the document (either 'landscape' or 'portrait')
202   */
203  function __construct($paper = "letter", $orientation = "portrait") {
204
205    if ( is_array($paper) )
206      $size = $paper;
207    else if ( isset(self::$PAPER_SIZES[mb_strtolower($paper)]) )
208      $size = self::$PAPER_SIZES[mb_strtolower($paper)];
209    else
210      $size = self::$PAPER_SIZES["letter"];
211
212    if ( mb_strtolower($orientation) == "landscape" ) {
213      $a = $size[3];
214      $size[3] = $size[2];
215      $size[2] = $a;
216    }
217   
218    $this->_pdf = new Cpdf($size, DOMPDF_UNICODE_ENABLED, DOMPDF_FONT_CACHE, DOMPDF_TEMP_DIR);
219    $this->_pdf->addInfo("Creator", "dompdf");
220
221    // Silence pedantic warnings about missing TZ settings
222    if ( function_exists("date_default_timezone_get") ) {
223      $tz = @date_default_timezone_get();
224      date_default_timezone_set("UTC");
225      $this->_pdf->addInfo("CreationDate", date("Y-m-d"));
226      date_default_timezone_set($tz);
227
228    } else {
229      $this->_pdf->addInfo("CreationDate", date("Y-m-d"));
230    }
231
232    $this->_width = $size[2] - $size[0];
233    $this->_height= $size[3] - $size[1];
234    $this->_pdf->openHere('Fit');
235   
236    $this->_page_number = $this->_page_count = 1;
237    $this->_page_text = array();
238
239    $this->_pages = array($this->_pdf->getFirstPageId());
240
241    $this->_image_cache = array();
242  }
243
244  /**
245   * Class destructor
246   *
247   * Deletes all temporary image files
248   */
249  function __destruct() {
250    foreach ($this->_image_cache as $img) {
251      //debugpng
252      if (DEBUGPNG) print '[__destruct unlink '.$img.']';
253      if (!DEBUGKEEPTEMP)
254        unlink($img);
255    }
256  }
257 
258  /**
259   * Returns the Cpdf instance
260   *
261   * @return Cpdf
262   */
263  function get_cpdf() { return $this->_pdf; }
264
265  /**
266   * Add meta information to the PDF
267   *
268   * @param string $label  label of the value (Creator, Producter, etc.)
269   * @param string $value  the text to set
270   */
271  function add_info($label, $value) {
272    $this->_pdf->addInfo($label, $value);
273  }
274
275  /**
276   * Opens a new 'object'
277   *
278   * While an object is open, all drawing actions are recored in the object,
279   * as opposed to being drawn on the current page.  Objects can be added
280   * later to a specific page or to several pages.
281   *
282   * The return value is an integer ID for the new object.
283   *
284   * @see CPDF_Adapter::close_object()
285   * @see CPDF_Adapter::add_object()
286   *
287   * @return int
288   */
289  function open_object() {
290    $ret = $this->_pdf->openObject();
291    $this->_pdf->saveState();
292    return $ret;
293  }
294
295  /**
296   * Reopens an existing 'object'
297   *
298   * @see CPDF_Adapter::open_object()
299   * @param int $object  the ID of a previously opened object
300   */
301  function reopen_object($object) {
302    $this->_pdf->reopenObject($object);
303    $this->_pdf->saveState();
304  }
305
306  /**
307   * Closes the current 'object'
308   *
309   * @see CPDF_Adapter::open_object()
310   */
311  function close_object() {
312    $this->_pdf->restoreState();
313    $this->_pdf->closeObject();
314  }
315
316  /**
317   * Adds a specified 'object' to the document
318   *
319   * $object int specifying an object created with {@link
320   * CPDF_Adapter::open_object()}.  $where can be one of:
321   * - 'add' add to current page only
322   * - 'all' add to every page from the current one onwards
323   * - 'odd' add to all odd numbered pages from now on
324   * - 'even' add to all even numbered pages from now on
325   * - 'next' add the object to the next page only
326   * - 'nextodd' add to all odd numbered pages from the next one
327   * - 'nexteven' add to all even numbered pages from the next one
328   *
329   * @see Cpdf::addObject()
330   *
331   * @param int $object
332   * @param string $where
333   */
334  function add_object($object, $where = 'all') {
335    $this->_pdf->addObject($object, $where);
336  }
337
338  /**
339   * Stops the specified 'object' from appearing in the document.
340   *
341   * The object will stop being displayed on the page following the current
342   * one.
343   *
344   * @param int $object
345   */
346  function stop_object($object) {
347    $this->_pdf->stopObject($object);
348  }
349
350  /**
351   * @access private
352   */
353  function serialize_object($id) {
354    // Serialize the pdf object's current state for retrieval later
355    return $this->_pdf->serializeObject($id);
356  }
357
358  /**
359   * @access private
360   */
361  function reopen_serialized_object($obj) {
362    return $this->_pdf->restoreSerializedObject($obj);
363  }
364   
365  //........................................................................
366
367  /**
368   * Returns the PDF's width in points
369   * @return float
370   */
371  function get_width() { return $this->_width; }
372
373  /**
374   * Returns the PDF's height in points
375   * @return float
376   */
377  function get_height() { return $this->_height; }
378
379  /**
380   * Returns the current page number
381   * @return int
382   */
383  function get_page_number() { return $this->_page_number; }
384
385  /**
386   * Returns the total number of pages in the document
387   * @return int
388   */
389  function get_page_count() { return $this->_page_count; }
390
391  /**
392   * Sets the current page number
393   *
394   * @param int $num
395   */
396  function set_page_number($num) { $this->_page_number = $num; }
397
398  /**
399   * Sets the page count
400   *
401   * @param int $count
402   */
403  function set_page_count($count) {  $this->_page_count = $count; }
404   
405  /**
406   * Sets the stroke colour
407   *
408   * See {@link Style::set_colour()} for the format of the color array.
409   * @param array $color
410   */
411  protected function _set_stroke_color($color) {
412    list($r, $g, $b) = $color;
413    $this->_pdf->setStrokeColor($r, $g, $b);
414  }
415 
416  /**
417   * Sets the fill colour
418   *
419   * See {@link Style::set_colour()} for the format of the colour array.
420   * @param array $color
421   */
422  protected function _set_fill_color($color) {
423    list($r, $g, $b) = $color;
424    $this->_pdf->setColor($r, $g, $b);
425  }
426
427  /**
428   * Sets line transparency
429   * @see Cpdf::setLineTransparency()
430   *
431   * Valid blend modes are (case-sensitive):
432   *
433   * Normal, Multiply, Screen, Overlay, Darken, Lighten,
434   * ColorDodge, ColorBurn, HardLight, SoftLight, Difference,
435   * Exclusion
436   *
437   * @param string $mode the blending mode to use
438   * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
439   */
440  protected function _set_line_transparency($mode, $opacity) {
441    $this->_pdf->setLineTransparency($mode, $opacity);
442  }
443 
444  /**
445   * Sets fill transparency
446   * @see Cpdf::setFillTransparency()
447   *
448   * Valid blend modes are (case-sensitive):
449   *
450   * Normal, Multiply, Screen, Overlay, Darken, Lighten,
451   * ColorDogde, ColorBurn, HardLight, SoftLight, Difference,
452   * Exclusion
453   *
454   * @param string $mode the blending mode to use
455   * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
456   */
457  protected function _set_fill_transparency($mode, $opacity) {
458    $this->_pdf->setFillTransparency($mode, $opacity);
459  }
460
461  /**
462   * Sets the line style
463   *
464   * @see Cpdf::setLineStyle()
465   *
466   * @param float width
467   * @param string cap
468   * @param string join
469   * @param array dash
470   */
471  protected function _set_line_style($width, $cap, $join, $dash) {
472    $this->_pdf->setLineStyle($width, $cap, $join, $dash);
473  }
474 
475  //........................................................................
476
477 
478  /**
479   * Remaps y coords from 4th to 1st quadrant
480   *
481   * @param float $y
482   * @return float
483   */
484  protected function y($y) { return $this->_height - $y; }
485
486  // Canvas implementation
487
488  function line($x1, $y1, $x2, $y2, $color, $width, $style = array(),
489                $blend = "Normal", $opacity = 1.0) {
490    //pre_r(compact("x1", "y1", "x2", "y2", "color", "width", "style"));
491
492    $this->_set_stroke_color($color);
493    $this->_set_line_style($width, "butt", "", $style);
494    $this->_set_line_transparency($blend, $opacity);
495   
496    $this->_pdf->line($x1, $this->y($y1),
497                      $x2, $this->y($y2));
498  }
499                             
500  //........................................................................
501
502  /**
503   * Convert a GIF image to a PNG image
504   *
505   * @return string The url of the newly converted image
506   */
507  protected function _convert_gif_to_png($image_url) {
508   
509    if ( !function_exists("imagecreatefromgif") ) {
510      throw new DOMPDF_Exception("Function imagecreatefromgif() not found.  Cannot convert gif image: $image_url.  Please install the image PHP extension.");
511    }
512
513    $old_err = set_error_handler("record_warnings");
514    $im = imagecreatefromgif($image_url);
515
516    if ( $im ) {
517      imageinterlace($im, 0);
518
519      $filename = tempnam(DOMPDF_TEMP_DIR, "gifdompdf_img_").'.png';
520      $this->_image_cache[] = $filename;
521
522      imagepng($im, $filename);
523
524    } else {
525      $filename = DOMPDF_LIB_DIR . "/res/broken_image.png";
526
527    }
528
529    restore_error_handler();
530
531    return $filename;
532   
533  }
534
535  function rectangle($x1, $y1, $w, $h, $color, $width, $style = array(),
536                     $blend = "Normal", $opacity = 1.0) {
537
538    $this->_set_stroke_color($color);
539    $this->_set_line_style($width, "square", "miter", $style);
540    $this->_set_line_transparency($blend, $opacity);
541   
542    $this->_pdf->rectangle($x1, $this->y($y1) - $h, $w, $h);
543  }
544
545  //........................................................................
546 
547  function filled_rectangle($x1, $y1, $w, $h, $color, $blend = "Normal", $opacity = 1.0) {
548
549    $this->_set_fill_color($color);
550    $this->_set_line_style(1, "square", "miter", array());
551    $this->_set_line_transparency($blend, $opacity);
552    $this->_set_fill_transparency($blend, $opacity);
553   
554    $this->_pdf->filledRectangle($x1, $this->y($y1) - $h, $w, $h);
555  }
556
557  //........................................................................
558
559  function polygon($points, $color, $width = null, $style = array(),
560                   $fill = false, $blend = "Normal", $opacity = 1.0) {
561
562    $this->_set_fill_color($color);
563    $this->_set_stroke_color($color);
564
565    $this->_set_line_transparency($blend, $opacity);
566    $this->_set_fill_transparency($blend, $opacity);
567   
568    if ( !$fill && isset($width) )
569      $this->_set_line_style($width, "square", "miter", $style);
570   
571    // Adjust y values
572    $points_count = count($points);
573    for ( $i = 1; $i < $points_count; $i += 2)
574      $points[$i] = $this->y($points[$i]);
575   
576    $this->_pdf->polygon($points, count($points) / 2, $fill);
577  }
578
579  //........................................................................
580
581  function circle($x, $y, $r1, $color, $width = null, $style = null,
582                  $fill = false, $blend = "Normal", $opacity = 1.0) {
583
584    $this->_set_fill_color($color);
585    $this->_set_stroke_color($color);
586   
587    $this->_set_line_transparency($blend, $opacity);
588    $this->_set_fill_transparency($blend, $opacity);
589
590    if ( !$fill && isset($width) )
591      $this->_set_line_style($width, "round", "round", $style);
592
593    $this->_pdf->ellipse($x, $this->y($y), $r1, 0, 0, 8, 0, 360, 1, $fill);
594  }
595 
596  //........................................................................
597
598  function image($img_url, $img_type, $x, $y, $w, $h) {
599    //debugpng
600    if (DEBUGPNG) print '[image:'.$img_url.'|'.$img_type.']';
601
602    $img_type = mb_strtolower($img_type);
603
604    switch ($img_type) {
605    case "jpeg":
606    case "jpg":
607      //debugpng
608      if (DEBUGPNG)  print '!!!jpg!!!';
609
610      $this->_pdf->addJpegFromFile($img_url, $x, $this->y($y) - $h, $w, $h);
611      break;
612
613    case "png":
614      //debugpng
615      if (DEBUGPNG)  print '!!!png!!!';
616
617      $this->_pdf->addPngFromFile($img_url, $x, $this->y($y) - $h, $w, $h);
618      break;
619
620    case "gif":
621      // Convert gifs to pngs
622      //DEBUG_IMG_TEMP
623      //if (0) {
624      if ( method_exists( $this->_pdf, "addImagePng" ) ) {
625        //debugpng
626        if (DEBUGPNG)  print '!!!gif addImagePng!!!';
627
628        //If optimization to direct png creation from gd object is available,
629        //don't create temp file, but place gd object directly into the pdf
630            if ( method_exists( $this->_pdf, "image_iscached" ) &&
631                 $this->_pdf->image_iscached($img_url) ) {
632              //If same image has occured already before, no need to load because
633              //duplicate will anyway be eliminated.
634              $img = null;
635            } else {
636          $img = @imagecreatefromgif($img_url);
637          if (!$img) {
638            return;
639          }
640          imageinterlace($img, 0);
641        }
642        $this->_pdf->addImagePng($img_url, $x, $this->y($y) - $h, $w, $h, $img);
643      } else {
644        //debugpng
645        if (DEBUGPNG)  print '!!!gif addPngFromFile!!!';
646        $img_url = $this->_convert_gif_to_png($img_url);
647        $this->_pdf->addPngFromFile($img_url, $x, $this->y($y) - $h, $w, $h);
648      }
649      break;
650
651    default:
652      //debugpng
653      if (DEBUGPNG) print '!!!unknown!!!';
654      break;
655    }
656   
657    return;
658  }
659
660  //........................................................................
661
662  function text($x, $y, $text, $font, $size, $color = array(0,0,0),
663                $adjust = 0, $angle = 0, $blend = "Normal", $opacity = 1.0) {
664
665    list($r, $g, $b) = $color;
666    $this->_pdf->setColor($r, $g, $b);
667
668    $this->_set_line_transparency($blend, $opacity);
669    $this->_set_fill_transparency($blend, $opacity);
670    $font .= ".afm";
671   
672    $this->_pdf->selectFont($font);
673   
674    //Font_Metrics::get_font_height($font, $size) ==
675    //$this->get_font_height($font, $size) ==
676    //$this->_pdf->selectFont($font),$this->_pdf->getFontHeight($size)
677    //- FontBBoxheight+FontHeightOffset, scaled to $size, in pt
678    //$this->_pdf->getFontDescender($size)
679    //- Descender scaled to size
680    //
681    //$this->_pdf->fonts[$this->_pdf->currentFont] sizes:
682    //['FontBBox'][0] left, ['FontBBox'][1] bottom, ['FontBBox'][2] right, ['FontBBox'][3] top
683    //Maximum extent of all glyphs of the font from the baseline point
684    //['Ascender'] maximum height above baseline except accents
685    //['Descender'] maximum depth below baseline, negative number means below baseline
686    //['FontHeightOffset'] manual enhancement of .afm files to trim windows fonts. currently not used.
687    //Values are in 1/1000 pt for a font size of 1 pt
688    //
689    //['FontBBox'][1] should be close to ['Descender']
690    //['FontBBox'][3] should be close to ['Ascender']+Accents
691    //in practice, FontBBox values are a little bigger
692    //
693    //The text position is referenced to the baseline, not to the lower corner of the FontBBox,
694    //for what the left,top corner is given.
695    //FontBBox spans also the background box for the text.
696    //If the lower corner would be used as reference point, the Descents of the glyphs would
697    //hang over the background box border.
698    //Therefore compensate only the extent above the Baseline.
699    //
700    //print '<pre>['.$font.','.$size.','.$this->_pdf->getFontHeight($size).','.$this->_pdf->getFontDescender($size).','.$this->_pdf->fonts[$this->_pdf->currentFont]['FontBBox'][3].','.$this->_pdf->fonts[$this->_pdf->currentFont]['FontBBox'][1].','.$this->_pdf->fonts[$this->_pdf->currentFont]['FontHeightOffset'].','.$this->_pdf->fonts[$this->_pdf->currentFont]['Ascender'].','.$this->_pdf->fonts[$this->_pdf->currentFont]['Descender'].']</pre>';
701    //
702    //$this->_pdf->addText($x, $this->y($y) - Font_Metrics::get_font_height($font, $size), $size, $text, $angle, $adjust);
703        //$this->_pdf->addText($x, $this->y($y) - $size, $size, $text, $angle, $adjust);
704        //$this->_pdf->addText($x, $this->y($y) - $this->_pdf->getFontHeight($size)-$this->_pdf->getFontDescender($size), $size, $text, $angle, $adjust);
705        $this->_pdf->addText($x, $this->y($y) - ($this->_pdf->fonts[$this->_pdf->currentFont]['FontBBox'][3]*$size)/1000, $size, $text, $angle, $adjust);
706  }
707
708  //........................................................................
709
710  /**
711   * Add a named destination (similar to <a name="foo">...</a> in html)
712   *
713   * @param string $anchorname The name of the named destination
714   */
715  function add_named_dest($anchorname) {
716    $this->_pdf->addDestination($anchorname,"Fit");
717  }
718
719  //........................................................................
720
721  /**
722   * Add a link to the pdf
723   *
724   * @param string $url The url to link to
725   * @param float  $x   The x position of the link
726   * @param float  $y   The y position of the link
727   * @param float  $width   The width of the link
728   * @param float  $height   The height of the link
729   */
730  function add_link($url, $x, $y, $width, $height) {
731
732    $y = $this->y($y) - $height;
733
734    if ( strpos($url, '#') === 0 ) {
735      // Local link
736      $name = substr($url,1);
737      if ( $name )
738        $this->_pdf->addInternalLink($name, $x, $y, $x + $width, $y + $height);
739
740    } else {
741      $this->_pdf->addLink(rawurldecode($url), $x, $y, $x + $width, $y + $height);
742    }
743   
744  }
745
746  //........................................................................
747
748  function get_text_width($text, $font, $size, $spacing = 0) {
749    $this->_pdf->selectFont($font);
750    $ascii = utf8_decode($text);
751//     // Hack for &nbsp;
752//     $ascii = str_replace("\xA0", " ", $ascii);
753
754    return $this->_pdf->getTextWidth($size, $ascii, $spacing);
755  }
756
757  //........................................................................
758
759  function get_font_height($font, $size) {
760    $this->_pdf->selectFont($font);
761    return $this->_pdf->getFontHeight($size);
762  }
763
764  //........................................................................
765 
766  /**
767   * Writes text at the specified x and y coordinates on every page
768   *
769   * The strings '{PAGE_NUM}' and '{PAGE_COUNT}' are automatically replaced
770   * with their current values.
771   *
772   * See {@link Style::munge_colour()} for the format of the colour array.
773   *
774   * @param float $x
775   * @param float $y
776   * @param string $text the text to write
777   * @param string $font the font file to use
778   * @param float $size the font size, in points
779   * @param array $color
780   * @param float $adjust word spacing adjustment
781   * @param float $angle angle to write the text at, measured CW starting from the x-axis
782   */
783  function page_text($x, $y, $text, $font, $size, $color = array(0,0,0),
784                     $adjust = 0, $angle = 0) {
785    $_t = "text";
786    $this->_page_text[] = compact("_t", "x", "y", "text", "font", "size", "color", "adjust", "angle");
787  }
788
789  //........................................................................
790   
791  /**
792   * Processes a script on every page
793   *
794   * The variables $pdf, $PAGE_NUM, and $PAGE_COUNT are available.
795   *
796   * This function can be used to add page numbers to all pages
797   * after the first one, for example.
798   *
799   * @param string $code the script code
800   * @param string $type the language type for script
801   */
802  function page_script($code, $type = "text/php") {
803    $_t = "script";
804    $this->_page_text[] = compact("_t", "code", "type");
805  }
806 
807  //........................................................................
808
809  function new_page() {
810    $this->_page_count++;
811
812    $ret = $this->_pdf->newPage();
813    $this->_pages[] = $ret;
814    return $ret;
815  }
816 
817  //........................................................................
818
819  /**
820   * Add text to each page after rendering is complete
821   */
822  protected function _add_page_text() {
823   
824    if ( !count($this->_page_text) )
825      return;
826
827    $page_number = 1;
828    $eval = null;
829
830    foreach ($this->_pages as $pid) {
831      $this->reopen_object($pid);
832
833      foreach ($this->_page_text as $pt) {
834        extract($pt);
835
836        switch ($_t) {
837           
838        case "text":
839        $text = str_replace(array("{PAGE_NUM}","{PAGE_COUNT}"),
840                            array($page_number, $this->_page_count), $text);
841        $this->text($x, $y, $text, $font, $size, $color, $adjust, $angle);
842          break;
843         
844        case "script":
845          if (!$eval) {
846            $eval = new PHP_Evaluator($this);
847          }
848          $eval->evaluate($code, array('PAGE_NUM' => $page_number, 'PAGE_COUNT' => $this->_page_count));
849          break;
850        }
851      }
852
853      $this->close_object();
854      ++$page_number;
855    }
856  }
857 
858  /**
859   * Streams the PDF directly to the browser
860   *
861   * @param string $filename the name of the PDF file
862   * @param array  $options associative array, 'Attachment' => 0 or 1, 'compress' => 1 or 0
863   */
864  function stream($filename, $options = null) {
865    // Add page text
866    $this->_add_page_text();
867   
868    $options["Content-Disposition"] = $filename;
869    $this->_pdf->stream($options);
870  }
871
872  //........................................................................
873
874  /**
875   * Returns the PDF as a string
876   *
877   * @return string
878   */
879  function output($options = null) {
880    // Add page text
881    $this->_add_page_text();
882
883    if ( isset($options["compress"]) && $options["compress"] != 1 )
884      $debug = 1;
885    else
886      $debug = 0;
887   
888    return $this->_pdf->output($debug);
889   
890  }
891 
892  //........................................................................
893
894  /**
895   * Returns logging messages generated by the Cpdf class
896   *
897   * @return string
898   */
899  function get_messages() { return $this->_pdf->messages; }
900 
901}
902
903?>
Note: See TracBrowser for help on using the repository browser.