TCPDF: merge conflict fixed
[phpmyadmin-themes.git] / libraries / tcpdf / tcpdf.php
blob3d134b61de0738d12142e2246de54651c62063dc
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(ob_get_contents().'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-Length: '.strlen($this->buffer));
3011 header('Content-disposition: attachment; filename="'.$name.'"');
3012 echo $this->buffer;
3013 break;
3015 case 'F': {
3016 //Save to local file
3017 $f=fopen($name,'wb');
3018 if(!$f) {
3019 $this->Error('Unable to create output file: '.$name);
3021 fwrite($f,$this->buffer,strlen($this->buffer));
3022 fclose($f);
3023 break;
3025 case 'S': {
3026 //Return as a string
3027 return $this->buffer;
3029 default: {
3030 $this->Error('Incorrect output destination: '.$dest);
3033 return '';
3036 // Protected methods
3039 * Check for locale-related bug
3040 * @access protected
3042 protected function _dochecks() {
3043 //Check for locale-related bug
3044 if(1.1==1) {
3045 $this->Error('Don\'t alter the locale before including class file');
3047 //Check for decimal separator
3048 if(sprintf('%.1f',1.0)!='1.0') {
3049 setlocale(LC_NUMERIC,'C');
3054 * Return fonts path
3055 * @access protected
3057 protected function _getfontpath() {
3058 if(!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/font')) {
3059 define('K_PATH_FONTS', dirname(__FILE__).'/font/');
3061 return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
3065 * Start document
3066 * @access protected
3068 protected function _begindoc() {
3069 //Start document
3070 $this->state=1;
3071 $this->_out('%PDF-'.$this->PDFVersion);
3075 * _putpages
3076 * @access protected
3078 protected function _putpages() {
3079 $nb = $this->page;
3080 if(!empty($this->AliasNbPages)) {
3081 $nbstr = $this->UTF8ToUTF16BE($nb, false);
3082 //Replace number of pages
3083 for($n=1;$n<=$nb;$n++) {
3084 $this->pages[$n]=str_replace($this->AliasNbPages, $nbstr, $this->pages[$n]);
3087 if($this->DefOrientation=='P') {
3088 $wPt=$this->fwPt;
3089 $hPt=$this->fhPt;
3091 else {
3092 $wPt=$this->fhPt;
3093 $hPt=$this->fwPt;
3095 $filter=($this->compress) ? '/Filter /FlateDecode ' : '';
3096 for($n=1;$n<=$nb;$n++) {
3097 //Page
3098 $this->_newobj();
3099 $this->_out('<</Type /Page');
3100 $this->_out('/Parent 1 0 R');
3101 if(isset($this->OrientationChanges[$n])) {
3102 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$hPt,$wPt));
3104 $this->_out('/Resources 2 0 R');
3105 if(isset($this->PageLinks[$n])) {
3106 //Links
3107 $annots='/Annots [';
3108 foreach($this->PageLinks[$n] as $pl) {
3109 $rect=sprintf('%.2f %.2f %.2f %.2f',$pl[0],$pl[1],$pl[0]+$pl[2],$pl[1]-$pl[3]);
3110 $annots.='<</Type /Annot /Subtype /Link /Rect ['.$rect.'] /Border [0 0 0] ';
3111 if(is_string($pl[4])) {
3112 $annots.='/A <</S /URI /URI '.$this->_uristring($pl[4]).'>>>>';
3114 else {
3115 $l=$this->links[$pl[4]];
3116 $h=isset($this->OrientationChanges[$l[0]]) ? $wPt : $hPt;
3117 $annots.=sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]>>',1+2*$l[0],$h-$l[1]*$this->k);
3120 $this->_out($annots.']');
3122 $this->_out('/Contents '.($this->n+1).' 0 R>>');
3123 $this->_out('endobj');
3124 //Page content
3125 $p=($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n];
3126 $this->_newobj();
3127 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
3128 $this->_putstream($p);
3129 $this->_out('endobj');
3131 //Pages root
3132 $this->offsets[1]=strlen($this->buffer);
3133 $this->_out('1 0 obj');
3134 $this->_out('<</Type /Pages');
3135 $kids='/Kids [';
3136 for($i=0;$i<$nb;$i++) {
3137 $kids.=(3+2*$i).' 0 R ';
3139 $this->_out($kids.']');
3140 $this->_out('/Count '.$nb);
3141 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$wPt,$hPt));
3142 $this->_out('>>');
3143 $this->_out('endobj');
3147 * Adds fonts
3148 * _putfonts
3149 * @access protected
3151 protected function _putfonts() {
3152 $nf=$this->n;
3153 foreach($this->diffs as $diff) {
3154 //Encodings
3155 $this->_newobj();
3156 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
3157 $this->_out('endobj');
3159 $mqr=get_magic_quotes_runtime();
3160 set_magic_quotes_runtime(0);
3161 foreach($this->FontFiles as $file=>$info) {
3162 //Font file embedding
3163 $this->_newobj();
3164 $this->FontFiles[$file]['n']=$this->n;
3165 $font='';
3166 $f=fopen($this->_getfontpath().strtolower($file),'rb',1);
3167 if(!$f) {
3168 $this->Error('Font file not found: '.$file);
3170 while(!feof($f)) {
3171 $font .= fread($f, 8192);
3173 fclose($f);
3174 $compressed=(substr($file,-2)=='.z');
3175 if(!$compressed && isset($info['length2'])) {
3176 $header=(ord($font{0})==128);
3177 if($header) {
3178 //Strip first binary header
3179 $font=substr($font,6);
3181 if($header && ord($font{$info['length1']})==128) {
3182 //Strip second binary header
3183 $font=substr($font,0,$info['length1']).substr($font,$info['length1']+6);
3186 $this->_out('<</Length '.strlen($font));
3187 if($compressed) {
3188 $this->_out('/Filter /FlateDecode');
3190 $this->_out('/Length1 '.$info['length1']);
3191 if(isset($info['length2'])) {
3192 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
3194 $this->_out('>>');
3195 $this->_putstream($font);
3196 $this->_out('endobj');
3198 set_magic_quotes_runtime($mqr);
3199 foreach($this->fonts as $k=>$font) {
3200 //Font objects
3201 $this->fonts[$k]['n']=$this->n+1;
3202 $type=$font['type'];
3203 $name=$font['name'];
3204 if($type=='core') {
3205 //Standard font
3206 $this->_newobj();
3207 $this->_out('<</Type /Font');
3208 $this->_out('/BaseFont /'.$name);
3209 $this->_out('/Subtype /Type1');
3210 if($name!='Symbol' && $name!='ZapfDingbats') {
3211 $this->_out('/Encoding /WinAnsiEncoding');
3213 $this->_out('>>');
3214 $this->_out('endobj');
3215 } elseif($type=='Type1' OR $type=='TrueType') {
3216 //Additional Type1 or TrueType font
3217 $this->_newobj();
3218 $this->_out('<</Type /Font');
3219 $this->_out('/BaseFont /'.$name);
3220 $this->_out('/Subtype /'.$type);
3221 $this->_out('/FirstChar 32 /LastChar 255');
3222 $this->_out('/Widths '.($this->n+1).' 0 R');
3223 $this->_out('/FontDescriptor '.($this->n+2).' 0 R');
3224 if($font['enc']) {
3225 if(isset($font['diff'])) {
3226 $this->_out('/Encoding '.($nf+$font['diff']).' 0 R');
3227 } else {
3228 $this->_out('/Encoding /WinAnsiEncoding');
3231 $this->_out('>>');
3232 $this->_out('endobj');
3233 //Widths
3234 $this->_newobj();
3235 $cw=&$font['cw'];
3236 $s='[';
3237 for($i=32;$i<=255;$i++) {
3238 $s.=$cw[chr($i)].' ';
3240 $this->_out($s.']');
3241 $this->_out('endobj');
3242 //Descriptor
3243 $this->_newobj();
3244 $s='<</Type /FontDescriptor /FontName /'.$name;
3245 foreach($font['desc'] as $k=>$v) {
3246 $s.=' /'.$k.' '.$v;
3248 $file = $font['file'];
3249 if($file) {
3250 $s.=' /FontFile'.($type=='Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
3252 $this->_out($s.'>>');
3253 $this->_out('endobj');
3254 } else {
3255 //Allow for additional types
3256 $mtd='_put'.strtolower($type);
3257 if(!method_exists($this, $mtd)) {
3258 $this->Error('Unsupported font type: '.$type);
3260 $this->$mtd($font);
3266 * _putimages
3267 * @access protected
3269 protected function _putimages() {
3270 $filter=($this->compress) ? '/Filter /FlateDecode ' : '';
3271 reset($this->images);
3272 while(list($file,$info)=each($this->images)) {
3273 $this->_newobj();
3274 $this->images[$file]['n']=$this->n;
3275 $this->_out('<</Type /XObject');
3276 $this->_out('/Subtype /Image');
3277 $this->_out('/Width '.$info['w']);
3278 $this->_out('/Height '.$info['h']);
3280 if (isset($info["masked"])) {
3281 $this->_out('/SMask '.($this->n-1).' 0 R');
3284 if($info['cs']=='Indexed') {
3285 $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal'])/3-1).' '.($this->n+1).' 0 R]');
3287 else {
3288 $this->_out('/ColorSpace /'.$info['cs']);
3289 if($info['cs']=='DeviceCMYK') {
3290 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
3293 $this->_out('/BitsPerComponent '.$info['bpc']);
3294 if(isset($info['f'])) {
3295 $this->_out('/Filter /'.$info['f']);
3297 if(isset($info['parms'])) {
3298 $this->_out($info['parms']);
3300 if(isset($info['trns']) and is_array($info['trns'])) {
3301 $trns='';
3302 for($i=0;$i<count($info['trns']);$i++) {
3303 $trns.=$info['trns'][$i].' '.$info['trns'][$i].' ';
3305 $this->_out('/Mask ['.$trns.']');
3307 $this->_out('/Length '.strlen($info['data']).'>>');
3308 $this->_putstream($info['data']);
3309 unset($this->images[$file]['data']);
3310 $this->_out('endobj');
3311 //Palette
3312 if($info['cs']=='Indexed') {
3313 $this->_newobj();
3314 $pal=($this->compress) ? gzcompress($info['pal']) : $info['pal'];
3315 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
3316 $this->_putstream($pal);
3317 $this->_out('endobj');
3323 * _putxobjectdict
3324 * @access protected
3326 function _putxobjectdict() {
3327 foreach($this->images as $image) {
3328 $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
3333 * _putresourcedict
3334 * @access protected
3336 function _putresourcedict(){
3337 $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
3338 $this->_out('/Font <<');
3339 foreach($this->fonts as $font) {
3340 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
3342 $this->_out('>>');
3343 $this->_out('/XObject <<');
3344 $this->_putxobjectdict();
3345 $this->_out('>>');
3349 * _putresources
3350 * @access protected
3352 function _putresources() {
3353 $this->_putfonts();
3354 $this->_putimages();
3355 //Resource dictionary
3356 $this->offsets[2]=strlen($this->buffer);
3357 $this->_out('2 0 obj');
3358 $this->_out('<<');
3359 $this->_putresourcedict();
3360 $this->_out('>>');
3361 $this->_out('endobj');
3362 $this->_putjavascript();
3363 $this->_putbookmarks();
3364 // encryption
3365 if ($this->encrypted) {
3366 $this->_newobj();
3367 $this->enc_obj_id = $this->n;
3368 $this->_out('<<');
3369 $this->_putencryption();
3370 $this->_out('>>');
3371 $this->_out('endobj');
3376 * _putinfo
3377 * Adds some meta information
3378 * @access protected
3380 protected function _putinfo() {
3381 $this->_out('/CreationDate ('.$this->_escape('D:'.date('YmdHis')).')');
3382 $this->_out('/ModDate ('.$this->_escape('D:'.date('YmdHis')).')');
3383 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
3384 if(!empty($this->title)) {
3385 $this->_out('/Title '.$this->_textstring($this->title));
3387 if(!empty($this->subject)) {
3388 $this->_out('/Subject '.$this->_textstring($this->subject));
3390 if(!empty($this->author)) {
3391 $this->_out('/Author '.$this->_textstring($this->author));
3393 if(!empty($this->keywords)) {
3394 $this->_out('/Keywords '.$this->_textstring($this->keywords));
3396 if(!empty($this->creator)) {
3397 $this->_out('/Creator '.$this->_textstring($this->creator));
3402 * _putcatalog
3403 * @access protected
3405 protected function _putcatalog() {
3406 $this->_out('/Type /Catalog');
3407 $this->_out('/Pages 1 0 R');
3408 if($this->ZoomMode=='fullpage') {
3409 $this->_out('/OpenAction [3 0 R /Fit]');
3411 elseif($this->ZoomMode=='fullwidth') {
3412 $this->_out('/OpenAction [3 0 R /FitH null]');
3414 elseif($this->ZoomMode=='real') {
3415 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
3417 elseif(!is_string($this->ZoomMode)) {
3418 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode/100).']');
3420 if($this->LayoutMode=='single') {
3421 $this->_out('/PageLayout /SinglePage');
3423 elseif($this->LayoutMode=='continuous') {
3424 $this->_out('/PageLayout /OneColumn');
3426 elseif($this->LayoutMode=='two') {
3427 $this->_out('/PageLayout /TwoColumnLeft');
3429 if (!empty($this->javascript)) {
3430 $this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
3432 if(count($this->outlines)>0) {
3433 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
3434 $this->_out('/PageMode /UseOutlines');
3436 if($this->rtl) {
3437 $this->_out('/ViewerPreferences << /Direction /R2L >>');
3442 * _puttrailer
3443 * @access protected
3445 protected function _puttrailer() {
3446 $this->_out('/Size '.($this->n+1));
3447 $this->_out('/Root '.$this->n.' 0 R');
3448 $this->_out('/Info '.($this->n-1).' 0 R');
3449 if ($this->encrypted) {
3450 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
3451 $this->_out('/ID [()()]');
3456 * _putheader
3457 * @access protected
3459 function _putheader() {
3460 $this->_out('%PDF-'.$this->PDFVersion);
3464 * _enddoc
3465 * @access protected
3467 protected function _enddoc() {
3468 $this->_putheader();
3469 $this->_putpages();
3470 $this->_putresources();
3471 //Info
3472 $this->_newobj();
3473 $this->_out('<<');
3474 $this->_putinfo();
3475 $this->_out('>>');
3476 $this->_out('endobj');
3477 //Catalog
3478 $this->_newobj();
3479 $this->_out('<<');
3480 $this->_putcatalog();
3481 $this->_out('>>');
3482 $this->_out('endobj');
3483 //Cross-ref
3484 $o=strlen($this->buffer);
3485 $this->_out('xref');
3486 $this->_out('0 '.($this->n+1));
3487 $this->_out('0000000000 65535 f ');
3488 for($i=1;$i<=$this->n;$i++) {
3489 $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i]));
3491 //Trailer
3492 $this->_out('trailer');
3493 $this->_out('<<');
3494 $this->_puttrailer();
3495 $this->_out('>>');
3496 $this->_out('startxref');
3497 $this->_out($o);
3498 $this->_out('%%EOF');
3499 $this->state=3;
3503 * _beginpage
3504 * @access protected
3506 protected function _beginpage($orientation) {
3507 $this->page++;
3508 $this->pages[$this->page]='';
3509 $this->state=2;
3510 if ($this->rtl) {
3511 $this->x = $this->w - $this->rMargin;
3512 } else {
3513 $this->x = $this->lMargin;
3515 $this->y = $this->tMargin;
3516 $this->FontFamily='';
3517 //Page orientation
3518 if(empty($orientation)) {
3519 $orientation=$this->DefOrientation;
3521 else {
3522 $orientation=strtoupper($orientation{0});
3523 if($orientation!=$this->DefOrientation) {
3524 $this->OrientationChanges[$this->page]=true;
3527 if($orientation!=$this->CurOrientation) {
3528 //Change orientation
3529 if($orientation=='P') {
3530 $this->wPt=$this->fwPt;
3531 $this->hPt=$this->fhPt;
3532 $this->w=$this->fw;
3533 $this->h=$this->fh;
3535 else {
3536 $this->wPt=$this->fhPt;
3537 $this->hPt=$this->fwPt;
3538 $this->w=$this->fh;
3539 $this->h=$this->fw;
3541 $this->PageBreakTrigger=$this->h-$this->bMargin;
3542 $this->CurOrientation=$orientation;
3547 * End of page contents
3548 * @access protected
3550 protected function _endpage() {
3551 $this->state=1;
3555 * Begin a new object
3556 * @access protected
3558 protected function _newobj() {
3559 $this->n++;
3560 $this->offsets[$this->n]=strlen($this->buffer);
3561 $this->_out($this->n.' 0 obj');
3565 * Underline text
3566 * @param int $x X coordinate
3567 * @param int $y Y coordinate
3568 * @param string $txt text to underline
3569 * @access protected
3571 protected function _dounderline($x, $y, $txt) {
3572 $up = $this->CurrentFont['up'];
3573 $ut = $this->CurrentFont['ut'];
3574 $w = $this->GetStringWidth($txt) + $this->ws * substr_count($txt,' ');
3575 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);
3579 // REWRITTEN by Warren Sherliker wsherliker@gmail.com
3580 // altered to allow compatibility with all sorts of image formats including gif.
3581 // Can easily extend to work with others
3582 // such as gd xbm etc. which are all supported by php 5+
3583 // (Requires GD library)
3586 * Extract info from a JPEG file
3587 * @param string $file image file to parse
3588 * @return string
3589 * @access protected
3591 protected function _parsejpg($file) {
3592 if(!function_exists('imagecreatefromjpeg')) {
3593 // GD is not installed, try legacy method
3594 return $this->_legacyparsejpg($file);
3596 $a=getimagesize($file);
3597 if(empty($a)) {
3598 $this->Error('Missing or incorrect image file: '.$file);
3600 if($a[2]!=2) {
3601 $this->Error('Not a JPEG file: '.$file);
3603 $jpeg = imagecreatefromjpeg($file);
3604 return $this->outputjpg($file, $jpeg);
3608 * Extract info from a GIF file
3609 * @param string $file image file to parse
3610 * @return string
3611 * @access protected
3613 protected function _parsegif($file) {
3614 if(!function_exists('imagecreatefromgif')) {
3615 // PDF doesn't support native GIF and GD is not installed
3616 return false;
3618 $a=getimagesize($file);
3619 if(empty($a)) {
3620 $this->Error('Missing or incorrect image file: '.$file);
3622 if($a[2]!=1) {
3623 $this->Error('Not a GIF file: '.$file);
3625 // Temporary convert file to jpg and then delete this temp data file
3626 $gif = imagecreatefromgif($file);
3627 return $this->toJPEG($file, $gif);
3631 * Extract info from a PNG file
3632 * @param string $file image file to parse
3633 * @return string
3634 * @access protected
3636 protected function _parsepng($file) {
3637 if(!function_exists('imagecreatefrompng')) {
3638 // GD is not installed, try legacy method
3639 return $this->_legacyparsepng($file);
3641 $f=fopen($file,'rb');
3642 if(empty($f)) {
3643 $this->Error('Can\'t open image file: '.$file);
3645 //Check signature
3646 if(fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3647 $this->Error('Not a PNG file: '.$file);
3649 //Read header chunk
3650 fread($f,4);
3651 if(fread($f,4)!='IHDR') {
3652 $this->Error('Incorrect PNG file: '.$file);
3654 // Temporary convert file to jpg and then delete this temp data file
3655 $a=getimagesize($file);
3656 $png = imagecreatefrompng($file);
3657 return $this->toJPEG($file, $png);
3661 * Extract info from a JPEG file without using GD
3662 * @param string $file image file to parse
3663 * @return string
3664 * @access protected
3666 protected function _legacyparsejpg($file) {
3667 $a=GetImageSize($file);
3668 if(empty($a)) {
3669 $this->Error('Missing or incorrect image file: '.$file);
3671 if($a[2]!=2) {
3672 $this->Error('Not a JPEG file: '.$file);
3674 if(!isset($a['channels']) or $a['channels']==3) {
3675 $colspace='DeviceRGB';
3677 elseif($a['channels']==4) {
3678 $colspace='DeviceCMYK';
3680 else {
3681 $colspace='DeviceGray';
3683 $bpc=isset($a['bits']) ? $a['bits'] : 8;
3684 //Read whole file
3685 $f=fopen($file,'rb');
3686 $data='';
3687 while(!feof($f)) {
3688 $data.=fread($f,4096);
3690 fclose($f);
3691 return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data);
3695 * Extract info from a PNG file without using GD
3696 * @param string $file image file to parse
3697 * @return string
3698 * @access protected
3700 protected function _legacyparsepng($file) {
3701 $f=fopen($file,'rb');
3702 if(empty($f)) {
3703 $this->Error('Can\'t open image file: '.$file);
3705 //Check signature
3706 if(fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3707 $this->Error('Not a PNG file: '.$file);
3709 //Read header chunk
3710 fread($f,4);
3711 if(fread($f,4)!='IHDR') {
3712 $this->Error('Incorrect PNG file: '.$file);
3714 $w=$this->_freadint($f);
3715 $h=$this->_freadint($f);
3716 $bpc=ord(fread($f,1));
3717 if($bpc>8) {
3718 $this->Error('16-bit depth not supported: '.$file);
3720 $ct=ord(fread($f,1));
3721 if($ct==0) {
3722 $colspace='DeviceGray';
3724 elseif($ct==2) {
3725 $colspace='DeviceRGB';
3727 elseif($ct==3) {
3728 $colspace='Indexed';
3730 else {
3731 $this->Error('Alpha channel not supported: '.$file);
3733 if(ord(fread($f,1))!=0) {
3734 $this->Error('Unknown compression method: '.$file);
3736 if(ord(fread($f,1))!=0) {
3737 $this->Error('Unknown filter method: '.$file);
3739 if(ord(fread($f,1))!=0) {
3740 $this->Error('Interlacing not supported: '.$file);
3742 fread($f,4);
3743 $parms='/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
3744 //Scan chunks looking for palette, transparency and image data
3745 $pal='';
3746 $trns='';
3747 $data='';
3748 do {
3749 $n=$this->_freadint($f);
3750 $type=fread($f,4);
3751 if($type=='PLTE') {
3752 //Read palette
3753 $pal=fread($f,$n);
3754 fread($f,4);
3756 elseif($type=='tRNS') {
3757 //Read transparency info
3758 $t=fread($f,$n);
3759 if($ct==0) {
3760 $trns=array(ord(substr($t,1,1)));
3762 elseif($ct==2) {
3763 $trns=array(ord(substr($t,1,1)),ord(substr($t,3,1)),ord(substr($t,5,1)));
3765 else {
3766 $pos=strpos($t,chr(0));
3767 if($pos!==false) {
3768 $trns=array($pos);
3771 fread($f,4);
3773 elseif($type=='IDAT') {
3774 //Read image data block
3775 $data.=fread($f,$n);
3776 fread($f,4);
3778 elseif($type=='IEND') {
3779 break;
3781 else {
3782 fread($f,$n+4);
3785 while($n);
3786 if($colspace=='Indexed' and empty($pal)) {
3787 $this->Error('Missing palette in '.$file);
3789 fclose($f);
3790 return array('w'=>$w, 'h'=>$h, 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'FlateDecode', 'parms'=>$parms, 'pal'=>$pal, 'trns'=>$trns, 'data'=>$data);
3794 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
3795 * @param string $file Image file name.
3796 * @param image $image Image object.
3797 * return image JPEG image object.
3798 * @access protected
3800 protected function toJPEG($file, $image) {
3801 if ($image) {
3802 // output
3803 $tempname = tempnam(K_PATH_CACHE,'jpg');
3804 imagejpeg($image, $tempname, 100);
3805 imagedestroy($image);
3806 $retvars = $this->outputjpg($tempname);
3807 // tidy up by removing temporary image
3808 unlink($tempname);
3809 return $retvars;
3810 } else {
3811 $this->Error('Can\'t open image file: '.$file);
3816 * Get a JPEG filename and return a structure for the PDF creator.
3817 * @param string $filename JPEG file name.
3818 * @return array structure containing the image data
3819 * @access protected
3821 protected function outputjpg($filename) {
3822 $a=getimagesize($filename);
3824 if(!isset($a['channels']) or $a['channels']==3) {
3825 $colspace='DeviceRGB';
3827 elseif($a['channels']==4) {
3828 $colspace='DeviceCMYK';
3830 else {
3831 $colspace='DeviceGray';
3833 $bpc=isset($a['bits']) ? $a['bits'] : 8;
3834 //Read whole file
3836 $f=fopen($filename,'rb');
3837 $data='';
3838 while(!feof($f)) {
3839 $data.=fread($f,4096);
3841 fclose($f);
3843 return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data);
3846 /// END OF REWRITE BY Warren Sherliker wsherliker@gmail.com
3849 * Read a 4-byte integer from file
3850 * @param string $f file name.
3851 * @return 4-byte integer
3852 * @access protected
3854 protected function _freadint($f) {
3855 $a=unpack('Ni',fread($f,4));
3856 return $a['i'];
3860 * Format a text string for meta information
3861 * @param string $s string to escape.
3862 * @return string escaped string.
3863 * @access protected
3865 protected function _textstring($s) {
3866 if($this->isunicode) {
3867 //Convert string to UTF-16BE
3868 $s = $this->UTF8ToUTF16BE($s, true);
3870 if ($this->encrypted) {
3871 $s = $this->_RC4($this->_objectkey($this->n), $s);
3873 return '('. $this->_escape($s).')';
3877 * Format an URI string
3878 * @param string $s string to escape.
3879 * @return string escaped string.
3880 * @access protected
3882 protected function _uristring($s) {
3883 if ($this->encrypted) {
3884 $s = $this->_RC4($this->_objectkey($this->n), $s);
3886 return '('.$this->_escape($s).')';
3890 * Format a text string
3891 * @param string $s string to escape.
3892 * @return string escaped string.
3893 * @access protected
3895 protected function _escapetext($s) {
3896 if($this->isunicode) {
3897 //Convert string to UTF-16BE and reverse RTL language
3898 $s = $this->utf8StrRev($s, false, $this->tmprtl);
3900 return $this->_escape($s);
3904 * Add \ before \, ( and )
3905 * @param string $s string to escape.
3906 * @return string escaped string.
3907 * @access protected
3909 protected function _escape($s) {
3910 // the chr(13) substitution fixes the Bugs item #1421290.
3911 return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
3915 * Output a stream.
3916 * @param string $s string to output.
3917 * @access protected
3919 protected function _putstream($s) {
3920 if ($this->encrypted) {
3921 $s = $this->_RC4($this->_objectkey($this->n), $s);
3923 $this->_out('stream');
3924 $this->_out($s);
3925 $this->_out('endstream');
3929 * Output a string to the document.
3930 * @param string $s string to output.
3931 * @access protected
3933 protected function _out($s) {
3934 if($this->state==2) {
3935 $this->pages[$this->page] .= $s."\n";
3937 else {
3938 $this->buffer .= $s."\n";
3943 * Adds unicode fonts.<br>
3944 * Based on PDF Reference 1.3 (section 5)
3945 * @access protected
3946 * @author Nicola Asuni
3947 * @since 1.52.0.TC005 (2005-01-05)
3949 protected function _puttruetypeunicode($font) {
3950 // Type0 Font
3951 // A composite font composed of other fonts, organized hierarchically
3952 $this->_newobj();
3953 $this->_out('<</Type /Font');
3954 $this->_out('/Subtype /Type0');
3955 $this->_out('/BaseFont /'.$font['name'].'');
3956 $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.
3957 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
3958 $this->_out('/ToUnicode '.($this->n + 2).' 0 R');
3959 $this->_out('>>');
3960 $this->_out('endobj');
3962 // CIDFontType2
3963 // A CIDFont whose glyph descriptions are based on TrueType font technology
3964 $this->_newobj();
3965 $this->_out('<</Type /Font');
3966 $this->_out('/Subtype /CIDFontType2');
3967 $this->_out('/BaseFont /'.$font['name'].'');
3968 $this->_out('/CIDSystemInfo '.($this->n + 2).' 0 R');
3969 $this->_out('/FontDescriptor '.($this->n + 3).' 0 R');
3970 if (isset($font['desc']['MissingWidth'])){
3971 $this->_out('/DW '.$font['desc']['MissingWidth'].''); // The default width for glyphs in the CIDFont MissingWidth
3973 $w = "";
3974 foreach ($font['cw'] as $cid => $width) {
3975 $w .= ''.$cid.' ['.$width.'] '; // define a specific width for each individual CID
3977 $this->_out('/W ['.$w.']'); // A description of the widths for the glyphs in the CIDFont
3978 $this->_out('/CIDToGIDMap '.($this->n + 4).' 0 R');
3979 $this->_out('>>');
3980 $this->_out('endobj');
3982 // ToUnicode
3983 // is a stream object that contains the definition of the CMap
3984 // (PDF Reference 1.3 chap. 5.9)
3985 $this->_newobj();
3986 $this->_out('<</Length 345>>');
3987 $this->_out('stream');
3988 $this->_out('/CIDInit /ProcSet findresource begin');
3989 $this->_out('12 dict begin');
3990 $this->_out('begincmap');
3991 $this->_out('/CIDSystemInfo');
3992 $this->_out('<</Registry (Adobe)');
3993 $this->_out('/Ordering (UCS)');
3994 $this->_out('/Supplement 0');
3995 $this->_out('>> def');
3996 $this->_out('/CMapName /Adobe-Identity-UCS def');
3997 $this->_out('/CMapType 2 def');
3998 $this->_out('1 begincodespacerange');
3999 $this->_out('<0000> <FFFF>');
4000 $this->_out('endcodespacerange');
4001 $this->_out('1 beginbfrange');
4002 $this->_out('<0000> <FFFF> <0000>');
4003 $this->_out('endbfrange');
4004 $this->_out('endcmap');
4005 $this->_out('CMapName currentdict /CMap defineresource pop');
4006 $this->_out('end');
4007 $this->_out('end');
4008 $this->_out('endstream');
4009 $this->_out('endobj');
4011 // CIDSystemInfo dictionary
4012 // A dictionary containing entries that define the character collection of the CIDFont.
4013 $this->_newobj();
4014 $this->_out('<</Registry (Adobe)'); // A string identifying an issuer of character collections
4015 $this->_out('/Ordering (UCS)'); // A string that uniquely names a character collection issued by a specific registry
4016 $this->_out('/Supplement 0'); // The supplement number of the character collection.
4017 $this->_out('>>');
4018 $this->_out('endobj');
4020 // Font descriptor
4021 // A font descriptor describing the CIDFont default metrics other than its glyph widths
4022 $this->_newobj();
4023 $this->_out('<</Type /FontDescriptor');
4024 $this->_out('/FontName /'.$font['name']);
4025 foreach ($font['desc'] as $key => $value) {
4026 $this->_out('/'.$key.' '.$value);
4028 if ($font['file']) {
4029 // A stream containing a TrueType font program
4030 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
4032 $this->_out('>>');
4033 $this->_out('endobj');
4035 // Embed CIDToGIDMap
4036 // A specification of the mapping from CIDs to glyph indices
4037 $this->_newobj();
4038 $ctgfile = $this->_getfontpath().strtolower($font['ctg']);
4039 if(!file_exists($ctgfile)) {
4040 $this->Error('Font file not found: '.$ctgfile);
4042 $size = filesize($ctgfile);
4043 $this->_out('<</Length '.$size.'');
4044 if(substr($ctgfile, -2) == '.z') { // check file extension
4045 /* Decompresses data encoded using the public-domain
4046 zlib/deflate compression method, reproducing the
4047 original text or binary data */
4048 $this->_out('/Filter /FlateDecode');
4050 $this->_out('>>');
4051 $this->_putstream(file_get_contents($ctgfile));
4052 $this->_out('endobj');
4056 * Converts UTF-8 strings to codepoints array.<br>
4057 * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
4058 * Based on: http://www.faqs.org/rfcs/rfc3629.html
4059 * <pre>
4060 * Char. number range | UTF-8 octet sequence
4061 * (hexadecimal) | (binary)
4062 * --------------------+-----------------------------------------------
4063 * 0000 0000-0000 007F | 0xxxxxxx
4064 * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
4065 * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
4066 * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
4067 * ---------------------------------------------------------------------
4069 * ABFN notation:
4070 * ---------------------------------------------------------------------
4071 * UTF8-octets = *( UTF8-char )
4072 * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
4073 * UTF8-1 = %x00-7F
4074 * UTF8-2 = %xC2-DF UTF8-tail
4076 * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
4077 * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
4078 * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
4079 * %xF4 %x80-8F 2( UTF8-tail )
4080 * UTF8-tail = %x80-BF
4081 * ---------------------------------------------------------------------
4082 * </pre>
4083 * @param string $str string to process.
4084 * @return array containing codepoints (UTF-8 characters values)
4085 * @access protected
4086 * @author Nicola Asuni
4087 * @since 1.53.0.TC005 (2005-01-05)
4089 protected function UTF8StringToArray($str) {
4090 if(!$this->isunicode) {
4091 return $str; // string is not in unicode
4093 $unicode = array(); // array containing unicode values
4094 $bytes = array(); // array containing single character byte sequences
4095 $numbytes = 1; // number of octetc needed to represent the UTF-8 character
4097 $str .= ""; // force $str to be a string
4098 $length = strlen($str);
4100 for($i = 0; $i < $length; $i++) {
4101 $char = ord($str{$i}); // get one string character at time
4102 if(count($bytes) == 0) { // get starting octect
4103 if ($char <= 0x7F) {
4104 $unicode[] = $char; // use the character "as is" because is ASCII
4105 $numbytes = 1;
4106 } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
4107 $bytes[] = ($char - 0xC0) << 0x06;
4108 $numbytes = 2;
4109 } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
4110 $bytes[] = ($char - 0xE0) << 0x0C;
4111 $numbytes = 3;
4112 } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
4113 $bytes[] = ($char - 0xF0) << 0x12;
4114 $numbytes = 4;
4115 } else {
4116 // use replacement character for other invalid sequences
4117 $unicode[] = 0xFFFD;
4118 $bytes = array();
4119 $numbytes = 1;
4121 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
4122 $bytes[] = $char - 0x80;
4123 if (count($bytes) == $numbytes) {
4124 // compose UTF-8 bytes to a single unicode value
4125 $char = $bytes[0];
4126 for($j = 1; $j < $numbytes; $j++) {
4127 $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
4129 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
4130 /* The definition of UTF-8 prohibits encoding character numbers between
4131 U+D800 and U+DFFF, which are reserved for use with the UTF-16
4132 encoding form (as surrogate pairs) and do not directly represent
4133 characters. */
4134 $unicode[] = 0xFFFD; // use replacement character
4136 else {
4137 $unicode[] = $char; // add char to array
4139 // reset data for next char
4140 $bytes = array();
4141 $numbytes = 1;
4143 } else {
4144 // use replacement character for other invalid sequences
4145 $unicode[] = 0xFFFD;
4146 $bytes = array();
4147 $numbytes = 1;
4150 return $unicode;
4154 * Converts UTF-8 strings to UTF16-BE.<br>
4155 * @param string $str string to process.
4156 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
4157 * @return string
4158 * @access protected
4159 * @author Nicola Asuni
4160 * @since 1.53.0.TC005 (2005-01-05)
4161 * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
4163 protected function UTF8ToUTF16BE($str, $setbom=true) {
4164 if(!$this->isunicode) {
4165 return $str; // string is not in unicode
4167 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
4168 return $this->arrUTF8ToUTF16BE($unicode, $setbom);
4172 * Converts array of UTF-8 characters to UTF16-BE string.<br>
4173 * Based on: http://www.faqs.org/rfcs/rfc2781.html
4174 * <pre>
4175 * Encoding UTF-16:
4177 * Encoding of a single character from an ISO 10646 character value to
4178 * UTF-16 proceeds as follows. Let U be the character number, no greater
4179 * than 0x10FFFF.
4181 * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
4182 * terminate.
4184 * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
4185 * U' must be less than or equal to 0xFFFFF. That is, U' can be
4186 * represented in 20 bits.
4188 * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
4189 * 0xDC00, respectively. These integers each have 10 bits free to
4190 * encode the character value, for a total of 20 bits.
4192 * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
4193 * bits of W1 and the 10 low-order bits of U' to the 10 low-order
4194 * bits of W2. Terminate.
4196 * Graphically, steps 2 through 4 look like:
4197 * U' = yyyyyyyyyyxxxxxxxxxx
4198 * W1 = 110110yyyyyyyyyy
4199 * W2 = 110111xxxxxxxxxx
4200 * </pre>
4201 * @param array $unicode array containing UTF-8 unicode values
4202 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
4203 * @return string
4204 * @access protected
4205 * @author Nicola Asuni
4206 * @since 2.1.000 (2008-01-08)
4207 * @see UTF8ToUTF16BE()
4209 protected function arrUTF8ToUTF16BE($unicode, $setbom=true) {
4210 $outstr = ""; // string to be returned
4211 if ($setbom) {
4212 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
4214 foreach($unicode as $char) {
4215 if($char == 0xFFFD) {
4216 $outstr .= "\xFF\xFD"; // replacement character
4217 } elseif ($char < 0x10000) {
4218 $outstr .= chr($char >> 0x08);
4219 $outstr .= chr($char & 0xFF);
4220 } else {
4221 $char -= 0x10000;
4222 $w1 = 0xD800 | ($char >> 0x10);
4223 $w2 = 0xDC00 | ($char & 0x3FF);
4224 $outstr .= chr($w1 >> 0x08);
4225 $outstr .= chr($w1 & 0xFF);
4226 $outstr .= chr($w2 >> 0x08);
4227 $outstr .= chr($w2 & 0xFF);
4230 return $outstr;
4232 // ====================================================
4235 * Set header font.
4236 * @param array $font font
4237 * @since 1.1
4239 public function setHeaderFont($font) {
4240 $this->header_font = $font;
4244 * Set footer font.
4245 * @param array $font font
4246 * @since 1.1
4248 public function setFooterFont($font) {
4249 $this->footer_font = $font;
4253 * Set language array.
4254 * @param array $language
4255 * @since 1.1
4257 public function setLanguageArray($language) {
4258 $this->l = $language;
4259 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
4263 * Set document barcode.
4264 * @param string $bc barcode
4266 public function setBarcode($bc="") {
4267 $this->barcode = $bc;
4271 * Print Barcode.
4272 * @param int $x x position in user units
4273 * @param int $y y position in user units
4274 * @param int $w width in user units
4275 * @param int $h height position in user units
4276 * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
4277 * @param string $style barcode style
4278 * @param string $font font for text
4279 * @param int $xres x resolution
4280 * @param string $code code to print
4282 public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
4283 require_once(dirname(__FILE__)."/barcode/barcode.php");
4284 require_once(dirname(__FILE__)."/barcode/i25object.php");
4285 require_once(dirname(__FILE__)."/barcode/c39object.php");
4286 require_once(dirname(__FILE__)."/barcode/c128aobject.php");
4287 require_once(dirname(__FILE__)."/barcode/c128bobject.php");
4288 require_once(dirname(__FILE__)."/barcode/c128cobject.php");
4290 if (empty($code)) {
4291 return;
4294 if (empty($style)) {
4295 $style = BCS_ALIGN_LEFT;
4296 $style |= BCS_IMAGE_PNG;
4297 $style |= BCS_TRANSPARENT;
4298 //$style |= BCS_BORDER;
4299 //$style |= BCS_DRAW_TEXT;
4300 //$style |= BCS_STRETCH_TEXT;
4301 //$style |= BCS_REVERSE_COLOR;
4303 if (empty($font)) {$font = BCD_DEFAULT_FONT;}
4304 if (empty($xres)) {$xres = BCD_DEFAULT_XRES;}
4306 $scale_factor = 1.5 * $xres * $this->k;
4307 $bc_w = round($w * $scale_factor); //width in points
4308 $bc_h = round($h * $scale_factor); //height in points
4310 switch (strtoupper($type)) {
4311 case "I25": {
4312 $obj = new I25Object($bc_w, $bc_h, $style, $code);
4313 break;
4315 case "C128A": {
4316 $obj = new C128AObject($bc_w, $bc_h, $style, $code);
4317 break;
4319 default:
4320 case "C128B": {
4321 $obj = new C128BObject($bc_w, $bc_h, $style, $code);
4322 break;
4324 case "C128C": {
4325 $obj = new C128CObject($bc_w, $bc_h, $style, $code);
4326 break;
4328 case "C39": {
4329 $obj = new C39Object($bc_w, $bc_h, $style, $code);
4330 break;
4334 $obj->SetFont($font);
4335 $obj->DrawObject($xres);
4337 //use a temporary file....
4338 $tmpName = tempnam(K_PATH_CACHE,'img');
4339 imagepng($obj->getImage(), $tmpName);
4340 $this->Image($tmpName, $x, $y, $w, $h, 'png');
4341 $obj->DestroyObject();
4342 unset($obj);
4343 unlink($tmpName);
4347 * Returns the PDF data.
4349 public function getPDFData() {
4350 if($this->state < 3) {
4351 $this->Close();
4353 return $this->buffer;
4356 // --- HTML PARSER FUNCTIONS ---
4359 * Allows to preserve some HTML formatting.<br />
4360 * 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
4361 * @param string $html text to display
4362 * @param boolean $ln if true add a new line after text (default = true)
4363 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
4364 * @param boolean $reseth if true reset the last cell height (default false).
4365 * @param boolean $cell if true add the default cMargin space to each Write.
4367 public function writeHTML($html, $ln=true, $fill=0, $reseth=false, $cell=false) {
4369 // store some variables
4370 $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
4371 //replace carriage returns, newlines and tabs
4372 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
4373 $html = strtr($html, $repTable);
4374 $pattern = '/(<[^>]+>)/Uu';
4375 $a = preg_split($pattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); //explodes the string
4377 if ((empty($this->lasth))OR ($reseth)) {
4378 //set row height
4379 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4382 foreach($a as $key=>$element) {
4383 if (!preg_match($pattern, $element)) {
4384 //Text
4385 if($this->HREF) {
4386 $this->addHtmlLink($this->HREF, $element, $fill);
4387 } elseif($this->tdbegin) {
4388 if((strlen(trim($element)) > 0) AND ($element != "&nbsp;")) {
4389 $this->Cell($this->tdwidth, $this->tdheight, $this->unhtmlentities($element), $this->tableborder, '', $this->tdalign, $this->tdbgcolor);
4390 } elseif($element == "&nbsp;") {
4391 $this->Cell($this->tdwidth, $this->tdheight, '', $this->tableborder, '', $this->tdalign, $this->tdbgcolor);
4393 } else {
4395 $ctmpmargin = $this->cMargin;
4396 if(!$cell) {
4397 $this->cMargin = 0;
4399 $this->Write($this->lasth, stripslashes($this->unhtmlentities($element)), '', $fill, 0);
4400 $this->cMargin = $ctmpmargin;
4402 } else {
4403 $element = substr($element, 1, -1);
4404 //Tag
4405 if($element{0}=='/') {
4406 $this->closedHTMLTagHandler(strtolower(substr($element, 1)));
4408 else {
4409 //Extract attributes
4410 // get tag name
4411 preg_match('/([a-zA-Z0-9]*)/', $element, $tag);
4412 $tag = strtolower($tag[0]);
4413 // get attributes
4414 preg_match_all('/([^=\s]*)=["\']?([^"\']*)["\']?/', $element, $attr_array, PREG_PATTERN_ORDER);
4415 $attr = array(); // reset attribute array
4416 while(list($id,$name)=each($attr_array[1])) {
4417 $attr[strtolower($name)] = $attr_array[2][$id];
4419 $this->openHTMLTagHandler($tag, $attr, $fill);
4423 if ($ln) {
4424 $this->Ln($this->lasth);
4429 * 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 />
4430 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
4431 * @param float $w Cell width. If 0, the cell extends up to the right margin.
4432 * @param float $h Cell minimum height. The cell extends automatically if needed.
4433 * @param float $x upper-left corner X coordinate
4434 * @param float $y upper-left corner Y coordinate
4435 * @param string $html html text to print. Default value: empty string.
4436 * @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>
4437 * @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>
4438 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
4439 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
4440 * @param boolean $reseth if true reset the last cell height (default false).
4441 * @see Cell()
4443 public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=false) {
4445 if ((empty($this->lasth))OR ($reseth)) {
4446 //set row height
4447 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4450 // get current page number
4451 $startpage = $this->page;
4453 if (!empty($y)) {
4454 $this->SetY($y);
4455 } else {
4456 $y = $this->GetY();
4458 if (!empty($x)) {
4459 $this->SetX($x);
4460 } else {
4461 $x = $this->GetX();
4464 if(empty($w)) {
4465 if ($this->rtl) {
4466 $w = $this->x - $this->lMargin;
4467 } else {
4468 $w = $this->w - $this->rMargin - $this->x;
4472 // store original margin values
4473 $lMargin = $this->lMargin;
4474 $rMargin = $this->rMargin;
4476 // set new margin values
4477 if ($this->rtl) {
4478 $this->SetLeftMargin($this->x - $w);
4479 $this->SetRightMargin($this->w - $this->x);
4480 } else {
4481 $this->SetLeftMargin($this->x);
4482 $this->SetRightMargin($this->w - $this->x - $w);
4485 // calculate remaining vertical space on first page ($startpage)
4486 $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin();
4488 // Write HTML text
4489 $this->writeHTML($html, true, $fill, $reseth, true);
4491 // Get end-of-text Y position
4492 $currentY = $this->GetY();
4493 // get latest page number
4494 $endpage = $this->page;
4496 if (!empty($border)) {
4497 // check if a new page has been created
4498 if ($endpage > $startpage) {
4499 // design borders around HTML cells.
4500 for ($page=$startpage; $page<=$endpage; $page++) {
4501 $this->page = $page;
4502 if ($page==$startpage) {
4503 $this->SetY($this->getPageHeight() - $restspace - $this->getBreakMargin());
4504 $h = $restspace - 1;
4505 } elseif ($page==$endpage) {
4506 $this->SetY($this->tMargin); // put cursor at the beginning of text
4507 $h = $currentY - $this->tMargin;
4508 } else {
4509 $this->SetY($this->tMargin); // put cursor at the beginning of text
4510 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
4512 $this->Cell($w, $h, "", $border, 1, '', 0);
4514 } else {
4515 $h = max($h, ($currentY - $y));
4516 $this->SetY($y); // put cursor at the beginning of text
4517 // design a cell around the text
4518 $this->Cell($w, $h, "", $border, 1, '', 0);
4522 // restore original margin values
4523 $this->SetLeftMargin($lMargin);
4524 $this->SetRightMargin($rMargin);
4527 if($ln>0) {
4528 //Go to the beginning of the next line
4529 $this->SetY($currentY);
4530 if($ln == 2) {
4531 $this->SetX($x + $w);
4533 } else {
4534 // go left or right by case
4535 $this->page = $startpage;
4536 $this->y = $y;
4537 $this->SetX($x + $w);
4543 * Process opening tags.
4544 * @param string $tag tag name (in uppercase)
4545 * @param string $attr tag attribute (in uppercase)
4546 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
4547 * @access private
4549 private function openHTMLTagHandler($tag, $attr, $fill=0) {
4550 // check for text direction attribute
4551 if (isset($attr['dir'])) {
4552 $this->tmprtl = $attr['dir']=='rtl' ? 'R' : 'L';
4553 } else {
4554 $this->tmprtl = false;
4556 //Opening tag
4557 switch($tag) {
4558 case 'table': {
4559 if ((isset($attr['border'])) AND ($attr['border'] != '')) {
4560 $this->tableborder = $attr['border'];
4562 else {
4563 $this->tableborder = 0;
4565 break;
4567 case 'tr': {
4568 break;
4570 case 'td':
4571 case 'th': {
4572 if ((isset($attr['width'])) AND ($attr['width'] != '')) {
4573 $this->tdwidth = ($attr['width']/4);
4575 else {
4576 $this->tdwidth = (($this->w - $this->lMargin - $this->rMargin) / $this->default_table_columns);
4578 if ((isset($attr['height'])) AND ($attr['height'] != '')) {
4579 $this->tdheight=($attr['height'] / $this->k);
4581 else {
4582 $this->tdheight = $this->lasth;
4584 if ((isset($attr['align'])) AND ($attr['align'] != '')) {
4585 switch ($attr['align']) {
4586 case 'center': {
4587 $this->tdalign = "C";
4588 break;
4590 case 'right': {
4591 $this->tdalign = "R";
4592 break;
4594 default:
4595 case 'left': {
4596 $this->tdalign = "L";
4597 break;
4600 } else {
4601 if($this->rtl) {
4602 $this->tdalign = "R";
4603 } else {
4604 $this->tdalign = "L";
4607 if ((isset($attr['bgcolor'])) AND ($attr['bgcolor'] != '')) {
4608 $coul = $this->convertColorHexToDec($attr['bgcolor']);
4609 $this->SetFillColor($coul['R'], $coul['G'], $coul['B']);
4610 $this->tdbgcolor=true;
4612 $this->tdbegin=true;
4613 break;
4615 case 'hr': {
4616 $this->Ln();
4617 if ((isset($attr['width'])) AND ($attr['width'] != '')) {
4618 $hrWidth = $attr['width'];
4620 else {
4621 $hrWidth = $this->w - $this->lMargin - $this->rMargin;
4623 $x = $this->GetX();
4624 $y = $this->GetY();
4625 $this->GetLineWidth();
4626 $prevlinewidth = $this->SetLineWidth(0.2);
4627 $this->Line($x, $y, $x + $hrWidth, $y);
4628 $this->SetLineWidth($prevlinewidth);
4629 $this->Ln();
4630 break;
4632 case 'strong': {
4633 $this->setStyle('b', true);
4634 break;
4636 case 'em': {
4637 $this->setStyle('i', true);
4638 break;
4640 case 'b':
4641 case 'i':
4642 case 'u': {
4643 $this->setStyle($tag, true);
4644 break;
4646 case 'a': {
4647 $this->HREF = $attr['href'];
4648 break;
4650 case 'img': {
4651 if(isset($attr['src'])) {
4652 // replace relative path with real server path
4653 if ($attr['src'][0] == '/') {
4654 $attr['src'] = $_SERVER['DOCUMENT_ROOT'].$attr['src'];
4656 $attr['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $attr['src']);
4657 if(!isset($attr['width'])) {
4658 $attr['width'] = 0;
4660 if(!isset($attr['height'])) {
4661 $attr['height'] = 0;
4663 if(!isset($attr['align'])) {
4664 $align = 'N';
4665 } else {
4666 switch($attr['align']) {
4667 case 'top':{
4668 $align = 'T';
4669 break;
4671 case 'middle':{
4672 $align = 'M';
4673 break;
4675 case 'bottom':{
4676 $align = 'B';
4677 break;
4679 default:{
4680 $align = 'N';
4681 break;
4685 $this->Image($attr['src'], $this->GetX(),$this->GetY(), $this->pixelsToMillimeters($attr['width']), $this->pixelsToMillimeters($attr['height']), '', '', $align);
4688 break;
4690 case 'ul': {
4691 $this->listordered = false;
4692 $this->listcount = 0;
4693 break;
4695 case 'ol': {
4696 $this->listordered = true;
4697 $this->listcount = 0;
4698 break;
4700 case 'li': {
4701 $this->Ln();
4702 if ($this->listordered) {
4703 if (isset($attr['value'])) {
4704 $this->listcount = intval($attr['value']);
4706 $this->lispacer = " ".(++$this->listcount).". ";
4707 } else {
4708 //unordered list simbol
4709 $this->lispacer = " - ";
4711 $rtldir = $this->tmprtl;
4712 $this->tmprtl = false;
4713 $this->Write($this->lasth, $this->lispacer, '', $fill);
4714 $this->tmprtl = $rtldir;
4715 break;
4717 case 'blockquote':
4718 case 'br': {
4719 $this->Ln();
4720 if(strlen($this->lispacer) > 0) {
4721 if ($this->rtl) {
4722 $this->x -= $this->GetStringWidth($this->lispacer);
4723 } else {
4724 $this->x += $this->GetStringWidth($this->lispacer);
4727 break;
4729 case 'p': {
4730 $this->Ln();
4731 $this->Ln();
4732 break;
4734 case 'sup': {
4735 $currentFontSize = $this->FontSize;
4736 $this->tempfontsize = $this->FontSizePt;
4737 $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO);
4738 $this->SetXY($this->GetX(), $this->GetY() - (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4739 break;
4741 case 'sub': {
4742 $currentFontSize = $this->FontSize;
4743 $this->tempfontsize = $this->FontSizePt;
4744 $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO);
4745 $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4746 break;
4748 case 'small': {
4749 $currentFontSize = $this->FontSize;
4750 $this->tempfontsize = $this->FontSizePt;
4751 $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO);
4752 $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)/3));
4753 break;
4755 case 'font': {
4756 if (isset($attr['color']) AND $attr['color']!='') {
4757 $coul = $this->convertColorHexToDec($attr['color']);
4758 $this->SetTextColor($coul['R'],$coul['G'],$coul['B']);
4759 $this->issetcolor=true;
4761 if (isset($attr['face']) and in_array(strtolower($attr['face']), $this->fontlist)) {
4762 $this->SetFont(strtolower($attr['face']));
4763 $this->issetfont=true;
4765 if (isset($attr['size'])) {
4766 $headsize = intval($attr['size']);
4767 } else {
4768 $headsize = 0;
4770 $currentFontSize = $this->FontSize;
4771 $this->tempfontsize = $this->FontSizePt;
4772 $this->SetFontSize($this->FontSizePt + $headsize);
4773 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4774 break;
4776 case 'h1':
4777 case 'h2':
4778 case 'h3':
4779 case 'h4':
4780 case 'h5':
4781 case 'h6': {
4782 $headsize = (4 - substr($tag, 1)) * 2;
4783 $currentFontSize = $this->FontSize;
4784 $this->tempfontsize = $this->FontSizePt;
4785 $this->SetFontSize($this->FontSizePt + $headsize);
4786 $this->setStyle('b', true);
4787 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4788 break;
4794 * Process closing tags.
4795 * @param string $tag tag name (in uppercase)
4796 * @access private
4798 private function closedHTMLTagHandler($tag) {
4799 //Closing tag
4800 switch($tag) {
4801 case 'td':
4802 case 'th': {
4803 $this->tdbegin = false;
4804 $this->tdwidth = 0;
4805 $this->tdheight = 0;
4806 if($this->rtl) {
4807 $this->tdalign = "R";
4808 } else {
4809 $this->tdalign = "L";
4811 $this->tdbgcolor = false;
4812 $this->SetFillColor($this->prevFillColor[0], $this->prevFillColor[1], $this->prevFillColor[2]);
4813 break;
4815 case 'tr': {
4816 $this->Ln();
4817 break;
4819 case 'table': {
4820 $this->tableborder=0;
4821 break;
4823 case 'strong': {
4824 $this->setStyle('b', false);
4825 break;
4827 case 'em': {
4828 $this->setStyle('i', false);
4829 break;
4831 case 'b':
4832 case 'i':
4833 case 'u': {
4834 $this->setStyle($tag, false);
4835 break;
4837 case 'a': {
4838 $this->HREF = '';
4839 break;
4841 case 'sup': {
4842 $currentFontSize = $this->FontSize;
4843 $this->SetFontSize($this->tempfontsize);
4844 $this->tempfontsize = $this->FontSizePt;
4845 $this->SetXY($this->GetX(), $this->GetY() - (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4846 break;
4848 case 'sub': {
4849 $currentFontSize = $this->FontSize;
4850 $this->SetFontSize($this->tempfontsize);
4851 $this->tempfontsize = $this->FontSizePt;
4852 $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4853 break;
4855 case 'small': {
4856 $currentFontSize = $this->FontSize;
4857 $this->SetFontSize($this->tempfontsize);
4858 $this->tempfontsize = $this->FontSizePt;
4859 $this->SetXY($this->GetX(), $this->GetY() - (($this->FontSize - $currentFontSize)/3));
4860 break;
4862 case 'font': {
4863 if ($this->issetcolor == true) {
4864 $this->SetTextColor($this->prevTextColor[0], $this->prevTextColor[1], $this->prevTextColor[2]);
4866 if ($this->issetfont) {
4867 $this->FontFamily = $this->prevFontFamily;
4868 $this->FontStyle = $this->prevFontStyle;
4869 $this->SetFont($this->FontFamily);
4870 $this->issetfont = false;
4872 $currentFontSize = $this->FontSize;
4873 $this->SetFontSize($this->tempfontsize);
4874 $this->tempfontsize = $this->FontSizePt;
4875 //$this->TextColor = $this->prevTextColor;
4876 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4877 break;
4879 case 'p': {
4880 $this->Ln();
4881 $this->Ln();
4882 break;
4884 case 'ul':
4885 case 'ol': {
4886 $this->Ln();
4887 $this->Ln();
4888 break;
4890 case 'li': {
4891 $this->lispacer = "";
4892 break;
4894 case 'h1':
4895 case 'h2':
4896 case 'h3':
4897 case 'h4':
4898 case 'h5':
4899 case 'h6': {
4900 $currentFontSize = $this->FontSize;
4901 $this->SetFontSize($this->tempfontsize);
4902 $this->tempfontsize = $this->FontSizePt;
4903 $this->setStyle('b', false);
4904 $this->Ln();
4905 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4906 break;
4908 default : {
4909 break;
4912 $this->tmprtl = false;
4916 * Sets font style.
4917 * @param string $tag tag name (in lowercase)
4918 * @param boolean $enable
4919 * @access private
4921 private function setStyle($tag, $enable) {
4922 //Modify style and select corresponding font
4923 $this->$tag += ($enable ? 1 : -1);
4924 $style='';
4925 foreach(array('b', 'i', 'u') as $s) {
4926 if($this->$s > 0) {
4927 $style .= $s;
4930 $this->SetFont('', $style);
4934 * Output anchor link.
4935 * @param string $url link URL
4936 * @param string $name link name
4937 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
4938 * @access public
4940 public function addHtmlLink($url, $name, $fill=0) {
4941 //Put a hyperlink
4942 $this->SetTextColor(0, 0, 255);
4943 $this->setStyle('u', true);
4944 $this->Write($this->lasth, $name, $url, $fill);
4945 $this->setStyle('u', false);
4946 $this->SetTextColor(0);
4950 * Returns an associative array (keys: R,G,B) from
4951 * a hex html code (e.g. #3FE5AA).
4952 * @param string $color hexadecimal html color [#rrggbb]
4953 * @return array
4954 * @access private
4956 private function convertColorHexToDec($color = "#000000"){
4957 $tbl_color = array();
4958 $tbl_color['R'] = hexdec(substr($color, 1, 2));
4959 $tbl_color['G'] = hexdec(substr($color, 3, 2));
4960 $tbl_color['B'] = hexdec(substr($color, 5, 2));
4961 return $tbl_color;
4965 * Converts pixels to millimeters in 72 dpi.
4966 * @param int $px pixels
4967 * @return float millimeters
4968 * @access private
4970 private function pixelsToMillimeters($px){
4971 return $px * 25.4 / 72;
4975 * Reverse function for htmlentities.
4976 * Convert entities in UTF-8.
4978 * @param $text_to_convert Text to convert.
4979 * @return string converted
4981 public function unhtmlentities($text_to_convert) {
4982 return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
4985 // ENCRYPTION METHODS ----------------------------------
4986 // SINCE 2.0.000 (2008-01-02)
4988 * Compute encryption key depending on object number where the encrypted data is stored
4989 * @param int $n object number
4990 * @since 2.0.000 (2008-01-02)
4992 protected function _objectkey($n) {
4993 return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);
4997 * Put encryption on PDF document
4998 * @since 2.0.000 (2008-01-02)
5000 protected function _putencryption() {
5001 $this->_out('/Filter /Standard');
5002 $this->_out('/V 1');
5003 $this->_out('/R 2');
5004 $this->_out('/O ('.$this->_escape($this->Ovalue).')');
5005 $this->_out('/U ('.$this->_escape($this->Uvalue).')');
5006 $this->_out('/P '.$this->Pvalue);
5010 * Returns the input text exrypted using RC4 algorithm and the specified key.
5011 * RC4 is the standard encryption algorithm used in PDF format
5012 * @param string $key encryption key
5013 * @param String $text input text to be encrypted
5014 * @return String encrypted text
5015 * @since 2.0.000 (2008-01-02)
5016 * @author Klemen Vodopivec
5018 protected function _RC4($key, $text) {
5019 if ($this->last_rc4_key != $key) {
5020 $k = str_repeat($key, 256/strlen($key)+1);
5021 $rc4 = range(0,255);
5022 $j = 0;
5023 for ($i=0; $i<256; $i++) {
5024 $t = $rc4[$i];
5025 $j = ($j + $t + ord($k{$i})) % 256;
5026 $rc4[$i] = $rc4[$j];
5027 $rc4[$j] = $t;
5029 $this->last_rc4_key = $key;
5030 $this->last_rc4_key_c = $rc4;
5031 } else {
5032 $rc4 = $this->last_rc4_key_c;
5034 $len = strlen($text);
5035 $a = 0;
5036 $b = 0;
5037 $out = '';
5038 for ($i=0; $i<$len; $i++) {
5039 $a = ($a+1)%256;
5040 $t= $rc4[$a];
5041 $b = ($b+$t)%256;
5042 $rc4[$a] = $rc4[$b];
5043 $rc4[$b] = $t;
5044 $k = $rc4[($rc4[$a]+$rc4[$b])%256];
5045 $out.=chr(ord($text{$i}) ^ $k);
5047 return $out;
5051 * Encrypts a string using MD5 and returns it's value as a binary string.
5052 * @param string $str input string
5053 * @return String MD5 encrypted binary string
5054 * @since 2.0.000 (2008-01-02)
5055 * @author Klemen Vodopivec
5057 protected function _md5_16($str) {
5058 return pack('H*',md5($str));
5062 * Compute O value (used for RC4 encryption)
5063 * @param String $user_pass user password
5064 * @param String $owner_pass user password
5065 * @return String O value
5066 * @since 2.0.000 (2008-01-02)
5067 * @author Klemen Vodopivec
5069 protected function _Ovalue($user_pass, $owner_pass) {
5070 $tmp = $this->_md5_16($owner_pass);
5071 $owner_RC4_key = substr($tmp,0,5);
5072 return $this->_RC4($owner_RC4_key, $user_pass);
5076 * Compute U value (used for RC4 encryption)
5077 * @return String U value
5078 * @since 2.0.000 (2008-01-02)
5079 * @author Klemen Vodopivec
5081 protected function _Uvalue() {
5082 return $this->_RC4($this->encryption_key, $this->padding);
5086 * Compute encryption key
5087 * @param String $user_pass user password
5088 * @param String $owner_pass user password
5089 * @param String $protection protection type
5090 * @since 2.0.000 (2008-01-02)
5091 * @author Klemen Vodopivec
5093 protected function _generateencryptionkey($user_pass, $owner_pass, $protection) {
5094 // Pad passwords
5095 $user_pass = substr($user_pass.$this->padding,0,32);
5096 $owner_pass = substr($owner_pass.$this->padding,0,32);
5097 // Compute O value
5098 $this->Ovalue = $this->_Ovalue($user_pass,$owner_pass);
5099 // Compute encyption key
5100 $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
5101 $this->encryption_key = substr($tmp,0,5);
5102 // Compute U value
5103 $this->Uvalue = $this->_Uvalue();
5104 // Compute P value
5105 $this->Pvalue = -(($protection^255)+1);
5109 * Set document protection
5110 * The permission array is composed of values taken from the following ones:
5111 * - copy: copy text and images to the clipboard
5112 * - print: print the document
5113 * - modify: modify it (except for annotations and forms)
5114 * - annot-forms: add annotations and forms
5115 * Remark: the protection against modification is for people who have the full Acrobat product.
5116 * 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.
5117 * 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.
5118 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
5119 * @param String $user_pass user password. Empty by default.
5120 * @param String $owner_pass owner password. If not specified, a random value is used.
5121 * @since 2.0.000 (2008-01-02)
5122 * @author Klemen Vodopivec
5124 public function SetProtection($permissions=array(),$user_pass='',$owner_pass=null) {
5125 $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
5126 $protection = 192;
5127 foreach($permissions as $permission) {
5128 if (!isset($options[$permission])) {
5129 $this->Error('Incorrect permission: '.$permission);
5131 $protection += $options[$permission];
5133 if ($owner_pass === null) {
5134 $owner_pass = uniqid(rand());
5136 $this->encrypted = true;
5137 $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
5140 // END OF ENCRYPTION FUNCTIONS -------------------------
5142 // START TRANSFORMATIONS SECTION -----------------------
5143 // authors: Moritz Wagner, Andreas Wurmser, Nicola Asuni
5146 * Starts a 2D tranformation saving current graphic state.
5147 * This function must be called before scaling, mirroring, translation, rotation and skewing.
5148 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5149 * @since 2.1.000 (2008-01-07)
5150 * @see StartTransform(), StopTransform()
5152 public function StartTransform() {
5153 $this->_out('q');
5157 * Stops a 2D tranformation restoring previous graphic state.
5158 * This function must be called after scaling, mirroring, translation, rotation and skewing.
5159 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5160 * @since 2.1.000 (2008-01-07)
5161 * @see StartTransform(), StopTransform()
5163 public function StopTransform() {
5164 $this->_out('Q');
5167 * Horizontal Scaling.
5168 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5169 * @param int $x abscissa of the scaling center. Default is current x position
5170 * @param int $y ordinate of the scaling center. Default is current y position
5171 * @since 2.1.000 (2008-01-07)
5172 * @see StartTransform(), StopTransform()
5174 public function ScaleX($s_x, $x='', $y=''){
5175 $this->Scale($s_x, 100, $x, $y);
5179 * Vertical Scaling.
5180 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5181 * @param int $x abscissa of the scaling center. Default is current x position
5182 * @param int $y ordinate of the scaling center. Default is current y position
5183 * @since 2.1.000 (2008-01-07)
5184 * @see StartTransform(), StopTransform()
5186 public function ScaleY($s_y, $x='', $y=''){
5187 $this->Scale(100, $s_y, $x, $y);
5191 * Vertical and horizontal proportional Scaling.
5192 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
5193 * @param int $x abscissa of the scaling center. Default is current x position
5194 * @param int $y ordinate of the scaling center. Default is current y position
5195 * @since 2.1.000 (2008-01-07)
5196 * @see StartTransform(), StopTransform()
5198 public function ScaleXY($s, $x='', $y=''){
5199 $this->Scale($s, $s, $x, $y);
5203 * Vertical and horizontal non-proportional Scaling.
5204 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5205 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5206 * @param int $x abscissa of the scaling center. Default is current x position
5207 * @param int $y ordinate of the scaling center. Default is current y position
5208 * @since 2.1.000 (2008-01-07)
5209 * @see StartTransform(), StopTransform()
5211 public function Scale($s_x, $s_y, $x='', $y=''){
5212 if($x === '') {
5213 $x=$this->x;
5215 if($y === '') {
5216 $y=$this->y;
5218 if($this->rtl) {
5219 $x = $this->w - $x;
5221 if($s_x == 0 OR $s_y == 0)
5222 $this->Error('Please use values unequal to zero for Scaling');
5223 $y=($this->h-$y)*$this->k;
5224 $x*=$this->k;
5225 //calculate elements of transformation matrix
5226 $s_x/=100;
5227 $s_y/=100;
5228 $tm[0]=$s_x;
5229 $tm[1]=0;
5230 $tm[2]=0;
5231 $tm[3]=$s_y;
5232 $tm[4]=$x*(1-$s_x);
5233 $tm[5]=$y*(1-$s_y);
5234 //scale the coordinate system
5235 $this->Transform($tm);
5239 * Horizontal Mirroring.
5240 * @param int $x abscissa of the point. Default is current x position
5241 * @since 2.1.000 (2008-01-07)
5242 * @see StartTransform(), StopTransform()
5244 public function MirrorH($x=''){
5245 $this->Scale(-100, 100, $x);
5249 * Verical Mirroring.
5250 * @param int $y ordinate of the point. Default is current y position
5251 * @since 2.1.000 (2008-01-07)
5252 * @see StartTransform(), StopTransform()
5254 public function MirrorV($y=''){
5255 $this->Scale(100, -100, '', $y);
5259 * Point reflection mirroring.
5260 * @param int $x abscissa of the point. Default is current x position
5261 * @param int $y ordinate of the point. Default is current y position
5262 * @since 2.1.000 (2008-01-07)
5263 * @see StartTransform(), StopTransform()
5265 public function MirrorP($x='',$y=''){
5266 $this->Scale(-100, -100, $x, $y);
5270 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
5271 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
5272 * @param int $x abscissa of the point. Default is current x position
5273 * @param int $y ordinate of the point. Default is current y position
5274 * @since 2.1.000 (2008-01-07)
5275 * @see StartTransform(), StopTransform()
5277 public function MirrorL($angle=0, $x='',$y=''){
5278 $this->Scale(-100, 100, $x, $y);
5279 $this->Rotate(-2*($angle-90),$x,$y);
5283 * Translate graphic object horizontally.
5284 * @param int $t_x movement to the right
5285 * @since 2.1.000 (2008-01-07)
5286 * @see StartTransform(), StopTransform()
5288 public function TranslateX($t_x){
5289 $this->Translate($t_x, 0);
5293 * Translate graphic object vertically.
5294 * @param int $t_y movement to the bottom
5295 * @since 2.1.000 (2008-01-07)
5296 * @see StartTransform(), StopTransform()
5298 public function TranslateY($t_y){
5299 $this->Translate(0, $t_y, $x, $y);
5303 * Translate graphic object horizontally and vertically.
5304 * @param int $t_x movement to the right
5305 * @param int $t_y movement to the bottom
5306 * @since 2.1.000 (2008-01-07)
5307 * @see StartTransform(), StopTransform()
5309 public function Translate($t_x, $t_y){
5310 if($this->rtl) {
5311 $t_x = -$t_x;
5313 //calculate elements of transformation matrix
5314 $tm[0]=1;
5315 $tm[1]=0;
5316 $tm[2]=0;
5317 $tm[3]=1;
5318 $tm[4]=$t_x*$this->k;
5319 $tm[5]=-$t_y*$this->k;
5320 //translate the coordinate system
5321 $this->Transform($tm);
5325 * Rotate object.
5326 * @param float $angle angle in degrees for counter-clockwise rotation
5327 * @param int $x abscissa of the rotation center. Default is current x position
5328 * @param int $y ordinate of the rotation center. Default is current y position
5329 * @since 2.1.000 (2008-01-07)
5330 * @see StartTransform(), StopTransform()
5332 public function Rotate($angle, $x='', $y=''){
5333 if($x === '') {
5334 $x=$this->x;
5336 if($y === '') {
5337 $y=$this->y;
5339 if($this->rtl) {
5340 $x = $this->w - $x;
5341 $angle = -$angle;
5343 $y=($this->h-$y)*$this->k;
5344 $x*=$this->k;
5345 //calculate elements of transformation matrix
5346 $tm[0]=cos(deg2rad($angle));
5347 $tm[1]=sin(deg2rad($angle));
5348 $tm[2]=-$tm[1];
5349 $tm[3]=$tm[0];
5350 $tm[4]=$x+$tm[1]*$y-$tm[0]*$x;
5351 $tm[5]=$y-$tm[0]*$y-$tm[1]*$x;
5352 //rotate the coordinate system around ($x,$y)
5353 $this->Transform($tm);
5357 * Skew horizontally.
5358 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
5359 * @param int $x abscissa of the skewing center. default is current x position
5360 * @param int $y ordinate of the skewing center. default is current y position
5361 * @since 2.1.000 (2008-01-07)
5362 * @see StartTransform(), StopTransform()
5364 public function SkewX($angle_x, $x='', $y=''){
5365 $this->Skew($angle_x, 0, $x, $y);
5369 * Skew vertically.
5370 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
5371 * @param int $x abscissa of the skewing center. default is current x position
5372 * @param int $y ordinate of the skewing center. default is current y position
5373 * @since 2.1.000 (2008-01-07)
5374 * @see StartTransform(), StopTransform()
5376 public function SkewY($angle_y, $x='', $y=''){
5377 $this->Skew(0, $angle_y, $x, $y);
5381 * Skew.
5382 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
5383 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
5384 * @param int $x abscissa of the skewing center. default is current x position
5385 * @param int $y ordinate of the skewing center. default is current y position
5386 * @since 2.1.000 (2008-01-07)
5387 * @see StartTransform(), StopTransform()
5389 public function Skew($angle_x, $angle_y, $x='', $y=''){
5390 if($x === '') {
5391 $x=$this->x;
5393 if($y === '') {
5394 $y=$this->y;
5396 if($this->rtl) {
5397 $x = $this->w - $x;
5398 $angle_x = -$angle_x;
5400 if($angle_x <= -90 OR $angle_x >= 90 OR $angle_y <= -90 OR $angle_y >= 90)
5401 $this->Error('Please use values between -90� and 90� for skewing');
5402 $x*=$this->k;
5403 $y=($this->h-$y)*$this->k;
5404 //calculate elements of transformation matrix
5405 $tm[0]=1;
5406 $tm[1]=tan(deg2rad($angle_y));
5407 $tm[2]=tan(deg2rad($angle_x));
5408 $tm[3]=1;
5409 $tm[4]=-$tm[2]*$y;
5410 $tm[5]=-$tm[1]*$x;
5411 //skew the coordinate system
5412 $this->Transform($tm);
5416 * Apply graphic transformations.
5417 * @since 2.1.000 (2008-01-07)
5418 * @see StartTransform(), StopTransform()
5420 protected function Transform($tm){
5421 $this->_out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', $tm[0],$tm[1],$tm[2],$tm[3],$tm[4],$tm[5]));
5424 // END TRANSFORMATIONS SECTION -------------------------
5427 // START GRAPHIC FUNCTIONS SECTION ---------------------
5428 // The following section is based on the code provided by David Hernandez Sanz
5431 * 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.
5432 * @param float $width The width.
5433 * @since 1.0
5434 * @see Line(), Rect(), Cell(), MultiCell()
5436 public function SetLineWidth($width) {
5437 //Set line width
5438 $this->LineWidth=$width;
5439 if($this->page>0) {
5440 $this->_out(sprintf('%.2f w',$width*$this->k));
5445 * Returns the current the line width.
5446 * @return int Line width
5447 * @since 2.1.000 (2008-01-07)
5448 * @see Line(), SetLineWidth()
5450 public function GetLineWidth() {
5451 return $this->LineWidth;
5455 * Set line style.
5457 * @param array $style Line style. Array with keys among the following:
5458 * <ul>
5459 * <li>width (float): Width of the line in user units.</li>
5460 * <li>cap (string): Type of cap to put on the line. Possible values are:
5461 * butt, round, square. The difference between "square" and "butt" is that
5462 * "square" projects a flat end past the end of the line.</li>
5463 * <li>join (string): Type of join. Possible values are: miter, round,
5464 * bevel.</li>
5465 * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
5466 * series of length values, which are the lengths of the on and off dashes.
5467 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
5468 * 1 off, 2 on, 1 off, ...</li>
5469 * <li>phase (integer): Modifier on the dash pattern which is used to shift
5470 * the point at which the pattern starts.</li>
5471 * <li>color (array): Draw color. Format: array(red, green, blue).</li>
5472 * </ul>
5473 * @access public
5474 * @since 2.1.000 (2008-01-08)
5476 public function SetLineStyle($style) {
5477 extract($style);
5478 if (isset($width)) {
5479 $width_prev = $this->LineWidth;
5480 $this->SetLineWidth($width);
5481 $this->LineWidth = $width_prev;
5483 if (isset($cap)) {
5484 $ca = array("butt" => 0, "round"=> 1, "square" => 2);
5485 if (isset($ca[$cap])) {
5486 $this->_out($ca[$cap] . " J");
5489 if (isset($join)) {
5490 $ja = array("miter" => 0, "round" => 1, "bevel" => 2);
5491 if (isset($ja[$join])) {
5492 $this->_out($ja[$join] . " j");
5495 if (isset($dash)) {
5496 $dash_string = "";
5497 if ($dash) {
5498 // phpMyAdmin change
5499 if (preg_match("/^.+,/", $dash)) {
5500 $tab = explode(",", $dash);
5501 } else {
5502 $tab = array($dash);
5504 $dash_string = "";
5505 foreach ($tab as $i => $v) {
5506 if ($i) {
5507 $dash_string .= " ";
5509 $dash_string .= sprintf("%.2f", $v);
5512 if (!isset($phase) OR !$dash) {
5513 $phase = 0;
5515 $this->_out(sprintf("[%s] %.2f d", $dash_string, $phase));
5517 if (isset($color)) {
5518 list($r, $g, $b) = $color;
5519 $this->SetDrawColor($r, $g, $b);
5524 * Set a draw point.
5525 * @param float $x Abscissa of point.
5526 * @param float $y Ordinate of point.
5527 * @access private
5528 * @since 2.1.000 (2008-01-08)
5530 protected function _outPoint($x, $y) {
5531 if($this->rtl) {
5532 $x = $this->w - $x;
5534 $this->_out(sprintf("%.2f %.2f m", $x * $this->k, ($this->h - $y) * $this->k));
5538 * Draws a line from last draw point.
5539 * @param float $x Abscissa of end point.
5540 * @param float $y Ordinate of end point.
5541 * @access private
5542 * @since 2.1.000 (2008-01-08)
5544 protected function _outLine($x, $y) {
5545 if($this->rtl) {
5546 $x = $this->w - $x;
5548 $this->_out(sprintf("%.2f %.2f l", $x * $this->k, ($this->h - $y) * $this->k));
5552 * Draws a rectangle.
5553 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
5554 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
5555 * @param float $w Width.
5556 * @param float $h Height.
5557 * @param string $op options
5558 * @access protected
5559 * @since 2.1.000 (2008-01-08)
5561 protected function _outRect($x, $y, $w, $h, $op) {
5562 if($this->rtl) {
5563 $x = $this->w - $x - $w;
5565 $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op));
5569 * Draws a Bezier curve from last draw point.
5570 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
5571 * @param float $x1 Abscissa of control point 1.
5572 * @param float $y1 Ordinate of control point 1.
5573 * @param float $x2 Abscissa of control point 2.
5574 * @param float $y2 Ordinate of control point 2.
5575 * @param float $x3 Abscissa of end point.
5576 * @param float $y3 Ordinate of end point.
5577 * @access private
5578 * @since 2.1.000 (2008-01-08)
5580 protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
5581 if($this->rtl) {
5582 $x1 = $this->w - $x1;
5583 $x2 = $this->w - $x2;
5584 $x3 = $this->w - $x3;
5586 $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));
5590 * Draws a line between two points.
5591 * @param float $x1 Abscissa of first point.
5592 * @param float $y1 Ordinate of first point.
5593 * @param float $x2 Abscissa of second point.
5594 * @param float $y2 Ordinate of second point.
5595 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5596 * @access public
5597 * @since 1.0
5598 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
5600 public function Line($x1, $y1, $x2, $y2, $style = array()) {
5601 if ($style) {
5602 $this->SetLineStyle($style);
5604 $this->_outPoint($x1, $y1);
5605 $this->_outLine($x2, $y2);
5606 $this->_out(" S");
5610 * Draws a rectangle.
5611 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
5612 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
5613 * @param float $w Width.
5614 * @param float $h Height.
5615 * @param string $style Style of rendering. Possible values are:
5616 * <ul>
5617 * <li>D or empty string: Draw (default).</li>
5618 * <li>F: Fill.</li>
5619 * <li>DF or FD: Draw and fill.</li>
5620 * </ul>
5621 * @param array $border_style Border style of rectangle. Array with keys among the following:
5622 * <ul>
5623 * <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
5624 * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
5625 * </ul>
5626 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
5627 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5628 * @access public
5629 * @since 1.0
5630 * @see SetLineStyle()
5632 public function Rect($x, $y, $w, $h, $style='', $border_style = array(), $fill_color = array()) {
5633 if (!(false === strpos($style, "F")) AND $fill_color) {
5634 list($r, $g, $b) = $fill_color;
5635 $this->SetFillColor($r, $g, $b);
5637 switch ($style) {
5638 case "F": {
5639 $op='f';
5640 $border_style = array();
5641 $this->_outRect($x, $y, $w, $h, $op);
5642 break;
5644 case "DF":
5645 case "FD": {
5646 if (!$border_style OR isset($border_style["all"])) {
5647 $op='B';
5648 if (isset($border_style["all"])) {
5649 $this->SetLineStyle($border_style["all"]);
5650 $border_style = array();
5652 } else {
5653 $op='f';
5655 $this->_outRect($x, $y, $w, $h, $op);
5656 break;
5658 default: {
5659 $op='S';
5660 if (!$border_style OR isset($border_style["all"])) {
5661 if (isset($border_style["all"]) && $border_style["all"]) {
5662 $this->SetLineStyle($border_style["all"]);
5663 $border_style = array();
5665 $this->_outRect($x, $y, $w, $h, $op);
5667 break;
5670 if ($border_style) {
5671 $border_style2 = array();
5672 foreach ($border_style as $line => $value) {
5673 $lenght = strlen($line);
5674 for ($i = 0; $i < $lenght; $i++) {
5675 $border_style2[$line[$i]] = $value;
5678 $border_style = $border_style2;
5679 if (isset($border_style["L"]) && $border_style["L"]) {
5680 $this->Line($x, $y, $x, $y + $h, $border_style["L"]);
5682 if (isset($border_style["T"]) && $border_style["T"]) {
5683 $this->Line($x, $y, $x + $w, $y, $border_style["T"]);
5685 if (isset($border_style["R"]) && $border_style["R"]) {
5686 $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style["R"]);
5688 if (isset($border_style["B"]) && $border_style["B"]) {
5689 $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style["B"]);
5696 * Draws a Bezier curve.
5697 * The Bezier curve is a tangent to the line between the control points at
5698 * either end of the curve.
5699 * @param float $x0 Abscissa of start point.
5700 * @param float $y0 Ordinate of start point.
5701 * @param float $x1 Abscissa of control point 1.
5702 * @param float $y1 Ordinate of control point 1.
5703 * @param float $x2 Abscissa of control point 2.
5704 * @param float $y2 Ordinate of control point 2.
5705 * @param float $x3 Abscissa of end point.
5706 * @param float $y3 Ordinate of end point.
5707 * @param string $style Style of rendering. Possible values are:
5708 * <ul>
5709 * <li>D or empty string: Draw (default).</li>
5710 * <li>F: Fill.</li>
5711 * <li>DF or FD: Draw and fill.</li>
5712 * </ul>
5713 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5714 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5715 * @access public
5716 * @see SetLineStyle()
5717 * @since 2.1.000 (2008-01-08)
5719 public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style = "", $line_style = array(), $fill_color = array()) {
5720 if (!(false === strpos($style, "F")) AND $fill_color) {
5721 list($r, $g, $b) = $fill_color;
5722 $this->SetFillColor($r, $g, $b);
5724 switch ($style) {
5725 case "F": {
5726 $op = "f";
5727 $line_style = array();
5728 break;
5730 case "FD":
5731 case "DF": {
5732 $op = "B";
5733 break;
5735 default: {
5736 $op = "S";
5737 break;
5740 if ($line_style) {
5741 $this->SetLineStyle($line_style);
5743 $this->_outPoint($x0, $y0);
5744 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
5745 $this->_out($op);
5749 * Draws an ellipse.
5750 * An ellipse is formed from n Bezier curves.
5751 * @param float $x0 Abscissa of center point.
5752 * @param float $y0 Ordinate of center point.
5753 * @param float $rx Horizontal radius.
5754 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
5755 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
5756 * @param float $astart: Angle start of draw line. Default value: 0.
5757 * @param float $afinish: Angle finish of draw line. Default value: 360.
5758 * @param string $style Style of rendering. Possible values are:
5759 * <ul>
5760 * <li>D or empty string: Draw (default).</li>
5761 * <li>F: Fill.</li>
5762 * <li>DF or FD: Draw and fill.</li>
5763 * <li>C: Draw close.</li>
5764 * </ul>
5765 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5766 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5767 * @param integer $nc Number of curves used in ellipse. Default value: 8.
5768 * @access public
5769 * @since 2.1.000 (2008-01-08)
5771 public function Ellipse($x0, $y0, $rx, $ry = 0, $angle = 0, $astart = 0, $afinish = 360, $style = "", $line_style = array(), $fill_color = array(), $nc = 8) {
5772 if ($angle) {
5773 $this->StartTransform();
5774 $this->Rotate($angle, $x0, $y0);
5775 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
5776 $this->StopTransform();
5777 return;
5779 if ($rx) {
5780 if (!(false === strpos($style, "F")) AND $fill_color) {
5781 list($r, $g, $b) = $fill_color;
5782 $this->SetFillColor($r, $g, $b);
5784 switch ($style) {
5785 case "F": {
5786 $op = "f";
5787 $line_style = array();
5788 break;
5790 case "FD":
5791 case "DF": {
5792 $op = "B";
5793 break;
5795 case "C": {
5796 $op = "s"; // Small "s" signifies closing the path as well
5797 break;
5799 default: {
5800 $op = "S";
5801 break;
5804 if ($line_style) {
5805 $this->SetLineStyle($line_style);
5807 if (!$ry) {
5808 $ry = $rx;
5810 $rx *= $this->k;
5811 $ry *= $this->k;
5812 if ($nc < 2){
5813 $nc = 2;
5815 $astart = deg2rad((float) $astart);
5816 $afinish = deg2rad((float) $afinish);
5817 $total_angle = $afinish - $astart;
5818 $dt = $total_angle / $nc;
5819 $dtm = $dt/3;
5820 $x0 *= $this->k;
5821 $y0 = ($this->h - $y0) * $this->k;
5822 $t1 = $astart;
5823 $a0 = $x0 + ($rx * cos($t1));
5824 $b0 = $y0 + ($ry * sin($t1));
5825 $c0 = -$rx * sin($t1);
5826 $d0 = $ry * cos($t1);
5827 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
5828 for ($i = 1; $i <= $nc; $i++) {
5829 // Draw this bit of the total curve
5830 $t1 = ($i * $dt) + $astart;
5831 $a1 = $x0 + ($rx * cos($t1));
5832 $b1 = $y0 + ($ry * sin($t1));
5833 $c1 = -$rx * sin($t1);
5834 $d1 = $ry * cos($t1);
5835 $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));
5836 $a0 = $a1;
5837 $b0 = $b1;
5838 $c0 = $c1;
5839 $d0 = $d1;
5841 $this->_out($op);
5846 * Draws a circle.
5847 * A circle is formed from n Bezier curves.
5848 * @param float $x0 Abscissa of center point.
5849 * @param float $y0 Ordinate of center point.
5850 * @param float $r Radius.
5851 * @param float $astart: Angle start of draw line. Default value: 0.
5852 * @param float $afinish: Angle finish of draw line. Default value: 360.
5853 * @param string $style Style of rendering. Possible values are:
5854 * <ul>
5855 * <li>D or empty string: Draw (default).</li>
5856 * <li>F: Fill.</li>
5857 * <li>DF or FD: Draw and fill.</li>
5858 * <li>C: Draw close.</li>
5859 * </ul>
5860 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5861 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5862 * @param integer $nc Number of curves used in circle. Default value: 8.
5863 * @access public
5864 * @since 2.1.000 (2008-01-08)
5866 public function Circle($x0, $y0, $r, $astart = 0, $afinish = 360, $style = "", $line_style = array(), $fill_color = array(), $nc = 8) {
5867 $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
5871 * Draws a polygon.
5872 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
5873 * @param string $style Style of rendering. Possible values are:
5874 * <ul>
5875 * <li>D or empty string: Draw (default).</li>
5876 * <li>F: Fill.</li>
5877 * <li>DF or FD: Draw and fill.</li>
5878 * </ul>
5879 * @param array $line_style Line style of polygon. Array with keys among the following:
5880 * <ul>
5881 * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
5882 * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
5883 * </ul>
5884 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
5885 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5886 * @access public
5887 * @since 2.1.000 (2008-01-08)
5889 public function Polygon($p, $style = "", $line_style = array(), $fill_color = array()) {
5890 $np = count($p) / 2;
5891 if (!(false === strpos($style, "F")) AND $fill_color) {
5892 list($r, $g, $b) = $fill_color;
5893 $this->SetFillColor($r, $g, $b);
5895 switch ($style) {
5896 case "F": {
5897 $line_style = array();
5898 $op = "f";
5899 break;
5901 case "FD":
5902 case "DF": {
5903 $op = "B";
5904 break;
5906 default: {
5907 $op = "S";
5908 break;
5911 $draw = true;
5912 if ($line_style) {
5913 if (isset($line_style["all"])) {
5914 $this->SetLineStyle($line_style["all"]);
5916 else { // 0 .. (np - 1), op = {B, S}
5917 $draw = false;
5918 if ("B" == $op) {
5919 $op = "f";
5920 $this->_outPoint($p[0], $p[1]);
5921 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
5922 $this->_outLine($p[$i], $p[$i + 1]);
5924 $this->_outLine($p[0], $p[1]);
5925 $this->_out($op);
5927 $p[$np * 2] = $p[0];
5928 $p[($np * 2) + 1] = $p[1];
5929 for ($i = 0; $i < $np; $i++) {
5930 if (isset($line_style[$i])) {
5931 $this->Line($p[$i * 2], $p[($i * 2) + 1], $p[($i * 2) + 2], $p[($i * 2) + 3], $line_style[$i]);
5936 if ($draw) {
5937 $this->_outPoint($p[0], $p[1]);
5938 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
5939 $this->_outLine($p[$i], $p[$i + 1]);
5941 $this->_outLine($p[0], $p[1]);
5942 $this->_out($op);
5947 * Draws a regular polygon.
5948 * @param float $x0 Abscissa of center point.
5949 * @param float $y0 Ordinate of center point.
5950 * @param float $r: Radius of inscribed circle.
5951 * @param integer $ns Number of sides.
5952 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
5953 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
5954 * @param string $style Style of rendering. Possible values are:
5955 * <ul>
5956 * <li>D or empty string: Draw (default).</li>
5957 * <li>F: Fill.</li>
5958 * <li>DF or FD: Draw and fill.</li>
5959 * </ul>
5960 * @param array $line_style Line style of polygon sides. Array with keys among the following:
5961 * <ul>
5962 * <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
5963 * <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
5964 * </ul>
5965 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
5966 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5967 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
5968 * <ul>
5969 * <li>D or empty string: Draw (default).</li>
5970 * <li>F: Fill.</li>
5971 * <li>DF or FD: Draw and fill.</li>
5972 * </ul>
5973 * @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).
5974 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
5975 * @access public
5976 * @since 2.1.000 (2008-01-08)
5978 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()) {
5979 if (3 > $ns) {
5980 $ns = 3;
5982 if ($draw_circle) {
5983 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
5985 $p = array();
5986 for ($i = 0; $i < $ns; $i++) {
5987 $a = $angle + ($i * 360 / $ns);
5988 $a_rad = deg2rad((float) $a);
5989 $p[] = $x0 + ($r * sin($a_rad));
5990 $p[] = $y0 + ($r * cos($a_rad));
5992 $this->Polygon($p, $style, $line_style, $fill_color);
5996 * Draws a star polygon
5997 * @param float $x0 Abscissa of center point.
5998 * @param float $y0 Ordinate of center point.
5999 * @param float $r Radius of inscribed circle.
6000 * @param integer $nv Number of vertices.
6001 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
6002 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6003 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
6004 * @param string $style Style of rendering. Possible values are:
6005 * <ul>
6006 * <li>D or empty string: Draw (default).</li>
6007 * <li>F: Fill.</li>
6008 * <li>DF or FD: Draw and fill.</li>
6009 * </ul>
6010 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6011 * <ul>
6012 * <li>all: Line style of all sides. Array like for
6013 * {@link SetLineStyle SetLineStyle}.</li>
6014 * <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6015 * </ul>
6016 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6017 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6018 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6019 * <ul>
6020 * <li>D or empty string: Draw (default).</li>
6021 * <li>F: Fill.</li>
6022 * <li>DF or FD: Draw and fill.</li>
6023 * </ul>
6024 * @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).
6025 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6026 * @access public
6027 * @since 2.1.000 (2008-01-08)
6029 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()) {
6030 if (2 > $nv) {
6031 $nv = 2;
6033 if ($draw_circle) {
6034 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6036 $p2 = array();
6037 $visited = array();
6038 for ($i = 0; $i < $nv; $i++) {
6039 $a = $angle + ($i * 360 / $nv);
6040 $a_rad = deg2rad((float) $a);
6041 $p2[] = $x0 + ($r * sin($a_rad));
6042 $p2[] = $y0 + ($r * cos($a_rad));
6043 $visited[] = false;
6045 $p = array();
6046 $i = 0;
6047 do {
6048 $p[] = $p2[$i * 2];
6049 $p[] = $p2[($i * 2) + 1];
6050 $visited[$i] = true;
6051 $i += $ng;
6052 $i %= $nv;
6053 } while (!$visited[$i]);
6054 $this->Polygon($p, $style, $line_style, $fill_color);
6058 * Draws a rounded rectangle.
6059 * @param float $x Abscissa of upper-left corner.
6060 * @param float $y Ordinate of upper-left corner.
6061 * @param float $w Width.
6062 * @param float $h Height.
6063 * @param float $r Radius of the rounded corners.
6064 * @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").
6065 * @param string $style Style of rendering. Possible values are:
6066 * <ul>
6067 * <li>D or empty string: Draw (default).</li>
6068 * <li>F: Fill.</li>
6069 * <li>DF or FD: Draw and fill.</li>
6070 * </ul>
6071 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6072 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6073 * @access public
6074 * @since 2.1.000 (2008-01-08)
6076 public function RoundedRect($x, $y, $w, $h, $r, $round_corner = "1111", $style = "", $border_style = array(), $fill_color = array()) {
6077 if ("0000" == $round_corner) { // Not rounded
6078 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
6079 } else { // Rounded
6080 if (!(false === strpos($style, "F")) AND $fill_color) {
6081 list($red, $g, $b) = $fill_color;
6082 $this->SetFillColor($red, $g, $b);
6084 switch ($style) {
6085 case "F": {
6086 $border_style = array();
6087 $op = "f";
6088 break;
6090 case "FD":
6091 case "DF": {
6092 $op = "B";
6093 break;
6095 default: {
6096 $op = "S";
6097 break;
6100 if ($border_style) {
6101 $this->SetLineStyle($border_style);
6103 $MyArc = 4 / 3 * (sqrt(2) - 1);
6104 $this->_outPoint($x + $r, $y);
6105 $xc = $x + $w - $r;
6106 $yc = $y + $r;
6107 $this->_outLine($xc, $y);
6108 if ($round_corner[0]) {
6109 $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
6110 } else {
6111 $this->_outLine($x + $w, $y);
6113 $xc = $x + $w - $r;
6114 $yc = $y + $h - $r;
6115 $this->_outLine($x + $w, $yc);
6116 if ($round_corner[1]) {
6117 $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
6118 } else {
6119 $this->_outLine($x + $w, $y + $h);
6121 $xc = $x + $r;
6122 $yc = $y + $h - $r;
6123 $this->_outLine($xc, $y + $h);
6124 if ($round_corner[2]) {
6125 $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
6126 } else {
6127 $this->_outLine($x, $y + $h);
6129 $xc = $x + $r;
6130 $yc = $y + $r;
6131 $this->_outLine($x, $yc);
6132 if ($round_corner[3]) {
6133 $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
6134 } else {
6135 $this->_outLine($x, $y);
6136 $this->_outLine($x + $r, $y);
6138 $this->_out($op);
6142 // END GRAPHIC FUNCTIONS SECTION -----------------------
6144 // BIDIRECTIONAL TEXT SECTION --------------------------
6147 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
6148 * @param string $str string to manipulate.
6149 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
6150 * @return string
6151 * @author Nicola Asuni
6152 * @since 2.1.000 (2008-01-08)
6154 protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
6155 global $unicode,$unicode_mirror, $unicode_arlet;
6156 require_once(dirname(__FILE__).'/unicode_data.php');
6158 // paragraph embedding level
6159 $pel = 0;
6160 // max level
6161 $maxlevel = 0;
6163 // check if string contains arabic text
6164 if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
6165 $arabic = true;
6166 } else {
6167 $arabic = false;
6170 // check if string contains RTL text
6171 if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
6172 return $this->UTF8ToUTF16BE($str, false);
6175 // convert string to array of unicode chars
6176 $ta = $this->UTF8StringToArray($str);
6177 // get number of chars
6178 $numchars = count($ta);
6180 if ($forcertl == 'R') {
6181 $pel = 1;
6182 } elseif ($forcertl == 'L') {
6183 $pel = 0;
6184 } else {
6185 // P2. In each paragraph, find the first character of type L, AL, or R.
6186 // 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.
6187 for ($i=0; $i < $numchars; $i++) {
6188 $type = $unicode[$ta[$i]];
6189 if ($type == 'L') {
6190 $pel = 0;
6191 break;
6192 } elseif (($type == 'AL') OR ($type == 'R')) {
6193 $pel = 1;
6194 break;
6199 // Current Embedding Level
6200 $cel = $pel;
6201 // directional override status
6202 $dos = 'N';
6203 $remember = array();
6204 // start-of-level-run
6205 $sor = $pel % 2 ? 'R' : 'L';
6206 $eor = $sor;
6208 //$levels = array(array('level' => $cel, 'sor' => $sor, 'eor' => '', 'chars' => array()));
6209 //$current_level = &$levels[count( $levels )-1];
6211 // Array of characters data
6212 $chardata = Array();
6214 // 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.
6215 // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
6216 for ($i=0; $i < $numchars; $i++) {
6217 if ($ta[$i] == K_RLE) {
6218 // X2. With each RLE, compute the least greater odd embedding level.
6219 // 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.
6220 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6221 $next_level = $cel + ($cel % 2) + 1;
6222 if ($next_level < 62) {
6223 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
6224 $cel = $next_level;
6225 $dos = 'N';
6226 $sor = $eor;
6227 $eor = $cel % 2 ? 'R' : 'L';
6229 } elseif ($ta[$i] == K_LRE) {
6230 // X3. With each LRE, compute the least greater even embedding level.
6231 // 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.
6232 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6233 $next_level = $cel + 2 - ($cel % 2);
6234 if ( $next_level < 62 ) {
6235 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
6236 $cel = $next_level;
6237 $dos = 'N';
6238 $sor = $eor;
6239 $eor = $cel % 2 ? 'R' : 'L';
6241 } elseif ($ta[$i] == K_RLO) {
6242 // X4. With each RLO, compute the least greater odd embedding level.
6243 // 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.
6244 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6245 $next_level = $cel + ($cel % 2) + 1;
6246 if ($next_level < 62) {
6247 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
6248 $cel = $next_level;
6249 $dos = 'R';
6250 $sor = $eor;
6251 $eor = $cel % 2 ? 'R' : 'L';
6253 } elseif ($ta[$i] == K_LRO) {
6254 // X5. With each LRO, compute the least greater even embedding level.
6255 // 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.
6256 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6257 $next_level = $cel + 2 - ($cel % 2);
6258 if ( $next_level < 62 ) {
6259 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
6260 $cel = $next_level;
6261 $dos = 'L';
6262 $sor = $eor;
6263 $eor = $cel % 2 ? 'R' : 'L';
6265 } elseif ($ta[$i] == K_PDF) {
6266 // 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.
6267 if (count($remember)) {
6268 $last = count($remember ) - 1;
6269 if (($remember[$last]['num'] == K_RLE) OR
6270 ($remember[$last]['num'] == K_LRE) OR
6271 ($remember[$last]['num'] == K_RLO) OR
6272 ($remember[$last]['num'] == K_LRO)) {
6273 $match = array_pop($remember);
6274 $cel = $match['cel'];
6275 $dos = $match['dos'];
6276 $sor = $eor;
6277 $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
6280 } elseif (($ta[$i] != K_RLE) AND
6281 ($ta[$i] != K_LRE) AND
6282 ($ta[$i] != K_RLO) AND
6283 ($ta[$i] != K_LRO) AND
6284 ($ta[$i] != K_PDF)) {
6285 // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
6286 // a. Set the level of the current character to the current embedding level.
6287 // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
6288 if ($dos != 'N') {
6289 $chardir = $dos;
6290 } else {
6291 $chardir = $unicode[$ta[$i]];
6293 // stores string characters and other information
6294 $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
6296 } // end for each char
6298 // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
6299 // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
6300 // 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.
6302 // 3.3.3 Resolving Weak Types
6303 // 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.
6304 // Nonspacing marks are now resolved based on the previous characters.
6305 $numchars = count($chardata);
6307 // 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.
6308 $prevlevel = -1; // track level changes
6309 $levcount = 0; // counts consecutive chars at the same level
6310 for ($i=0; $i < $numchars; $i++) {
6311 if ($chardata[$i]['type'] == 'NSM') {
6312 if ($levcount) {
6313 $chardata[$i]['type'] = $chardata[$i]['sor'];
6314 } elseif ($i > 0) {
6315 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
6318 if ($chardata[$i]['level'] != $prevlevel) {
6319 $levcount = 0;
6320 } else {
6321 $levcount++;
6323 $prevlevel = $chardata[$i]['level'];
6326 // 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.
6327 $prevlevel = -1;
6328 $levcount = 0;
6329 for ($i=0; $i < $numchars; $i++) {
6330 if ($chardata[$i]['char'] == 'EN') {
6331 for ($j=$levcount; $j >= 0; $j--) {
6332 if ($chardata[$j]['type'] == 'AL') {
6333 $chardata[$i]['type'] = 'AN';
6334 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
6335 break;
6339 if ($chardata[$i]['level'] != $prevlevel) {
6340 $levcount = 0;
6341 } else {
6342 $levcount++;
6344 $prevlevel = $chardata[$i]['level'];
6347 // W3. Change all ALs to R.
6348 for ($i=0; $i < $numchars; $i++) {
6349 if ($chardata[$i]['type'] == 'AL') {
6350 $chardata[$i]['type'] = 'R';
6354 // 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.
6355 $prevlevel = -1;
6356 $levcount = 0;
6357 for ($i=0; $i < $numchars; $i++) {
6358 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
6359 if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
6360 $chardata[$i]['type'] = 'EN';
6361 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
6362 $chardata[$i]['type'] = 'EN';
6363 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
6364 $chardata[$i]['type'] = 'AN';
6367 if ($chardata[$i]['level'] != $prevlevel) {
6368 $levcount = 0;
6369 } else {
6370 $levcount++;
6372 $prevlevel = $chardata[$i]['level'];
6375 // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
6376 $prevlevel = -1;
6377 $levcount = 0;
6378 for ($i=0; $i < $numchars; $i++) {
6379 if($chardata[$i]['type'] == 'ET') {
6380 if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
6381 $chardata[$i]['type'] = 'EN';
6382 } else {
6383 $j = $i+1;
6384 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
6385 if ($chardata[$j]['type'] == 'EN') {
6386 $chardata[$i]['type'] = 'EN';
6387 break;
6388 } elseif ($chardata[$j]['type'] != 'ET') {
6389 break;
6391 $j++;
6395 if ($chardata[$i]['level'] != $prevlevel) {
6396 $levcount = 0;
6397 } else {
6398 $levcount++;
6400 $prevlevel = $chardata[$i]['level'];
6403 // W6. Otherwise, separators and terminators change to Other Neutral.
6404 $prevlevel = -1;
6405 $levcount = 0;
6406 for ($i=0; $i < $numchars; $i++) {
6407 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
6408 $chardata[$i]['type'] = 'ON';
6410 if ($chardata[$i]['level'] != $prevlevel) {
6411 $levcount = 0;
6412 } else {
6413 $levcount++;
6415 $prevlevel = $chardata[$i]['level'];
6418 //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.
6419 $prevlevel = -1;
6420 $levcount = 0;
6421 for ($i=0; $i < $numchars; $i++) {
6422 if ($chardata[$i]['char'] == 'EN') {
6423 for ($j=$levcount; $j >= 0; $j--) {
6424 if ($chardata[$j]['type'] == 'L') {
6425 $chardata[$i]['type'] = 'L';
6426 } elseif ($chardata[$j]['type'] == 'R') {
6427 break;
6431 if ($chardata[$i]['level'] != $prevlevel) {
6432 $levcount = 0;
6433 } else {
6434 $levcount++;
6436 $prevlevel = $chardata[$i]['level'];
6439 // 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.
6440 $prevlevel = -1;
6441 $levcount = 0;
6442 for ($i=0; $i < $numchars; $i++) {
6443 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
6444 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
6445 $chardata[$i]['type'] = 'L';
6446 } elseif (($chardata[$i]['type'] == 'N') AND
6447 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
6448 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
6449 $chardata[$i]['type'] = 'R';
6450 } elseif ($chardata[$i]['type'] == 'N') {
6451 // N2. Any remaining neutrals take the embedding direction
6452 $chardata[$i]['type'] = $chardata[$i]['sor'];
6454 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
6455 // first char
6456 if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
6457 $chardata[$i]['type'] = 'L';
6458 } elseif (($chardata[$i]['type'] == 'N') AND
6459 (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
6460 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
6461 $chardata[$i]['type'] = 'R';
6462 } elseif ($chardata[$i]['type'] == 'N') {
6463 // N2. Any remaining neutrals take the embedding direction
6464 $chardata[$i]['type'] = $chardata[$i]['sor'];
6466 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
6467 //last char
6468 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
6469 $chardata[$i]['type'] = 'L';
6470 } elseif (($chardata[$i]['type'] == 'N') AND
6471 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
6472 (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
6473 $chardata[$i]['type'] = 'R';
6474 } elseif ($chardata[$i]['type'] == 'N') {
6475 // N2. Any remaining neutrals take the embedding direction
6476 $chardata[$i]['type'] = $chardata[$i]['sor'];
6478 } elseif ($chardata[$i]['type'] == 'N') {
6479 // N2. Any remaining neutrals take the embedding direction
6480 $chardata[$i]['type'] = $chardata[$i]['sor'];
6482 if ($chardata[$i]['level'] != $prevlevel) {
6483 $levcount = 0;
6484 } else {
6485 $levcount++;
6487 $prevlevel = $chardata[$i]['level'];
6490 // 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.
6491 // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
6492 for ($i=0; $i < $numchars; $i++) {
6493 $odd = $chardata[$i]['level'] % 2;
6494 if ($odd) {
6495 if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
6496 $chardata[$i]['level'] += 1;
6498 } else {
6499 if ($chardata[$i]['type'] == 'R') {
6500 $chardata[$i]['level'] += 1;
6501 } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
6502 $chardata[$i]['level'] += 2;
6505 $maxlevel = max($chardata[$i]['level'],$maxlevel);
6508 // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
6509 // 1. Segment separators,
6510 // 2. Paragraph separators,
6511 // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
6512 // 4. Any sequence of white space characters at the end of the line.
6513 for ($i=0; $i < $numchars; $i++) {
6514 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
6515 $chardata[$i]['level'] = $pel;
6516 } elseif ($chardata[$i]['type'] == 'WS') {
6517 $j = $i+1;
6518 while ($j < $numchars) {
6519 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
6520 (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
6521 $chardata[$i]['level'] = $pel;;
6522 break;
6523 } elseif ($chardata[$j]['type'] != 'WS') {
6524 break;
6526 $j++;
6531 // Arabic Shaping
6532 // 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.
6533 if ($arabic) {
6534 for ($i=0; $i < $numchars; $i++) {
6535 if ($unicode[$chardata[$i]['char']] == 'AL') {
6536 if (($i > 0) AND (($i+1) < $numchars) AND
6537 ($unicode[$chardata[($i-1)]['char']] == 'AL') AND
6538 ($unicode[$chardata[($i+1)]['char']] == 'AL') AND
6539 ($chardata[($i-1)]['type'] == $chardata[$i]['type']) AND
6540 ($chardata[($i+1)]['type'] == $chardata[$i]['type'])) {
6541 // medial
6542 if (isset($unicode_arlet[$chardata[$i]['char']][3])) {
6543 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][3];
6545 } elseif ((($i+1) < $numchars) AND
6546 ($unicode[$chardata[($i+1)]['char']] == 'AL') AND
6547 ($chardata[($i+1)]['type'] == $chardata[$i]['type'])) {
6548 // initial
6549 if (isset($unicode_arlet[$chardata[$i]['char']][2])) {
6550 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][2];
6552 } elseif (($i > 0) AND
6553 ($unicode[$chardata[($i-1)]['char']] == 'AL') AND
6554 ($chardata[($i-1)]['type'] == $chardata[$i]['type'])) {
6555 // final
6556 if (isset($unicode_arlet[$chardata[$i]['char']][1])) {
6557 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][1];
6559 } elseif (isset($unicode_arlet[$chardata[$i]['char']][0])) {
6560 // isolated
6561 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][0];
6567 // 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.
6568 for ($j=$maxlevel; $j > 0; $j--) {
6569 $ordarray = Array();
6570 $revarr = Array();
6571 $onlevel = false;
6572 for ($i=0; $i < $numchars; $i++) {
6573 if ($chardata[$i]['level'] >= $j) {
6574 $onlevel = true;
6575 if (isset($unicode_mirror[$chardata[$i]['char']])) {
6576 // 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.
6577 $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
6579 $revarr[] = $chardata[$i];
6580 } else {
6581 if($onlevel) {
6582 $revarr = array_reverse($revarr);
6583 $ordarray = array_merge($ordarray, $revarr);
6584 $revarr = Array();
6585 $onlevel = false;
6587 $ordarray[] = $chardata[$i];
6590 if($onlevel) {
6591 $revarr = array_reverse($revarr);
6592 $ordarray = array_merge($ordarray, $revarr);
6594 $chardata = $ordarray;
6597 $ordarray = array();
6598 for ($i=0; $i < $numchars; $i++) {
6599 $ordarray[] = $chardata[$i]['char'];
6602 return $this->arrUTF8ToUTF16BE($ordarray, $setbom);
6605 // END OF BIDIRECTIONAL TEXT SECTION -------------------
6608 * Adds a bookmark.
6609 * @param string $txt bookmark description.
6610 * @param int $level bookmark level.
6611 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
6612 * @access public
6613 * @author Olivier Plathey, Nicola Asuni
6614 * @since 2.1.002 (2008-02-12)
6616 public function Bookmark($txt, $level=0, $y=-1) {
6617 if($y == -1) {
6618 $y = $this->GetY();
6620 $this->outlines[]=array('t'=>$txt,'l'=>$level,'y'=>$y,'p'=>$this->PageNo());
6624 * Create a bookmark PDF string.
6625 * @access private
6626 * @author Olivier Plathey, Nicola Asuni
6627 * @since 2.1.002 (2008-02-12)
6629 private function _putbookmarks() {
6630 $nb = count($this->outlines);
6631 if($nb == 0) {
6632 return;
6634 $lru = array();
6635 $level = 0;
6636 foreach($this->outlines as $i=>$o) {
6637 if($o['l'] > 0) {
6638 $parent = $lru[$o['l'] - 1];
6639 //Set parent and last pointers
6640 $this->outlines[$i]['parent'] = $parent;
6641 $this->outlines[$parent]['last'] = $i;
6642 if($o['l'] > $level) {
6643 //Level increasing: set first pointer
6644 $this->outlines[$parent]['first'] = $i;
6646 } else {
6647 $this->outlines[$i]['parent']=$nb;
6649 if($o['l']<=$level and $i>0) {
6650 //Set prev and next pointers
6651 $prev = $lru[$o['l']];
6652 $this->outlines[$prev]['next'] = $i;
6653 $this->outlines[$i]['prev'] = $prev;
6655 $lru[$o['l']] = $i;
6656 $level = $o['l'];
6658 //Outline items
6659 $n = $this->n+1;
6660 foreach($this->outlines as $i=>$o) {
6661 $this->_newobj();
6662 $this->_out('<</Title '.$this->_textstring($o['t']));
6663 $this->_out('/Parent '.($n+$o['parent']).' 0 R');
6664 if(isset($o['prev']))
6665 $this->_out('/Prev '.($n+$o['prev']).' 0 R');
6666 if(isset($o['next']))
6667 $this->_out('/Next '.($n+$o['next']).' 0 R');
6668 if(isset($o['first']))
6669 $this->_out('/First '.($n+$o['first']).' 0 R');
6670 if(isset($o['last']))
6671 $this->_out('/Last '.($n+$o['last']).' 0 R');
6672 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]',1+2*$o['p'],($this->h-$o['y'])*$this->k));
6673 $this->_out('/Count 0>>');
6674 $this->_out('endobj');
6676 //Outline root
6677 $this->_newobj();
6678 $this->OutlineRoot=$this->n;
6679 $this->_out('<</Type /Outlines /First '.$n.' 0 R');
6680 $this->_out('/Last '.($n+$lru[0]).' 0 R>>');
6681 $this->_out('endobj');
6685 // --- JAVASCRIPT - FORMS ------------------------------
6688 * Adds a javascript
6689 * @access public
6690 * @author Johannes Güntert, Nicola Asuni
6691 * @since 2.1.002 (2008-02-12)
6693 public function IncludeJS($script) {
6694 $this->javascript .= $script;
6698 * Create a javascript PDF string.
6699 * @access private
6700 * @author Johannes Güntert, Nicola Asuni
6701 * @since 2.1.002 (2008-02-12)
6703 private function _putjavascript() {
6704 if (empty($this->javascript)) {
6705 return;
6707 $this->_newobj();
6708 $this->n_js = $this->n;
6709 $this->_out('<<');
6710 $this->_out('/Names [(EmbeddedJS) '.($this->n+1).' 0 R ]');
6711 $this->_out('>>');
6712 $this->_out('endobj');
6713 $this->_newobj();
6714 $this->_out('<<');
6715 $this->_out('/S /JavaScript');
6716 $this->_out('/JS '.$this->_textstring($this->javascript));
6717 $this->_out('>>');
6718 $this->_out('endobj');
6722 * Convert color to javascript color.
6723 * @param string $color color name or #RRGGBB
6724 * @access private
6725 * @author Denis Van Nuffelen, Nicola Asuni
6726 * @since 2.1.002 (2008-02-12)
6728 private function _JScolor($color) {
6729 static $aColors = array('transparent','black','white','red','green','blue','cyan','magenta','yellow','dkGray','gray','ltGray');
6730 if(substr($color,0,1) == '#') {
6731 return sprintf("['RGB',%.3f,%.3f,%.3f]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
6733 if(!in_array($color,$aColors)) {
6734 $this->Error('Invalid color: '.$color);
6736 return 'color.'.$color;
6740 * Adds a javascript form field.
6741 * @param string $type field type
6742 * @param string $name field name
6743 * @param int $x horizontal position
6744 * @param int $y vertical position
6745 * @param int $w width
6746 * @param int $h height
6747 * @param string $prop properties
6748 * @access private
6749 * @author Denis Van Nuffelen, Nicola Asuni
6750 * @since 2.1.002 (2008-02-12)
6752 private function _addfield($type, $name, $x, $y, $w, $h, $prop) {
6753 $k = $this->k;
6754 $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);
6755 $this->javascript .= 'f.textSize='.$this->FontSizePt.';';
6756 if(isset($prop['value'])) {
6757 $this->javascript .= "f.value='".addslashes($prop['value'])."';";
6759 if(isset($prop['TextColor'])) {
6760 $this->javascript .= 'f.textColor='.$this->_JScolor($prop['TextColor']).';';
6762 if(isset($prop['FillColor'])) {
6763 $this->javascript .= 'f.fillColor='.$this->_JScolor($prop['FillColor']).';';
6765 if(isset($prop['BorderColor'])) {
6766 $this->javascript .= 'f.strokeColor='.$this->_JScolor($prop['BorderColor']).';';
6768 if(isset($prop['BorderStyle'])) {
6769 $this->javascript .= "f.borderStyle='".$prop['BorderStyle']."';";
6771 $this->x+=$w;
6775 * Creates a text field
6776 * @param string $name field name
6777 * @param int $w width
6778 * @param int $h height
6779 * @param string $prop properties. The value property allows to set the initial value. The multiline property allows to define the field as multiline.
6780 * @access public
6781 * @author Denis Van Nuffelen, Nicola Asuni
6782 * @since 2.1.002 (2008-02-12)
6784 public function TextField($name, $w, $h, $prop=array()) {
6785 $this->_addfield('text',$name,$this->x,$this->y,$w,$h,$prop);
6786 if(isset($prop['multiline']) AND $prop['multiline']) {
6787 $this->javascript .= 'f.multiline=true;';
6792 * Creates a Combo-box field
6793 * @param string $name field name
6794 * @param int $w width
6795 * @param int $h height
6796 * @param array $values array containing the list of values.
6797 * @param string $prop properties.
6798 * @access public
6799 * @author Denis Van Nuffelen, Nicola Asuni
6800 * @since 2.1.002 (2008-02-12)
6802 public function ComboBox($name, $w, $h, $values, $prop=array()) {
6803 $this->_addfield('combobox',$name,$this->x,$this->y,$w,$h,$prop);
6804 $s = '';
6805 foreach($values as $value) {
6806 $s .= "'".addslashes($value)."',";
6808 $this->javascript .= 'f.setItems(['.substr($s,0,-1).']);';
6812 * Creates a CheckBox field
6813 * @param string $name field name
6814 * @param int $w width
6815 * @param boolean $checked define the initial state (default = false).
6816 * @param string $prop properties.
6817 * @access public
6818 * @author Denis Van Nuffelen, Nicola Asuni
6819 * @since 2.1.002 (2008-02-12)
6821 public function CheckBox($name, $w, $checked=false, $prop=array()) {
6822 $prop['value'] = ($checked ? 'Yes' : 'Off');
6823 if(!isset($prop['BorderColor'])) {
6824 $prop['BorderColor']='black';
6826 $this->_addfield('checkbox',$name,$this->x,$this->y,$w,$w,$prop);
6830 * Creates a button field
6831 * @param string $name field name
6832 * @param int $w width
6833 * @param int $h height
6834 * @param string $caption caption.
6835 * @param string $action action triggered by the button (JavaScript code).
6836 * @param string $prop properties.
6837 * @access public
6838 * @author Denis Van Nuffelen, Nicola Asuni
6839 * @since 2.1.002 (2008-02-12)
6841 public function Button($name, $w, $h, $caption, $action, $prop=array()) {
6842 if(!isset($prop['BorderColor'])) {
6843 $prop['BorderColor']='black';
6845 $prop['BorderStyle']='beveled';
6846 $this->_addfield('button',$name,$this->x,$this->y,$w,$h,$prop);
6847 $this->javascript .= "f.buttonSetCaption('".addslashes($caption)."');";
6848 $this->javascript .= "f.setAction('MouseUp','".addslashes($action)."');";
6849 $this->javascript .= "f.highlight='push';";
6850 $this->javascript .= 'f.print=false;';
6853 // END JAVASCRIPT - FORMS ------------------------------
6855 } // END OF TCPDF CLASS
6857 //Handle special IE contype request
6858 if(isset($_SERVER['HTTP_USER_AGENT']) AND ($_SERVER['HTTP_USER_AGENT']=='contype')) {
6859 header('Content-Type: application/pdf');
6860 exit;
6864 //============================================================+
6865 // END OF FILE
6866 //============================================================+