Translation update done using Pootle.
[phpmyadmin/dkf.git] / libraries / tcpdf / tcpdf.php
bloba6b707ac2a3c2fcc0ab51226cf605c263c24a38c
1 <?php
2 //============================================================+
3 // File name : tcpdf.php
4 // Begin : 2002-08-03
5 // Last Update : 2008-02-28
6 // Author : Nicola Asuni
7 // Version : 2.2.002
8 // License : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
9 //
10 // Description : This is a PHP5 class for generating PDF files
11 // on-the-fly without requiring external
12 // extensions.
14 // IMPORTANT:
15 // This class was originally derived in 2002 from the Public
16 // Domain FPDF class by Olivier Plathey (http://www.fpdf.org).
18 // Main features:
19 // - supports all ISO page formats;
20 // - supports UTF-8 Unicode and Right-To-Left languages;
21 // - supports document encryption;
22 // - includes methods to publish some xhtml code;
23 // - includes graphic and transformation methods;
24 // - includes bookmarks;
25 // - includes Javascript and forms support;
26 // - includes a method to print various barcode formats using an improved version of "Generic Barcode Render Class" by Karim Mribti (http://www.mribti.com/barcode/) (require GD library: http://www.boutell.com/gd/)
27 // - supports TrueTypeUnicode, TrueType, Type1 and encoding;
28 // - supports custom page formats, margins and units of measure;
29 // - includes methods for page header and footer management;
30 // - supports automatic page break;
31 // - supports automatic page numbering;
32 // - supports automatic line break and text justification;
33 // - supports JPEG, PNG anf GIF images;
34 // - supports colors;
35 // - supports links;
36 // - support page compression (require zlib extension: http://www.gzip.org/zlib/);
37 // - the source code is full documented in PhpDocumentor Style (http://www.phpdoc.org).
39 // -----------------------------------------------------------
40 // THANKS TO:
41 //
42 // Olivier Plathey (http://www.fpdf.org) for original FPDF.
43 // Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support.
44 // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm.
45 // Warren Sherliker (wsherliker@gmail.com) for better image handling.
46 // dullus for text Justification.
47 // Bob Vincent (pillarsdotnet@users.sourceforge.net) for <li> value attribute.
48 // Patrick Benny for text stretch suggestion on Cell().
49 // Johannes Güntert for JavaScript support.
50 // Denis Van Nuffelen for Dynamic Form.
51 // Jacek Czekaj for multibyte justification
52 // Anthony Ferrara for the reintroduction of legacy image methods.
53 // Anyone that has reported a bug or sent a suggestion.
54 //============================================================+
58 /**
59 * This is a PHP5 class for generating PDF files on-the-fly without requiring external extensions.<br>
60 * TCPDF project (http://tcpdf.sourceforge.net) has been originally derived from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org).<br>
61 * <h3>TCPDF main features are:</h3>
62 * <ul>
63 * <li>supports all ISO page formats;</li>
64 * <li>supports UTF-8 Unicode and Right-To-Left languages;</li>
65 * <li>supports document encryption;</li>
66 * <li>includes methods to publish some xhtml code, supporting the following elements: h1, h2, h3, h4, h5, h6, b, u, i, a, img, p, br, strong, em, font, blockquote, li, ul, ol, hr, td, th, tr, table, sup, sub, small;</li>
67 * <li>includes a method to print various barcode formats using an improved version of "Generic Barcode Render Class" by Karim Mribti (<a href="http://www.mribti.com/barcode/" target="_blank" title="Generic Barcode Render Class by Karim Mribti">http://www.mribti.com/barcode/</a>) (require GD library: <a href="http://www.boutell.com/gd/" target="_blank" title="GD library">http://www.boutell.com/gd/</a>)</li>
68 * <li>supports TrueTypeUnicode, TrueType, Type1 and encoding; </li>
69 * <li>supports custom page formats, margins and units of measure;</li>
70 * <li>includes methods for page header and footer management;</li>
71 * <li>supports automatic page break;</li>
72 * <li>supports automatic page numbering;</li>
73 * <li>supports automatic line break and text justification;</li>
74 * <li>supports JPEG, PNG anf GIF images;</li>
75 * <li>supports colors;</li>
76 * <li>supports links;</li>
77 * <li>support page compression (require zlib extension: <a href="http://www.gzip.org/zlib/" target="_blank" title="zlib">http://www.gzip.org/zlib/</a>);</li>
78 * <li>the source code is full documented in PhpDocumentor Style (<a href="http://www.phpdoc.org" target="_blank" title="phpDocumentor">http://www.phpdoc.org</a>).</li>
79 * </ul>
80 * Tools to encode your unicode fonts are on fonts/ttf2ufm directory.</p>
81 * @name TCPDF
82 * @package com.tecnick.tcpdf
83 * @abstract Class for generating PDF files on-the-fly without requiring external extensions.
84 * @author Nicola Asuni
85 * @copyright 2004-2008 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
86 * @link http://tcpdf.sourceforge.net
87 * @license http://www.gnu.org/copyleft/lesser.html LGPL
88 * @version 2.2.002
91 /**
92 * include configuration file
93 * (Disabled in phpMyAdmin)
95 //require_once(dirname(__FILE__).'/config/tcpdf_config.php');
97 if(!class_exists('TCPDF', false)) {
98 /**
99 * define default PDF document producer
101 define('PDF_PRODUCER','TCPDF 2.2.002 (http://tcpdf.sf.net)');
104 * This is a PHP5 class for generating PDF files on-the-fly without requiring external extensions.<br>
105 * TCPDF project (http://tcpdf.sourceforge.net) has been originally derived from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org).<br>
106 * To add your own TTF fonts please read /fonts/README.TXT
107 * @name TCPDF
108 * @package com.tecnick.tcpdf
109 * @version 2.2.002
110 * @author Nicola Asuni
111 * @link http://tcpdf.sourceforge.net
112 * @license http://www.gnu.org/copyleft/lesser.html LGPL
114 class TCPDF {
116 // Private or Protected properties
119 * @var current page number
120 * @access protected
122 protected $page;
125 * @var current object number
126 * @access protected
128 protected $n;
131 * @var array of object offsets
132 * @access protected
134 protected $offsets;
137 * @var buffer holding in-memory PDF
138 * @access protected
140 protected $buffer;
143 * @var array containing pages
144 * @access protected
146 protected $pages;
149 * @var current document state
150 * @access protected
152 protected $state;
155 * @var compression flag
156 * @access protected
158 protected $compress;
161 * @var default page orientation (P = Portrait, L = Landscape)
162 * @access protected
164 protected $DefOrientation;
167 * @var current page orientation (P = Portrait, L = Landscape)
168 * @access protected
170 protected $CurOrientation;
173 * @var array indicating page orientation changes
174 * @access protected
176 protected $OrientationChanges;
179 * @var scale factor (number of points in user unit)
180 * @access protected
182 protected $k;
185 * @var width of page format in points
186 * @access protected
188 protected $fwPt;
191 * @var height of page format in points
192 * @access protected
194 protected $fhPt;
197 * @var width of page format in user unit
198 * @access protected
200 protected $fw;
203 * @var height of page format in user unit
204 * @access protected
206 protected $fh;
209 * @var current width of page in points
210 * @access protected
212 protected $wPt;
215 * @var current height of page in points
216 * @access protected
218 protected $hPt;
221 * @var current width of page in user unit
222 * @access protected
224 protected $w;
227 * @var current height of page in user unit
228 * @access protected
230 protected $h;
233 * @var left margin
234 * @access protected
236 protected $lMargin;
239 * @var top margin
240 * @access protected
242 protected $tMargin;
245 * @var right margin
246 * @access protected
248 protected $rMargin;
251 * @var page break margin
252 * @access protected
254 protected $bMargin;
257 * @var cell internal padding
258 * @access protected
260 protected $cMargin;
263 * @var current horizontal position in user unit for cell positioning
264 * @access protected
266 protected $x;
269 * @var current vertical position in user unit for cell positioning
270 * @access protected
272 protected $y;
275 * @var height of last cell printed
276 * @access protected
278 protected $lasth;
281 * @var line width in user unit
282 * @access protected
284 protected $LineWidth;
287 * @var array of standard font names
288 * @access protected
290 protected $CoreFonts;
293 * @var array of used fonts
294 * @access protected
296 protected $fonts;
299 * @var array of font files
300 * @access protected
302 protected $FontFiles;
305 * @var array of encoding differences
306 * @access protected
308 protected $diffs;
311 * @var array of used images
312 * @access protected
314 protected $images;
317 * @var array of links in pages
318 * @access protected
320 protected $PageLinks;
323 * @var array of internal links
324 * @access protected
326 protected $links;
329 * @var current font family
330 * @access protected
332 protected $FontFamily;
335 * @var current font style
336 * @access protected
338 protected $FontStyle;
341 * @var underlining flag
342 * @access protected
344 protected $underline;
347 * @var current font info
348 * @access protected
350 protected $CurrentFont;
353 * @var current font size in points
354 * @access protected
356 protected $FontSizePt;
359 * @var current font size in user unit
360 * @access protected
362 protected $FontSize;
365 * @var commands for drawing color
366 * @access protected
368 protected $DrawColor;
371 * @var commands for filling color
372 * @access protected
374 protected $FillColor;
377 * @var commands for text color
378 * @access protected
380 protected $TextColor;
383 * @var indicates whether fill and text colors are different
384 * @access protected
386 protected $ColorFlag;
389 * @var word spacing
390 * @access protected
392 protected $ws;
395 * @var automatic page breaking
396 * @access protected
398 protected $AutoPageBreak;
401 * @var threshold used to trigger page breaks
402 * @access protected
404 protected $PageBreakTrigger;
407 * @var flag set when processing footer
408 * @access protected
410 protected $InFooter;
413 * @var zoom display mode
414 * @access protected
416 protected $ZoomMode;
419 * @var layout display mode
420 * @access protected
422 protected $LayoutMode;
425 * @var title
426 * @access protected
428 protected $title;
431 * @var subject
432 * @access protected
434 protected $subject;
437 * @var author
438 * @access protected
440 protected $author;
443 * @var keywords
444 * @access protected
446 protected $keywords;
449 * @var creator
450 * @access protected
452 protected $creator;
455 * @var alias for total number of pages
456 * @access protected
458 protected $AliasNbPages;
461 * @var right-bottom corner X coordinate of inserted image
462 * @since 2002-07-31
463 * @author Nicola Asuni
464 * @access protected
466 protected $img_rb_x;
469 * @var right-bottom corner Y coordinate of inserted image
470 * @since 2002-07-31
471 * @author Nicola Asuni
472 * @access protected
474 protected $img_rb_y;
477 * @var image scale factor
478 * @since 2004-06-14
479 * @author Nicola Asuni
480 * @access protected
482 protected $imgscale = 1;
485 * @var boolean set to true when the input text is unicode (require unicode fonts)
486 * @since 2005-01-02
487 * @author Nicola Asuni
488 * @access protected
490 protected $isunicode = false;
493 * @var PDF version
494 * @since 1.5.3
495 * @access protected
497 protected $PDFVersion = "1.5";
500 // ----------------------
503 * @var Minimum distance between header and top page margin.
504 * @access private
506 private $header_margin;
509 * @var Minimum distance between footer and bottom page margin.
510 * @access private
512 private $footer_margin;
515 * @var original left margin value
516 * @access private
517 * @since 1.53.0.TC013
519 private $original_lMargin;
522 * @var original right margin value
523 * @access private
524 * @since 1.53.0.TC013
526 private $original_rMargin;
529 * @var Header font.
530 * @access private
532 private $header_font;
535 * @var Footer font.
536 * @access private
538 private $footer_font;
541 * @var Language templates.
542 * @access private
544 private $l;
547 * @var Barcode to print on page footer (only if set).
548 * @access private
550 private $barcode = false;
553 * @var If true prints header
554 * @access private
556 private $print_header = true;
559 * @var If true prints footer.
560 * @access private
562 private $print_footer = true;
565 * @var Header width (0 = full page width).
566 * @access private
568 private $header_width = 0;
571 * @var Header image logo.
572 * @access private
574 private $header_logo = "";
577 * @var Header image logo width in mm.
578 * @access private
580 private $header_logo_width = 30;
583 * @var String to print as title on document header.
584 * @access private
586 private $header_title = "";
589 * @var String to print on document header.
590 * @access private
592 private $header_string = "";
595 * @var Default number of columns for html table.
596 * @access private
598 private $default_table_columns = 4;
601 // variables for html parser
604 * @var HTML PARSER: store current link.
605 * @access private
607 private $HREF;
610 * @var HTML PARSER: store font list.
611 * @access private
613 private $fontList;
616 * @var HTML PARSER: true when font attribute is set.
617 * @access private
619 private $issetfont;
622 * @var HTML PARSER: true when color attribute is set.
623 * @access private
625 private $issetcolor;
628 * @var HTML PARSER: true in case of ordered list (OL), false otherwise.
629 * @access private
631 private $listordered = false;
634 * @var HTML PARSER: count list items.
635 * @access private
637 private $listcount = 0;
640 * @var HTML PARSER: size of table border.
641 * @access private
643 private $tableborder = 0;
646 * @var HTML PARSER: true at the beginning of table.
647 * @access private
649 private $tdbegin = false;
652 * @var HTML PARSER: table width.
653 * @access private
655 private $tdwidth = 0;
658 * @var HTML PARSER: table height.
659 * @access private
661 private $tdheight = 0;
664 * @var HTML PARSER: table align.
665 * @access private
667 private $tdalign = "L";
670 * @var HTML PARSER: table background color.
671 * @access private
673 private $tdbgcolor = false;
676 * @var Store temporary font size in points.
677 * @access private
679 private $tempfontsize = 10;
682 * @var Bold font style status.
683 * @access private
685 private $b;
688 * @var Underlined font style status.
689 * @access private
691 private $u;
694 * @var Italic font style status.
695 * @access private
697 private $i;
700 * @var spacer for LI tags.
701 * @access private
703 private $lispacer = "";
706 * @var default encoding
707 * @access private
708 * @since 1.53.0.TC010
710 private $encoding = "UTF-8";
713 * @var PHP internal encoding
714 * @access private
715 * @since 1.53.0.TC016
717 private $internal_encoding;
720 * @var store previous fill color as RGB array
721 * @access private
722 * @since 1.53.0.TC017
724 private $prevFillColor = array(255,255,255);
727 * @var store previous text color as RGB array
728 * @access private
729 * @since 1.53.0.TC017
731 private $prevTextColor = array(0,0,0);
734 * @var store previous font family
735 * @access private
736 * @since 1.53.0.TC017
738 private $prevFontFamily;
741 * @var store previous font style
742 * @access private
743 * @since 1.53.0.TC017
745 private $prevFontStyle;
748 * @var indicates if the document language is Right-To-Left
749 * @access private
750 * @since 2.0.000
752 private $rtl = false;
755 * @var used to force RTL or LTR string inversion
756 * @access private
757 * @since 2.0.000
759 private $tmprtl = false;
761 // --- Variables used for document encryption:
764 * Indicates whether document is protected
765 * @access private
766 * @since 2.0.000 (2008-01-02)
768 private $encrypted;
771 * U entry in pdf document
772 * @access private
773 * @since 2.0.000 (2008-01-02)
775 private $Uvalue;
778 * O entry in pdf document
779 * @access private
780 * @since 2.0.000 (2008-01-02)
782 private $Ovalue;
785 * P entry in pdf document
786 * @access private
787 * @since 2.0.000 (2008-01-02)
789 private $Pvalue;
792 * encryption object id
793 * @access private
794 * @since 2.0.000 (2008-01-02)
796 private $enc_obj_id;
799 * last RC4 key encrypted (cached for optimisation)
800 * @access private
801 * @since 2.0.000 (2008-01-02)
803 private $last_rc4_key;
806 * last RC4 computed key
807 * @access private
808 * @since 2.0.000 (2008-01-02)
810 private $last_rc4_key_c;
812 // --- bookmark ---
815 * Outlines for bookmark
816 * @access private
817 * @since 2.1.002 (2008-02-12)
819 private $outlines = array();
822 * Outline root for bookmark
823 * @access private
824 * @since 2.1.002 (2008-02-12)
826 private $OutlineRoot;
829 // --- javascript and form ---
832 * javascript code
833 * @access private
834 * @since 2.1.002 (2008-02-12)
836 private $javascript = "";
839 * javascript counter
840 * @access private
841 * @since 2.1.002 (2008-02-12)
843 private $n_js;
845 //------------------------------------------------------------
846 // Public methods
847 //------------------------------------------------------------
850 * This is the class constructor.
851 * It allows to set up the page format, the orientation and
852 * the measure unit used in all the methods (except for the font sizes).
853 * @since 1.0
854 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
855 * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
856 * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
857 * @param boolean $unicode TRUE means that the input text is unicode (default = true)
858 * @param String $encoding charset encoding; default is UTF-8
860 public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding="UTF-8") {
862 /* Set internal character encoding to ASCII */
863 if (function_exists("mb_internal_encoding") AND mb_internal_encoding()) {
864 $this->internal_encoding = mb_internal_encoding();
865 mb_internal_encoding("ASCII");
868 // set language direction
869 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
870 $this->tmprtl = false;
872 //Some checks
873 $this->_dochecks();
875 //Initialization of properties
876 $this->isunicode=$unicode;
877 $this->page=0;
878 $this->n=2;
879 $this->buffer='';
880 $this->pages=array();
881 $this->OrientationChanges=array();
882 $this->state=0;
883 $this->fonts=array();
884 $this->FontFiles=array();
885 $this->diffs=array();
886 $this->images=array();
887 $this->links=array();
888 $this->InFooter=false;
889 $this->lasth=0;
890 $this->FontFamily='';
891 $this->FontStyle='';
892 $this->FontSizePt=12;
893 $this->underline=false;
894 $this->DrawColor='0 G';
895 $this->FillColor='0 g';
896 $this->TextColor='0 g';
897 $this->ColorFlag=false;
898 $this->ws=0;
899 // encryption values
900 $this->encrypted=false;
901 $this->last_rc4_key='';
902 $this->padding="\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
904 //Standard Unicode fonts
905 $this->CoreFonts=array(
906 'courier'=>'Courier',
907 'courierB'=>'Courier-Bold',
908 'courierI'=>'Courier-Oblique',
909 'courierBI'=>'Courier-BoldOblique',
910 'helvetica'=>'Helvetica',
911 'helveticaB'=>'Helvetica-Bold',
912 'helveticaI'=>'Helvetica-Oblique',
913 'helveticaBI'=>'Helvetica-BoldOblique',
914 'times'=>'Times-Roman',
915 'timesB'=>'Times-Bold',
916 'timesI'=>'Times-Italic',
917 'timesBI'=>'Times-BoldItalic',
918 'symbol'=>'Symbol',
919 'zapfdingbats'=>'ZapfDingbats'
922 //Scale factor
923 switch (strtolower($unit)){
924 case 'pt': {$this->k=1; break;}
925 case 'mm': {$this->k=72/25.4; break;}
926 case 'cm': {$this->k=72/2.54; break;}
927 case 'in': {$this->k=72; break;}
928 default : {$this->Error('Incorrect unit: '.$unit); break;}
931 //Page format
932 if(is_string($format)) {
933 // Page formats (45 standard ISO paper formats and 4 american common formats).
934 // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm)
935 switch (strtoupper($format)){
936 case '4A0': {$format = array(4767.87,6740.79); break;}
937 case '2A0': {$format = array(3370.39,4767.87); break;}
938 case 'A0': {$format = array(2383.94,3370.39); break;}
939 case 'A1': {$format = array(1683.78,2383.94); break;}
940 case 'A2': {$format = array(1190.55,1683.78); break;}
941 case 'A3': {$format = array(841.89,1190.55); break;}
942 case 'A4': default: {$format = array(595.28,841.89); break;}
943 case 'A5': {$format = array(419.53,595.28); break;}
944 case 'A6': {$format = array(297.64,419.53); break;}
945 case 'A7': {$format = array(209.76,297.64); break;}
946 case 'A8': {$format = array(147.40,209.76); break;}
947 case 'A9': {$format = array(104.88,147.40); break;}
948 case 'A10': {$format = array(73.70,104.88); break;}
949 case 'B0': {$format = array(2834.65,4008.19); break;}
950 case 'B1': {$format = array(2004.09,2834.65); break;}
951 case 'B2': {$format = array(1417.32,2004.09); break;}
952 case 'B3': {$format = array(1000.63,1417.32); break;}
953 case 'B4': {$format = array(708.66,1000.63); break;}
954 case 'B5': {$format = array(498.90,708.66); break;}
955 case 'B6': {$format = array(354.33,498.90); break;}
956 case 'B7': {$format = array(249.45,354.33); break;}
957 case 'B8': {$format = array(175.75,249.45); break;}
958 case 'B9': {$format = array(124.72,175.75); break;}
959 case 'B10': {$format = array(87.87,124.72); break;}
960 case 'C0': {$format = array(2599.37,3676.54); break;}
961 case 'C1': {$format = array(1836.85,2599.37); break;}
962 case 'C2': {$format = array(1298.27,1836.85); break;}
963 case 'C3': {$format = array(918.43,1298.27); break;}
964 case 'C4': {$format = array(649.13,918.43); break;}
965 case 'C5': {$format = array(459.21,649.13); break;}
966 case 'C6': {$format = array(323.15,459.21); break;}
967 case 'C7': {$format = array(229.61,323.15); break;}
968 case 'C8': {$format = array(161.57,229.61); break;}
969 case 'C9': {$format = array(113.39,161.57); break;}
970 case 'C10': {$format = array(79.37,113.39); break;}
971 case 'RA0': {$format = array(2437.80,3458.27); break;}
972 case 'RA1': {$format = array(1729.13,2437.80); break;}
973 case 'RA2': {$format = array(1218.90,1729.13); break;}
974 case 'RA3': {$format = array(864.57,1218.90); break;}
975 case 'RA4': {$format = array(609.45,864.57); break;}
976 case 'SRA0': {$format = array(2551.18,3628.35); break;}
977 case 'SRA1': {$format = array(1814.17,2551.18); break;}
978 case 'SRA2': {$format = array(1275.59,1814.17); break;}
979 case 'SRA3': {$format = array(907.09,1275.59); break;}
980 case 'SRA4': {$format = array(637.80,907.09); break;}
981 case 'LETTER': {$format = array(612.00,792.00); break;}
982 case 'LEGAL': {$format = array(612.00,1008.00); break;}
983 case 'EXECUTIVE': {$format = array(521.86,756.00); break;}
984 case 'FOLIO': {$format = array(612.00,936.00); break;}
985 // default: {$this->Error('Unknown page format: '.$format); break;}
987 $this->fwPt=$format[0];
988 $this->fhPt=$format[1];
990 else {
991 $this->fwPt=$format[0]*$this->k;
992 $this->fhPt=$format[1]*$this->k;
995 $this->fw=$this->fwPt/$this->k;
996 $this->fh=$this->fhPt/$this->k;
998 //Page orientation
999 $orientation=strtolower($orientation);
1000 if($orientation=='p' or $orientation=='portrait') {
1001 $this->DefOrientation='P';
1002 $this->wPt=$this->fwPt;
1003 $this->hPt=$this->fhPt;
1005 elseif($orientation=='l' or $orientation=='landscape') {
1006 $this->DefOrientation='L';
1007 $this->wPt=$this->fhPt;
1008 $this->hPt=$this->fwPt;
1010 else {
1011 $this->Error('Incorrect orientation: '.$orientation);
1014 $this->CurOrientation=$this->DefOrientation;
1015 $this->w=$this->wPt/$this->k;
1016 $this->h=$this->hPt/$this->k;
1017 //Page margins (1 cm)
1018 $margin=28.35/$this->k;
1019 $this->SetMargins($margin,$margin);
1020 //Interior cell margin (1 mm)
1021 $this->cMargin=$margin/10;
1022 //Line width (0.2 mm)
1023 $this->LineWidth=.567/$this->k;
1024 //Automatic page break
1025 $this->SetAutoPageBreak(true,2*$margin);
1026 //Full width display mode
1027 $this->SetDisplayMode('fullwidth');
1028 //Compression
1029 $this->SetCompression(true);
1030 //Set default PDF version number
1031 $this->PDFVersion = "1.5";
1033 $this->encoding = $encoding;
1034 $this->b = 0;
1035 $this->i = 0;
1036 $this->u = 0;
1037 $this->HREF = '';
1038 $this->fontlist = array("arial", "times", "courier", "helvetica", "symbol");
1039 $this->issetfont = false;
1040 $this->issetcolor = false;
1041 $this->tableborder = 0;
1042 $this->tdbegin = false;
1043 $this->tdwidth= 0;
1044 $this->tdheight = 0;
1045 if($this->rtl) {
1046 $this->tdalign = "R";
1047 } else {
1048 $this->tdalign = "L";
1050 $this->tdbgcolor = false;
1052 $this->SetFillColor(200, 200, 200, true);
1053 $this->SetTextColor(0, 0, 0, true);
1057 * Default destructor.
1058 * @since 1.53.0.TC016
1060 public function __destruct() {
1061 // restore internal encoding
1062 if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
1063 mb_internal_encoding($this->internal_encoding);
1068 * Enable or disable Right-To-Left language mode
1069 * @param Boolean $enable if true enable Right-To-Left language mode.
1070 * @since 2.0.000 (2008-01-03)
1072 public function setRTL($enable) {
1073 $this->rtl = $enable ? true : false;
1074 $this->tmprtl = false;
1078 * Force temporary RTL language direction
1079 * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL
1080 * @since 2.1.000 (2008-01-09)
1082 public function setTempRTL($mode) {
1083 switch ($mode) {
1084 case false:
1085 case 'L':
1086 case 'R': {
1087 $this->tmprtl = $mode;
1093 * Set the last cell height.
1094 * @param float $h cell height.
1095 * @author Nicola Asuni
1096 * @since 1.53.0.TC034
1098 public function setLastH($h) {
1099 $this->lasth=$h;
1103 * Set the image scale.
1104 * @param float $scale image scale.
1105 * @author Nicola Asuni
1106 * @since 1.5.2
1108 public function setImageScale($scale) {
1109 $this->imgscale=$scale;
1113 * Returns the image scale.
1114 * @return float image scale.
1115 * @author Nicola Asuni
1116 * @since 1.5.2
1118 public function getImageScale() {
1119 return $this->imgscale;
1123 * Returns the page width in units.
1124 * @return int page width.
1125 * @author Nicola Asuni
1126 * @since 1.5.2
1128 public function getPageWidth() {
1129 return $this->w;
1133 * Returns the page height in units.
1134 * @return int page height.
1135 * @author Nicola Asuni
1136 * @since 1.5.2
1138 public function getPageHeight() {
1139 return $this->h;
1143 * Returns the page break margin.
1144 * @return int page break margin.
1145 * @author Nicola Asuni
1146 * @since 1.5.2
1148 public function getBreakMargin() {
1149 return $this->bMargin;
1153 * Returns the scale factor (number of points in user unit).
1154 * @return int scale factor.
1155 * @author Nicola Asuni
1156 * @since 1.5.2
1158 public function getScaleFactor() {
1159 return $this->k;
1163 * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
1164 * @param float $left Left margin.
1165 * @param float $top Top margin.
1166 * @param float $right Right margin. Default value is the left one.
1167 * @since 1.0
1168 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
1170 public function SetMargins($left, $top, $right=-1) {
1171 //Set left, top and right margins
1172 $this->lMargin=$left;
1173 $this->tMargin=$top;
1174 if($right==-1) {
1175 $right=$left;
1177 $this->rMargin=$right;
1181 * Defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin.
1182 * @param float $margin The margin.
1183 * @since 1.4
1184 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1186 public function SetLeftMargin($margin) {
1187 //Set left margin
1188 $this->lMargin=$margin;
1189 if(($this->page > 0) AND ($this->x < $margin)) {
1190 $this->x = $margin;
1195 * Defines the top margin. The method can be called before creating the first page.
1196 * @param float $margin The margin.
1197 * @since 1.5
1198 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1200 public function SetTopMargin($margin) {
1201 //Set top margin
1202 $this->tMargin=$margin;
1203 if(($this->page > 0) AND ($this->y < $margin)) {
1204 $this->y = $margin;
1209 * Defines the right margin. The method can be called before creating the first page.
1210 * @param float $margin The margin.
1211 * @since 1.5
1212 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1214 public function SetRightMargin($margin) {
1215 $this->rMargin=$margin;
1216 if(($this->page > 0) AND ($this->x > ($this->w - $margin))) {
1217 $this->x = $this->w - $margin;
1222 * Set the internal Cell padding.
1223 * @param float $pad internal padding.
1224 * @since 2.1.000 (2008-01-09)
1225 * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1227 public function SetCellPadding($pad) {
1228 $this->cMargin=$pad;
1232 * Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm.
1233 * @param boolean $auto Boolean indicating if mode should be on or off.
1234 * @param float $margin Distance from the bottom of the page.
1235 * @since 1.0
1236 * @see Cell(), MultiCell(), AcceptPageBreak()
1238 public function SetAutoPageBreak($auto, $margin=0) {
1239 //Set auto page break mode and triggering margin
1240 $this->AutoPageBreak = $auto;
1241 $this->bMargin = $margin;
1242 $this->PageBreakTrigger = $this->h - $margin;
1246 * Defines the way the document is to be displayed by the viewer. The zoom level can be set: pages can be displayed entirely on screen, occupy the full width of the window, use real size, be scaled by a specific zooming factor or use viewer default (configured in the Preferences menu of Acrobat). The page layout can be specified too: single at once, continuous display, two columns or viewer default. By default, documents use the full width mode with continuous display.
1247 * @param mixed $zoom The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul>
1248 * @param string $layout The page layout. Possible values are:<ul><li>single: displays one page at once</li><li>continuous: displays pages continuously (default)</li><li>two: displays two pages on two columns</li><li>default: uses viewer default mode</li></ul>
1249 * @since 1.2
1251 public function SetDisplayMode($zoom, $layout='continuous') {
1252 //Set display mode in viewer
1253 if($zoom=='fullpage' or $zoom=='fullwidth' or $zoom=='real' or $zoom=='default' or !is_string($zoom)) {
1254 $this->ZoomMode=$zoom;
1256 else {
1257 $this->Error('Incorrect zoom display mode: '.$zoom);
1259 if($layout=='single' or $layout=='continuous' or $layout=='two' or $layout=='default') {
1260 $this->LayoutMode=$layout;
1262 else {
1263 $this->Error('Incorrect layout display mode: '.$layout);
1268 * Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default.
1269 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
1270 * @param boolean $compress Boolean indicating if compression must be enabled.
1271 * @since 1.4
1273 public function SetCompression($compress) {
1274 //Set page compression
1275 if(function_exists('gzcompress')) {
1276 $this->compress=$compress;
1278 else {
1279 $this->compress=false;
1284 * Defines the title of the document.
1285 * @param string $title The title.
1286 * @since 1.2
1287 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
1289 public function SetTitle($title) {
1290 //Title of document
1291 $this->title=$title;
1295 * Defines the subject of the document.
1296 * @param string $subject The subject.
1297 * @since 1.2
1298 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
1300 public function SetSubject($subject) {
1301 //Subject of document
1302 $this->subject=$subject;
1306 * Defines the author of the document.
1307 * @param string $author The name of the author.
1308 * @since 1.2
1309 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
1311 public function SetAuthor($author) {
1312 //Author of document
1313 $this->author=$author;
1317 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
1318 * @param string $keywords The list of keywords.
1319 * @since 1.2
1320 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
1322 public function SetKeywords($keywords) {
1323 //Keywords of document
1324 $this->keywords=$keywords;
1328 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
1329 * @param string $creator The name of the creator.
1330 * @since 1.2
1331 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
1333 public function SetCreator($creator) {
1334 //Creator of document
1335 $this->creator=$creator;
1339 * Defines an alias for the total number of pages. It will be substituted as the document is closed.<br />
1340 * <b>Example:</b><br />
1341 * <pre>
1342 * class PDF extends TCPDF {
1343 * public function Footer() {
1344 * //Go to 1.5 cm from bottom
1345 * $this->SetY(-15);
1346 * //Select Arial italic 8
1347 * $this->SetFont('Arial','I',8);
1348 * //Print current and total page numbers
1349 * $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
1352 * $pdf=new PDF();
1353 * $pdf->AliasNbPages();
1354 * </pre>
1355 * @param string $alias The alias. Default value: {nb}.
1356 * @since 1.4
1357 * @see PageNo(), Footer()
1359 public function AliasNbPages($alias='{nb}') {
1360 //Define an alias for total number of pages
1361 $this->AliasNbPages = $this->_escapetext($alias);
1365 * This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid.
1366 * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
1367 * @param string $msg The error message
1368 * @since 1.0
1370 public function Error($msg) {
1371 //Fatal error
1372 die('<strong>TCPDF error: </strong>'.$msg);
1376 * This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.
1377 * Note: no page is created by this method
1378 * @since 1.0
1379 * @see AddPage(), Close()
1381 public function Open() {
1382 //Begin document
1383 $this->state=1;
1387 * Terminates the PDF document. It is not necessary to call this method explicitly because Output() does it automatically. If the document contains no page, AddPage() is called to prevent from getting an invalid document.
1388 * @since 1.0
1389 * @see Open(), Output()
1391 public function Close() {
1392 //Terminate document
1393 if($this->state==3) {
1394 return;
1396 if($this->page==0) {
1397 $this->AddPage();
1399 //Page footer
1400 $this->InFooter=true;
1401 $this->Footer();
1402 $this->InFooter=false;
1403 //Close page
1404 $this->_endpage();
1405 //Close document
1406 $this->_enddoc();
1410 * Reset pointer to the last document page.
1411 * @since 2.0.000 (2008-01-04)
1412 * @see setPage(), getPage(), getNumPages()
1414 public function lastPage() {
1415 $this->page = count($this->pages);
1419 * Move pointer to the apecified document page.
1420 * @param int $pnum page number
1421 * @since 2.1.000 (2008-01-07)
1422 * @see getPage(), lastpage(), getNumPages()
1424 public function setPage($pnum) {
1425 if(($pnum > 0) AND ($pnum <= count($this->pages))) {
1426 $this->page = $pnum;
1431 * Get current document page number.
1432 * @return int page number
1433 * @since 2.1.000 (2008-01-07)
1434 * @see setPage(), lastpage(), getNumPages()
1436 public function getPage() {
1437 return $this->page;
1442 * Get the total number of insered pages.
1443 * @return int number of pages
1444 * @since 2.1.000 (2008-01-07)
1445 * @see setPage(), getPage(), lastpage()
1447 public function getNumPages() {
1448 return count($this->pages);
1452 * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer. Then the page is added, the current position set to the top-left corner according to the left and top margins, and Header() is called to display the header.
1453 * The font which was set before calling is automatically restored. There is no need to call SetFont() again if you want to continue with the same font. The same is true for colors and line width.
1454 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
1455 * @param string $orientation Page orientation. Possible values are (case insensitive):<ul><li>P or Portrait</li><li>L or Landscape</li></ul> The default value is the one passed to the constructor.
1456 * @since 1.0
1457 * @see TCPDF(), Header(), Footer(), SetMargins()
1459 public function AddPage($orientation='') {
1460 if (count($this->pages) > ($this->page + 1)) {
1461 // this page has been already added
1462 $this->page++;
1463 return;
1465 //Start a new page
1466 if($this->state==0) {
1467 $this->Open();
1469 $family=$this->FontFamily;
1470 $style=$this->FontStyle.($this->underline ? 'U' : '');
1471 $size=$this->FontSizePt;
1472 $lw=$this->LineWidth;
1473 $dc=$this->DrawColor;
1474 $fc=$this->FillColor;
1475 $tc=$this->TextColor;
1476 $cf=$this->ColorFlag;
1477 if($this->page>0) {
1478 //Page footer
1479 $this->InFooter=true;
1480 $this->Footer();
1481 $this->InFooter=false;
1482 //Close page
1483 $this->_endpage();
1485 //Start new page
1486 $this->_beginpage($orientation);
1487 //Set line cap style to square
1488 $this->_out('2 J');
1489 //Set line width
1490 $this->LineWidth=$lw;
1491 $this->_out(sprintf('%.2f w',$lw*$this->k));
1492 //Set font
1493 if($family) {
1494 $this->SetFont($family,$style,$size);
1496 //Set colors
1497 $this->DrawColor=$dc;
1498 if($dc!='0 G') {
1499 $this->_out($dc);
1501 $this->FillColor=$fc;
1502 if($fc!='0 g') {
1503 $this->_out($fc);
1505 $this->TextColor=$tc;
1506 $this->ColorFlag=$cf;
1507 //Page header
1508 $this->Header();
1509 //Restore line width
1510 if($this->LineWidth!=$lw) {
1511 $this->LineWidth=$lw;
1512 $this->_out(sprintf('%.2f w',$lw*$this->k));
1514 //Restore font
1515 if($family) {
1516 $this->SetFont($family,$style,$size);
1518 //Restore colors
1519 if($this->DrawColor!=$dc) {
1520 $this->DrawColor=$dc;
1521 $this->_out($dc);
1523 if($this->FillColor!=$fc) {
1524 $this->FillColor=$fc;
1525 $this->_out($fc);
1527 $this->TextColor=$tc;
1528 $this->ColorFlag=$cf;
1532 * Set header data.
1533 * @param string $ln header image logo
1534 * @param string $lw header image logo width in mm
1535 * @param string $ht string to print as title on document header
1536 * @param string $hs string to print on document header
1538 public function setHeaderData($ln="", $lw=0, $ht="", $hs="") {
1539 $this->header_logo = $ln;
1540 $this->header_logo_width = $lw;
1541 $this->header_title = $ht;
1542 $this->header_string = $hs;
1546 * Set header margin.
1547 * (minimum distance between header and top page margin)
1548 * @param int $hm distance in millimeters
1550 public function setHeaderMargin($hm=10) {
1551 $this->header_margin = $hm;
1555 * Set footer margin.
1556 * (minimum distance between footer and bottom page margin)
1557 * @param int $fm distance in millimeters
1559 public function setFooterMargin($fm=10) {
1560 $this->footer_margin = $fm;
1564 * Set a flag to print page header.
1565 * @param boolean $val set to true to print the page header (default), false otherwise.
1567 public function setPrintHeader($val=true) {
1568 $this->print_header = $val;
1572 * Set a flag to print page footer.
1573 * @param boolean $value set to true to print the page footer (default), false otherwise.
1575 public function setPrintFooter($val=true) {
1576 $this->print_footer = $val;
1580 * This method is used to render the page header.
1581 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
1583 public function Header() {
1584 if ($this->print_header) {
1586 if (!isset($this->original_lMargin)) {
1587 $this->original_lMargin = $this->lMargin;
1589 if (!isset($this->original_rMargin)) {
1590 $this->original_rMargin = $this->rMargin;
1593 //set current position
1594 if ($this->rtl) {
1595 $this->SetXY($this->original_rMargin, $this->header_margin);
1596 } else {
1597 $this->SetXY($this->original_lMargin, $this->header_margin);
1600 if (($this->header_logo) AND ($this->header_logo != K_BLANK_IMAGE)) {
1601 $this->Image(K_PATH_IMAGES.$this->header_logo, $this->GetX(), $this->header_margin, $this->header_logo_width);
1602 } else {
1603 $this->img_rb_x = $this->GetX();
1604 $this->img_rb_y = $this->GetY();
1607 $cell_height = round((K_CELL_HEIGHT_RATIO * $this->header_font[2]) / $this->k, 2);
1608 // set starting margin for text data cell
1609 if ($this->rtl) {
1610 $header_x = $this->original_rMargin + ($this->header_logo_width * 1.1);
1611 } else {
1612 $header_x = $this->original_lMargin + ($this->header_logo_width * 1.1);
1615 // header title
1616 $this->SetFont($this->header_font[0], 'B', $this->header_font[2] + 1);
1617 $this->SetX($header_x);
1618 $this->Cell($this->header_width, $cell_height, $this->header_title, 0, 1, '');
1620 // header string
1621 $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
1622 $this->SetX($header_x);
1623 $this->MultiCell($this->header_width, $cell_height, $this->header_string, 0, '', 0);
1625 // print an ending header line
1626 if (empty($this->header_width)) {
1627 //set style for cell border
1628 $prevlinewidth = $this->GetLineWidth();
1629 $line_width = 0.3;
1630 $this->SetLineWidth($line_width);
1631 $this->SetDrawColor(0, 0, 0);
1632 $this->SetY(1 + max($this->img_rb_y, $this->GetY()));
1633 if ($this->rtl) {
1634 $this->SetX($this->original_rMargin);
1635 } else {
1636 $this->SetX($this->original_lMargin);
1638 $this->Cell(0, 0, '', 'T', 0, 'C');
1639 $this->SetLineWidth($prevlinewidth);
1642 //restore position
1643 if ($this->rtl) {
1644 $this->SetXY($this->original_rMargin, $this->tMargin);
1645 } else {
1646 $this->SetXY($this->original_lMargin, $this->tMargin);
1652 * This method is used to render the page footer.
1653 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
1655 public function Footer() {
1656 if ($this->print_footer) {
1658 if (!isset($this->original_lMargin)) {
1659 $this->original_lMargin = $this->lMargin;
1661 if (!isset($this->original_rMargin)) {
1662 $this->original_rMargin = $this->rMargin;
1665 //set font
1666 $this->SetFont($this->footer_font[0], $this->footer_font[1] , $this->footer_font[2]);
1667 //set style for cell border
1668 $prevlinewidth = $this->GetLineWidth();
1669 $line_width = 0.3;
1670 $this->SetLineWidth($line_width);
1671 $this->SetDrawColor(0, 0, 0);
1673 $footer_height = round((K_CELL_HEIGHT_RATIO * $this->footer_font[2]) / $this->k, 2); //footer height
1674 //get footer y position
1675 $footer_y = $this->h - $this->footer_margin - $footer_height;
1676 //set current position
1677 if ($this->rtl) {
1678 $this->SetXY($this->original_rMargin, $footer_y);
1679 } else {
1680 $this->SetXY($this->original_lMargin, $footer_y);
1683 //print document barcode
1684 if ($this->barcode) {
1685 $this->Ln();
1686 $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin)/3); //max width
1687 $this->writeBarcode($this->GetX(), $footer_y + $line_width, $barcode_width, $footer_height - $line_width, "C128B", false, false, 2, $this->barcode);
1690 $pagenumtxt = $this->l['w_page']." ".$this->PageNo().' / {nb}';
1692 $this->SetY($footer_y);
1694 //Print page number
1695 if ($this->rtl) {
1696 $this->SetX($this->original_rMargin);
1697 $this->Cell(0, $footer_height, $pagenumtxt, 'T', 0, 'L');
1698 } else {
1699 $this->SetX($this->original_lMargin);
1700 $this->Cell(0, $footer_height, $pagenumtxt, 'T', 0, 'R');
1702 // restore line width
1703 $this->SetLineWidth($prevlinewidth);
1708 * Returns the current page number.
1709 * @return int page number
1710 * @since 1.0
1711 * @see AliasNbPages()
1713 public function PageNo() {
1714 //Get current page number
1715 return $this->page;
1719 * Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
1720 * @param int $r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
1721 * @param int $g Green component (between 0 and 255)
1722 * @param int $b Blue component (between 0 and 255)
1723 * @since 1.3
1724 * @see SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
1726 public function SetDrawColor($r, $g=-1, $b=-1) {
1727 //Set color for all stroking operations
1728 if(($r==0 and $g==0 and $b==0) or $g==-1) {
1729 $this->DrawColor=sprintf('%.3f G',$r/255);
1731 else {
1732 $this->DrawColor=sprintf('%.3f %.3f %.3f RG',$r/255,$g/255,$b/255);
1734 if($this->page>0) {
1735 $this->_out($this->DrawColor);
1740 * Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
1741 * @param int $r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
1742 * @param int $g Green component (between 0 and 255)
1743 * @param int $b Blue component (between 0 and 255)
1744 * @param boolean $storeprev if true stores the RGB array on $prevFillColor variable.
1745 * @since 1.3
1746 * @see SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
1748 public function SetFillColor($r, $g=-1, $b=-1, $storeprev=false) {
1749 //Set color for all filling operations
1750 if(($r==0 and $g==0 and $b==0) or $g==-1) {
1751 $this->FillColor=sprintf('%.3f g',$r/255);
1753 else {
1754 $this->FillColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255);
1756 $this->ColorFlag=($this->FillColor!=$this->TextColor);
1757 if($this->page>0) {
1758 $this->_out($this->FillColor);
1760 if ($storeprev) {
1761 // store color as previous value
1762 $this->prevFillColor = array($r, $g, $b);
1767 * Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
1768 * @param int $r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
1769 * @param int $g Green component (between 0 and 255)
1770 * @param int $b Blue component (between 0 and 255)
1771 * @param boolean $storeprev if true stores the RGB array on $prevTextColor variable.
1772 * @since 1.3
1773 * @see SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
1775 public function SetTextColor($r, $g=-1, $b=-1, $storeprev=false) {
1776 //Set color for text
1777 if(($r==0 and $g==0 and $b==0) or $g==-1) {
1778 $this->TextColor=sprintf('%.3f g',$r/255);
1780 else {
1781 $this->TextColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255);
1783 $this->ColorFlag=($this->FillColor!=$this->TextColor);
1784 if ($storeprev) {
1785 // store color as previous value
1786 $this->prevTextColor = array($r, $g, $b);
1791 * Returns the length of a string in user unit. A font must be selected.<br>
1792 * Support UTF-8 Unicode [Nicola Asuni, 2005-01-02]
1793 * @param string $s The string whose length is to be computed
1794 * @return int
1795 * @since 1.2
1797 public function GetStringWidth($s) {
1798 //Get width of a string in the current font
1799 $s = (string)$s;
1800 $cw = &$this->CurrentFont['cw'];
1801 $w = 0;
1802 if($this->isunicode) {
1803 $unicode = $this->UTF8StringToArray($s);
1804 foreach($unicode as $char) {
1805 if (isset($cw[$char])) {
1806 $w+=$cw[$char];
1807 } elseif(isset($cw[ord($char)])) {
1808 $w+=$cw[ord($char)];
1809 } elseif(isset($cw[chr($char)])) {
1810 $w+=$cw[chr($char)];
1811 } elseif(isset($this->CurrentFont['desc']['MissingWidth'])) {
1812 $w += $this->CurrentFont['desc']['MissingWidth']; // set default size
1813 } else {
1814 $w += 500;
1817 } else {
1818 $l = strlen($s);
1819 for($i=0; $i < $l; $i++) {
1820 if (isset($cw[$s{$i}])) {
1821 $w += $cw[$s{$i}];
1822 } else if (isset($cw[ord($s{$i})])) {
1823 $w += $cw[ord($s{$i})];
1827 return ($w * $this->FontSize / 1000);
1831 * Returns the numbero of characters in a string.
1832 * @param string $s The input string.
1833 * @return int number of characters
1834 * @since 2.0.0001 (2008-01-07)
1836 public function GetNumChars($s) {
1837 if($this->isunicode) {
1838 return count($this->UTF8StringToArray($s));
1840 return strlen($s);
1844 * Imports a TrueType or Type1 font and makes it available. It is necessary to generate a font definition file first with the makefont.php utility. The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.
1845 * Support UTF-8 Unicode [Nicola Asuni, 2005-01-02].
1846 * <b>Example</b>:<br />
1847 * <pre>
1848 * $pdf->AddFont('Comic','I');
1849 * // is equivalent to:
1850 * $pdf->AddFont('Comic','I','comici.php');
1851 * </pre>
1852 * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
1853 * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
1854 * @param string $file The font definition file. By default, the name is built from the family and style, in lower case with no space.
1855 * @since 1.5
1856 * @see SetFont()
1858 public function AddFont($family, $style='', $file='') {
1859 if(empty($family)) {
1860 return;
1863 //Add a TrueType or Type1 font
1864 $family = strtolower($family);
1865 if((!$this->isunicode) AND ($family == 'arial')) {
1866 $family = 'helvetica';
1869 $style=strtoupper($style);
1870 $style=str_replace('U','',$style);
1871 if($style == 'IB') {
1872 $style = 'BI';
1875 $fontkey = $family.$style;
1876 // check if the font has been already added
1877 if(isset($this->fonts[$fontkey])) {
1878 return;
1881 if($file=='') {
1882 $file = str_replace(' ', '', $family).strtolower($style).'.php';
1884 if(!file_exists($this->_getfontpath().$file)) {
1885 // try to load the basic file without styles
1886 $file = str_replace(' ', '', $family).'.php';
1889 include($this->_getfontpath().$file);
1891 if(!isset($name) AND !isset($fpdf_charwidths)) {
1892 $this->Error('Could not include font definition file');
1895 $i = count($this->fonts)+1;
1897 if($this->isunicode) {
1898 $this->fonts[$fontkey] = array('i'=>$i, 'type'=>$type, 'name'=>$name, 'desc'=>$desc, 'up'=>$up, 'ut'=>$ut, 'cw'=>$cw, 'enc'=>$enc, 'file'=>$file, 'ctg'=>$ctg);
1899 $fpdf_charwidths[$fontkey] = $cw;
1900 } else {
1901 $this->fonts[$fontkey]=array('i'=>$i, 'type'=>'core', 'name'=>$this->CoreFonts[$fontkey], 'up'=>-100, 'ut'=>50, 'cw'=>$fpdf_charwidths[$fontkey]);
1904 if(isset($diff) AND (!empty($diff))) {
1905 //Search existing encodings
1906 $d=0;
1907 $nb=count($this->diffs);
1908 for($i=1;$i<=$nb;$i++) {
1909 if($this->diffs[$i]==$diff) {
1910 $d=$i;
1911 break;
1914 if($d==0) {
1915 $d=$nb+1;
1916 $this->diffs[$d]=$diff;
1918 $this->fonts[$fontkey]['diff']=$d;
1920 if(!empty($file)) {
1921 if((strcasecmp($type,"TrueType") == 0) OR (strcasecmp($type,"TrueTypeUnicode") == 0)) {
1922 $this->FontFiles[$file]=array('length1'=>$originalsize);
1924 else {
1925 $this->FontFiles[$file]=array('length1'=>$size1,'length2'=>$size2);
1931 * Sets the font used to print character strings. It is mandatory to call this method at least once before printing text or the resulting document would not be valid.
1932 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
1933 * The method can be called before the first page is created and the font is retained from page to page.
1934 If you just wish to change the current font size, it is simpler to call SetFontSize().
1935 * Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this:<ul><li>They are in the current directory (the one where the running script lies)</li><li>They are in one of the directories defined by the include_path parameter</li><li>They are in the directory defined by the K_PATH_FONTS constant</li></ul><br />
1936 * Example for the last case (note the trailing slash):<br />
1937 * <pre>
1938 * define('K_PATH_FONTS','/home/www/font/');
1939 * require('tcpdf.php');
1941 * //Times regular 12
1942 * $pdf->SetFont('Times');
1943 * //Arial bold 14
1944 * $pdf->SetFont('Arial','B',14);
1945 * //Removes bold
1946 * $pdf->SetFont('');
1947 * //Times bold, italic and underlined 14
1948 * $pdf->SetFont('Times','BIU');
1949 * </pre><br />
1950 * If the file corresponding to the requested font is not found, the error "Could not include font metric file" is generated.
1951 * @param string $family Family font. It can be either a name defined by AddFont() or one of the standard families (case insensitive):<ul><li>Courier (fixed-width)</li><li>Helvetica or Arial (synonymous; sans serif)</li><li>Times (serif)</li><li>Symbol (symbolic)</li><li>ZapfDingbats (symbolic)</li></ul>It is also possible to pass an empty string. In that case, the current family is retained.
1952 * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li></ul>or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats
1953 * @param float $size Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
1954 * @since 1.0
1955 * @see AddFont(), SetFontSize(), Cell(), MultiCell(), Write()
1957 public function SetFont($family, $style='', $size=0) {
1958 // save previous values
1959 $this->prevFontFamily = $this->FontFamily;
1960 $this->prevFontStyle = $this->FontStyle;
1962 //Select a font; size given in points
1963 global $fpdf_charwidths;
1965 $family=strtolower($family);
1966 if($family=='') {
1967 $family=$this->FontFamily;
1969 if((!$this->isunicode) AND ($family == 'arial')) {
1970 $family = 'helvetica';
1972 elseif(($family=="symbol") OR ($family=="zapfdingbats")) {
1973 $style='';
1975 $style=strtoupper($style);
1977 if(strpos($style,'U')!==false) {
1978 $this->underline=true;
1979 $style=str_replace('U','',$style);
1981 else {
1982 $this->underline=false;
1984 if($style=='IB') {
1985 $style='BI';
1987 if($size==0) {
1988 $size=$this->FontSizePt;
1991 // try to add font (if not already added)
1992 if($this->isunicode) {
1993 $this->AddFont($family, $style);
1996 //Test if font is already selected
1997 if(($this->FontFamily == $family) AND ($this->FontStyle == $style) AND ($this->FontSizePt == $size)) {
1998 return;
2001 $fontkey = $family.$style;
2002 //if(!isset($this->fonts[$fontkey]) AND isset($this->fonts[$family])) {
2003 // $style='';
2006 //Test if used for the first time
2007 if(!isset($this->fonts[$fontkey])) {
2008 //Check if one of the standard fonts
2009 if(isset($this->CoreFonts[$fontkey])) {
2010 if(!isset($fpdf_charwidths[$fontkey])) {
2011 //Load metric file
2012 $file = $family;
2013 if(($family!='symbol') AND ($family!='zapfdingbats')) {
2014 $file .= strtolower($style);
2016 if(!file_exists($this->_getfontpath().$file.'.php')) {
2017 // try to load the basic file without styles
2018 $file = $family;
2019 $fontkey = $family;
2021 include($this->_getfontpath().$file.'.php');
2022 if (($this->isunicode AND !isset($ctg)) OR ((!$this->isunicode) AND (!isset($fpdf_charwidths[$fontkey]))) ) {
2023 $this->Error("Could not include font metric file [".$fontkey."]: ".$this->_getfontpath().$file.".php");
2026 $i = count($this->fonts) + 1;
2028 if($this->isunicode) {
2029 $this->fonts[$fontkey] = array('i'=>$i, 'type'=>$type, 'name'=>$name, 'desc'=>$desc, 'up'=>$up, 'ut'=>$ut, 'cw'=>$cw, 'enc'=>$enc, 'file'=>$file, 'ctg'=>$ctg);
2030 $fpdf_charwidths[$fontkey] = $cw;
2031 } else {
2032 $this->fonts[$fontkey]=array('i'=>$i, 'type'=>'core', 'name'=>$this->CoreFonts[$fontkey], 'up'=>-100, 'ut'=>50, 'cw'=>$fpdf_charwidths[$fontkey]);
2035 else {
2036 $this->Error('Undefined font: '.$family.' '.$style);
2039 //Select it
2040 $this->FontFamily = $family;
2041 $this->FontStyle = $style;
2042 $this->FontSizePt = $size;
2043 $this->FontSize = $size / $this->k;
2044 $this->CurrentFont = &$this->fonts[$fontkey];
2045 if($this->page>0) {
2046 $this->_out(sprintf('BT /F%d %.2f Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
2051 * Defines the size of the current font.
2052 * @param float $size The size (in points)
2053 * @since 1.0
2054 * @see SetFont()
2056 public function SetFontSize($size) {
2057 //Set font size in points
2058 if($this->FontSizePt==$size) {
2059 return;
2061 $this->FontSizePt = $size;
2062 $this->FontSize = $size / $this->k;
2063 if($this->page > 0) {
2064 $this->_out(sprintf('BT /F%d %.2f Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
2069 * Creates a new internal link and returns its identifier. An internal link is a clickable area which directs to another place within the document.<br />
2070 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
2071 * @since 1.5
2072 * @see Cell(), Write(), Image(), Link(), SetLink()
2074 public function AddLink() {
2075 //Create a new internal link
2076 $n=count($this->links)+1;
2077 $this->links[$n]=array(0,0);
2078 return $n;
2082 * Defines the page and position a link points to
2083 * @param int $link The link identifier returned by AddLink()
2084 * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
2085 * @param int $page Number of target page; -1 indicates the current page. This is the default value
2086 * @since 1.5
2087 * @see AddLink()
2089 public function SetLink($link, $y=0, $page=-1) {
2090 //Set destination of internal link
2091 if($y==-1) {
2092 $y=$this->y;
2094 if($page==-1) {
2095 $page=$this->page;
2097 $this->links[$link]=array($page,$y);
2101 * Puts a link on a rectangular area of the page. Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image.
2102 * @param float $x Abscissa of the upper-left corner of the rectangle (or upper-right for RTL languages)
2103 * @param float $y Ordinate of the upper-left corner of the rectangle (or upper-right for RTL languages)
2104 * @param float $w Width of the rectangle
2105 * @param float $h Height of the rectangle
2106 * @param mixed $link URL or identifier returned by AddLink()
2107 * @since 1.5
2108 * @see AddLink(), Cell(), Write(), Image()
2110 public function Link($x, $y, $w, $h, $link) {
2111 $this->PageLinks[$this->page][] = array($x * $this->k, $this->hPt - $y * $this->k, $w * $this->k, $h*$this->k, $link);
2115 * Prints a character string. The origin is on the left of the first charcter, on the baseline. This method allows to place a string precisely on the page, but it is usually easier to use Cell(), MultiCell() or Write() which are the standard methods to print text.
2116 * @param float $x Abscissa of the origin
2117 * @param float $y Ordinate of the origin
2118 * @param string $txt String to print
2119 * @since 1.0
2120 * @see SetFont(), SetTextColor(), Cell(), MultiCell(), Write()
2122 public function Text($x, $y, $txt) {
2123 //Output a string
2124 if($this->rtl) {
2125 $xr = $this->w - $x - $this->GetStringWidth($txt);
2126 } else {
2127 $xr = $x;
2129 $s = sprintf('BT %.2f %.2f Td (%s) Tj ET', $xr * $this->k, ($this->h-$y) * $this->k, $this->_escapetext($txt));
2130 if($this->underline AND ($txt!='')) {
2131 $s .= ' '.$this->_dounderline($xr, $y, $txt);
2133 if($this->ColorFlag) {
2134 $s='q '.$this->TextColor.' '.$s.' Q';
2136 $this->_out($s);
2140 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value. The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
2141 * This method is called automatically and should not be called directly by the application.<br />
2142 * <b>Example:</b><br />
2143 * The method is overriden in an inherited class in order to obtain a 3 column layout:<br />
2144 * <pre>
2145 * class PDF extends TCPDF {
2146 * var $col=0;
2148 * public function SetCol($col) {
2149 * //Move position to a column
2150 * $this->col=$col;
2151 * $x=10+$col*65;
2152 * $this->SetLeftMargin($x);
2153 * $this->SetX($x);
2156 * public function AcceptPageBreak() {
2157 * if($this->col<2) {
2158 * //Go to next column
2159 * $this->SetCol($this->col+1);
2160 * $this->SetY(10);
2161 * return false;
2163 * else {
2164 * //Go back to first column and issue page break
2165 * $this->SetCol(0);
2166 * return true;
2171 * $pdf=new PDF();
2172 * $pdf->Open();
2173 * $pdf->AddPage();
2174 * $pdf->SetFont('Arial','',12);
2175 * for($i=1;$i<=300;$i++) {
2176 * $pdf->Cell(0,5,"Line $i",0,1);
2178 * $pdf->Output();
2179 * </pre>
2180 * @return boolean
2181 * @since 1.4
2182 * @see SetAutoPageBreak()
2184 public function AcceptPageBreak() {
2185 //Accept automatic page break or not
2186 return $this->AutoPageBreak;
2190 * Prints a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
2191 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2192 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2193 * @param float $h Cell height. Default value: 0.
2194 * @param string $txt String to print. Default value: empty string.
2195 * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
2196 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
2197 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
2198 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
2199 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2200 * @param mixed $link URL or identifier returned by AddLink().
2201 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
2202 * @since 1.0
2203 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
2205 public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2206 //Output a cell
2207 $k=$this->k;
2208 if(($this->y + $h) > $this->PageBreakTrigger AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
2209 //Automatic page break
2210 $x = $this->x;
2211 $ws = $this->ws;
2212 if($ws > 0) {
2213 $this->ws = 0;
2214 $this->_out('0 Tw');
2216 $this->AddPage($this->CurOrientation);
2217 $this->x = $x;
2218 if($ws > 0) {
2219 $this->ws = $ws;
2220 $this->_out(sprintf('%.3f Tw',$ws * $k));
2223 if($w == 0) {
2224 if ($this->rtl) {
2225 $w = $this->x - $this->lMargin;
2226 } else {
2227 $w = $this->w - $this->rMargin - $this->x;
2230 $s = '';
2231 if(($fill == 1) OR ($border == 1)) {
2232 if($fill == 1) {
2233 $op = ($border == 1) ? 'B' : 'f';
2234 } else {
2235 $op = 'S';
2237 if ($this->rtl) {
2238 $xk = ($this->x - $w) * $k;
2239 } else {
2240 $xk = $this->x * $k;
2242 $s .= sprintf('%.2f %.2f %.2f %.2f re %s ', $xk, ($this->h - $this->y) * $k, $w * $k, -$h * $k, $op);
2244 if(is_string($border)) {
2245 $x=$this->x;
2246 $y=$this->y;
2247 if(strpos($border,'L')!==false) {
2248 if ($this->rtl) {
2249 $xk = ($x - $w) * $k;
2250 } else {
2251 $xk = $x * $k;
2253 $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$xk,($this->h-$y)*$k,$xk,($this->h-($y+$h))*$k);
2255 if(strpos($border,'T')!==false) {
2256 if ($this->rtl) {
2257 $xk = ($x - $w) * $k;
2258 $xwk = $x * $k;
2259 } else {
2260 $xk = $x * $k;
2261 $xwk = ($x + $w) * $k;
2263 $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$xk,($this->h-$y)*$k,$xwk,($this->h-$y)*$k);
2265 if(strpos($border,'R')!==false) {
2266 if ($this->rtl) {
2267 $xk = $x * $k;
2268 } else {
2269 $xk = ($x + $w) * $k;
2271 $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$xk,($this->h-$y)*$k,$xk,($this->h-($y+$h))*$k);
2273 if(strpos($border,'B')!==false) {
2274 if ($this->rtl) {
2275 $xk = ($x - $w) * $k;
2276 $xwk = $x * $k;
2277 } else {
2278 $xk = $x * $k;
2279 $xwk = ($x + $w) * $k;
2281 $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$xk,($this->h-($y+$h))*$k,$xwk,($this->h-($y+$h))*$k);
2284 if($txt != '') {
2285 // text lenght
2286 $width = $this->GetStringWidth($txt);
2287 // ratio between cell lenght and text lenght
2288 $ratio = ($w - (2 * $this->cMargin)) / $width;
2290 // stretch text if requested
2291 if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) {
2292 if ($stretch > 2) {
2293 // spacing
2294 //Calculate character spacing in points
2295 $char_space = ($w - (2 * $this->cMargin) - $width) / max($this->GetNumChars($s)-1,1) * $this->k;
2296 //Set character spacing
2297 $this->_out(sprintf('BT %.2f Tc ET', $char_space));
2298 } else {
2299 // scaling
2300 //Calculate horizontal scaling
2301 $horiz_scale = $ratio*100.0;
2302 //Set horizontal scaling
2303 $this->_out(sprintf('BT %.2f Tz ET', $horiz_scale));
2305 $align = '';
2306 $width = $w - (2 * $this->cMargin);
2307 } else {
2308 $stretch == 0;
2311 if($align == 'L') {
2312 if ($this->rtl) {
2313 $dx = $w - $this->cMargin - $width;
2314 } else {
2315 $dx = $this->cMargin;
2317 } elseif($align == 'R') {
2318 if ($this->rtl) {
2319 $dx = $this->cMargin;
2320 } else {
2321 $dx = $w - $this->cMargin - $width;
2323 } elseif($align=='C') {
2324 $dx = ($w - $width)/2;
2325 } elseif($align=='J') {
2326 if ($this->rtl) {
2327 $dx = $w - $this->cMargin - $width;
2328 } else {
2329 $dx = $this->cMargin;
2331 } else {
2332 $dx = $this->cMargin;
2334 if($this->ColorFlag) {
2335 $s .= 'q '.$this->TextColor.' ';
2337 $txt2 = $this->_escapetext($txt);
2338 if ($this->rtl) {
2339 $xdk = ($this->x - $dx - $width) * $k;
2340 } else {
2341 $xdk = ($this->x + $dx) * $k;
2343 // 2008-02-16 Jacek Czekaj - multibyte justification
2344 if ($align == 'J') {
2345 // count number of spaces
2346 $ns = substr_count($txt, ' ');
2347 // get string width without spaces
2348 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
2349 // set word position to be used with TJ operator
2350 $txt2 = str_replace(chr(0).' ', ') '. -2830*($w-$width-2)/($ns?$ns:1)/$this->FontSize/$this->k . ' (', $txt2);
2352 $s.=sprintf('BT %.2f %.2f Td [(%s)] TJ ET', $xdk, ($this->h - ($this->y + 0.5 * $h + 0.3 * $this->FontSize)) * $k, $txt2);
2353 //$s.=sprintf('BT %.2f %.2f Td (%s) Tj ET', $xdk, ($this->h - ($this->y + 0.5 * $h + 0.3 * $this->FontSize)) * $k, $txt2);
2354 if($this->underline) {
2355 if ($this->rtl) {
2356 $xdx = $this->x - $dx - $width;
2357 } else {
2358 $xdx = $this->x + $dx;
2360 $s.=' '.$this->_dounderline($xdx, $this->y + 0.5 * $h + 0.3 * $this->FontSize, $txt);
2362 if($this->ColorFlag) {
2363 $s.=' Q';
2365 if($link) {
2366 if ($this->rtl) {
2367 $xdx = $this->x - $dx - $width;
2368 } else {
2369 $xdx = $this->x + $dx;
2371 $this->Link($xdx, $this->y + 0.5 * $h - 0.5 * $this->FontSize, $width, $this->FontSize, $link);
2375 // output cell
2376 if($s) {
2377 // output cell
2378 $this->_out($s);
2379 // reset text stretching
2380 if($stretch > 2) {
2381 //Reset character horizontal spacing
2382 $this->_out('BT 0 Tc ET');
2383 } elseif($stretch > 0) {
2384 //Reset character horizontal scaling
2385 $this->_out('BT 100 Tz ET');
2389 $this->lasth = $h;
2390 if($ln>0) {
2391 //Go to the beginning of the next line
2392 $this->y += $h;
2393 if($ln == 1) {
2394 if ($this->rtl) {
2395 $this->x = $this->w - $this->rMargin;
2396 } else {
2397 $this->x = $this->lMargin;
2400 } else {
2401 // go left or right by case
2402 if ($this->rtl) {
2403 $this->x -= $w;
2404 } else {
2405 $this->x += $w;
2411 * This method allows printing text with line breaks. They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other.<br />
2412 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
2413 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
2414 * @param float $h Height of cells.
2415 * @param string $txt String to print
2416 * @param mixed $border Indicates if borders must be drawn around the cell block. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
2417 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value)</li></ul>
2418 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2419 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul>
2420 * @return int number of cells (number of lines)
2421 * @since 1.3
2422 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
2424 public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1) {
2426 // save current position
2427 $prevx = $this->x;
2428 $prevy = $this->y;
2430 // get current page number
2431 $startpage = $this->page;
2433 // calculate remaining vertical space on first page ($startpage)
2434 $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin();
2436 //Output text with automatic or explicit line breaks
2437 $cw = &$this->CurrentFont['cw'];
2439 if($w == 0) {
2440 if ($this->rtl) {
2441 $w = $this->x - $this->lMargin;
2442 } else {
2443 $w = $this->w - $this->rMargin - $this->x;
2447 $wmax = ($w - 2 * $this->cMargin);
2449 $s = str_replace("\r", '', $txt); // remove carriage returns
2450 $nb = strlen($s);
2452 $sep=-1;
2453 $i=0;
2454 $j=0;
2455 $l=0;
2456 $ns=0;
2457 $nl=1;
2458 while($i < $nb) {
2459 //Get next character
2460 $c = $s{$i};
2461 if(preg_match("/[\n]/u", $c)) {
2462 //Explicit line break
2463 if($this->ws > 0) {
2464 $this->ws = 0;
2465 $this->_out('0 Tw');
2467 $this->Cell($w, $h, substr($s, $j, $i-$j), 0, 2, $align, $fill, '');
2468 $i++;
2469 $sep=-1;
2470 $j=$i;
2471 $l=0;
2472 $ns=0;
2473 $nl++;
2474 continue;
2476 if(preg_match("/[ ]/u", $c)) {
2477 $sep = $i;
2478 $ls = $l;
2479 $ns++;
2482 $l = $this->GetStringWidth(substr($s, $j, $i-$j));
2484 if($l > $wmax) {
2485 //Automatic line break
2486 if($sep == -1) {
2487 if($i == $j) {
2488 $i++;
2490 if($this->ws > 0) {
2491 $this->ws = 0;
2492 $this->_out('0 Tw');
2494 $this->Cell($w, $h, substr($s, $j, $i-$j), 0, 2, $align, $fill, '');
2496 else {
2497 if($align=='J') {
2498 $this->ws = ($ns>1) ? ($wmax-$ls)/1000*$this->FontSize/($ns-1) : 0;
2499 $this->_out(sprintf('%.3f Tw', $this->ws * $this->k));
2501 $this->Cell($w, $h, substr($s, $j, $sep-$j), 0, 2, $align, $fill, '');
2502 $i = $sep + 1;
2504 $sep=-1;
2505 $j=$i;
2506 $l=0;
2507 $ns=0;
2508 $nl++;
2510 else {
2511 $i++;
2514 //Last chunk
2515 if($this->ws>0) {
2516 $this->ws=0;
2517 $this->_out('0 Tw');
2519 if($align == "J") {
2520 $align = "L";
2522 $this->Cell($w, $h, substr($s, $j, $i-$j), 0, 2, $align, $fill, '');
2524 // Get end-of-text Y position
2525 $currentY = $this->GetY();
2526 // get latest page number
2527 $endpage = $this->page;
2529 if (!empty($border)) {
2530 // check if a new page has been created
2531 if ($endpage > $startpage) {
2532 // design borders around HTML cells.
2533 for ($page=$startpage; $page<=$endpage; $page++) {
2534 $this->page = $page;
2535 if ($page==$startpage) {
2536 $this->y = $this->getPageHeight() - $restspace - $this->getBreakMargin();
2537 $h = $restspace - 1;
2538 } elseif ($page==$endpage) {
2539 $this->y = $this->tMargin; // put cursor at the beginning of text
2540 $h = $currentY - $this->tMargin;
2541 } else {
2542 $this->y = $this->tMargin; // put cursor at the beginning of text
2543 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
2545 $this->Cell($w, $h, "", $border, 1, '', 0);
2547 } else {
2548 $h = max($h, ($currentY - $prevy));
2549 $this->y = $prevy; // put cursor at the beginning of text
2550 // design a cell around the text
2551 $this->Cell($w, $h, "", $border, 1, '', 0);
2555 // move cursor to specified position
2556 if($ln>0) {
2557 //Go to the beginning of the next line
2558 $this->SetY($currentY);
2559 if($ln == 2) {
2560 $this->SetX($prevx + $w);
2562 } else {
2563 // go left or right by case
2564 $this->page = $startpage;
2565 $this->y = $prevy;
2566 $this->SetX($prevx + $w);
2569 return $nl;
2573 * This method prints text from the current position. When the right margin is reached (or the \n character is met) a line break occurs and text continues from the left margin. Upon method exit, the current position is left just at the end of the text. It is possible to put a link on the text.<br />
2574 * <b>Example:</b><br />
2575 * <pre>
2576 * //Begin with regular font
2577 * $pdf->SetFont('Arial','',14);
2578 * $pdf->Write(5,'Visit ');
2579 * //Then put a blue underlined link
2580 * $pdf->SetTextColor(0,0,255);
2581 * $pdf->SetFont('','U');
2582 * $pdf->Write(5,'www.tecnick.com','http://www.tecnick.com');
2583 * </pre>
2584 * @param float $h Line height
2585 * @param string $txt String to print
2586 * @param mixed $link URL or identifier returned by AddLink()
2587 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
2588 * @since 1.5
2589 * @see SetFont(), SetTextColor(), AddLink(), MultiCell(), SetAutoPageBreak()
2591 public function Write($h, $txt, $link='', $fill=0) {
2592 //Output text in flowing mode
2593 $cw = &$this->CurrentFont['cw'];
2594 // calculating remaining line width ($w)
2595 if ($this->rtl) {
2596 $w = $this->x - $this->lMargin;
2597 } else {
2598 $w = $this->w - $this->rMargin - $this->x;
2600 $wmax = $w - 2 * $this->cMargin;
2601 $s = str_replace("\r", '', $txt);
2602 $nb = strlen($s);
2603 // handle single space character
2604 if(($nb==1) AND preg_match("/[ ]/u", $s)) {
2605 if ($this->rtl) {
2606 $this->x -= $this->GetStringWidth($s);
2607 } else {
2608 $this->x += $this->GetStringWidth($s);
2610 return;
2612 $sep=-1;
2613 $i=0;
2614 $j=0;
2615 $l=0;
2616 $nl=1;
2617 while($i<$nb) {
2618 //Get next character
2619 $c=$s{$i};
2620 if(preg_match("/[\n]/u", $c)) {
2621 //Explicit line break
2622 $this->Cell($w, $h, substr($s, $j, $i-$j), 0, 2, '', $fill, $link);
2623 $i++;
2624 $sep = -1;
2625 $j = $i;
2626 $l = 0;
2627 if($nl == 1) {
2628 if ($this->rtl) {
2629 $this->x = $this->w - $this->rMargin;
2630 $w = $this->x - $this->lMargin;
2632 else {
2633 $this->x = $this->lMargin;
2634 $w = $this->w - $this->rMargin - $this->x;
2636 $wmax = ($w - 2 * $this->cMargin);
2638 $nl++;
2639 continue;
2641 if(preg_match("/[ ]/u", $c)) {
2642 $sep= $i;
2644 $l = $this->GetStringWidth(substr($s, $j, $i-$j));
2645 if($l > $wmax) {
2646 //Automatic line break (word wrapping)
2647 if($sep == -1) {
2648 if((!$this->rtl) AND ($this->x > $this->lMargin)) {
2649 //Move to next line
2650 $this->x = $this->lMargin;
2651 $this->y += $h;
2652 $w=$this->w - $this->rMargin - $this->x;
2653 $wmax=($w - 2 * $this->cMargin);
2654 $i++;
2655 $nl++;
2656 continue;
2658 if($this->rtl AND ($this->x < $this->rMargin)) {
2659 //Move to next line
2660 $this->x = $this->w - $this->rMargin;
2661 $this->y += $h;
2662 $w=$this->x - $this->lMargin;
2663 $wmax=($w - 2 * $this->cMargin);
2664 $i++;
2665 $nl++;
2666 continue;
2668 if($i==$j) {
2669 $i++;
2671 $this->Cell($w, $h, substr($s, $j, $i-$j), 0, 2, '', $fill, $link);
2673 else {
2674 $this->Cell($w, $h, substr($s, $j, $sep-$j), 0, 2, '', $fill, $link);
2675 $i=$sep+1;
2677 $sep = -1;
2678 $j = $i;
2679 $l = 0;
2680 if($nl==1) {
2681 if ($this->rtl) {
2682 $this->x = $this->w - $this->rMargin;
2683 $w = $this->x - $this->lMargin;
2684 } else {
2685 $this->x = $this->lMargin;
2686 $w = $this->w - $this->rMargin - $this->x;
2688 $wmax = ($w - 2 * $this->cMargin);
2690 $nl++;
2692 else {
2693 $i++;
2697 //Last chunk
2698 if($i!=$j) {
2699 $this->Cell($this->GetStringWidth(substr($s, $j)) + 2 * $this->cMargin, $h, substr($s, $j), 0, 0, '', $fill, $link);
2704 * Puts an image in the page. The upper-left corner must be given. The dimensions can be specified in different ways:<ul><li>explicit width and height (expressed in user unit)</li><li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li><li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
2705 * Supported formats are JPEG and PNG.
2706 * For JPEG, all flavors are allowed:<ul><li>gray scales</li><li>true colors (24 bits)</li><li>CMYK (32 bits)</li></ul>
2707 * For PNG, are allowed:<ul><li>gray scales on at most 8 bits (256 levels)</li><li>indexed colors</li><li>true colors (24 bits)</li></ul>
2708 * If a transparent color is defined, it will be taken into account (but will be only interpreted by Acrobat 4 and above).<br />
2709 * The format can be specified explicitly or inferred from the file extension.<br />
2710 * It is possible to put a link on the image.<br />
2711 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
2712 * @param string $file Name of the file containing the image.
2713 * @param float $x Abscissa of the upper-left corner.
2714 * @param float $y Ordinate of the upper-left corner.
2715 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
2716 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
2717 * @param string $type Image format. Possible values are (case insensitive): JPG, JPEG, PNG. If not specified, the type is inferred from the file extension.
2718 * @param mixed $link URL or identifier returned by AddLink().
2719 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
2720 * @since 1.1
2721 * @see AddLink()
2723 public function Image($file, $x, $y, $w=0, $h=0, $type='', $link='', $align='') {
2724 //Put an image on the page
2725 if(!isset($this->images[$file])) {
2726 //First use of image, get info
2727 if($type == '') {
2728 $pos = strrpos($file,'.');
2729 if(empty($pos)) {
2730 $this->Error('Image file has no extension and no type was specified: '.$file);
2732 $type = substr($file, $pos+1);
2734 $type = strtolower($type);
2735 $mqr = get_magic_quotes_runtime();
2736 set_magic_quotes_runtime(0);
2737 if($type == 'jpg' or $type == 'jpeg') {
2738 $info=$this->_parsejpg($file);
2739 } elseif($type == 'gif') {
2740 $info=$this->_parsegif($file);
2741 } elseif($type == 'png') {
2742 $info=$this->_parsepng($file);
2743 }else {
2744 //Allow for additional formats
2745 $mtd='_parse'.$type;
2746 if(!method_exists($this,$mtd)) {
2747 $this->Error('Unsupported image type: '.$type);
2749 $info=$this->$mtd($file);
2751 if($info === false) {
2752 //If false, we cannot process image
2753 return;
2755 set_magic_quotes_runtime($mqr);
2756 $info['i']=count($this->images)+1;
2757 $this->images[$file]=$info;
2759 else {
2760 $info=$this->images[$file];
2762 //Automatic width and height calculation if needed
2763 if(($w == 0) and ($h == 0)) {
2764 //Put image at 72 dpi
2765 // 2004-06-14 :: Nicola Asuni, scale factor where added
2766 $w = $info['w'] / ($this->imgscale * $this->k);
2767 $h = $info['h'] / ($this->imgscale * $this->k);
2769 if($w == 0) {
2770 $w = $h * $info['w'] / $info['h'];
2772 if($h == 0) {
2773 $h = $w * $info['h'] / $info['w'];
2776 // 2007-10-19 Warren Sherliker
2777 // Check whether we need a new page first as this does not fit
2778 // Copied from Cell()
2779 if((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
2780 // Automatic page break
2781 $this->AddPage($this->CurOrientation);
2782 // Reset coordinates to top fo next page
2783 $x = $this->GetX();
2784 $y = $this->GetY();
2786 // 2007-10-19 Warren Sherliker: End Edit
2788 // set bottomcoordinates
2789 $this->img_rb_y = $y + $h;
2790 if ($this->rtl) {
2791 $ximg = ($this->w - $x -$w);
2792 // set left side coordinate
2793 $this->img_rb_x = $ximg;
2794 } else {
2795 $ximg = $x;
2796 // set right side coordinate
2797 $this->img_rb_x = $ximg + $w;
2799 $xkimg = $ximg * $this->k;
2800 $this->_out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q', $w*$this->k, $h*$this->k, $xkimg, ($this->h-($y+$h))*$this->k, $info['i']));
2802 if($link) {
2803 $this->Link($ximg, $y, $w, $h, $link);
2806 // set pointer to align the successive text/objects
2807 switch($align) {
2808 case 'T':{
2809 $this->y = $y;
2810 $this->x = $this->img_rb_x;
2811 break;
2813 case 'M':{
2814 $this->y = $y + round($h/2);
2815 $this->x = $this->img_rb_x;
2816 break;
2818 case 'B':{
2819 $this->y = $this->img_rb_y;
2820 $this->x = $this->img_rb_x;
2821 break;
2823 case 'N':{
2824 $this->SetY($this->img_rb_y);
2825 break;
2827 default:{
2828 break;
2835 * Performs a line break. The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
2836 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
2837 * @since 1.0
2838 * @see Cell()
2840 public function Ln($h='') {
2841 //Line feed; default value is last cell height
2842 if ($this->rtl) {
2843 $this->x = $this->w - $this->rMargin;
2844 } else {
2845 $this->x = $this->lMargin;
2847 if(is_string($h)) {
2848 $this->y += $this->lasth;
2849 } else {
2850 $this->y += $h;
2855 * Returns the relative X value of current position.
2856 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
2857 * @return float
2858 * @since 1.2
2859 * @see SetX(), GetY(), SetY()
2861 public function GetX() {
2862 //Get x position
2863 if ($this->rtl) {
2864 return ($this->w - $this->x);
2865 } else {
2866 return $this->x;
2871 * Returns the absolute X value of current position.
2872 * @return float
2873 * @since 1.2
2874 * @see SetX(), GetY(), SetY()
2876 public function GetAbsX() {
2877 return $this->x;
2881 * Returns the ordinate of the current position.
2882 * @return float
2883 * @since 1.0
2884 * @see SetY(), GetX(), SetX()
2886 public function GetY() {
2887 //Get y position
2888 return $this->y;
2892 * Defines the abscissa of the current position.
2893 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
2894 * @param float $x The value of the abscissa.
2895 * @since 1.2
2896 * @see GetX(), GetY(), SetY(), SetXY()
2898 public function SetX($x) {
2899 //Set x position
2900 if ($this->rtl) {
2901 if($x >= 0) {
2902 $this->x = $this->w - $x;
2903 } else {
2904 $this->x = abs($x);
2906 } else {
2907 if($x >= 0) {
2908 $this->x = $x;
2909 } else {
2910 $this->x = $this->w + $x;
2916 * Moves the current abscissa back to the left margin and sets the ordinate.
2917 * If the passed value is negative, it is relative to the bottom of the page.
2918 * @param float $y The value of the ordinate.
2919 * @since 1.0
2920 * @see GetX(), GetY(), SetY(), SetXY()
2922 public function SetY($y) {
2923 //Set y position and reset x
2924 if ($this->rtl) {
2925 $this->x = $this->w - $this->rMargin;
2926 } else {
2927 $this->x = $this->lMargin;
2929 if($y >= 0) {
2930 $this->y = $y;
2931 } else {
2932 $this->y = $this->h + $y;
2938 * Defines the abscissa and ordinate of the current position. If the passed values are negative, they are relative respectively to the right and bottom of the page.
2939 * @param float $x The value of the abscissa
2940 * @param float $y The value of the ordinate
2941 * @since 1.2
2942 * @see SetX(), SetY()
2944 public function SetXY($x, $y) {
2945 //Set x and y positions
2946 $this->SetY($y);
2947 $this->SetX($x);
2951 * Send the document to a given destination: string, local file or browser. In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
2952 * The method first calls Close() if necessary to terminate the document.
2953 * @param string $name The name of the file. If not given, the document will be sent to the browser (destination I) with the name doc.pdf.
2954 * @param string $dest Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser. The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local file with the name given by name.</li><li>S: return the document as a string. name is ignored.</li></ul>If the parameter is not specified but a name is given, destination is F. If no parameter is specified at all, destination is I.<br />Note: for compatibility with previous versions, a boolean value is also accepted (false for F and true for D).
2955 * @since 1.0
2956 * @see Close()
2958 public function Output($name='',$dest='') {
2959 //Output PDF to some destination
2960 //Finish document if necessary
2961 if($this->state < 3) {
2962 $this->Close();
2964 //Normalize parameters
2965 if(is_bool($dest)) {
2966 $dest=$dest ? 'D' : 'F';
2968 $dest=strtoupper($dest);
2969 if($dest=='') {
2970 if($name=='') {
2971 $name='doc.pdf';
2972 $dest='I';
2973 } else {
2974 $dest='F';
2977 switch($dest) {
2978 case 'I': {
2979 //Send to standard output
2980 if(ob_get_contents()) {
2981 $this->Error('Some data has already been output, can\'t send PDF file');
2984 if(php_sapi_name()!='cli') {
2985 //We send to a browser
2986 header('Content-Type: application/pdf');
2987 if(headers_sent()) {
2988 $this->Error('Some data has already been output to browser, can\'t send PDF file');
2990 header('Content-Length: '.strlen($this->buffer));
2991 header('Content-disposition: inline; filename="'.$name.'"');
2993 echo $this->buffer;
2994 break;
2996 case 'D': {
2997 //Download file
2998 if(ob_get_contents()) {
2999 $this->Error('Some data has already been output, can\'t send PDF file');
3002 if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) {
3003 header('Content-Type: application/force-download');
3004 } else {
3005 header('Content-Type: application/octet-stream');
3007 if(headers_sent()) {
3008 $this->Error('Some data has already been output to browser, can\'t send PDF file');
3010 header('Content-Type: application/pdf');
3011 header('Content-Length: '.strlen($this->buffer));
3012 header('Content-disposition: attachment; filename="'.$name.'"');
3013 echo $this->buffer;
3014 break;
3016 case 'F': {
3017 //Save to local file
3018 $f=fopen($name,'wb');
3019 if(!$f) {
3020 $this->Error('Unable to create output file: '.$name);
3022 fwrite($f,$this->buffer,strlen($this->buffer));
3023 fclose($f);
3024 break;
3026 case 'S': {
3027 //Return as a string
3028 return $this->buffer;
3030 default: {
3031 $this->Error('Incorrect output destination: '.$dest);
3034 return '';
3037 // Protected methods
3040 * Check for locale-related bug
3041 * @access protected
3043 protected function _dochecks() {
3044 //Check for locale-related bug
3045 if(1.1==1) {
3046 $this->Error('Don\'t alter the locale before including class file');
3048 //Check for decimal separator
3049 if(sprintf('%.1f',1.0)!='1.0') {
3050 setlocale(LC_NUMERIC,'C');
3055 * Return fonts path
3056 * @access protected
3058 protected function _getfontpath() {
3059 if(!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/font')) {
3060 define('K_PATH_FONTS', dirname(__FILE__).'/font/');
3062 return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
3066 * Start document
3067 * @access protected
3069 protected function _begindoc() {
3070 //Start document
3071 $this->state=1;
3072 $this->_out('%PDF-'.$this->PDFVersion);
3076 * _putpages
3077 * @access protected
3079 protected function _putpages() {
3080 $nb = $this->page;
3081 if(!empty($this->AliasNbPages)) {
3082 $nbstr = $this->UTF8ToUTF16BE($nb, false);
3083 //Replace number of pages
3084 for($n=1;$n<=$nb;$n++) {
3085 $this->pages[$n]=str_replace($this->AliasNbPages, $nbstr, $this->pages[$n]);
3088 if($this->DefOrientation=='P') {
3089 $wPt=$this->fwPt;
3090 $hPt=$this->fhPt;
3092 else {
3093 $wPt=$this->fhPt;
3094 $hPt=$this->fwPt;
3096 $filter=($this->compress) ? '/Filter /FlateDecode ' : '';
3097 for($n=1;$n<=$nb;$n++) {
3098 //Page
3099 $this->_newobj();
3100 $this->_out('<</Type /Page');
3101 $this->_out('/Parent 1 0 R');
3102 if(isset($this->OrientationChanges[$n])) {
3103 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$hPt,$wPt));
3105 $this->_out('/Resources 2 0 R');
3106 if(isset($this->PageLinks[$n])) {
3107 //Links
3108 $annots='/Annots [';
3109 foreach($this->PageLinks[$n] as $pl) {
3110 $rect=sprintf('%.2f %.2f %.2f %.2f',$pl[0],$pl[1],$pl[0]+$pl[2],$pl[1]-$pl[3]);
3111 $annots.='<</Type /Annot /Subtype /Link /Rect ['.$rect.'] /Border [0 0 0] ';
3112 if(is_string($pl[4])) {
3113 $annots.='/A <</S /URI /URI '.$this->_uristring($pl[4]).'>>>>';
3115 else {
3116 $l=$this->links[$pl[4]];
3117 $h=isset($this->OrientationChanges[$l[0]]) ? $wPt : $hPt;
3118 $annots.=sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]>>',1+2*$l[0],$h-$l[1]*$this->k);
3121 $this->_out($annots.']');
3123 $this->_out('/Contents '.($this->n+1).' 0 R>>');
3124 $this->_out('endobj');
3125 //Page content
3126 $p=($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n];
3127 $this->_newobj();
3128 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
3129 $this->_putstream($p);
3130 $this->_out('endobj');
3132 //Pages root
3133 $this->offsets[1]=strlen($this->buffer);
3134 $this->_out('1 0 obj');
3135 $this->_out('<</Type /Pages');
3136 $kids='/Kids [';
3137 for($i=0;$i<$nb;$i++) {
3138 $kids.=(3+2*$i).' 0 R ';
3140 $this->_out($kids.']');
3141 $this->_out('/Count '.$nb);
3142 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$wPt,$hPt));
3143 $this->_out('>>');
3144 $this->_out('endobj');
3148 * Adds fonts
3149 * _putfonts
3150 * @access protected
3152 protected function _putfonts() {
3153 $nf=$this->n;
3154 foreach($this->diffs as $diff) {
3155 //Encodings
3156 $this->_newobj();
3157 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
3158 $this->_out('endobj');
3160 $mqr=get_magic_quotes_runtime();
3161 set_magic_quotes_runtime(0);
3162 foreach($this->FontFiles as $file=>$info) {
3163 //Font file embedding
3164 $this->_newobj();
3165 $this->FontFiles[$file]['n']=$this->n;
3166 $font='';
3167 $f=fopen($this->_getfontpath().strtolower($file),'rb',1);
3168 if(!$f) {
3169 $this->Error('Font file not found: '.$file);
3171 while(!feof($f)) {
3172 $font .= fread($f, 8192);
3174 fclose($f);
3175 $compressed=(substr($file,-2)=='.z');
3176 if(!$compressed && isset($info['length2'])) {
3177 $header=(ord($font{0})==128);
3178 if($header) {
3179 //Strip first binary header
3180 $font=substr($font,6);
3182 if($header && ord($font{$info['length1']})==128) {
3183 //Strip second binary header
3184 $font=substr($font,0,$info['length1']).substr($font,$info['length1']+6);
3187 $this->_out('<</Length '.strlen($font));
3188 if($compressed) {
3189 $this->_out('/Filter /FlateDecode');
3191 $this->_out('/Length1 '.$info['length1']);
3192 if(isset($info['length2'])) {
3193 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
3195 $this->_out('>>');
3196 $this->_putstream($font);
3197 $this->_out('endobj');
3199 set_magic_quotes_runtime($mqr);
3200 foreach($this->fonts as $k=>$font) {
3201 //Font objects
3202 $this->fonts[$k]['n']=$this->n+1;
3203 $type=$font['type'];
3204 $name=$font['name'];
3205 if($type=='core') {
3206 //Standard font
3207 $this->_newobj();
3208 $this->_out('<</Type /Font');
3209 $this->_out('/BaseFont /'.$name);
3210 $this->_out('/Subtype /Type1');
3211 if($name!='Symbol' && $name!='ZapfDingbats') {
3212 $this->_out('/Encoding /WinAnsiEncoding');
3214 $this->_out('>>');
3215 $this->_out('endobj');
3216 } elseif($type=='Type1' OR $type=='TrueType') {
3217 //Additional Type1 or TrueType font
3218 $this->_newobj();
3219 $this->_out('<</Type /Font');
3220 $this->_out('/BaseFont /'.$name);
3221 $this->_out('/Subtype /'.$type);
3222 $this->_out('/FirstChar 32 /LastChar 255');
3223 $this->_out('/Widths '.($this->n+1).' 0 R');
3224 $this->_out('/FontDescriptor '.($this->n+2).' 0 R');
3225 if($font['enc']) {
3226 if(isset($font['diff'])) {
3227 $this->_out('/Encoding '.($nf+$font['diff']).' 0 R');
3228 } else {
3229 $this->_out('/Encoding /WinAnsiEncoding');
3232 $this->_out('>>');
3233 $this->_out('endobj');
3234 //Widths
3235 $this->_newobj();
3236 $cw=&$font['cw'];
3237 $s='[';
3238 for($i=32;$i<=255;$i++) {
3239 $s.=$cw[chr($i)].' ';
3241 $this->_out($s.']');
3242 $this->_out('endobj');
3243 //Descriptor
3244 $this->_newobj();
3245 $s='<</Type /FontDescriptor /FontName /'.$name;
3246 foreach($font['desc'] as $k=>$v) {
3247 $s.=' /'.$k.' '.$v;
3249 $file = $font['file'];
3250 if($file) {
3251 $s.=' /FontFile'.($type=='Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
3253 $this->_out($s.'>>');
3254 $this->_out('endobj');
3255 } else {
3256 //Allow for additional types
3257 $mtd='_put'.strtolower($type);
3258 if(!method_exists($this, $mtd)) {
3259 $this->Error('Unsupported font type: '.$type);
3261 $this->$mtd($font);
3267 * _putimages
3268 * @access protected
3270 protected function _putimages() {
3271 $filter=($this->compress) ? '/Filter /FlateDecode ' : '';
3272 reset($this->images);
3273 while(list($file,$info)=each($this->images)) {
3274 $this->_newobj();
3275 $this->images[$file]['n']=$this->n;
3276 $this->_out('<</Type /XObject');
3277 $this->_out('/Subtype /Image');
3278 $this->_out('/Width '.$info['w']);
3279 $this->_out('/Height '.$info['h']);
3281 if (isset($info["masked"])) {
3282 $this->_out('/SMask '.($this->n-1).' 0 R');
3285 if($info['cs']=='Indexed') {
3286 $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal'])/3-1).' '.($this->n+1).' 0 R]');
3288 else {
3289 $this->_out('/ColorSpace /'.$info['cs']);
3290 if($info['cs']=='DeviceCMYK') {
3291 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
3294 $this->_out('/BitsPerComponent '.$info['bpc']);
3295 if(isset($info['f'])) {
3296 $this->_out('/Filter /'.$info['f']);
3298 if(isset($info['parms'])) {
3299 $this->_out($info['parms']);
3301 if(isset($info['trns']) and is_array($info['trns'])) {
3302 $trns='';
3303 for($i=0;$i<count($info['trns']);$i++) {
3304 $trns.=$info['trns'][$i].' '.$info['trns'][$i].' ';
3306 $this->_out('/Mask ['.$trns.']');
3308 $this->_out('/Length '.strlen($info['data']).'>>');
3309 $this->_putstream($info['data']);
3310 unset($this->images[$file]['data']);
3311 $this->_out('endobj');
3312 //Palette
3313 if($info['cs']=='Indexed') {
3314 $this->_newobj();
3315 $pal=($this->compress) ? gzcompress($info['pal']) : $info['pal'];
3316 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
3317 $this->_putstream($pal);
3318 $this->_out('endobj');
3324 * _putxobjectdict
3325 * @access protected
3327 function _putxobjectdict() {
3328 foreach($this->images as $image) {
3329 $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
3334 * _putresourcedict
3335 * @access protected
3337 function _putresourcedict(){
3338 $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
3339 $this->_out('/Font <<');
3340 foreach($this->fonts as $font) {
3341 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
3343 $this->_out('>>');
3344 $this->_out('/XObject <<');
3345 $this->_putxobjectdict();
3346 $this->_out('>>');
3350 * _putresources
3351 * @access protected
3353 function _putresources() {
3354 $this->_putfonts();
3355 $this->_putimages();
3356 //Resource dictionary
3357 $this->offsets[2]=strlen($this->buffer);
3358 $this->_out('2 0 obj');
3359 $this->_out('<<');
3360 $this->_putresourcedict();
3361 $this->_out('>>');
3362 $this->_out('endobj');
3363 $this->_putjavascript();
3364 $this->_putbookmarks();
3365 // encryption
3366 if ($this->encrypted) {
3367 $this->_newobj();
3368 $this->enc_obj_id = $this->n;
3369 $this->_out('<<');
3370 $this->_putencryption();
3371 $this->_out('>>');
3372 $this->_out('endobj');
3377 * _putinfo
3378 * Adds some meta information
3379 * @access protected
3381 protected function _putinfo() {
3382 $this->_out('/CreationDate ('.$this->_escape('D:'.date('YmdHis')).')');
3383 $this->_out('/ModDate ('.$this->_escape('D:'.date('YmdHis')).')');
3384 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
3385 if(!empty($this->title)) {
3386 $this->_out('/Title '.$this->_textstring($this->title));
3388 if(!empty($this->subject)) {
3389 $this->_out('/Subject '.$this->_textstring($this->subject));
3391 if(!empty($this->author)) {
3392 $this->_out('/Author '.$this->_textstring($this->author));
3394 if(!empty($this->keywords)) {
3395 $this->_out('/Keywords '.$this->_textstring($this->keywords));
3397 if(!empty($this->creator)) {
3398 $this->_out('/Creator '.$this->_textstring($this->creator));
3403 * _putcatalog
3404 * @access protected
3406 protected function _putcatalog() {
3407 $this->_out('/Type /Catalog');
3408 $this->_out('/Pages 1 0 R');
3409 if($this->ZoomMode=='fullpage') {
3410 $this->_out('/OpenAction [3 0 R /Fit]');
3412 elseif($this->ZoomMode=='fullwidth') {
3413 $this->_out('/OpenAction [3 0 R /FitH null]');
3415 elseif($this->ZoomMode=='real') {
3416 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
3418 elseif(!is_string($this->ZoomMode)) {
3419 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode/100).']');
3421 if($this->LayoutMode=='single') {
3422 $this->_out('/PageLayout /SinglePage');
3424 elseif($this->LayoutMode=='continuous') {
3425 $this->_out('/PageLayout /OneColumn');
3427 elseif($this->LayoutMode=='two') {
3428 $this->_out('/PageLayout /TwoColumnLeft');
3430 if (!empty($this->javascript)) {
3431 $this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
3433 if(count($this->outlines)>0) {
3434 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
3435 $this->_out('/PageMode /UseOutlines');
3437 if($this->rtl) {
3438 $this->_out('/ViewerPreferences << /Direction /R2L >>');
3443 * _puttrailer
3444 * @access protected
3446 protected function _puttrailer() {
3447 $this->_out('/Size '.($this->n+1));
3448 $this->_out('/Root '.$this->n.' 0 R');
3449 $this->_out('/Info '.($this->n-1).' 0 R');
3450 if ($this->encrypted) {
3451 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
3452 $this->_out('/ID [()()]');
3457 * _putheader
3458 * @access protected
3460 function _putheader() {
3461 $this->_out('%PDF-'.$this->PDFVersion);
3465 * _enddoc
3466 * @access protected
3468 protected function _enddoc() {
3469 $this->_putheader();
3470 $this->_putpages();
3471 $this->_putresources();
3472 //Info
3473 $this->_newobj();
3474 $this->_out('<<');
3475 $this->_putinfo();
3476 $this->_out('>>');
3477 $this->_out('endobj');
3478 //Catalog
3479 $this->_newobj();
3480 $this->_out('<<');
3481 $this->_putcatalog();
3482 $this->_out('>>');
3483 $this->_out('endobj');
3484 //Cross-ref
3485 $o=strlen($this->buffer);
3486 $this->_out('xref');
3487 $this->_out('0 '.($this->n+1));
3488 $this->_out('0000000000 65535 f ');
3489 for($i=1;$i<=$this->n;$i++) {
3490 $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i]));
3492 //Trailer
3493 $this->_out('trailer');
3494 $this->_out('<<');
3495 $this->_puttrailer();
3496 $this->_out('>>');
3497 $this->_out('startxref');
3498 $this->_out($o);
3499 $this->_out('%%EOF');
3500 $this->state=3;
3504 * _beginpage
3505 * @access protected
3507 protected function _beginpage($orientation) {
3508 $this->page++;
3509 $this->pages[$this->page]='';
3510 $this->state=2;
3511 if ($this->rtl) {
3512 $this->x = $this->w - $this->rMargin;
3513 } else {
3514 $this->x = $this->lMargin;
3516 $this->y = $this->tMargin;
3517 $this->FontFamily='';
3518 //Page orientation
3519 if(empty($orientation)) {
3520 $orientation=$this->DefOrientation;
3522 else {
3523 $orientation=strtoupper($orientation{0});
3524 if($orientation!=$this->DefOrientation) {
3525 $this->OrientationChanges[$this->page]=true;
3528 if($orientation!=$this->CurOrientation) {
3529 //Change orientation
3530 if($orientation=='P') {
3531 $this->wPt=$this->fwPt;
3532 $this->hPt=$this->fhPt;
3533 $this->w=$this->fw;
3534 $this->h=$this->fh;
3536 else {
3537 $this->wPt=$this->fhPt;
3538 $this->hPt=$this->fwPt;
3539 $this->w=$this->fh;
3540 $this->h=$this->fw;
3542 $this->PageBreakTrigger=$this->h-$this->bMargin;
3543 $this->CurOrientation=$orientation;
3548 * End of page contents
3549 * @access protected
3551 protected function _endpage() {
3552 $this->state=1;
3556 * Begin a new object
3557 * @access protected
3559 protected function _newobj() {
3560 $this->n++;
3561 $this->offsets[$this->n]=strlen($this->buffer);
3562 $this->_out($this->n.' 0 obj');
3566 * Underline text
3567 * @param int $x X coordinate
3568 * @param int $y Y coordinate
3569 * @param string $txt text to underline
3570 * @access protected
3572 protected function _dounderline($x, $y, $txt) {
3573 $up = $this->CurrentFont['up'];
3574 $ut = $this->CurrentFont['ut'];
3575 $w = $this->GetStringWidth($txt) + $this->ws * substr_count($txt,' ');
3576 return sprintf('%.2f %.2f %.2f %.2f re f', $x * $this->k, ($this->h - ($y - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
3580 // REWRITTEN by Warren Sherliker wsherliker@gmail.com
3581 // altered to allow compatibility with all sorts of image formats including gif.
3582 // Can easily extend to work with others
3583 // such as gd xbm etc. which are all supported by php 5+
3584 // (Requires GD library)
3587 * Extract info from a JPEG file
3588 * @param string $file image file to parse
3589 * @return string
3590 * @access protected
3592 protected function _parsejpg($file) {
3593 if(!function_exists('imagecreatefromjpeg')) {
3594 // GD is not installed, try legacy method
3595 return $this->_legacyparsejpg($file);
3597 $a=getimagesize($file);
3598 if(empty($a)) {
3599 $this->Error('Missing or incorrect image file: '.$file);
3601 if($a[2]!=2) {
3602 $this->Error('Not a JPEG file: '.$file);
3604 $jpeg = imagecreatefromjpeg($file);
3605 return $this->outputjpg($file, $jpeg);
3609 * Extract info from a GIF file
3610 * @param string $file image file to parse
3611 * @return string
3612 * @access protected
3614 protected function _parsegif($file) {
3615 if(!function_exists('imagecreatefromgif')) {
3616 // PDF doesn't support native GIF and GD is not installed
3617 return false;
3619 $a=getimagesize($file);
3620 if(empty($a)) {
3621 $this->Error('Missing or incorrect image file: '.$file);
3623 if($a[2]!=1) {
3624 $this->Error('Not a GIF file: '.$file);
3626 // Temporary convert file to jpg and then delete this temp data file
3627 $gif = imagecreatefromgif($file);
3628 return $this->toJPEG($file, $gif);
3632 * Extract info from a PNG file
3633 * @param string $file image file to parse
3634 * @return string
3635 * @access protected
3637 protected function _parsepng($file) {
3638 if(!function_exists('imagecreatefrompng')) {
3639 // GD is not installed, try legacy method
3640 return $this->_legacyparsepng($file);
3642 $f=fopen($file,'rb');
3643 if(empty($f)) {
3644 $this->Error('Can\'t open image file: '.$file);
3646 //Check signature
3647 if(fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3648 $this->Error('Not a PNG file: '.$file);
3650 //Read header chunk
3651 fread($f,4);
3652 if(fread($f,4)!='IHDR') {
3653 $this->Error('Incorrect PNG file: '.$file);
3655 // Temporary convert file to jpg and then delete this temp data file
3656 $a=getimagesize($file);
3657 $png = imagecreatefrompng($file);
3658 return $this->toJPEG($file, $png);
3662 * Extract info from a JPEG file without using GD
3663 * @param string $file image file to parse
3664 * @return string
3665 * @access protected
3667 protected function _legacyparsejpg($file) {
3668 $a=GetImageSize($file);
3669 if(empty($a)) {
3670 $this->Error('Missing or incorrect image file: '.$file);
3672 if($a[2]!=2) {
3673 $this->Error('Not a JPEG file: '.$file);
3675 if(!isset($a['channels']) or $a['channels']==3) {
3676 $colspace='DeviceRGB';
3678 elseif($a['channels']==4) {
3679 $colspace='DeviceCMYK';
3681 else {
3682 $colspace='DeviceGray';
3684 $bpc=isset($a['bits']) ? $a['bits'] : 8;
3685 //Read whole file
3686 $f=fopen($file,'rb');
3687 $data='';
3688 while(!feof($f)) {
3689 $data.=fread($f,4096);
3691 fclose($f);
3692 return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data);
3696 * Extract info from a PNG file without using GD
3697 * @param string $file image file to parse
3698 * @return string
3699 * @access protected
3701 protected function _legacyparsepng($file) {
3702 $f=fopen($file,'rb');
3703 if(empty($f)) {
3704 $this->Error('Can\'t open image file: '.$file);
3706 //Check signature
3707 if(fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3708 $this->Error('Not a PNG file: '.$file);
3710 //Read header chunk
3711 fread($f,4);
3712 if(fread($f,4)!='IHDR') {
3713 $this->Error('Incorrect PNG file: '.$file);
3715 $w=$this->_freadint($f);
3716 $h=$this->_freadint($f);
3717 $bpc=ord(fread($f,1));
3718 if($bpc>8) {
3719 $this->Error('16-bit depth not supported: '.$file);
3721 $ct=ord(fread($f,1));
3722 if($ct==0) {
3723 $colspace='DeviceGray';
3725 elseif($ct==2) {
3726 $colspace='DeviceRGB';
3728 elseif($ct==3) {
3729 $colspace='Indexed';
3731 else {
3732 $this->Error('Alpha channel not supported: '.$file);
3734 if(ord(fread($f,1))!=0) {
3735 $this->Error('Unknown compression method: '.$file);
3737 if(ord(fread($f,1))!=0) {
3738 $this->Error('Unknown filter method: '.$file);
3740 if(ord(fread($f,1))!=0) {
3741 $this->Error('Interlacing not supported: '.$file);
3743 fread($f,4);
3744 $parms='/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
3745 //Scan chunks looking for palette, transparency and image data
3746 $pal='';
3747 $trns='';
3748 $data='';
3749 do {
3750 $n=$this->_freadint($f);
3751 $type=fread($f,4);
3752 if($type=='PLTE') {
3753 //Read palette
3754 $pal=fread($f,$n);
3755 fread($f,4);
3757 elseif($type=='tRNS') {
3758 //Read transparency info
3759 $t=fread($f,$n);
3760 if($ct==0) {
3761 $trns=array(ord(substr($t,1,1)));
3763 elseif($ct==2) {
3764 $trns=array(ord(substr($t,1,1)),ord(substr($t,3,1)),ord(substr($t,5,1)));
3766 else {
3767 $pos=strpos($t,chr(0));
3768 if($pos!==false) {
3769 $trns=array($pos);
3772 fread($f,4);
3774 elseif($type=='IDAT') {
3775 //Read image data block
3776 $data.=fread($f,$n);
3777 fread($f,4);
3779 elseif($type=='IEND') {
3780 break;
3782 else {
3783 fread($f,$n+4);
3786 while($n);
3787 if($colspace=='Indexed' and empty($pal)) {
3788 $this->Error('Missing palette in '.$file);
3790 fclose($f);
3791 return array('w'=>$w, 'h'=>$h, 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'FlateDecode', 'parms'=>$parms, 'pal'=>$pal, 'trns'=>$trns, 'data'=>$data);
3795 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
3796 * @param string $file Image file name.
3797 * @param image $image Image object.
3798 * return image JPEG image object.
3799 * @access protected
3801 protected function toJPEG($file, $image) {
3802 if ($image) {
3803 // output
3804 $tempname = tempnam(K_PATH_CACHE,'jpg');
3805 imagejpeg($image, $tempname, 100);
3806 imagedestroy($image);
3807 $retvars = $this->outputjpg($tempname);
3808 // tidy up by removing temporary image
3809 unlink($tempname);
3810 return $retvars;
3811 } else {
3812 $this->Error('Can\'t open image file: '.$file);
3817 * Get a JPEG filename and return a structure for the PDF creator.
3818 * @param string $filename JPEG file name.
3819 * @return array structure containing the image data
3820 * @access protected
3822 protected function outputjpg($filename) {
3823 $a=getimagesize($filename);
3825 if(!isset($a['channels']) or $a['channels']==3) {
3826 $colspace='DeviceRGB';
3828 elseif($a['channels']==4) {
3829 $colspace='DeviceCMYK';
3831 else {
3832 $colspace='DeviceGray';
3834 $bpc=isset($a['bits']) ? $a['bits'] : 8;
3835 //Read whole file
3837 $f=fopen($filename,'rb');
3838 $data='';
3839 while(!feof($f)) {
3840 $data.=fread($f,4096);
3842 fclose($f);
3844 return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data);
3847 /// END OF REWRITE BY Warren Sherliker wsherliker@gmail.com
3850 * Read a 4-byte integer from file
3851 * @param string $f file name.
3852 * @return 4-byte integer
3853 * @access protected
3855 protected function _freadint($f) {
3856 $a=unpack('Ni',fread($f,4));
3857 return $a['i'];
3861 * Format a text string for meta information
3862 * @param string $s string to escape.
3863 * @return string escaped string.
3864 * @access protected
3866 protected function _textstring($s) {
3867 if($this->isunicode) {
3868 //Convert string to UTF-16BE
3869 $s = $this->UTF8ToUTF16BE($s, true);
3871 if ($this->encrypted) {
3872 $s = $this->_RC4($this->_objectkey($this->n), $s);
3874 return '('. $this->_escape($s).')';
3878 * Format an URI string
3879 * @param string $s string to escape.
3880 * @return string escaped string.
3881 * @access protected
3883 protected function _uristring($s) {
3884 if ($this->encrypted) {
3885 $s = $this->_RC4($this->_objectkey($this->n), $s);
3887 return '('.$this->_escape($s).')';
3891 * Format a text string
3892 * @param string $s string to escape.
3893 * @return string escaped string.
3894 * @access protected
3896 protected function _escapetext($s) {
3897 if($this->isunicode) {
3898 //Convert string to UTF-16BE and reverse RTL language
3899 $s = $this->utf8StrRev($s, false, $this->tmprtl);
3901 return $this->_escape($s);
3905 * Add \ before \, ( and )
3906 * @param string $s string to escape.
3907 * @return string escaped string.
3908 * @access protected
3910 protected function _escape($s) {
3911 // the chr(13) substitution fixes the Bugs item #1421290.
3912 return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
3916 * Output a stream.
3917 * @param string $s string to output.
3918 * @access protected
3920 protected function _putstream($s) {
3921 if ($this->encrypted) {
3922 $s = $this->_RC4($this->_objectkey($this->n), $s);
3924 $this->_out('stream');
3925 $this->_out($s);
3926 $this->_out('endstream');
3930 * Output a string to the document.
3931 * @param string $s string to output.
3932 * @access protected
3934 protected function _out($s) {
3935 if($this->state==2) {
3936 $this->pages[$this->page] .= $s."\n";
3938 else {
3939 $this->buffer .= $s."\n";
3944 * Adds unicode fonts.<br>
3945 * Based on PDF Reference 1.3 (section 5)
3946 * @access protected
3947 * @author Nicola Asuni
3948 * @since 1.52.0.TC005 (2005-01-05)
3950 protected function _puttruetypeunicode($font) {
3951 // Type0 Font
3952 // A composite font composed of other fonts, organized hierarchically
3953 $this->_newobj();
3954 $this->_out('<</Type /Font');
3955 $this->_out('/Subtype /Type0');
3956 $this->_out('/BaseFont /'.$font['name'].'');
3957 $this->_out('/Encoding /Identity-H'); //The horizontal identity mapping for 2-byte CIDs; may be used with CIDFonts using any Registry, Ordering, and Supplement values.
3958 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
3959 $this->_out('/ToUnicode '.($this->n + 2).' 0 R');
3960 $this->_out('>>');
3961 $this->_out('endobj');
3963 // CIDFontType2
3964 // A CIDFont whose glyph descriptions are based on TrueType font technology
3965 $this->_newobj();
3966 $this->_out('<</Type /Font');
3967 $this->_out('/Subtype /CIDFontType2');
3968 $this->_out('/BaseFont /'.$font['name'].'');
3969 $this->_out('/CIDSystemInfo '.($this->n + 2).' 0 R');
3970 $this->_out('/FontDescriptor '.($this->n + 3).' 0 R');
3971 if (isset($font['desc']['MissingWidth'])){
3972 $this->_out('/DW '.$font['desc']['MissingWidth'].''); // The default width for glyphs in the CIDFont MissingWidth
3974 $w = "";
3975 foreach ($font['cw'] as $cid => $width) {
3976 $w .= ''.$cid.' ['.$width.'] '; // define a specific width for each individual CID
3978 $this->_out('/W ['.$w.']'); // A description of the widths for the glyphs in the CIDFont
3979 $this->_out('/CIDToGIDMap '.($this->n + 4).' 0 R');
3980 $this->_out('>>');
3981 $this->_out('endobj');
3983 // ToUnicode
3984 // is a stream object that contains the definition of the CMap
3985 // (PDF Reference 1.3 chap. 5.9)
3986 $this->_newobj();
3987 $this->_out('<</Length 345>>');
3988 $this->_out('stream');
3989 $this->_out('/CIDInit /ProcSet findresource begin');
3990 $this->_out('12 dict begin');
3991 $this->_out('begincmap');
3992 $this->_out('/CIDSystemInfo');
3993 $this->_out('<</Registry (Adobe)');
3994 $this->_out('/Ordering (UCS)');
3995 $this->_out('/Supplement 0');
3996 $this->_out('>> def');
3997 $this->_out('/CMapName /Adobe-Identity-UCS def');
3998 $this->_out('/CMapType 2 def');
3999 $this->_out('1 begincodespacerange');
4000 $this->_out('<0000> <FFFF>');
4001 $this->_out('endcodespacerange');
4002 $this->_out('1 beginbfrange');
4003 $this->_out('<0000> <FFFF> <0000>');
4004 $this->_out('endbfrange');
4005 $this->_out('endcmap');
4006 $this->_out('CMapName currentdict /CMap defineresource pop');
4007 $this->_out('end');
4008 $this->_out('end');
4009 $this->_out('endstream');
4010 $this->_out('endobj');
4012 // CIDSystemInfo dictionary
4013 // A dictionary containing entries that define the character collection of the CIDFont.
4014 $this->_newobj();
4015 $this->_out('<</Registry (Adobe)'); // A string identifying an issuer of character collections
4016 $this->_out('/Ordering (UCS)'); // A string that uniquely names a character collection issued by a specific registry
4017 $this->_out('/Supplement 0'); // The supplement number of the character collection.
4018 $this->_out('>>');
4019 $this->_out('endobj');
4021 // Font descriptor
4022 // A font descriptor describing the CIDFont default metrics other than its glyph widths
4023 $this->_newobj();
4024 $this->_out('<</Type /FontDescriptor');
4025 $this->_out('/FontName /'.$font['name']);
4026 foreach ($font['desc'] as $key => $value) {
4027 $this->_out('/'.$key.' '.$value);
4029 if ($font['file']) {
4030 // A stream containing a TrueType font program
4031 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
4033 $this->_out('>>');
4034 $this->_out('endobj');
4036 // Embed CIDToGIDMap
4037 // A specification of the mapping from CIDs to glyph indices
4038 $this->_newobj();
4039 $ctgfile = $this->_getfontpath().strtolower($font['ctg']);
4040 if(!file_exists($ctgfile)) {
4041 $this->Error('Font file not found: '.$ctgfile);
4043 $size = filesize($ctgfile);
4044 $this->_out('<</Length '.$size.'');
4045 if(substr($ctgfile, -2) == '.z') { // check file extension
4046 /* Decompresses data encoded using the public-domain
4047 zlib/deflate compression method, reproducing the
4048 original text or binary data */
4049 $this->_out('/Filter /FlateDecode');
4051 $this->_out('>>');
4052 $this->_putstream(file_get_contents($ctgfile));
4053 $this->_out('endobj');
4057 * Converts UTF-8 strings to codepoints array.<br>
4058 * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
4059 * Based on: http://www.faqs.org/rfcs/rfc3629.html
4060 * <pre>
4061 * Char. number range | UTF-8 octet sequence
4062 * (hexadecimal) | (binary)
4063 * --------------------+-----------------------------------------------
4064 * 0000 0000-0000 007F | 0xxxxxxx
4065 * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
4066 * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
4067 * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
4068 * ---------------------------------------------------------------------
4070 * ABFN notation:
4071 * ---------------------------------------------------------------------
4072 * UTF8-octets = *( UTF8-char )
4073 * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
4074 * UTF8-1 = %x00-7F
4075 * UTF8-2 = %xC2-DF UTF8-tail
4077 * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
4078 * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
4079 * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
4080 * %xF4 %x80-8F 2( UTF8-tail )
4081 * UTF8-tail = %x80-BF
4082 * ---------------------------------------------------------------------
4083 * </pre>
4084 * @param string $str string to process.
4085 * @return array containing codepoints (UTF-8 characters values)
4086 * @access protected
4087 * @author Nicola Asuni
4088 * @since 1.53.0.TC005 (2005-01-05)
4090 protected function UTF8StringToArray($str) {
4091 if(!$this->isunicode) {
4092 return $str; // string is not in unicode
4094 $unicode = array(); // array containing unicode values
4095 $bytes = array(); // array containing single character byte sequences
4096 $numbytes = 1; // number of octetc needed to represent the UTF-8 character
4098 $str .= ""; // force $str to be a string
4099 $length = strlen($str);
4101 for($i = 0; $i < $length; $i++) {
4102 $char = ord($str{$i}); // get one string character at time
4103 if(count($bytes) == 0) { // get starting octect
4104 if ($char <= 0x7F) {
4105 $unicode[] = $char; // use the character "as is" because is ASCII
4106 $numbytes = 1;
4107 } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
4108 $bytes[] = ($char - 0xC0) << 0x06;
4109 $numbytes = 2;
4110 } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
4111 $bytes[] = ($char - 0xE0) << 0x0C;
4112 $numbytes = 3;
4113 } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
4114 $bytes[] = ($char - 0xF0) << 0x12;
4115 $numbytes = 4;
4116 } else {
4117 // use replacement character for other invalid sequences
4118 $unicode[] = 0xFFFD;
4119 $bytes = array();
4120 $numbytes = 1;
4122 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
4123 $bytes[] = $char - 0x80;
4124 if (count($bytes) == $numbytes) {
4125 // compose UTF-8 bytes to a single unicode value
4126 $char = $bytes[0];
4127 for($j = 1; $j < $numbytes; $j++) {
4128 $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
4130 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
4131 /* The definition of UTF-8 prohibits encoding character numbers between
4132 U+D800 and U+DFFF, which are reserved for use with the UTF-16
4133 encoding form (as surrogate pairs) and do not directly represent
4134 characters. */
4135 $unicode[] = 0xFFFD; // use replacement character
4137 else {
4138 $unicode[] = $char; // add char to array
4140 // reset data for next char
4141 $bytes = array();
4142 $numbytes = 1;
4144 } else {
4145 // use replacement character for other invalid sequences
4146 $unicode[] = 0xFFFD;
4147 $bytes = array();
4148 $numbytes = 1;
4151 return $unicode;
4155 * Converts UTF-8 strings to UTF16-BE.<br>
4156 * @param string $str string to process.
4157 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
4158 * @return string
4159 * @access protected
4160 * @author Nicola Asuni
4161 * @since 1.53.0.TC005 (2005-01-05)
4162 * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
4164 protected function UTF8ToUTF16BE($str, $setbom=true) {
4165 if(!$this->isunicode) {
4166 return $str; // string is not in unicode
4168 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
4169 return $this->arrUTF8ToUTF16BE($unicode, $setbom);
4173 * Converts array of UTF-8 characters to UTF16-BE string.<br>
4174 * Based on: http://www.faqs.org/rfcs/rfc2781.html
4175 * <pre>
4176 * Encoding UTF-16:
4178 * Encoding of a single character from an ISO 10646 character value to
4179 * UTF-16 proceeds as follows. Let U be the character number, no greater
4180 * than 0x10FFFF.
4182 * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
4183 * terminate.
4185 * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
4186 * U' must be less than or equal to 0xFFFFF. That is, U' can be
4187 * represented in 20 bits.
4189 * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
4190 * 0xDC00, respectively. These integers each have 10 bits free to
4191 * encode the character value, for a total of 20 bits.
4193 * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
4194 * bits of W1 and the 10 low-order bits of U' to the 10 low-order
4195 * bits of W2. Terminate.
4197 * Graphically, steps 2 through 4 look like:
4198 * U' = yyyyyyyyyyxxxxxxxxxx
4199 * W1 = 110110yyyyyyyyyy
4200 * W2 = 110111xxxxxxxxxx
4201 * </pre>
4202 * @param array $unicode array containing UTF-8 unicode values
4203 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
4204 * @return string
4205 * @access protected
4206 * @author Nicola Asuni
4207 * @since 2.1.000 (2008-01-08)
4208 * @see UTF8ToUTF16BE()
4210 protected function arrUTF8ToUTF16BE($unicode, $setbom=true) {
4211 $outstr = ""; // string to be returned
4212 if ($setbom) {
4213 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
4215 foreach($unicode as $char) {
4216 if($char == 0xFFFD) {
4217 $outstr .= "\xFF\xFD"; // replacement character
4218 } elseif ($char < 0x10000) {
4219 $outstr .= chr($char >> 0x08);
4220 $outstr .= chr($char & 0xFF);
4221 } else {
4222 $char -= 0x10000;
4223 $w1 = 0xD800 | ($char >> 0x10);
4224 $w2 = 0xDC00 | ($char & 0x3FF);
4225 $outstr .= chr($w1 >> 0x08);
4226 $outstr .= chr($w1 & 0xFF);
4227 $outstr .= chr($w2 >> 0x08);
4228 $outstr .= chr($w2 & 0xFF);
4231 return $outstr;
4233 // ====================================================
4236 * Set header font.
4237 * @param array $font font
4238 * @since 1.1
4240 public function setHeaderFont($font) {
4241 $this->header_font = $font;
4245 * Set footer font.
4246 * @param array $font font
4247 * @since 1.1
4249 public function setFooterFont($font) {
4250 $this->footer_font = $font;
4254 * Set language array.
4255 * @param array $language
4256 * @since 1.1
4258 public function setLanguageArray($language) {
4259 $this->l = $language;
4260 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
4264 * Set document barcode.
4265 * @param string $bc barcode
4267 public function setBarcode($bc="") {
4268 $this->barcode = $bc;
4272 * Print Barcode.
4273 * @param int $x x position in user units
4274 * @param int $y y position in user units
4275 * @param int $w width in user units
4276 * @param int $h height position in user units
4277 * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
4278 * @param string $style barcode style
4279 * @param string $font font for text
4280 * @param int $xres x resolution
4281 * @param string $code code to print
4283 public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
4284 require_once(dirname(__FILE__)."/barcode/barcode.php");
4285 require_once(dirname(__FILE__)."/barcode/i25object.php");
4286 require_once(dirname(__FILE__)."/barcode/c39object.php");
4287 require_once(dirname(__FILE__)."/barcode/c128aobject.php");
4288 require_once(dirname(__FILE__)."/barcode/c128bobject.php");
4289 require_once(dirname(__FILE__)."/barcode/c128cobject.php");
4291 if (empty($code)) {
4292 return;
4295 if (empty($style)) {
4296 $style = BCS_ALIGN_LEFT;
4297 $style |= BCS_IMAGE_PNG;
4298 $style |= BCS_TRANSPARENT;
4299 //$style |= BCS_BORDER;
4300 //$style |= BCS_DRAW_TEXT;
4301 //$style |= BCS_STRETCH_TEXT;
4302 //$style |= BCS_REVERSE_COLOR;
4304 if (empty($font)) {$font = BCD_DEFAULT_FONT;}
4305 if (empty($xres)) {$xres = BCD_DEFAULT_XRES;}
4307 $scale_factor = 1.5 * $xres * $this->k;
4308 $bc_w = round($w * $scale_factor); //width in points
4309 $bc_h = round($h * $scale_factor); //height in points
4311 switch (strtoupper($type)) {
4312 case "I25": {
4313 $obj = new I25Object($bc_w, $bc_h, $style, $code);
4314 break;
4316 case "C128A": {
4317 $obj = new C128AObject($bc_w, $bc_h, $style, $code);
4318 break;
4320 default:
4321 case "C128B": {
4322 $obj = new C128BObject($bc_w, $bc_h, $style, $code);
4323 break;
4325 case "C128C": {
4326 $obj = new C128CObject($bc_w, $bc_h, $style, $code);
4327 break;
4329 case "C39": {
4330 $obj = new C39Object($bc_w, $bc_h, $style, $code);
4331 break;
4335 $obj->SetFont($font);
4336 $obj->DrawObject($xres);
4338 //use a temporary file....
4339 $tmpName = tempnam(K_PATH_CACHE,'img');
4340 imagepng($obj->getImage(), $tmpName);
4341 $this->Image($tmpName, $x, $y, $w, $h, 'png');
4342 $obj->DestroyObject();
4343 unset($obj);
4344 unlink($tmpName);
4348 * Returns the PDF data.
4350 public function getPDFData() {
4351 if($this->state < 3) {
4352 $this->Close();
4354 return $this->buffer;
4357 // --- HTML PARSER FUNCTIONS ---
4360 * Allows to preserve some HTML formatting.<br />
4361 * Supports: h1, h2, h3, h4, h5, h6, b, u, i, a, img, p, br, strong, em, font, blockquote, li, ul, ol, hr, td, th, tr, table, sup, sub, small
4362 * @param string $html text to display
4363 * @param boolean $ln if true add a new line after text (default = true)
4364 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
4365 * @param boolean $reseth if true reset the last cell height (default false).
4366 * @param boolean $cell if true add the default cMargin space to each Write.
4368 public function writeHTML($html, $ln=true, $fill=0, $reseth=false, $cell=false) {
4370 // store some variables
4371 $html=strip_tags($html,"<h1><h2><h3><h4><h5><h6><b><u><i><a><img><p><br><br/><strong><em><font><blockquote><li><ul><ol><hr><td><th><tr><table><sup><sub><small><span><div>"); //remove all unsupported tags
4372 //replace carriage returns, newlines and tabs
4373 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
4374 $html = strtr($html, $repTable);
4375 $pattern = '/(<[^>]+>)/Uu';
4376 $a = preg_split($pattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); //explodes the string
4378 if ((empty($this->lasth))OR ($reseth)) {
4379 //set row height
4380 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4383 foreach($a as $key=>$element) {
4384 if (!preg_match($pattern, $element)) {
4385 //Text
4386 if($this->HREF) {
4387 $this->addHtmlLink($this->HREF, $element, $fill);
4388 } elseif($this->tdbegin) {
4389 if((strlen(trim($element)) > 0) AND ($element != "&nbsp;")) {
4390 $this->Cell($this->tdwidth, $this->tdheight, $this->unhtmlentities($element), $this->tableborder, '', $this->tdalign, $this->tdbgcolor);
4391 } elseif($element == "&nbsp;") {
4392 $this->Cell($this->tdwidth, $this->tdheight, '', $this->tableborder, '', $this->tdalign, $this->tdbgcolor);
4394 } else {
4396 $ctmpmargin = $this->cMargin;
4397 if(!$cell) {
4398 $this->cMargin = 0;
4400 $this->Write($this->lasth, stripslashes($this->unhtmlentities($element)), '', $fill, 0);
4401 $this->cMargin = $ctmpmargin;
4403 } else {
4404 $element = substr($element, 1, -1);
4405 //Tag
4406 if($element{0}=='/') {
4407 $this->closedHTMLTagHandler(strtolower(substr($element, 1)));
4409 else {
4410 //Extract attributes
4411 // get tag name
4412 preg_match('/([a-zA-Z0-9]*)/', $element, $tag);
4413 $tag = strtolower($tag[0]);
4414 // get attributes
4415 preg_match_all('/([^=\s]*)=["\']?([^"\']*)["\']?/', $element, $attr_array, PREG_PATTERN_ORDER);
4416 $attr = array(); // reset attribute array
4417 while(list($id,$name)=each($attr_array[1])) {
4418 $attr[strtolower($name)] = $attr_array[2][$id];
4420 $this->openHTMLTagHandler($tag, $attr, $fill);
4424 if ($ln) {
4425 $this->Ln($this->lasth);
4430 * Prints a cell (rectangular area) with optional borders, background color and html text string. The upper-left corner of the cell corresponds to the current position. After the call, the current position moves to the right or to the next line.<br />
4431 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
4432 * @param float $w Cell width. If 0, the cell extends up to the right margin.
4433 * @param float $h Cell minimum height. The cell extends automatically if needed.
4434 * @param float $x upper-left corner X coordinate
4435 * @param float $y upper-left corner Y coordinate
4436 * @param string $html html text to print. Default value: empty string.
4437 * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
4438 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL language)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
4439 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
4440 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
4441 * @param boolean $reseth if true reset the last cell height (default false).
4442 * @see Cell()
4444 public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=false) {
4446 if ((empty($this->lasth))OR ($reseth)) {
4447 //set row height
4448 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4451 // get current page number
4452 $startpage = $this->page;
4454 if (!empty($y)) {
4455 $this->SetY($y);
4456 } else {
4457 $y = $this->GetY();
4459 if (!empty($x)) {
4460 $this->SetX($x);
4461 } else {
4462 $x = $this->GetX();
4465 if(empty($w)) {
4466 if ($this->rtl) {
4467 $w = $this->x - $this->lMargin;
4468 } else {
4469 $w = $this->w - $this->rMargin - $this->x;
4473 // store original margin values
4474 $lMargin = $this->lMargin;
4475 $rMargin = $this->rMargin;
4477 // set new margin values
4478 if ($this->rtl) {
4479 $this->SetLeftMargin($this->x - $w);
4480 $this->SetRightMargin($this->w - $this->x);
4481 } else {
4482 $this->SetLeftMargin($this->x);
4483 $this->SetRightMargin($this->w - $this->x - $w);
4486 // calculate remaining vertical space on first page ($startpage)
4487 $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin();
4489 // Write HTML text
4490 $this->writeHTML($html, true, $fill, $reseth, true);
4492 // Get end-of-text Y position
4493 $currentY = $this->GetY();
4494 // get latest page number
4495 $endpage = $this->page;
4497 if (!empty($border)) {
4498 // check if a new page has been created
4499 if ($endpage > $startpage) {
4500 // design borders around HTML cells.
4501 for ($page=$startpage; $page<=$endpage; $page++) {
4502 $this->page = $page;
4503 if ($page==$startpage) {
4504 $this->SetY($this->getPageHeight() - $restspace - $this->getBreakMargin());
4505 $h = $restspace - 1;
4506 } elseif ($page==$endpage) {
4507 $this->SetY($this->tMargin); // put cursor at the beginning of text
4508 $h = $currentY - $this->tMargin;
4509 } else {
4510 $this->SetY($this->tMargin); // put cursor at the beginning of text
4511 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
4513 $this->Cell($w, $h, "", $border, 1, '', 0);
4515 } else {
4516 $h = max($h, ($currentY - $y));
4517 $this->SetY($y); // put cursor at the beginning of text
4518 // design a cell around the text
4519 $this->Cell($w, $h, "", $border, 1, '', 0);
4523 // restore original margin values
4524 $this->SetLeftMargin($lMargin);
4525 $this->SetRightMargin($rMargin);
4528 if($ln>0) {
4529 //Go to the beginning of the next line
4530 $this->SetY($currentY);
4531 if($ln == 2) {
4532 $this->SetX($x + $w);
4534 } else {
4535 // go left or right by case
4536 $this->page = $startpage;
4537 $this->y = $y;
4538 $this->SetX($x + $w);
4544 * Process opening tags.
4545 * @param string $tag tag name (in uppercase)
4546 * @param string $attr tag attribute (in uppercase)
4547 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
4548 * @access private
4550 private function openHTMLTagHandler($tag, $attr, $fill=0) {
4551 // check for text direction attribute
4552 if (isset($attr['dir'])) {
4553 $this->tmprtl = $attr['dir']=='rtl' ? 'R' : 'L';
4554 } else {
4555 $this->tmprtl = false;
4557 //Opening tag
4558 switch($tag) {
4559 case 'table': {
4560 if ((isset($attr['border'])) AND ($attr['border'] != '')) {
4561 $this->tableborder = $attr['border'];
4563 else {
4564 $this->tableborder = 0;
4566 break;
4568 case 'tr': {
4569 break;
4571 case 'td':
4572 case 'th': {
4573 if ((isset($attr['width'])) AND ($attr['width'] != '')) {
4574 $this->tdwidth = ($attr['width']/4);
4576 else {
4577 $this->tdwidth = (($this->w - $this->lMargin - $this->rMargin) / $this->default_table_columns);
4579 if ((isset($attr['height'])) AND ($attr['height'] != '')) {
4580 $this->tdheight=($attr['height'] / $this->k);
4582 else {
4583 $this->tdheight = $this->lasth;
4585 if ((isset($attr['align'])) AND ($attr['align'] != '')) {
4586 switch ($attr['align']) {
4587 case 'center': {
4588 $this->tdalign = "C";
4589 break;
4591 case 'right': {
4592 $this->tdalign = "R";
4593 break;
4595 default:
4596 case 'left': {
4597 $this->tdalign = "L";
4598 break;
4601 } else {
4602 if($this->rtl) {
4603 $this->tdalign = "R";
4604 } else {
4605 $this->tdalign = "L";
4608 if ((isset($attr['bgcolor'])) AND ($attr['bgcolor'] != '')) {
4609 $coul = $this->convertColorHexToDec($attr['bgcolor']);
4610 $this->SetFillColor($coul['R'], $coul['G'], $coul['B']);
4611 $this->tdbgcolor=true;
4613 $this->tdbegin=true;
4614 break;
4616 case 'hr': {
4617 $this->Ln();
4618 if ((isset($attr['width'])) AND ($attr['width'] != '')) {
4619 $hrWidth = $attr['width'];
4621 else {
4622 $hrWidth = $this->w - $this->lMargin - $this->rMargin;
4624 $x = $this->GetX();
4625 $y = $this->GetY();
4626 $this->GetLineWidth();
4627 $prevlinewidth = $this->SetLineWidth(0.2);
4628 $this->Line($x, $y, $x + $hrWidth, $y);
4629 $this->SetLineWidth($prevlinewidth);
4630 $this->Ln();
4631 break;
4633 case 'strong': {
4634 $this->setStyle('b', true);
4635 break;
4637 case 'em': {
4638 $this->setStyle('i', true);
4639 break;
4641 case 'b':
4642 case 'i':
4643 case 'u': {
4644 $this->setStyle($tag, true);
4645 break;
4647 case 'a': {
4648 $this->HREF = $attr['href'];
4649 break;
4651 case 'img': {
4652 if(isset($attr['src'])) {
4653 // replace relative path with real server path
4654 if ($attr['src'][0] == '/') {
4655 $attr['src'] = $_SERVER['DOCUMENT_ROOT'].$attr['src'];
4657 $attr['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $attr['src']);
4658 if(!isset($attr['width'])) {
4659 $attr['width'] = 0;
4661 if(!isset($attr['height'])) {
4662 $attr['height'] = 0;
4664 if(!isset($attr['align'])) {
4665 $align = 'N';
4666 } else {
4667 switch($attr['align']) {
4668 case 'top':{
4669 $align = 'T';
4670 break;
4672 case 'middle':{
4673 $align = 'M';
4674 break;
4676 case 'bottom':{
4677 $align = 'B';
4678 break;
4680 default:{
4681 $align = 'N';
4682 break;
4686 $this->Image($attr['src'], $this->GetX(),$this->GetY(), $this->pixelsToMillimeters($attr['width']), $this->pixelsToMillimeters($attr['height']), '', '', $align);
4689 break;
4691 case 'ul': {
4692 $this->listordered = false;
4693 $this->listcount = 0;
4694 break;
4696 case 'ol': {
4697 $this->listordered = true;
4698 $this->listcount = 0;
4699 break;
4701 case 'li': {
4702 $this->Ln();
4703 if ($this->listordered) {
4704 if (isset($attr['value'])) {
4705 $this->listcount = intval($attr['value']);
4707 $this->lispacer = " ".(++$this->listcount).". ";
4708 } else {
4709 //unordered list simbol
4710 $this->lispacer = " - ";
4712 $rtldir = $this->tmprtl;
4713 $this->tmprtl = false;
4714 $this->Write($this->lasth, $this->lispacer, '', $fill);
4715 $this->tmprtl = $rtldir;
4716 break;
4718 case 'blockquote':
4719 case 'br': {
4720 $this->Ln();
4721 if(strlen($this->lispacer) > 0) {
4722 if ($this->rtl) {
4723 $this->x -= $this->GetStringWidth($this->lispacer);
4724 } else {
4725 $this->x += $this->GetStringWidth($this->lispacer);
4728 break;
4730 case 'p': {
4731 $this->Ln();
4732 $this->Ln();
4733 break;
4735 case 'sup': {
4736 $currentFontSize = $this->FontSize;
4737 $this->tempfontsize = $this->FontSizePt;
4738 $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO);
4739 $this->SetXY($this->GetX(), $this->GetY() - (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4740 break;
4742 case 'sub': {
4743 $currentFontSize = $this->FontSize;
4744 $this->tempfontsize = $this->FontSizePt;
4745 $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO);
4746 $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4747 break;
4749 case 'small': {
4750 $currentFontSize = $this->FontSize;
4751 $this->tempfontsize = $this->FontSizePt;
4752 $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO);
4753 $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)/3));
4754 break;
4756 case 'font': {
4757 if (isset($attr['color']) AND $attr['color']!='') {
4758 $coul = $this->convertColorHexToDec($attr['color']);
4759 $this->SetTextColor($coul['R'],$coul['G'],$coul['B']);
4760 $this->issetcolor=true;
4762 if (isset($attr['face']) and in_array(strtolower($attr['face']), $this->fontlist)) {
4763 $this->SetFont(strtolower($attr['face']));
4764 $this->issetfont=true;
4766 if (isset($attr['size'])) {
4767 $headsize = intval($attr['size']);
4768 } else {
4769 $headsize = 0;
4771 $currentFontSize = $this->FontSize;
4772 $this->tempfontsize = $this->FontSizePt;
4773 $this->SetFontSize($this->FontSizePt + $headsize);
4774 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4775 break;
4777 case 'h1':
4778 case 'h2':
4779 case 'h3':
4780 case 'h4':
4781 case 'h5':
4782 case 'h6': {
4783 $headsize = (4 - substr($tag, 1)) * 2;
4784 $currentFontSize = $this->FontSize;
4785 $this->tempfontsize = $this->FontSizePt;
4786 $this->SetFontSize($this->FontSizePt + $headsize);
4787 $this->setStyle('b', true);
4788 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4789 break;
4795 * Process closing tags.
4796 * @param string $tag tag name (in uppercase)
4797 * @access private
4799 private function closedHTMLTagHandler($tag) {
4800 //Closing tag
4801 switch($tag) {
4802 case 'td':
4803 case 'th': {
4804 $this->tdbegin = false;
4805 $this->tdwidth = 0;
4806 $this->tdheight = 0;
4807 if($this->rtl) {
4808 $this->tdalign = "R";
4809 } else {
4810 $this->tdalign = "L";
4812 $this->tdbgcolor = false;
4813 $this->SetFillColor($this->prevFillColor[0], $this->prevFillColor[1], $this->prevFillColor[2]);
4814 break;
4816 case 'tr': {
4817 $this->Ln();
4818 break;
4820 case 'table': {
4821 $this->tableborder=0;
4822 break;
4824 case 'strong': {
4825 $this->setStyle('b', false);
4826 break;
4828 case 'em': {
4829 $this->setStyle('i', false);
4830 break;
4832 case 'b':
4833 case 'i':
4834 case 'u': {
4835 $this->setStyle($tag, false);
4836 break;
4838 case 'a': {
4839 $this->HREF = '';
4840 break;
4842 case 'sup': {
4843 $currentFontSize = $this->FontSize;
4844 $this->SetFontSize($this->tempfontsize);
4845 $this->tempfontsize = $this->FontSizePt;
4846 $this->SetXY($this->GetX(), $this->GetY() - (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4847 break;
4849 case 'sub': {
4850 $currentFontSize = $this->FontSize;
4851 $this->SetFontSize($this->tempfontsize);
4852 $this->tempfontsize = $this->FontSizePt;
4853 $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4854 break;
4856 case 'small': {
4857 $currentFontSize = $this->FontSize;
4858 $this->SetFontSize($this->tempfontsize);
4859 $this->tempfontsize = $this->FontSizePt;
4860 $this->SetXY($this->GetX(), $this->GetY() - (($this->FontSize - $currentFontSize)/3));
4861 break;
4863 case 'font': {
4864 if ($this->issetcolor == true) {
4865 $this->SetTextColor($this->prevTextColor[0], $this->prevTextColor[1], $this->prevTextColor[2]);
4867 if ($this->issetfont) {
4868 $this->FontFamily = $this->prevFontFamily;
4869 $this->FontStyle = $this->prevFontStyle;
4870 $this->SetFont($this->FontFamily);
4871 $this->issetfont = false;
4873 $currentFontSize = $this->FontSize;
4874 $this->SetFontSize($this->tempfontsize);
4875 $this->tempfontsize = $this->FontSizePt;
4876 //$this->TextColor = $this->prevTextColor;
4877 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4878 break;
4880 case 'p': {
4881 $this->Ln();
4882 $this->Ln();
4883 break;
4885 case 'ul':
4886 case 'ol': {
4887 $this->Ln();
4888 $this->Ln();
4889 break;
4891 case 'li': {
4892 $this->lispacer = "";
4893 break;
4895 case 'h1':
4896 case 'h2':
4897 case 'h3':
4898 case 'h4':
4899 case 'h5':
4900 case 'h6': {
4901 $currentFontSize = $this->FontSize;
4902 $this->SetFontSize($this->tempfontsize);
4903 $this->tempfontsize = $this->FontSizePt;
4904 $this->setStyle('b', false);
4905 $this->Ln();
4906 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4907 break;
4909 default : {
4910 break;
4913 $this->tmprtl = false;
4917 * Sets font style.
4918 * @param string $tag tag name (in lowercase)
4919 * @param boolean $enable
4920 * @access private
4922 private function setStyle($tag, $enable) {
4923 //Modify style and select corresponding font
4924 $this->$tag += ($enable ? 1 : -1);
4925 $style='';
4926 foreach(array('b', 'i', 'u') as $s) {
4927 if($this->$s > 0) {
4928 $style .= $s;
4931 $this->SetFont('', $style);
4935 * Output anchor link.
4936 * @param string $url link URL
4937 * @param string $name link name
4938 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
4939 * @access public
4941 public function addHtmlLink($url, $name, $fill=0) {
4942 //Put a hyperlink
4943 $this->SetTextColor(0, 0, 255);
4944 $this->setStyle('u', true);
4945 $this->Write($this->lasth, $name, $url, $fill);
4946 $this->setStyle('u', false);
4947 $this->SetTextColor(0);
4951 * Returns an associative array (keys: R,G,B) from
4952 * a hex html code (e.g. #3FE5AA).
4953 * @param string $color hexadecimal html color [#rrggbb]
4954 * @return array
4955 * @access private
4957 private function convertColorHexToDec($color = "#000000"){
4958 $tbl_color = array();
4959 $tbl_color['R'] = hexdec(substr($color, 1, 2));
4960 $tbl_color['G'] = hexdec(substr($color, 3, 2));
4961 $tbl_color['B'] = hexdec(substr($color, 5, 2));
4962 return $tbl_color;
4966 * Converts pixels to millimeters in 72 dpi.
4967 * @param int $px pixels
4968 * @return float millimeters
4969 * @access private
4971 private function pixelsToMillimeters($px){
4972 return $px * 25.4 / 72;
4976 * Reverse function for htmlentities.
4977 * Convert entities in UTF-8.
4979 * @param $text_to_convert Text to convert.
4980 * @return string converted
4982 public function unhtmlentities($text_to_convert) {
4983 return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
4986 // ENCRYPTION METHODS ----------------------------------
4987 // SINCE 2.0.000 (2008-01-02)
4989 * Compute encryption key depending on object number where the encrypted data is stored
4990 * @param int $n object number
4991 * @since 2.0.000 (2008-01-02)
4993 protected function _objectkey($n) {
4994 return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);
4998 * Put encryption on PDF document
4999 * @since 2.0.000 (2008-01-02)
5001 protected function _putencryption() {
5002 $this->_out('/Filter /Standard');
5003 $this->_out('/V 1');
5004 $this->_out('/R 2');
5005 $this->_out('/O ('.$this->_escape($this->Ovalue).')');
5006 $this->_out('/U ('.$this->_escape($this->Uvalue).')');
5007 $this->_out('/P '.$this->Pvalue);
5011 * Returns the input text exrypted using RC4 algorithm and the specified key.
5012 * RC4 is the standard encryption algorithm used in PDF format
5013 * @param string $key encryption key
5014 * @param String $text input text to be encrypted
5015 * @return String encrypted text
5016 * @since 2.0.000 (2008-01-02)
5017 * @author Klemen Vodopivec
5019 protected function _RC4($key, $text) {
5020 if ($this->last_rc4_key != $key) {
5021 $k = str_repeat($key, 256/strlen($key)+1);
5022 $rc4 = range(0,255);
5023 $j = 0;
5024 for ($i=0; $i<256; $i++) {
5025 $t = $rc4[$i];
5026 $j = ($j + $t + ord($k{$i})) % 256;
5027 $rc4[$i] = $rc4[$j];
5028 $rc4[$j] = $t;
5030 $this->last_rc4_key = $key;
5031 $this->last_rc4_key_c = $rc4;
5032 } else {
5033 $rc4 = $this->last_rc4_key_c;
5035 $len = strlen($text);
5036 $a = 0;
5037 $b = 0;
5038 $out = '';
5039 for ($i=0; $i<$len; $i++) {
5040 $a = ($a+1)%256;
5041 $t= $rc4[$a];
5042 $b = ($b+$t)%256;
5043 $rc4[$a] = $rc4[$b];
5044 $rc4[$b] = $t;
5045 $k = $rc4[($rc4[$a]+$rc4[$b])%256];
5046 $out.=chr(ord($text{$i}) ^ $k);
5048 return $out;
5052 * Encrypts a string using MD5 and returns it's value as a binary string.
5053 * @param string $str input string
5054 * @return String MD5 encrypted binary string
5055 * @since 2.0.000 (2008-01-02)
5056 * @author Klemen Vodopivec
5058 protected function _md5_16($str) {
5059 return pack('H*',md5($str));
5063 * Compute O value (used for RC4 encryption)
5064 * @param String $user_pass user password
5065 * @param String $owner_pass user password
5066 * @return String O value
5067 * @since 2.0.000 (2008-01-02)
5068 * @author Klemen Vodopivec
5070 protected function _Ovalue($user_pass, $owner_pass) {
5071 $tmp = $this->_md5_16($owner_pass);
5072 $owner_RC4_key = substr($tmp,0,5);
5073 return $this->_RC4($owner_RC4_key, $user_pass);
5077 * Compute U value (used for RC4 encryption)
5078 * @return String U value
5079 * @since 2.0.000 (2008-01-02)
5080 * @author Klemen Vodopivec
5082 protected function _Uvalue() {
5083 return $this->_RC4($this->encryption_key, $this->padding);
5087 * Compute encryption key
5088 * @param String $user_pass user password
5089 * @param String $owner_pass user password
5090 * @param String $protection protection type
5091 * @since 2.0.000 (2008-01-02)
5092 * @author Klemen Vodopivec
5094 protected function _generateencryptionkey($user_pass, $owner_pass, $protection) {
5095 // Pad passwords
5096 $user_pass = substr($user_pass.$this->padding,0,32);
5097 $owner_pass = substr($owner_pass.$this->padding,0,32);
5098 // Compute O value
5099 $this->Ovalue = $this->_Ovalue($user_pass,$owner_pass);
5100 // Compute encyption key
5101 $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
5102 $this->encryption_key = substr($tmp,0,5);
5103 // Compute U value
5104 $this->Uvalue = $this->_Uvalue();
5105 // Compute P value
5106 $this->Pvalue = -(($protection^255)+1);
5110 * Set document protection
5111 * The permission array is composed of values taken from the following ones:
5112 * - copy: copy text and images to the clipboard
5113 * - print: print the document
5114 * - modify: modify it (except for annotations and forms)
5115 * - annot-forms: add annotations and forms
5116 * Remark: the protection against modification is for people who have the full Acrobat product.
5117 * If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access.
5118 * Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts.
5119 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
5120 * @param String $user_pass user password. Empty by default.
5121 * @param String $owner_pass owner password. If not specified, a random value is used.
5122 * @since 2.0.000 (2008-01-02)
5123 * @author Klemen Vodopivec
5125 public function SetProtection($permissions=array(),$user_pass='',$owner_pass=null) {
5126 $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
5127 $protection = 192;
5128 foreach($permissions as $permission) {
5129 if (!isset($options[$permission])) {
5130 $this->Error('Incorrect permission: '.$permission);
5132 $protection += $options[$permission];
5134 if ($owner_pass === null) {
5135 $owner_pass = uniqid(rand());
5137 $this->encrypted = true;
5138 $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
5141 // END OF ENCRYPTION FUNCTIONS -------------------------
5143 // START TRANSFORMATIONS SECTION -----------------------
5144 // authors: Moritz Wagner, Andreas Wurmser, Nicola Asuni
5147 * Starts a 2D tranformation saving current graphic state.
5148 * This function must be called before scaling, mirroring, translation, rotation and skewing.
5149 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5150 * @since 2.1.000 (2008-01-07)
5151 * @see StartTransform(), StopTransform()
5153 public function StartTransform() {
5154 $this->_out('q');
5158 * Stops a 2D tranformation restoring previous graphic state.
5159 * This function must be called after scaling, mirroring, translation, rotation and skewing.
5160 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5161 * @since 2.1.000 (2008-01-07)
5162 * @see StartTransform(), StopTransform()
5164 public function StopTransform() {
5165 $this->_out('Q');
5168 * Horizontal Scaling.
5169 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5170 * @param int $x abscissa of the scaling center. Default is current x position
5171 * @param int $y ordinate of the scaling center. Default is current y position
5172 * @since 2.1.000 (2008-01-07)
5173 * @see StartTransform(), StopTransform()
5175 public function ScaleX($s_x, $x='', $y=''){
5176 $this->Scale($s_x, 100, $x, $y);
5180 * Vertical Scaling.
5181 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5182 * @param int $x abscissa of the scaling center. Default is current x position
5183 * @param int $y ordinate of the scaling center. Default is current y position
5184 * @since 2.1.000 (2008-01-07)
5185 * @see StartTransform(), StopTransform()
5187 public function ScaleY($s_y, $x='', $y=''){
5188 $this->Scale(100, $s_y, $x, $y);
5192 * Vertical and horizontal proportional Scaling.
5193 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
5194 * @param int $x abscissa of the scaling center. Default is current x position
5195 * @param int $y ordinate of the scaling center. Default is current y position
5196 * @since 2.1.000 (2008-01-07)
5197 * @see StartTransform(), StopTransform()
5199 public function ScaleXY($s, $x='', $y=''){
5200 $this->Scale($s, $s, $x, $y);
5204 * Vertical and horizontal non-proportional Scaling.
5205 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5206 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5207 * @param int $x abscissa of the scaling center. Default is current x position
5208 * @param int $y ordinate of the scaling center. Default is current y position
5209 * @since 2.1.000 (2008-01-07)
5210 * @see StartTransform(), StopTransform()
5212 public function Scale($s_x, $s_y, $x='', $y=''){
5213 if($x === '') {
5214 $x=$this->x;
5216 if($y === '') {
5217 $y=$this->y;
5219 if($this->rtl) {
5220 $x = $this->w - $x;
5222 if($s_x == 0 OR $s_y == 0)
5223 $this->Error('Please use values unequal to zero for Scaling');
5224 $y=($this->h-$y)*$this->k;
5225 $x*=$this->k;
5226 //calculate elements of transformation matrix
5227 $s_x/=100;
5228 $s_y/=100;
5229 $tm[0]=$s_x;
5230 $tm[1]=0;
5231 $tm[2]=0;
5232 $tm[3]=$s_y;
5233 $tm[4]=$x*(1-$s_x);
5234 $tm[5]=$y*(1-$s_y);
5235 //scale the coordinate system
5236 $this->Transform($tm);
5240 * Horizontal Mirroring.
5241 * @param int $x abscissa of the point. Default is current x position
5242 * @since 2.1.000 (2008-01-07)
5243 * @see StartTransform(), StopTransform()
5245 public function MirrorH($x=''){
5246 $this->Scale(-100, 100, $x);
5250 * Verical Mirroring.
5251 * @param int $y ordinate of the point. Default is current y position
5252 * @since 2.1.000 (2008-01-07)
5253 * @see StartTransform(), StopTransform()
5255 public function MirrorV($y=''){
5256 $this->Scale(100, -100, '', $y);
5260 * Point reflection mirroring.
5261 * @param int $x abscissa of the point. Default is current x position
5262 * @param int $y ordinate of the point. Default is current y position
5263 * @since 2.1.000 (2008-01-07)
5264 * @see StartTransform(), StopTransform()
5266 public function MirrorP($x='',$y=''){
5267 $this->Scale(-100, -100, $x, $y);
5271 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
5272 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
5273 * @param int $x abscissa of the point. Default is current x position
5274 * @param int $y ordinate of the point. Default is current y position
5275 * @since 2.1.000 (2008-01-07)
5276 * @see StartTransform(), StopTransform()
5278 public function MirrorL($angle=0, $x='',$y=''){
5279 $this->Scale(-100, 100, $x, $y);
5280 $this->Rotate(-2*($angle-90),$x,$y);
5284 * Translate graphic object horizontally.
5285 * @param int $t_x movement to the right
5286 * @since 2.1.000 (2008-01-07)
5287 * @see StartTransform(), StopTransform()
5289 public function TranslateX($t_x){
5290 $this->Translate($t_x, 0);
5294 * Translate graphic object vertically.
5295 * @param int $t_y movement to the bottom
5296 * @since 2.1.000 (2008-01-07)
5297 * @see StartTransform(), StopTransform()
5299 public function TranslateY($t_y){
5300 $this->Translate(0, $t_y, $x, $y);
5304 * Translate graphic object horizontally and vertically.
5305 * @param int $t_x movement to the right
5306 * @param int $t_y movement to the bottom
5307 * @since 2.1.000 (2008-01-07)
5308 * @see StartTransform(), StopTransform()
5310 public function Translate($t_x, $t_y){
5311 if($this->rtl) {
5312 $t_x = -$t_x;
5314 //calculate elements of transformation matrix
5315 $tm[0]=1;
5316 $tm[1]=0;
5317 $tm[2]=0;
5318 $tm[3]=1;
5319 $tm[4]=$t_x*$this->k;
5320 $tm[5]=-$t_y*$this->k;
5321 //translate the coordinate system
5322 $this->Transform($tm);
5326 * Rotate object.
5327 * @param float $angle angle in degrees for counter-clockwise rotation
5328 * @param int $x abscissa of the rotation center. Default is current x position
5329 * @param int $y ordinate of the rotation center. Default is current y position
5330 * @since 2.1.000 (2008-01-07)
5331 * @see StartTransform(), StopTransform()
5333 public function Rotate($angle, $x='', $y=''){
5334 if($x === '') {
5335 $x=$this->x;
5337 if($y === '') {
5338 $y=$this->y;
5340 if($this->rtl) {
5341 $x = $this->w - $x;
5342 $angle = -$angle;
5344 $y=($this->h-$y)*$this->k;
5345 $x*=$this->k;
5346 //calculate elements of transformation matrix
5347 $tm[0]=cos(deg2rad($angle));
5348 $tm[1]=sin(deg2rad($angle));
5349 $tm[2]=-$tm[1];
5350 $tm[3]=$tm[0];
5351 $tm[4]=$x+$tm[1]*$y-$tm[0]*$x;
5352 $tm[5]=$y-$tm[0]*$y-$tm[1]*$x;
5353 //rotate the coordinate system around ($x,$y)
5354 $this->Transform($tm);
5358 * Skew horizontally.
5359 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
5360 * @param int $x abscissa of the skewing center. default is current x position
5361 * @param int $y ordinate of the skewing center. default is current y position
5362 * @since 2.1.000 (2008-01-07)
5363 * @see StartTransform(), StopTransform()
5365 public function SkewX($angle_x, $x='', $y=''){
5366 $this->Skew($angle_x, 0, $x, $y);
5370 * Skew vertically.
5371 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
5372 * @param int $x abscissa of the skewing center. default is current x position
5373 * @param int $y ordinate of the skewing center. default is current y position
5374 * @since 2.1.000 (2008-01-07)
5375 * @see StartTransform(), StopTransform()
5377 public function SkewY($angle_y, $x='', $y=''){
5378 $this->Skew(0, $angle_y, $x, $y);
5382 * Skew.
5383 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
5384 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
5385 * @param int $x abscissa of the skewing center. default is current x position
5386 * @param int $y ordinate of the skewing center. default is current y position
5387 * @since 2.1.000 (2008-01-07)
5388 * @see StartTransform(), StopTransform()
5390 public function Skew($angle_x, $angle_y, $x='', $y=''){
5391 if($x === '') {
5392 $x=$this->x;
5394 if($y === '') {
5395 $y=$this->y;
5397 if($this->rtl) {
5398 $x = $this->w - $x;
5399 $angle_x = -$angle_x;
5401 if($angle_x <= -90 OR $angle_x >= 90 OR $angle_y <= -90 OR $angle_y >= 90)
5402 $this->Error('Please use values between -90� and 90� for skewing');
5403 $x*=$this->k;
5404 $y=($this->h-$y)*$this->k;
5405 //calculate elements of transformation matrix
5406 $tm[0]=1;
5407 $tm[1]=tan(deg2rad($angle_y));
5408 $tm[2]=tan(deg2rad($angle_x));
5409 $tm[3]=1;
5410 $tm[4]=-$tm[2]*$y;
5411 $tm[5]=-$tm[1]*$x;
5412 //skew the coordinate system
5413 $this->Transform($tm);
5417 * Apply graphic transformations.
5418 * @since 2.1.000 (2008-01-07)
5419 * @see StartTransform(), StopTransform()
5421 protected function Transform($tm){
5422 $this->_out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', $tm[0],$tm[1],$tm[2],$tm[3],$tm[4],$tm[5]));
5425 // END TRANSFORMATIONS SECTION -------------------------
5428 // START GRAPHIC FUNCTIONS SECTION ---------------------
5429 // The following section is based on the code provided by David Hernandez Sanz
5432 * Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page.
5433 * @param float $width The width.
5434 * @since 1.0
5435 * @see Line(), Rect(), Cell(), MultiCell()
5437 public function SetLineWidth($width) {
5438 //Set line width
5439 $this->LineWidth=$width;
5440 if($this->page>0) {
5441 $this->_out(sprintf('%.2f w',$width*$this->k));
5446 * Returns the current the line width.
5447 * @return int Line width
5448 * @since 2.1.000 (2008-01-07)
5449 * @see Line(), SetLineWidth()
5451 public function GetLineWidth() {
5452 return $this->LineWidth;
5456 * Set line style.
5458 * @param array $style Line style. Array with keys among the following:
5459 * <ul>
5460 * <li>width (float): Width of the line in user units.</li>
5461 * <li>cap (string): Type of cap to put on the line. Possible values are:
5462 * butt, round, square. The difference between "square" and "butt" is that
5463 * "square" projects a flat end past the end of the line.</li>
5464 * <li>join (string): Type of join. Possible values are: miter, round,
5465 * bevel.</li>
5466 * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
5467 * series of length values, which are the lengths of the on and off dashes.
5468 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
5469 * 1 off, 2 on, 1 off, ...</li>
5470 * <li>phase (integer): Modifier on the dash pattern which is used to shift
5471 * the point at which the pattern starts.</li>
5472 * <li>color (array): Draw color. Format: array(red, green, blue).</li>
5473 * </ul>
5474 * @access public
5475 * @since 2.1.000 (2008-01-08)
5477 public function SetLineStyle($style) {
5478 extract($style);
5479 if (isset($width)) {
5480 $width_prev = $this->LineWidth;
5481 $this->SetLineWidth($width);
5482 $this->LineWidth = $width_prev;
5484 if (isset($cap)) {
5485 $ca = array("butt" => 0, "round"=> 1, "square" => 2);
5486 if (isset($ca[$cap])) {
5487 $this->_out($ca[$cap] . " J");
5490 if (isset($join)) {
5491 $ja = array("miter" => 0, "round" => 1, "bevel" => 2);
5492 if (isset($ja[$join])) {
5493 $this->_out($ja[$join] . " j");
5496 if (isset($dash)) {
5497 $dash_string = "";
5498 if ($dash) {
5499 // phpMyAdmin change
5500 if (preg_match("/^.+,/", $dash)) {
5501 $tab = explode(",", $dash);
5502 } else {
5503 $tab = array($dash);
5505 $dash_string = "";
5506 foreach ($tab as $i => $v) {
5507 if ($i) {
5508 $dash_string .= " ";
5510 $dash_string .= sprintf("%.2f", $v);
5513 if (!isset($phase) OR !$dash) {
5514 $phase = 0;
5516 $this->_out(sprintf("[%s] %.2f d", $dash_string, $phase));
5518 if (isset($color)) {
5519 list($r, $g, $b) = $color;
5520 $this->SetDrawColor($r, $g, $b);
5525 * Set a draw point.
5526 * @param float $x Abscissa of point.
5527 * @param float $y Ordinate of point.
5528 * @access private
5529 * @since 2.1.000 (2008-01-08)
5531 protected function _outPoint($x, $y) {
5532 if($this->rtl) {
5533 $x = $this->w - $x;
5535 $this->_out(sprintf("%.2f %.2f m", $x * $this->k, ($this->h - $y) * $this->k));
5539 * Draws a line from last draw point.
5540 * @param float $x Abscissa of end point.
5541 * @param float $y Ordinate of end point.
5542 * @access private
5543 * @since 2.1.000 (2008-01-08)
5545 protected function _outLine($x, $y) {
5546 if($this->rtl) {
5547 $x = $this->w - $x;
5549 $this->_out(sprintf("%.2f %.2f l", $x * $this->k, ($this->h - $y) * $this->k));
5553 * Draws a rectangle.
5554 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
5555 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
5556 * @param float $w Width.
5557 * @param float $h Height.
5558 * @param string $op options
5559 * @access protected
5560 * @since 2.1.000 (2008-01-08)
5562 protected function _outRect($x, $y, $w, $h, $op) {
5563 if($this->rtl) {
5564 $x = $this->w - $x - $w;
5566 $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op));
5570 * Draws a Bezier curve from last draw point.
5571 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
5572 * @param float $x1 Abscissa of control point 1.
5573 * @param float $y1 Ordinate of control point 1.
5574 * @param float $x2 Abscissa of control point 2.
5575 * @param float $y2 Ordinate of control point 2.
5576 * @param float $x3 Abscissa of end point.
5577 * @param float $y3 Ordinate of end point.
5578 * @access private
5579 * @since 2.1.000 (2008-01-08)
5581 protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
5582 if($this->rtl) {
5583 $x1 = $this->w - $x1;
5584 $x2 = $this->w - $x2;
5585 $x3 = $this->w - $x3;
5587 $this->_out(sprintf("%.2f %.2f %.2f %.2f %.2f %.2f c", $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
5591 * Draws a line between two points.
5592 * @param float $x1 Abscissa of first point.
5593 * @param float $y1 Ordinate of first point.
5594 * @param float $x2 Abscissa of second point.
5595 * @param float $y2 Ordinate of second point.
5596 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5597 * @access public
5598 * @since 1.0
5599 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
5601 public function Line($x1, $y1, $x2, $y2, $style = array()) {
5602 if ($style) {
5603 $this->SetLineStyle($style);
5605 $this->_outPoint($x1, $y1);
5606 $this->_outLine($x2, $y2);
5607 $this->_out(" S");
5611 * Draws a rectangle.
5612 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
5613 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
5614 * @param float $w Width.
5615 * @param float $h Height.
5616 * @param string $style Style of rendering. Possible values are:
5617 * <ul>
5618 * <li>D or empty string: Draw (default).</li>
5619 * <li>F: Fill.</li>
5620 * <li>DF or FD: Draw and fill.</li>
5621 * </ul>
5622 * @param array $border_style Border style of rectangle. Array with keys among the following:
5623 * <ul>
5624 * <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
5625 * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
5626 * </ul>
5627 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
5628 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5629 * @access public
5630 * @since 1.0
5631 * @see SetLineStyle()
5633 public function Rect($x, $y, $w, $h, $style='', $border_style = array(), $fill_color = array()) {
5634 if (!(false === strpos($style, "F")) AND $fill_color) {
5635 list($r, $g, $b) = $fill_color;
5636 $this->SetFillColor($r, $g, $b);
5638 switch ($style) {
5639 case "F": {
5640 $op='f';
5641 $border_style = array();
5642 $this->_outRect($x, $y, $w, $h, $op);
5643 break;
5645 case "DF":
5646 case "FD": {
5647 if (!$border_style OR isset($border_style["all"])) {
5648 $op='B';
5649 if (isset($border_style["all"])) {
5650 $this->SetLineStyle($border_style["all"]);
5651 $border_style = array();
5653 } else {
5654 $op='f';
5656 $this->_outRect($x, $y, $w, $h, $op);
5657 break;
5659 default: {
5660 $op='S';
5661 if (!$border_style OR isset($border_style["all"])) {
5662 if (isset($border_style["all"]) && $border_style["all"]) {
5663 $this->SetLineStyle($border_style["all"]);
5664 $border_style = array();
5666 $this->_outRect($x, $y, $w, $h, $op);
5668 break;
5671 if ($border_style) {
5672 $border_style2 = array();
5673 foreach ($border_style as $line => $value) {
5674 $lenght = strlen($line);
5675 for ($i = 0; $i < $lenght; $i++) {
5676 $border_style2[$line[$i]] = $value;
5679 $border_style = $border_style2;
5680 if (isset($border_style["L"]) && $border_style["L"]) {
5681 $this->Line($x, $y, $x, $y + $h, $border_style["L"]);
5683 if (isset($border_style["T"]) && $border_style["T"]) {
5684 $this->Line($x, $y, $x + $w, $y, $border_style["T"]);
5686 if (isset($border_style["R"]) && $border_style["R"]) {
5687 $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style["R"]);
5689 if (isset($border_style["B"]) && $border_style["B"]) {
5690 $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style["B"]);
5697 * Draws a Bezier curve.
5698 * The Bezier curve is a tangent to the line between the control points at
5699 * either end of the curve.
5700 * @param float $x0 Abscissa of start point.
5701 * @param float $y0 Ordinate of start point.
5702 * @param float $x1 Abscissa of control point 1.
5703 * @param float $y1 Ordinate of control point 1.
5704 * @param float $x2 Abscissa of control point 2.
5705 * @param float $y2 Ordinate of control point 2.
5706 * @param float $x3 Abscissa of end point.
5707 * @param float $y3 Ordinate of end point.
5708 * @param string $style Style of rendering. Possible values are:
5709 * <ul>
5710 * <li>D or empty string: Draw (default).</li>
5711 * <li>F: Fill.</li>
5712 * <li>DF or FD: Draw and fill.</li>
5713 * </ul>
5714 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5715 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5716 * @access public
5717 * @see SetLineStyle()
5718 * @since 2.1.000 (2008-01-08)
5720 public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style = "", $line_style = array(), $fill_color = array()) {
5721 if (!(false === strpos($style, "F")) AND $fill_color) {
5722 list($r, $g, $b) = $fill_color;
5723 $this->SetFillColor($r, $g, $b);
5725 switch ($style) {
5726 case "F": {
5727 $op = "f";
5728 $line_style = array();
5729 break;
5731 case "FD":
5732 case "DF": {
5733 $op = "B";
5734 break;
5736 default: {
5737 $op = "S";
5738 break;
5741 if ($line_style) {
5742 $this->SetLineStyle($line_style);
5744 $this->_outPoint($x0, $y0);
5745 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
5746 $this->_out($op);
5750 * Draws an ellipse.
5751 * An ellipse is formed from n Bezier curves.
5752 * @param float $x0 Abscissa of center point.
5753 * @param float $y0 Ordinate of center point.
5754 * @param float $rx Horizontal radius.
5755 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
5756 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
5757 * @param float $astart: Angle start of draw line. Default value: 0.
5758 * @param float $afinish: Angle finish of draw line. Default value: 360.
5759 * @param string $style Style of rendering. Possible values are:
5760 * <ul>
5761 * <li>D or empty string: Draw (default).</li>
5762 * <li>F: Fill.</li>
5763 * <li>DF or FD: Draw and fill.</li>
5764 * <li>C: Draw close.</li>
5765 * </ul>
5766 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5767 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5768 * @param integer $nc Number of curves used in ellipse. Default value: 8.
5769 * @access public
5770 * @since 2.1.000 (2008-01-08)
5772 public function Ellipse($x0, $y0, $rx, $ry = 0, $angle = 0, $astart = 0, $afinish = 360, $style = "", $line_style = array(), $fill_color = array(), $nc = 8) {
5773 if ($angle) {
5774 $this->StartTransform();
5775 $this->Rotate($angle, $x0, $y0);
5776 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
5777 $this->StopTransform();
5778 return;
5780 if ($rx) {
5781 if (!(false === strpos($style, "F")) AND $fill_color) {
5782 list($r, $g, $b) = $fill_color;
5783 $this->SetFillColor($r, $g, $b);
5785 switch ($style) {
5786 case "F": {
5787 $op = "f";
5788 $line_style = array();
5789 break;
5791 case "FD":
5792 case "DF": {
5793 $op = "B";
5794 break;
5796 case "C": {
5797 $op = "s"; // Small "s" signifies closing the path as well
5798 break;
5800 default: {
5801 $op = "S";
5802 break;
5805 if ($line_style) {
5806 $this->SetLineStyle($line_style);
5808 if (!$ry) {
5809 $ry = $rx;
5811 $rx *= $this->k;
5812 $ry *= $this->k;
5813 if ($nc < 2){
5814 $nc = 2;
5816 $astart = deg2rad((float) $astart);
5817 $afinish = deg2rad((float) $afinish);
5818 $total_angle = $afinish - $astart;
5819 $dt = $total_angle / $nc;
5820 $dtm = $dt/3;
5821 $x0 *= $this->k;
5822 $y0 = ($this->h - $y0) * $this->k;
5823 $t1 = $astart;
5824 $a0 = $x0 + ($rx * cos($t1));
5825 $b0 = $y0 + ($ry * sin($t1));
5826 $c0 = -$rx * sin($t1);
5827 $d0 = $ry * cos($t1);
5828 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
5829 for ($i = 1; $i <= $nc; $i++) {
5830 // Draw this bit of the total curve
5831 $t1 = ($i * $dt) + $astart;
5832 $a1 = $x0 + ($rx * cos($t1));
5833 $b1 = $y0 + ($ry * sin($t1));
5834 $c1 = -$rx * sin($t1);
5835 $d1 = $ry * cos($t1);
5836 $this->_outCurve(($a0 + ($c0 * $dtm)) / $this->k, $this->h - (($b0 + ($d0 * $dtm)) / $this->k), ($a1 - ($c1 * $dtm)) / $this->k, $this->h - (($b1 - ($d1 * $dtm)) / $this->k), $a1 / $this->k, $this->h - ($b1 / $this->k));
5837 $a0 = $a1;
5838 $b0 = $b1;
5839 $c0 = $c1;
5840 $d0 = $d1;
5842 $this->_out($op);
5847 * Draws a circle.
5848 * A circle is formed from n Bezier curves.
5849 * @param float $x0 Abscissa of center point.
5850 * @param float $y0 Ordinate of center point.
5851 * @param float $r Radius.
5852 * @param float $astart: Angle start of draw line. Default value: 0.
5853 * @param float $afinish: Angle finish of draw line. Default value: 360.
5854 * @param string $style Style of rendering. Possible values are:
5855 * <ul>
5856 * <li>D or empty string: Draw (default).</li>
5857 * <li>F: Fill.</li>
5858 * <li>DF or FD: Draw and fill.</li>
5859 * <li>C: Draw close.</li>
5860 * </ul>
5861 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5862 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5863 * @param integer $nc Number of curves used in circle. Default value: 8.
5864 * @access public
5865 * @since 2.1.000 (2008-01-08)
5867 public function Circle($x0, $y0, $r, $astart = 0, $afinish = 360, $style = "", $line_style = array(), $fill_color = array(), $nc = 8) {
5868 $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
5872 * Draws a polygon.
5873 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
5874 * @param string $style Style of rendering. Possible values are:
5875 * <ul>
5876 * <li>D or empty string: Draw (default).</li>
5877 * <li>F: Fill.</li>
5878 * <li>DF or FD: Draw and fill.</li>
5879 * </ul>
5880 * @param array $line_style Line style of polygon. Array with keys among the following:
5881 * <ul>
5882 * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
5883 * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
5884 * </ul>
5885 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
5886 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5887 * @access public
5888 * @since 2.1.000 (2008-01-08)
5890 public function Polygon($p, $style = "", $line_style = array(), $fill_color = array()) {
5891 $np = count($p) / 2;
5892 if (!(false === strpos($style, "F")) AND $fill_color) {
5893 list($r, $g, $b) = $fill_color;
5894 $this->SetFillColor($r, $g, $b);
5896 switch ($style) {
5897 case "F": {
5898 $line_style = array();
5899 $op = "f";
5900 break;
5902 case "FD":
5903 case "DF": {
5904 $op = "B";
5905 break;
5907 default: {
5908 $op = "S";
5909 break;
5912 $draw = true;
5913 if ($line_style) {
5914 if (isset($line_style["all"])) {
5915 $this->SetLineStyle($line_style["all"]);
5917 else { // 0 .. (np - 1), op = {B, S}
5918 $draw = false;
5919 if ("B" == $op) {
5920 $op = "f";
5921 $this->_outPoint($p[0], $p[1]);
5922 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
5923 $this->_outLine($p[$i], $p[$i + 1]);
5925 $this->_outLine($p[0], $p[1]);
5926 $this->_out($op);
5928 $p[$np * 2] = $p[0];
5929 $p[($np * 2) + 1] = $p[1];
5930 for ($i = 0; $i < $np; $i++) {
5931 if (isset($line_style[$i])) {
5932 $this->Line($p[$i * 2], $p[($i * 2) + 1], $p[($i * 2) + 2], $p[($i * 2) + 3], $line_style[$i]);
5937 if ($draw) {
5938 $this->_outPoint($p[0], $p[1]);
5939 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
5940 $this->_outLine($p[$i], $p[$i + 1]);
5942 $this->_outLine($p[0], $p[1]);
5943 $this->_out($op);
5948 * Draws a regular polygon.
5949 * @param float $x0 Abscissa of center point.
5950 * @param float $y0 Ordinate of center point.
5951 * @param float $r: Radius of inscribed circle.
5952 * @param integer $ns Number of sides.
5953 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
5954 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
5955 * @param string $style Style of rendering. Possible values are:
5956 * <ul>
5957 * <li>D or empty string: Draw (default).</li>
5958 * <li>F: Fill.</li>
5959 * <li>DF or FD: Draw and fill.</li>
5960 * </ul>
5961 * @param array $line_style Line style of polygon sides. Array with keys among the following:
5962 * <ul>
5963 * <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
5964 * <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
5965 * </ul>
5966 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
5967 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5968 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
5969 * <ul>
5970 * <li>D or empty string: Draw (default).</li>
5971 * <li>F: Fill.</li>
5972 * <li>DF or FD: Draw and fill.</li>
5973 * </ul>
5974 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5975 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
5976 * @access public
5977 * @since 2.1.000 (2008-01-08)
5979 public function RegularPolygon($x0, $y0, $r, $ns, $angle = 0, $draw_circle = false, $style = "", $line_style = array(), $fill_color = array(), $circle_style = "", $circle_outLine_style = array(), $circle_fill_color = array()) {
5980 if (3 > $ns) {
5981 $ns = 3;
5983 if ($draw_circle) {
5984 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
5986 $p = array();
5987 for ($i = 0; $i < $ns; $i++) {
5988 $a = $angle + ($i * 360 / $ns);
5989 $a_rad = deg2rad((float) $a);
5990 $p[] = $x0 + ($r * sin($a_rad));
5991 $p[] = $y0 + ($r * cos($a_rad));
5993 $this->Polygon($p, $style, $line_style, $fill_color);
5997 * Draws a star polygon
5998 * @param float $x0 Abscissa of center point.
5999 * @param float $y0 Ordinate of center point.
6000 * @param float $r Radius of inscribed circle.
6001 * @param integer $nv Number of vertices.
6002 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
6003 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6004 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
6005 * @param string $style Style of rendering. Possible values are:
6006 * <ul>
6007 * <li>D or empty string: Draw (default).</li>
6008 * <li>F: Fill.</li>
6009 * <li>DF or FD: Draw and fill.</li>
6010 * </ul>
6011 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6012 * <ul>
6013 * <li>all: Line style of all sides. Array like for
6014 * {@link SetLineStyle SetLineStyle}.</li>
6015 * <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6016 * </ul>
6017 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6018 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6019 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6020 * <ul>
6021 * <li>D or empty string: Draw (default).</li>
6022 * <li>F: Fill.</li>
6023 * <li>DF or FD: Draw and fill.</li>
6024 * </ul>
6025 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6026 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6027 * @access public
6028 * @since 2.1.000 (2008-01-08)
6030 public function StarPolygon($x0, $y0, $r, $nv, $ng, $angle = 0, $draw_circle = false, $style = "", $line_style = array(), $fill_color = array(), $circle_style = "", $circle_outLine_style = array(), $circle_fill_color = array()) {
6031 if (2 > $nv) {
6032 $nv = 2;
6034 if ($draw_circle) {
6035 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6037 $p2 = array();
6038 $visited = array();
6039 for ($i = 0; $i < $nv; $i++) {
6040 $a = $angle + ($i * 360 / $nv);
6041 $a_rad = deg2rad((float) $a);
6042 $p2[] = $x0 + ($r * sin($a_rad));
6043 $p2[] = $y0 + ($r * cos($a_rad));
6044 $visited[] = false;
6046 $p = array();
6047 $i = 0;
6048 do {
6049 $p[] = $p2[$i * 2];
6050 $p[] = $p2[($i * 2) + 1];
6051 $visited[$i] = true;
6052 $i += $ng;
6053 $i %= $nv;
6054 } while (!$visited[$i]);
6055 $this->Polygon($p, $style, $line_style, $fill_color);
6059 * Draws a rounded rectangle.
6060 * @param float $x Abscissa of upper-left corner.
6061 * @param float $y Ordinate of upper-left corner.
6062 * @param float $w Width.
6063 * @param float $h Height.
6064 * @param float $r Radius of the rounded corners.
6065 * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111").
6066 * @param string $style Style of rendering. Possible values are:
6067 * <ul>
6068 * <li>D or empty string: Draw (default).</li>
6069 * <li>F: Fill.</li>
6070 * <li>DF or FD: Draw and fill.</li>
6071 * </ul>
6072 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6073 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6074 * @access public
6075 * @since 2.1.000 (2008-01-08)
6077 public function RoundedRect($x, $y, $w, $h, $r, $round_corner = "1111", $style = "", $border_style = array(), $fill_color = array()) {
6078 if ("0000" == $round_corner) { // Not rounded
6079 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
6080 } else { // Rounded
6081 if (!(false === strpos($style, "F")) AND $fill_color) {
6082 list($red, $g, $b) = $fill_color;
6083 $this->SetFillColor($red, $g, $b);
6085 switch ($style) {
6086 case "F": {
6087 $border_style = array();
6088 $op = "f";
6089 break;
6091 case "FD":
6092 case "DF": {
6093 $op = "B";
6094 break;
6096 default: {
6097 $op = "S";
6098 break;
6101 if ($border_style) {
6102 $this->SetLineStyle($border_style);
6104 $MyArc = 4 / 3 * (sqrt(2) - 1);
6105 $this->_outPoint($x + $r, $y);
6106 $xc = $x + $w - $r;
6107 $yc = $y + $r;
6108 $this->_outLine($xc, $y);
6109 if ($round_corner[0]) {
6110 $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
6111 } else {
6112 $this->_outLine($x + $w, $y);
6114 $xc = $x + $w - $r;
6115 $yc = $y + $h - $r;
6116 $this->_outLine($x + $w, $yc);
6117 if ($round_corner[1]) {
6118 $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
6119 } else {
6120 $this->_outLine($x + $w, $y + $h);
6122 $xc = $x + $r;
6123 $yc = $y + $h - $r;
6124 $this->_outLine($xc, $y + $h);
6125 if ($round_corner[2]) {
6126 $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
6127 } else {
6128 $this->_outLine($x, $y + $h);
6130 $xc = $x + $r;
6131 $yc = $y + $r;
6132 $this->_outLine($x, $yc);
6133 if ($round_corner[3]) {
6134 $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
6135 } else {
6136 $this->_outLine($x, $y);
6137 $this->_outLine($x + $r, $y);
6139 $this->_out($op);
6143 // END GRAPHIC FUNCTIONS SECTION -----------------------
6145 // BIDIRECTIONAL TEXT SECTION --------------------------
6148 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
6149 * @param string $str string to manipulate.
6150 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
6151 * @return string
6152 * @author Nicola Asuni
6153 * @since 2.1.000 (2008-01-08)
6155 protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
6156 global $unicode,$unicode_mirror, $unicode_arlet;
6157 require_once(dirname(__FILE__).'/unicode_data.php');
6159 // paragraph embedding level
6160 $pel = 0;
6161 // max level
6162 $maxlevel = 0;
6164 // check if string contains arabic text
6165 if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
6166 $arabic = true;
6167 } else {
6168 $arabic = false;
6171 // check if string contains RTL text
6172 if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
6173 return $this->UTF8ToUTF16BE($str, false);
6176 // convert string to array of unicode chars
6177 $ta = $this->UTF8StringToArray($str);
6178 // get number of chars
6179 $numchars = count($ta);
6181 if ($forcertl == 'R') {
6182 $pel = 1;
6183 } elseif ($forcertl == 'L') {
6184 $pel = 0;
6185 } else {
6186 // P2. In each paragraph, find the first character of type L, AL, or R.
6187 // P3. If a character is found in P2 and it is of type AL or R, then set the paragraph embedding level to one; otherwise, set it to zero.
6188 for ($i=0; $i < $numchars; $i++) {
6189 $type = $unicode[$ta[$i]];
6190 if ($type == 'L') {
6191 $pel = 0;
6192 break;
6193 } elseif (($type == 'AL') OR ($type == 'R')) {
6194 $pel = 1;
6195 break;
6200 // Current Embedding Level
6201 $cel = $pel;
6202 // directional override status
6203 $dos = 'N';
6204 $remember = array();
6205 // start-of-level-run
6206 $sor = $pel % 2 ? 'R' : 'L';
6207 $eor = $sor;
6209 //$levels = array(array('level' => $cel, 'sor' => $sor, 'eor' => '', 'chars' => array()));
6210 //$current_level = &$levels[count( $levels )-1];
6212 // Array of characters data
6213 $chardata = Array();
6215 // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase.
6216 // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
6217 for ($i=0; $i < $numchars; $i++) {
6218 if ($ta[$i] == K_RLE) {
6219 // X2. With each RLE, compute the least greater odd embedding level.
6220 // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
6221 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6222 $next_level = $cel + ($cel % 2) + 1;
6223 if ($next_level < 62) {
6224 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
6225 $cel = $next_level;
6226 $dos = 'N';
6227 $sor = $eor;
6228 $eor = $cel % 2 ? 'R' : 'L';
6230 } elseif ($ta[$i] == K_LRE) {
6231 // X3. With each LRE, compute the least greater even embedding level.
6232 // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
6233 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6234 $next_level = $cel + 2 - ($cel % 2);
6235 if ( $next_level < 62 ) {
6236 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
6237 $cel = $next_level;
6238 $dos = 'N';
6239 $sor = $eor;
6240 $eor = $cel % 2 ? 'R' : 'L';
6242 } elseif ($ta[$i] == K_RLO) {
6243 // X4. With each RLO, compute the least greater odd embedding level.
6244 // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left.
6245 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6246 $next_level = $cel + ($cel % 2) + 1;
6247 if ($next_level < 62) {
6248 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
6249 $cel = $next_level;
6250 $dos = 'R';
6251 $sor = $eor;
6252 $eor = $cel % 2 ? 'R' : 'L';
6254 } elseif ($ta[$i] == K_LRO) {
6255 // X5. With each LRO, compute the least greater even embedding level.
6256 // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right.
6257 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6258 $next_level = $cel + 2 - ($cel % 2);
6259 if ( $next_level < 62 ) {
6260 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
6261 $cel = $next_level;
6262 $dos = 'L';
6263 $sor = $eor;
6264 $eor = $cel % 2 ? 'R' : 'L';
6266 } elseif ($ta[$i] == K_PDF) {
6267 // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override.
6268 if (count($remember)) {
6269 $last = count($remember ) - 1;
6270 if (($remember[$last]['num'] == K_RLE) OR
6271 ($remember[$last]['num'] == K_LRE) OR
6272 ($remember[$last]['num'] == K_RLO) OR
6273 ($remember[$last]['num'] == K_LRO)) {
6274 $match = array_pop($remember);
6275 $cel = $match['cel'];
6276 $dos = $match['dos'];
6277 $sor = $eor;
6278 $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
6281 } elseif (($ta[$i] != K_RLE) AND
6282 ($ta[$i] != K_LRE) AND
6283 ($ta[$i] != K_RLO) AND
6284 ($ta[$i] != K_LRO) AND
6285 ($ta[$i] != K_PDF)) {
6286 // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
6287 // a. Set the level of the current character to the current embedding level.
6288 // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
6289 if ($dos != 'N') {
6290 $chardir = $dos;
6291 } else {
6292 $chardir = $unicode[$ta[$i]];
6294 // stores string characters and other information
6295 $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
6297 } // end for each char
6299 // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
6300 // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
6301 // X10. The remaining rules are applied to each run of characters at the same level. For each run, determine the start-of-level-run (sor) and end-of-level-run (eor) type, either L or R. This depends on the higher of the two levels on either side of the boundary (at the start or end of the paragraph, the level of the “other” run is the base embedding level). If the higher level is odd, the type is R; otherwise, it is L.
6303 // 3.3.3 Resolving Weak Types
6304 // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used.
6305 // Nonspacing marks are now resolved based on the previous characters.
6306 $numchars = count($chardata);
6308 // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor.
6309 $prevlevel = -1; // track level changes
6310 $levcount = 0; // counts consecutive chars at the same level
6311 for ($i=0; $i < $numchars; $i++) {
6312 if ($chardata[$i]['type'] == 'NSM') {
6313 if ($levcount) {
6314 $chardata[$i]['type'] = $chardata[$i]['sor'];
6315 } elseif ($i > 0) {
6316 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
6319 if ($chardata[$i]['level'] != $prevlevel) {
6320 $levcount = 0;
6321 } else {
6322 $levcount++;
6324 $prevlevel = $chardata[$i]['level'];
6327 // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number.
6328 $prevlevel = -1;
6329 $levcount = 0;
6330 for ($i=0; $i < $numchars; $i++) {
6331 if ($chardata[$i]['char'] == 'EN') {
6332 for ($j=$levcount; $j >= 0; $j--) {
6333 if ($chardata[$j]['type'] == 'AL') {
6334 $chardata[$i]['type'] = 'AN';
6335 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
6336 break;
6340 if ($chardata[$i]['level'] != $prevlevel) {
6341 $levcount = 0;
6342 } else {
6343 $levcount++;
6345 $prevlevel = $chardata[$i]['level'];
6348 // W3. Change all ALs to R.
6349 for ($i=0; $i < $numchars; $i++) {
6350 if ($chardata[$i]['type'] == 'AL') {
6351 $chardata[$i]['type'] = 'R';
6355 // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type.
6356 $prevlevel = -1;
6357 $levcount = 0;
6358 for ($i=0; $i < $numchars; $i++) {
6359 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
6360 if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
6361 $chardata[$i]['type'] = 'EN';
6362 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
6363 $chardata[$i]['type'] = 'EN';
6364 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
6365 $chardata[$i]['type'] = 'AN';
6368 if ($chardata[$i]['level'] != $prevlevel) {
6369 $levcount = 0;
6370 } else {
6371 $levcount++;
6373 $prevlevel = $chardata[$i]['level'];
6376 // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
6377 $prevlevel = -1;
6378 $levcount = 0;
6379 for ($i=0; $i < $numchars; $i++) {
6380 if($chardata[$i]['type'] == 'ET') {
6381 if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
6382 $chardata[$i]['type'] = 'EN';
6383 } else {
6384 $j = $i+1;
6385 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
6386 if ($chardata[$j]['type'] == 'EN') {
6387 $chardata[$i]['type'] = 'EN';
6388 break;
6389 } elseif ($chardata[$j]['type'] != 'ET') {
6390 break;
6392 $j++;
6396 if ($chardata[$i]['level'] != $prevlevel) {
6397 $levcount = 0;
6398 } else {
6399 $levcount++;
6401 $prevlevel = $chardata[$i]['level'];
6404 // W6. Otherwise, separators and terminators change to Other Neutral.
6405 $prevlevel = -1;
6406 $levcount = 0;
6407 for ($i=0; $i < $numchars; $i++) {
6408 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
6409 $chardata[$i]['type'] = 'ON';
6411 if ($chardata[$i]['level'] != $prevlevel) {
6412 $levcount = 0;
6413 } else {
6414 $levcount++;
6416 $prevlevel = $chardata[$i]['level'];
6419 //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L.
6420 $prevlevel = -1;
6421 $levcount = 0;
6422 for ($i=0; $i < $numchars; $i++) {
6423 if ($chardata[$i]['char'] == 'EN') {
6424 for ($j=$levcount; $j >= 0; $j--) {
6425 if ($chardata[$j]['type'] == 'L') {
6426 $chardata[$i]['type'] = 'L';
6427 } elseif ($chardata[$j]['type'] == 'R') {
6428 break;
6432 if ($chardata[$i]['level'] != $prevlevel) {
6433 $levcount = 0;
6434 } else {
6435 $levcount++;
6437 $prevlevel = $chardata[$i]['level'];
6440 // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries.
6441 $prevlevel = -1;
6442 $levcount = 0;
6443 for ($i=0; $i < $numchars; $i++) {
6444 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
6445 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
6446 $chardata[$i]['type'] = 'L';
6447 } elseif (($chardata[$i]['type'] == 'N') AND
6448 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
6449 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
6450 $chardata[$i]['type'] = 'R';
6451 } elseif ($chardata[$i]['type'] == 'N') {
6452 // N2. Any remaining neutrals take the embedding direction
6453 $chardata[$i]['type'] = $chardata[$i]['sor'];
6455 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
6456 // first char
6457 if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
6458 $chardata[$i]['type'] = 'L';
6459 } elseif (($chardata[$i]['type'] == 'N') AND
6460 (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
6461 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
6462 $chardata[$i]['type'] = 'R';
6463 } elseif ($chardata[$i]['type'] == 'N') {
6464 // N2. Any remaining neutrals take the embedding direction
6465 $chardata[$i]['type'] = $chardata[$i]['sor'];
6467 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
6468 //last char
6469 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
6470 $chardata[$i]['type'] = 'L';
6471 } elseif (($chardata[$i]['type'] == 'N') AND
6472 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
6473 (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
6474 $chardata[$i]['type'] = 'R';
6475 } elseif ($chardata[$i]['type'] == 'N') {
6476 // N2. Any remaining neutrals take the embedding direction
6477 $chardata[$i]['type'] = $chardata[$i]['sor'];
6479 } elseif ($chardata[$i]['type'] == 'N') {
6480 // N2. Any remaining neutrals take the embedding direction
6481 $chardata[$i]['type'] = $chardata[$i]['sor'];
6483 if ($chardata[$i]['level'] != $prevlevel) {
6484 $levcount = 0;
6485 } else {
6486 $levcount++;
6488 $prevlevel = $chardata[$i]['level'];
6491 // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels.
6492 // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
6493 for ($i=0; $i < $numchars; $i++) {
6494 $odd = $chardata[$i]['level'] % 2;
6495 if ($odd) {
6496 if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
6497 $chardata[$i]['level'] += 1;
6499 } else {
6500 if ($chardata[$i]['type'] == 'R') {
6501 $chardata[$i]['level'] += 1;
6502 } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
6503 $chardata[$i]['level'] += 2;
6506 $maxlevel = max($chardata[$i]['level'],$maxlevel);
6509 // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
6510 // 1. Segment separators,
6511 // 2. Paragraph separators,
6512 // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
6513 // 4. Any sequence of white space characters at the end of the line.
6514 for ($i=0; $i < $numchars; $i++) {
6515 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
6516 $chardata[$i]['level'] = $pel;
6517 } elseif ($chardata[$i]['type'] == 'WS') {
6518 $j = $i+1;
6519 while ($j < $numchars) {
6520 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
6521 (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
6522 $chardata[$i]['level'] = $pel;;
6523 break;
6524 } elseif ($chardata[$j]['type'] != 'WS') {
6525 break;
6527 $j++;
6532 // Arabic Shaping
6533 // Cursively connected scripts, such as Arabic or Syriac, require the selection of positional character shapes that depend on adjacent characters. Shaping is logically applied after the Bidirectional Algorithm is used and is limited to characters within the same directional run.
6534 if ($arabic) {
6535 for ($i=0; $i < $numchars; $i++) {
6536 if ($unicode[$chardata[$i]['char']] == 'AL') {
6537 if (($i > 0) AND (($i+1) < $numchars) AND
6538 ($unicode[$chardata[($i-1)]['char']] == 'AL') AND
6539 ($unicode[$chardata[($i+1)]['char']] == 'AL') AND
6540 ($chardata[($i-1)]['type'] == $chardata[$i]['type']) AND
6541 ($chardata[($i+1)]['type'] == $chardata[$i]['type'])) {
6542 // medial
6543 if (isset($unicode_arlet[$chardata[$i]['char']][3])) {
6544 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][3];
6546 } elseif ((($i+1) < $numchars) AND
6547 ($unicode[$chardata[($i+1)]['char']] == 'AL') AND
6548 ($chardata[($i+1)]['type'] == $chardata[$i]['type'])) {
6549 // initial
6550 if (isset($unicode_arlet[$chardata[$i]['char']][2])) {
6551 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][2];
6553 } elseif (($i > 0) AND
6554 ($unicode[$chardata[($i-1)]['char']] == 'AL') AND
6555 ($chardata[($i-1)]['type'] == $chardata[$i]['type'])) {
6556 // final
6557 if (isset($unicode_arlet[$chardata[$i]['char']][1])) {
6558 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][1];
6560 } elseif (isset($unicode_arlet[$chardata[$i]['char']][0])) {
6561 // isolated
6562 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][0];
6568 // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher.
6569 for ($j=$maxlevel; $j > 0; $j--) {
6570 $ordarray = Array();
6571 $revarr = Array();
6572 $onlevel = false;
6573 for ($i=0; $i < $numchars; $i++) {
6574 if ($chardata[$i]['level'] >= $j) {
6575 $onlevel = true;
6576 if (isset($unicode_mirror[$chardata[$i]['char']])) {
6577 // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true.
6578 $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
6580 $revarr[] = $chardata[$i];
6581 } else {
6582 if($onlevel) {
6583 $revarr = array_reverse($revarr);
6584 $ordarray = array_merge($ordarray, $revarr);
6585 $revarr = Array();
6586 $onlevel = false;
6588 $ordarray[] = $chardata[$i];
6591 if($onlevel) {
6592 $revarr = array_reverse($revarr);
6593 $ordarray = array_merge($ordarray, $revarr);
6595 $chardata = $ordarray;
6598 $ordarray = array();
6599 for ($i=0; $i < $numchars; $i++) {
6600 $ordarray[] = $chardata[$i]['char'];
6603 return $this->arrUTF8ToUTF16BE($ordarray, $setbom);
6606 // END OF BIDIRECTIONAL TEXT SECTION -------------------
6609 * Adds a bookmark.
6610 * @param string $txt bookmark description.
6611 * @param int $level bookmark level.
6612 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
6613 * @access public
6614 * @author Olivier Plathey, Nicola Asuni
6615 * @since 2.1.002 (2008-02-12)
6617 public function Bookmark($txt, $level=0, $y=-1) {
6618 if($y == -1) {
6619 $y = $this->GetY();
6621 $this->outlines[]=array('t'=>$txt,'l'=>$level,'y'=>$y,'p'=>$this->PageNo());
6625 * Create a bookmark PDF string.
6626 * @access private
6627 * @author Olivier Plathey, Nicola Asuni
6628 * @since 2.1.002 (2008-02-12)
6630 private function _putbookmarks() {
6631 $nb = count($this->outlines);
6632 if($nb == 0) {
6633 return;
6635 $lru = array();
6636 $level = 0;
6637 foreach($this->outlines as $i=>$o) {
6638 if($o['l'] > 0) {
6639 $parent = $lru[$o['l'] - 1];
6640 //Set parent and last pointers
6641 $this->outlines[$i]['parent'] = $parent;
6642 $this->outlines[$parent]['last'] = $i;
6643 if($o['l'] > $level) {
6644 //Level increasing: set first pointer
6645 $this->outlines[$parent]['first'] = $i;
6647 } else {
6648 $this->outlines[$i]['parent']=$nb;
6650 if($o['l']<=$level and $i>0) {
6651 //Set prev and next pointers
6652 $prev = $lru[$o['l']];
6653 $this->outlines[$prev]['next'] = $i;
6654 $this->outlines[$i]['prev'] = $prev;
6656 $lru[$o['l']] = $i;
6657 $level = $o['l'];
6659 //Outline items
6660 $n = $this->n+1;
6661 foreach($this->outlines as $i=>$o) {
6662 $this->_newobj();
6663 $this->_out('<</Title '.$this->_textstring($o['t']));
6664 $this->_out('/Parent '.($n+$o['parent']).' 0 R');
6665 if(isset($o['prev']))
6666 $this->_out('/Prev '.($n+$o['prev']).' 0 R');
6667 if(isset($o['next']))
6668 $this->_out('/Next '.($n+$o['next']).' 0 R');
6669 if(isset($o['first']))
6670 $this->_out('/First '.($n+$o['first']).' 0 R');
6671 if(isset($o['last']))
6672 $this->_out('/Last '.($n+$o['last']).' 0 R');
6673 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]',1+2*$o['p'],($this->h-$o['y'])*$this->k));
6674 $this->_out('/Count 0>>');
6675 $this->_out('endobj');
6677 //Outline root
6678 $this->_newobj();
6679 $this->OutlineRoot=$this->n;
6680 $this->_out('<</Type /Outlines /First '.$n.' 0 R');
6681 $this->_out('/Last '.($n+$lru[0]).' 0 R>>');
6682 $this->_out('endobj');
6686 // --- JAVASCRIPT - FORMS ------------------------------
6689 * Adds a javascript
6690 * @access public
6691 * @author Johannes Güntert, Nicola Asuni
6692 * @since 2.1.002 (2008-02-12)
6694 public function IncludeJS($script) {
6695 $this->javascript .= $script;
6699 * Create a javascript PDF string.
6700 * @access private
6701 * @author Johannes Güntert, Nicola Asuni
6702 * @since 2.1.002 (2008-02-12)
6704 private function _putjavascript() {
6705 if (empty($this->javascript)) {
6706 return;
6708 $this->_newobj();
6709 $this->n_js = $this->n;
6710 $this->_out('<<');
6711 $this->_out('/Names [(EmbeddedJS) '.($this->n+1).' 0 R ]');
6712 $this->_out('>>');
6713 $this->_out('endobj');
6714 $this->_newobj();
6715 $this->_out('<<');
6716 $this->_out('/S /JavaScript');
6717 $this->_out('/JS '.$this->_textstring($this->javascript));
6718 $this->_out('>>');
6719 $this->_out('endobj');
6723 * Convert color to javascript color.
6724 * @param string $color color name or #RRGGBB
6725 * @access private
6726 * @author Denis Van Nuffelen, Nicola Asuni
6727 * @since 2.1.002 (2008-02-12)
6729 private function _JScolor($color) {
6730 static $aColors = array('transparent','black','white','red','green','blue','cyan','magenta','yellow','dkGray','gray','ltGray');
6731 if(substr($color,0,1) == '#') {
6732 return sprintf("['RGB',%.3f,%.3f,%.3f]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
6734 if(!in_array($color,$aColors)) {
6735 $this->Error('Invalid color: '.$color);
6737 return 'color.'.$color;
6741 * Adds a javascript form field.
6742 * @param string $type field type
6743 * @param string $name field name
6744 * @param int $x horizontal position
6745 * @param int $y vertical position
6746 * @param int $w width
6747 * @param int $h height
6748 * @param string $prop properties
6749 * @access private
6750 * @author Denis Van Nuffelen, Nicola Asuni
6751 * @since 2.1.002 (2008-02-12)
6753 private function _addfield($type, $name, $x, $y, $w, $h, $prop) {
6754 $k = $this->k;
6755 $this->javascript .= sprintf("f=addField('%s','%s',%d,[%.2f,%.2f,%.2f,%.2f]);",$name,$type,$this->PageNo()-1,$x*$k,($this->h-$y)*$k+1,($x+$w)*$k,($this->h-$y-$h)*$k+1);
6756 $this->javascript .= 'f.textSize='.$this->FontSizePt.';';
6757 if(isset($prop['value'])) {
6758 $this->javascript .= "f.value='".addslashes($prop['value'])."';";
6760 if(isset($prop['TextColor'])) {
6761 $this->javascript .= 'f.textColor='.$this->_JScolor($prop['TextColor']).';';
6763 if(isset($prop['FillColor'])) {
6764 $this->javascript .= 'f.fillColor='.$this->_JScolor($prop['FillColor']).';';
6766 if(isset($prop['BorderColor'])) {
6767 $this->javascript .= 'f.strokeColor='.$this->_JScolor($prop['BorderColor']).';';
6769 if(isset($prop['BorderStyle'])) {
6770 $this->javascript .= "f.borderStyle='".$prop['BorderStyle']."';";
6772 $this->x+=$w;
6776 * Creates a text field
6777 * @param string $name field name
6778 * @param int $w width
6779 * @param int $h height
6780 * @param string $prop properties. The value property allows to set the initial value. The multiline property allows to define the field as multiline.
6781 * @access public
6782 * @author Denis Van Nuffelen, Nicola Asuni
6783 * @since 2.1.002 (2008-02-12)
6785 public function TextField($name, $w, $h, $prop=array()) {
6786 $this->_addfield('text',$name,$this->x,$this->y,$w,$h,$prop);
6787 if(isset($prop['multiline']) AND $prop['multiline']) {
6788 $this->javascript .= 'f.multiline=true;';
6793 * Creates a Combo-box field
6794 * @param string $name field name
6795 * @param int $w width
6796 * @param int $h height
6797 * @param array $values array containing the list of values.
6798 * @param string $prop properties.
6799 * @access public
6800 * @author Denis Van Nuffelen, Nicola Asuni
6801 * @since 2.1.002 (2008-02-12)
6803 public function ComboBox($name, $w, $h, $values, $prop=array()) {
6804 $this->_addfield('combobox',$name,$this->x,$this->y,$w,$h,$prop);
6805 $s = '';
6806 foreach($values as $value) {
6807 $s .= "'".addslashes($value)."',";
6809 $this->javascript .= 'f.setItems(['.substr($s,0,-1).']);';
6813 * Creates a CheckBox field
6814 * @param string $name field name
6815 * @param int $w width
6816 * @param boolean $checked define the initial state (default = false).
6817 * @param string $prop properties.
6818 * @access public
6819 * @author Denis Van Nuffelen, Nicola Asuni
6820 * @since 2.1.002 (2008-02-12)
6822 public function CheckBox($name, $w, $checked=false, $prop=array()) {
6823 $prop['value'] = ($checked ? 'Yes' : 'Off');
6824 if(!isset($prop['BorderColor'])) {
6825 $prop['BorderColor']='black';
6827 $this->_addfield('checkbox',$name,$this->x,$this->y,$w,$w,$prop);
6831 * Creates a button field
6832 * @param string $name field name
6833 * @param int $w width
6834 * @param int $h height
6835 * @param string $caption caption.
6836 * @param string $action action triggered by the button (JavaScript code).
6837 * @param string $prop properties.
6838 * @access public
6839 * @author Denis Van Nuffelen, Nicola Asuni
6840 * @since 2.1.002 (2008-02-12)
6842 public function Button($name, $w, $h, $caption, $action, $prop=array()) {
6843 if(!isset($prop['BorderColor'])) {
6844 $prop['BorderColor']='black';
6846 $prop['BorderStyle']='beveled';
6847 $this->_addfield('button',$name,$this->x,$this->y,$w,$h,$prop);
6848 $this->javascript .= "f.buttonSetCaption('".addslashes($caption)."');";
6849 $this->javascript .= "f.setAction('MouseUp','".addslashes($action)."');";
6850 $this->javascript .= "f.highlight='push';";
6851 $this->javascript .= 'f.print=false;';
6854 // END JAVASCRIPT - FORMS ------------------------------
6856 } // END OF TCPDF CLASS
6858 //Handle special IE contype request
6859 if(isset($_SERVER['HTTP_USER_AGENT']) AND ($_SERVER['HTTP_USER_AGENT']=='contype')) {
6860 header('Content-Type: application/pdf');
6861 exit;
6865 //============================================================+
6866 // END OF FILE
6867 //============================================================+