Convert Excel column name correctly
[phpmyadmin/arisferyanto.git] / libraries / tcpdf / tcpdf.php
blob26f2dc1ba3d25e000783a135ca08d77e60ae17ff
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');
2983 if(php_sapi_name()!='cli') {
2984 //We send to a browser
2985 header('Content-Type: application/pdf');
2986 if(headers_sent()) {
2987 $this->Error('Some data has already been output to browser, can\'t send PDF file');
2989 header('Content-Length: '.strlen($this->buffer));
2990 header('Content-disposition: inline; filename="'.$name.'"');
2992 echo $this->buffer;
2993 break;
2995 case 'D': {
2996 //Download file
2997 if(ob_get_contents()) {
2998 $this->Error('Some data has already been output, can\'t send PDF file');
3000 if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) {
3001 header('Content-Type: application/force-download');
3002 } else {
3003 header('Content-Type: application/octet-stream');
3005 if(headers_sent()) {
3006 $this->Error('Some data has already been output to browser, can\'t send PDF file');
3008 header('Content-Length: '.strlen($this->buffer));
3009 header('Content-disposition: attachment; filename="'.$name.'"');
3010 echo $this->buffer;
3011 break;
3013 case 'F': {
3014 //Save to local file
3015 $f=fopen($name,'wb');
3016 if(!$f) {
3017 $this->Error('Unable to create output file: '.$name);
3019 fwrite($f,$this->buffer,strlen($this->buffer));
3020 fclose($f);
3021 break;
3023 case 'S': {
3024 //Return as a string
3025 return $this->buffer;
3027 default: {
3028 $this->Error('Incorrect output destination: '.$dest);
3031 return '';
3034 // Protected methods
3037 * Check for locale-related bug
3038 * @access protected
3040 protected function _dochecks() {
3041 //Check for locale-related bug
3042 if(1.1==1) {
3043 $this->Error('Don\'t alter the locale before including class file');
3045 //Check for decimal separator
3046 if(sprintf('%.1f',1.0)!='1.0') {
3047 setlocale(LC_NUMERIC,'C');
3052 * Return fonts path
3053 * @access protected
3055 protected function _getfontpath() {
3056 if(!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/font')) {
3057 define('K_PATH_FONTS', dirname(__FILE__).'/font/');
3059 return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
3063 * Start document
3064 * @access protected
3066 protected function _begindoc() {
3067 //Start document
3068 $this->state=1;
3069 $this->_out('%PDF-'.$this->PDFVersion);
3073 * _putpages
3074 * @access protected
3076 protected function _putpages() {
3077 $nb = $this->page;
3078 if(!empty($this->AliasNbPages)) {
3079 $nbstr = $this->UTF8ToUTF16BE($nb, false);
3080 //Replace number of pages
3081 for($n=1;$n<=$nb;$n++) {
3082 $this->pages[$n]=str_replace($this->AliasNbPages, $nbstr, $this->pages[$n]);
3085 if($this->DefOrientation=='P') {
3086 $wPt=$this->fwPt;
3087 $hPt=$this->fhPt;
3089 else {
3090 $wPt=$this->fhPt;
3091 $hPt=$this->fwPt;
3093 $filter=($this->compress) ? '/Filter /FlateDecode ' : '';
3094 for($n=1;$n<=$nb;$n++) {
3095 //Page
3096 $this->_newobj();
3097 $this->_out('<</Type /Page');
3098 $this->_out('/Parent 1 0 R');
3099 if(isset($this->OrientationChanges[$n])) {
3100 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$hPt,$wPt));
3102 $this->_out('/Resources 2 0 R');
3103 if(isset($this->PageLinks[$n])) {
3104 //Links
3105 $annots='/Annots [';
3106 foreach($this->PageLinks[$n] as $pl) {
3107 $rect=sprintf('%.2f %.2f %.2f %.2f',$pl[0],$pl[1],$pl[0]+$pl[2],$pl[1]-$pl[3]);
3108 $annots.='<</Type /Annot /Subtype /Link /Rect ['.$rect.'] /Border [0 0 0] ';
3109 if(is_string($pl[4])) {
3110 $annots.='/A <</S /URI /URI '.$this->_uristring($pl[4]).'>>>>';
3112 else {
3113 $l=$this->links[$pl[4]];
3114 $h=isset($this->OrientationChanges[$l[0]]) ? $wPt : $hPt;
3115 $annots.=sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]>>',1+2*$l[0],$h-$l[1]*$this->k);
3118 $this->_out($annots.']');
3120 $this->_out('/Contents '.($this->n+1).' 0 R>>');
3121 $this->_out('endobj');
3122 //Page content
3123 $p=($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n];
3124 $this->_newobj();
3125 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
3126 $this->_putstream($p);
3127 $this->_out('endobj');
3129 //Pages root
3130 $this->offsets[1]=strlen($this->buffer);
3131 $this->_out('1 0 obj');
3132 $this->_out('<</Type /Pages');
3133 $kids='/Kids [';
3134 for($i=0;$i<$nb;$i++) {
3135 $kids.=(3+2*$i).' 0 R ';
3137 $this->_out($kids.']');
3138 $this->_out('/Count '.$nb);
3139 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$wPt,$hPt));
3140 $this->_out('>>');
3141 $this->_out('endobj');
3145 * Adds fonts
3146 * _putfonts
3147 * @access protected
3149 protected function _putfonts() {
3150 $nf=$this->n;
3151 foreach($this->diffs as $diff) {
3152 //Encodings
3153 $this->_newobj();
3154 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
3155 $this->_out('endobj');
3157 $mqr=get_magic_quotes_runtime();
3158 set_magic_quotes_runtime(0);
3159 foreach($this->FontFiles as $file=>$info) {
3160 //Font file embedding
3161 $this->_newobj();
3162 $this->FontFiles[$file]['n']=$this->n;
3163 $font='';
3164 $f=fopen($this->_getfontpath().strtolower($file),'rb',1);
3165 if(!$f) {
3166 $this->Error('Font file not found: '.$file);
3168 while(!feof($f)) {
3169 $font .= fread($f, 8192);
3171 fclose($f);
3172 $compressed=(substr($file,-2)=='.z');
3173 if(!$compressed && isset($info['length2'])) {
3174 $header=(ord($font{0})==128);
3175 if($header) {
3176 //Strip first binary header
3177 $font=substr($font,6);
3179 if($header && ord($font{$info['length1']})==128) {
3180 //Strip second binary header
3181 $font=substr($font,0,$info['length1']).substr($font,$info['length1']+6);
3184 $this->_out('<</Length '.strlen($font));
3185 if($compressed) {
3186 $this->_out('/Filter /FlateDecode');
3188 $this->_out('/Length1 '.$info['length1']);
3189 if(isset($info['length2'])) {
3190 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
3192 $this->_out('>>');
3193 $this->_putstream($font);
3194 $this->_out('endobj');
3196 set_magic_quotes_runtime($mqr);
3197 foreach($this->fonts as $k=>$font) {
3198 //Font objects
3199 $this->fonts[$k]['n']=$this->n+1;
3200 $type=$font['type'];
3201 $name=$font['name'];
3202 if($type=='core') {
3203 //Standard font
3204 $this->_newobj();
3205 $this->_out('<</Type /Font');
3206 $this->_out('/BaseFont /'.$name);
3207 $this->_out('/Subtype /Type1');
3208 if($name!='Symbol' && $name!='ZapfDingbats') {
3209 $this->_out('/Encoding /WinAnsiEncoding');
3211 $this->_out('>>');
3212 $this->_out('endobj');
3213 } elseif($type=='Type1' OR $type=='TrueType') {
3214 //Additional Type1 or TrueType font
3215 $this->_newobj();
3216 $this->_out('<</Type /Font');
3217 $this->_out('/BaseFont /'.$name);
3218 $this->_out('/Subtype /'.$type);
3219 $this->_out('/FirstChar 32 /LastChar 255');
3220 $this->_out('/Widths '.($this->n+1).' 0 R');
3221 $this->_out('/FontDescriptor '.($this->n+2).' 0 R');
3222 if($font['enc']) {
3223 if(isset($font['diff'])) {
3224 $this->_out('/Encoding '.($nf+$font['diff']).' 0 R');
3225 } else {
3226 $this->_out('/Encoding /WinAnsiEncoding');
3229 $this->_out('>>');
3230 $this->_out('endobj');
3231 //Widths
3232 $this->_newobj();
3233 $cw=&$font['cw'];
3234 $s='[';
3235 for($i=32;$i<=255;$i++) {
3236 $s.=$cw[chr($i)].' ';
3238 $this->_out($s.']');
3239 $this->_out('endobj');
3240 //Descriptor
3241 $this->_newobj();
3242 $s='<</Type /FontDescriptor /FontName /'.$name;
3243 foreach($font['desc'] as $k=>$v) {
3244 $s.=' /'.$k.' '.$v;
3246 $file = $font['file'];
3247 if($file) {
3248 $s.=' /FontFile'.($type=='Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
3250 $this->_out($s.'>>');
3251 $this->_out('endobj');
3252 } else {
3253 //Allow for additional types
3254 $mtd='_put'.strtolower($type);
3255 if(!method_exists($this, $mtd)) {
3256 $this->Error('Unsupported font type: '.$type);
3258 $this->$mtd($font);
3264 * _putimages
3265 * @access protected
3267 protected function _putimages() {
3268 $filter=($this->compress) ? '/Filter /FlateDecode ' : '';
3269 reset($this->images);
3270 while(list($file,$info)=each($this->images)) {
3271 $this->_newobj();
3272 $this->images[$file]['n']=$this->n;
3273 $this->_out('<</Type /XObject');
3274 $this->_out('/Subtype /Image');
3275 $this->_out('/Width '.$info['w']);
3276 $this->_out('/Height '.$info['h']);
3278 if (isset($info["masked"])) {
3279 $this->_out('/SMask '.($this->n-1).' 0 R');
3282 if($info['cs']=='Indexed') {
3283 $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal'])/3-1).' '.($this->n+1).' 0 R]');
3285 else {
3286 $this->_out('/ColorSpace /'.$info['cs']);
3287 if($info['cs']=='DeviceCMYK') {
3288 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
3291 $this->_out('/BitsPerComponent '.$info['bpc']);
3292 if(isset($info['f'])) {
3293 $this->_out('/Filter /'.$info['f']);
3295 if(isset($info['parms'])) {
3296 $this->_out($info['parms']);
3298 if(isset($info['trns']) and is_array($info['trns'])) {
3299 $trns='';
3300 for($i=0;$i<count($info['trns']);$i++) {
3301 $trns.=$info['trns'][$i].' '.$info['trns'][$i].' ';
3303 $this->_out('/Mask ['.$trns.']');
3305 $this->_out('/Length '.strlen($info['data']).'>>');
3306 $this->_putstream($info['data']);
3307 unset($this->images[$file]['data']);
3308 $this->_out('endobj');
3309 //Palette
3310 if($info['cs']=='Indexed') {
3311 $this->_newobj();
3312 $pal=($this->compress) ? gzcompress($info['pal']) : $info['pal'];
3313 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
3314 $this->_putstream($pal);
3315 $this->_out('endobj');
3321 * _putxobjectdict
3322 * @access protected
3324 function _putxobjectdict() {
3325 foreach($this->images as $image) {
3326 $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
3331 * _putresourcedict
3332 * @access protected
3334 function _putresourcedict(){
3335 $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
3336 $this->_out('/Font <<');
3337 foreach($this->fonts as $font) {
3338 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
3340 $this->_out('>>');
3341 $this->_out('/XObject <<');
3342 $this->_putxobjectdict();
3343 $this->_out('>>');
3347 * _putresources
3348 * @access protected
3350 function _putresources() {
3351 $this->_putfonts();
3352 $this->_putimages();
3353 //Resource dictionary
3354 $this->offsets[2]=strlen($this->buffer);
3355 $this->_out('2 0 obj');
3356 $this->_out('<<');
3357 $this->_putresourcedict();
3358 $this->_out('>>');
3359 $this->_out('endobj');
3360 $this->_putjavascript();
3361 $this->_putbookmarks();
3362 // encryption
3363 if ($this->encrypted) {
3364 $this->_newobj();
3365 $this->enc_obj_id = $this->n;
3366 $this->_out('<<');
3367 $this->_putencryption();
3368 $this->_out('>>');
3369 $this->_out('endobj');
3374 * _putinfo
3375 * Adds some meta information
3376 * @access protected
3378 protected function _putinfo() {
3379 $this->_out('/CreationDate ('.$this->_escape('D:'.date('YmdHis')).')');
3380 $this->_out('/ModDate ('.$this->_escape('D:'.date('YmdHis')).')');
3381 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
3382 if(!empty($this->title)) {
3383 $this->_out('/Title '.$this->_textstring($this->title));
3385 if(!empty($this->subject)) {
3386 $this->_out('/Subject '.$this->_textstring($this->subject));
3388 if(!empty($this->author)) {
3389 $this->_out('/Author '.$this->_textstring($this->author));
3391 if(!empty($this->keywords)) {
3392 $this->_out('/Keywords '.$this->_textstring($this->keywords));
3394 if(!empty($this->creator)) {
3395 $this->_out('/Creator '.$this->_textstring($this->creator));
3400 * _putcatalog
3401 * @access protected
3403 protected function _putcatalog() {
3404 $this->_out('/Type /Catalog');
3405 $this->_out('/Pages 1 0 R');
3406 if($this->ZoomMode=='fullpage') {
3407 $this->_out('/OpenAction [3 0 R /Fit]');
3409 elseif($this->ZoomMode=='fullwidth') {
3410 $this->_out('/OpenAction [3 0 R /FitH null]');
3412 elseif($this->ZoomMode=='real') {
3413 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
3415 elseif(!is_string($this->ZoomMode)) {
3416 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode/100).']');
3418 if($this->LayoutMode=='single') {
3419 $this->_out('/PageLayout /SinglePage');
3421 elseif($this->LayoutMode=='continuous') {
3422 $this->_out('/PageLayout /OneColumn');
3424 elseif($this->LayoutMode=='two') {
3425 $this->_out('/PageLayout /TwoColumnLeft');
3427 if (!empty($this->javascript)) {
3428 $this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
3430 if(count($this->outlines)>0) {
3431 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
3432 $this->_out('/PageMode /UseOutlines');
3434 if($this->rtl) {
3435 $this->_out('/ViewerPreferences << /Direction /R2L >>');
3440 * _puttrailer
3441 * @access protected
3443 protected function _puttrailer() {
3444 $this->_out('/Size '.($this->n+1));
3445 $this->_out('/Root '.$this->n.' 0 R');
3446 $this->_out('/Info '.($this->n-1).' 0 R');
3447 if ($this->encrypted) {
3448 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
3449 $this->_out('/ID [()()]');
3454 * _putheader
3455 * @access protected
3457 function _putheader() {
3458 $this->_out('%PDF-'.$this->PDFVersion);
3462 * _enddoc
3463 * @access protected
3465 protected function _enddoc() {
3466 $this->_putheader();
3467 $this->_putpages();
3468 $this->_putresources();
3469 //Info
3470 $this->_newobj();
3471 $this->_out('<<');
3472 $this->_putinfo();
3473 $this->_out('>>');
3474 $this->_out('endobj');
3475 //Catalog
3476 $this->_newobj();
3477 $this->_out('<<');
3478 $this->_putcatalog();
3479 $this->_out('>>');
3480 $this->_out('endobj');
3481 //Cross-ref
3482 $o=strlen($this->buffer);
3483 $this->_out('xref');
3484 $this->_out('0 '.($this->n+1));
3485 $this->_out('0000000000 65535 f ');
3486 for($i=1;$i<=$this->n;$i++) {
3487 $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i]));
3489 //Trailer
3490 $this->_out('trailer');
3491 $this->_out('<<');
3492 $this->_puttrailer();
3493 $this->_out('>>');
3494 $this->_out('startxref');
3495 $this->_out($o);
3496 $this->_out('%%EOF');
3497 $this->state=3;
3501 * _beginpage
3502 * @access protected
3504 protected function _beginpage($orientation) {
3505 $this->page++;
3506 $this->pages[$this->page]='';
3507 $this->state=2;
3508 if ($this->rtl) {
3509 $this->x = $this->w - $this->rMargin;
3510 } else {
3511 $this->x = $this->lMargin;
3513 $this->y = $this->tMargin;
3514 $this->FontFamily='';
3515 //Page orientation
3516 if(empty($orientation)) {
3517 $orientation=$this->DefOrientation;
3519 else {
3520 $orientation=strtoupper($orientation{0});
3521 if($orientation!=$this->DefOrientation) {
3522 $this->OrientationChanges[$this->page]=true;
3525 if($orientation!=$this->CurOrientation) {
3526 //Change orientation
3527 if($orientation=='P') {
3528 $this->wPt=$this->fwPt;
3529 $this->hPt=$this->fhPt;
3530 $this->w=$this->fw;
3531 $this->h=$this->fh;
3533 else {
3534 $this->wPt=$this->fhPt;
3535 $this->hPt=$this->fwPt;
3536 $this->w=$this->fh;
3537 $this->h=$this->fw;
3539 $this->PageBreakTrigger=$this->h-$this->bMargin;
3540 $this->CurOrientation=$orientation;
3545 * End of page contents
3546 * @access protected
3548 protected function _endpage() {
3549 $this->state=1;
3553 * Begin a new object
3554 * @access protected
3556 protected function _newobj() {
3557 $this->n++;
3558 $this->offsets[$this->n]=strlen($this->buffer);
3559 $this->_out($this->n.' 0 obj');
3563 * Underline text
3564 * @param int $x X coordinate
3565 * @param int $y Y coordinate
3566 * @param string $txt text to underline
3567 * @access protected
3569 protected function _dounderline($x, $y, $txt) {
3570 $up = $this->CurrentFont['up'];
3571 $ut = $this->CurrentFont['ut'];
3572 $w = $this->GetStringWidth($txt) + $this->ws * substr_count($txt,' ');
3573 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);
3577 // REWRITTEN by Warren Sherliker wsherliker@gmail.com
3578 // altered to allow compatibility with all sorts of image formats including gif.
3579 // Can easily extend to work with others
3580 // such as gd xbm etc. which are all supported by php 5+
3581 // (Requires GD library)
3584 * Extract info from a JPEG file
3585 * @param string $file image file to parse
3586 * @return string
3587 * @access protected
3589 protected function _parsejpg($file) {
3590 if(!function_exists('imagecreatefromjpeg')) {
3591 // GD is not installed, try legacy method
3592 return $this->_legacyparsejpg($file);
3594 $a=getimagesize($file);
3595 if(empty($a)) {
3596 $this->Error('Missing or incorrect image file: '.$file);
3598 if($a[2]!=2) {
3599 $this->Error('Not a JPEG file: '.$file);
3601 $jpeg = imagecreatefromjpeg($file);
3602 return $this->outputjpg($file, $jpeg);
3606 * Extract info from a GIF file
3607 * @param string $file image file to parse
3608 * @return string
3609 * @access protected
3611 protected function _parsegif($file) {
3612 if(!function_exists('imagecreatefromgif')) {
3613 // PDF doesn't support native GIF and GD is not installed
3614 return false;
3616 $a=getimagesize($file);
3617 if(empty($a)) {
3618 $this->Error('Missing or incorrect image file: '.$file);
3620 if($a[2]!=1) {
3621 $this->Error('Not a GIF file: '.$file);
3623 // Temporary convert file to jpg and then delete this temp data file
3624 $gif = imagecreatefromgif($file);
3625 return $this->toJPEG($file, $gif);
3629 * Extract info from a PNG file
3630 * @param string $file image file to parse
3631 * @return string
3632 * @access protected
3634 protected function _parsepng($file) {
3635 if(!function_exists('imagecreatefrompng')) {
3636 // GD is not installed, try legacy method
3637 return $this->_legacyparsepng($file);
3639 $f=fopen($file,'rb');
3640 if(empty($f)) {
3641 $this->Error('Can\'t open image file: '.$file);
3643 //Check signature
3644 if(fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3645 $this->Error('Not a PNG file: '.$file);
3647 //Read header chunk
3648 fread($f,4);
3649 if(fread($f,4)!='IHDR') {
3650 $this->Error('Incorrect PNG file: '.$file);
3652 // Temporary convert file to jpg and then delete this temp data file
3653 $a=getimagesize($file);
3654 $png = imagecreatefrompng($file);
3655 return $this->toJPEG($file, $png);
3659 * Extract info from a JPEG file without using GD
3660 * @param string $file image file to parse
3661 * @return string
3662 * @access protected
3664 protected function _legacyparsejpg($file) {
3665 $a=GetImageSize($file);
3666 if(empty($a)) {
3667 $this->Error('Missing or incorrect image file: '.$file);
3669 if($a[2]!=2) {
3670 $this->Error('Not a JPEG file: '.$file);
3672 if(!isset($a['channels']) or $a['channels']==3) {
3673 $colspace='DeviceRGB';
3675 elseif($a['channels']==4) {
3676 $colspace='DeviceCMYK';
3678 else {
3679 $colspace='DeviceGray';
3681 $bpc=isset($a['bits']) ? $a['bits'] : 8;
3682 //Read whole file
3683 $f=fopen($file,'rb');
3684 $data='';
3685 while(!feof($f)) {
3686 $data.=fread($f,4096);
3688 fclose($f);
3689 return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data);
3693 * Extract info from a PNG file without using GD
3694 * @param string $file image file to parse
3695 * @return string
3696 * @access protected
3698 protected function _legacyparsepng($file) {
3699 $f=fopen($file,'rb');
3700 if(empty($f)) {
3701 $this->Error('Can\'t open image file: '.$file);
3703 //Check signature
3704 if(fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3705 $this->Error('Not a PNG file: '.$file);
3707 //Read header chunk
3708 fread($f,4);
3709 if(fread($f,4)!='IHDR') {
3710 $this->Error('Incorrect PNG file: '.$file);
3712 $w=$this->_freadint($f);
3713 $h=$this->_freadint($f);
3714 $bpc=ord(fread($f,1));
3715 if($bpc>8) {
3716 $this->Error('16-bit depth not supported: '.$file);
3718 $ct=ord(fread($f,1));
3719 if($ct==0) {
3720 $colspace='DeviceGray';
3722 elseif($ct==2) {
3723 $colspace='DeviceRGB';
3725 elseif($ct==3) {
3726 $colspace='Indexed';
3728 else {
3729 $this->Error('Alpha channel not supported: '.$file);
3731 if(ord(fread($f,1))!=0) {
3732 $this->Error('Unknown compression method: '.$file);
3734 if(ord(fread($f,1))!=0) {
3735 $this->Error('Unknown filter method: '.$file);
3737 if(ord(fread($f,1))!=0) {
3738 $this->Error('Interlacing not supported: '.$file);
3740 fread($f,4);
3741 $parms='/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
3742 //Scan chunks looking for palette, transparency and image data
3743 $pal='';
3744 $trns='';
3745 $data='';
3746 do {
3747 $n=$this->_freadint($f);
3748 $type=fread($f,4);
3749 if($type=='PLTE') {
3750 //Read palette
3751 $pal=fread($f,$n);
3752 fread($f,4);
3754 elseif($type=='tRNS') {
3755 //Read transparency info
3756 $t=fread($f,$n);
3757 if($ct==0) {
3758 $trns=array(ord(substr($t,1,1)));
3760 elseif($ct==2) {
3761 $trns=array(ord(substr($t,1,1)),ord(substr($t,3,1)),ord(substr($t,5,1)));
3763 else {
3764 $pos=strpos($t,chr(0));
3765 if($pos!==false) {
3766 $trns=array($pos);
3769 fread($f,4);
3771 elseif($type=='IDAT') {
3772 //Read image data block
3773 $data.=fread($f,$n);
3774 fread($f,4);
3776 elseif($type=='IEND') {
3777 break;
3779 else {
3780 fread($f,$n+4);
3783 while($n);
3784 if($colspace=='Indexed' and empty($pal)) {
3785 $this->Error('Missing palette in '.$file);
3787 fclose($f);
3788 return array('w'=>$w, 'h'=>$h, 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'FlateDecode', 'parms'=>$parms, 'pal'=>$pal, 'trns'=>$trns, 'data'=>$data);
3792 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
3793 * @param string $file Image file name.
3794 * @param image $image Image object.
3795 * return image JPEG image object.
3796 * @access protected
3798 protected function toJPEG($file, $image) {
3799 if ($image) {
3800 // output
3801 $tempname = tempnam(K_PATH_CACHE,'jpg');
3802 imagejpeg($image, $tempname, 100);
3803 imagedestroy($image);
3804 $retvars = $this->outputjpg($tempname);
3805 // tidy up by removing temporary image
3806 unlink($tempname);
3807 return $retvars;
3808 } else {
3809 $this->Error('Can\'t open image file: '.$file);
3814 * Get a JPEG filename and return a structure for the PDF creator.
3815 * @param string $filename JPEG file name.
3816 * @return array structure containing the image data
3817 * @access protected
3819 protected function outputjpg($filename) {
3820 $a=getimagesize($filename);
3822 if(!isset($a['channels']) or $a['channels']==3) {
3823 $colspace='DeviceRGB';
3825 elseif($a['channels']==4) {
3826 $colspace='DeviceCMYK';
3828 else {
3829 $colspace='DeviceGray';
3831 $bpc=isset($a['bits']) ? $a['bits'] : 8;
3832 //Read whole file
3834 $f=fopen($filename,'rb');
3835 $data='';
3836 while(!feof($f)) {
3837 $data.=fread($f,4096);
3839 fclose($f);
3841 return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data);
3844 /// END OF REWRITE BY Warren Sherliker wsherliker@gmail.com
3847 * Read a 4-byte integer from file
3848 * @param string $f file name.
3849 * @return 4-byte integer
3850 * @access protected
3852 protected function _freadint($f) {
3853 $a=unpack('Ni',fread($f,4));
3854 return $a['i'];
3858 * Format a text string for meta information
3859 * @param string $s string to escape.
3860 * @return string escaped string.
3861 * @access protected
3863 protected function _textstring($s) {
3864 if($this->isunicode) {
3865 //Convert string to UTF-16BE
3866 $s = $this->UTF8ToUTF16BE($s, true);
3868 if ($this->encrypted) {
3869 $s = $this->_RC4($this->_objectkey($this->n), $s);
3871 return '('. $this->_escape($s).')';
3875 * Format an URI string
3876 * @param string $s string to escape.
3877 * @return string escaped string.
3878 * @access protected
3880 protected function _uristring($s) {
3881 if ($this->encrypted) {
3882 $s = $this->_RC4($this->_objectkey($this->n), $s);
3884 return '('.$this->_escape($s).')';
3888 * Format a text string
3889 * @param string $s string to escape.
3890 * @return string escaped string.
3891 * @access protected
3893 protected function _escapetext($s) {
3894 if($this->isunicode) {
3895 //Convert string to UTF-16BE and reverse RTL language
3896 $s = $this->utf8StrRev($s, false, $this->tmprtl);
3898 return $this->_escape($s);
3902 * Add \ before \, ( and )
3903 * @param string $s string to escape.
3904 * @return string escaped string.
3905 * @access protected
3907 protected function _escape($s) {
3908 // the chr(13) substitution fixes the Bugs item #1421290.
3909 return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
3913 * Output a stream.
3914 * @param string $s string to output.
3915 * @access protected
3917 protected function _putstream($s) {
3918 if ($this->encrypted) {
3919 $s = $this->_RC4($this->_objectkey($this->n), $s);
3921 $this->_out('stream');
3922 $this->_out($s);
3923 $this->_out('endstream');
3927 * Output a string to the document.
3928 * @param string $s string to output.
3929 * @access protected
3931 protected function _out($s) {
3932 if($this->state==2) {
3933 $this->pages[$this->page] .= $s."\n";
3935 else {
3936 $this->buffer .= $s."\n";
3941 * Adds unicode fonts.<br>
3942 * Based on PDF Reference 1.3 (section 5)
3943 * @access protected
3944 * @author Nicola Asuni
3945 * @since 1.52.0.TC005 (2005-01-05)
3947 protected function _puttruetypeunicode($font) {
3948 // Type0 Font
3949 // A composite font composed of other fonts, organized hierarchically
3950 $this->_newobj();
3951 $this->_out('<</Type /Font');
3952 $this->_out('/Subtype /Type0');
3953 $this->_out('/BaseFont /'.$font['name'].'');
3954 $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.
3955 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
3956 $this->_out('/ToUnicode '.($this->n + 2).' 0 R');
3957 $this->_out('>>');
3958 $this->_out('endobj');
3960 // CIDFontType2
3961 // A CIDFont whose glyph descriptions are based on TrueType font technology
3962 $this->_newobj();
3963 $this->_out('<</Type /Font');
3964 $this->_out('/Subtype /CIDFontType2');
3965 $this->_out('/BaseFont /'.$font['name'].'');
3966 $this->_out('/CIDSystemInfo '.($this->n + 2).' 0 R');
3967 $this->_out('/FontDescriptor '.($this->n + 3).' 0 R');
3968 if (isset($font['desc']['MissingWidth'])){
3969 $this->_out('/DW '.$font['desc']['MissingWidth'].''); // The default width for glyphs in the CIDFont MissingWidth
3971 $w = "";
3972 foreach ($font['cw'] as $cid => $width) {
3973 $w .= ''.$cid.' ['.$width.'] '; // define a specific width for each individual CID
3975 $this->_out('/W ['.$w.']'); // A description of the widths for the glyphs in the CIDFont
3976 $this->_out('/CIDToGIDMap '.($this->n + 4).' 0 R');
3977 $this->_out('>>');
3978 $this->_out('endobj');
3980 // ToUnicode
3981 // is a stream object that contains the definition of the CMap
3982 // (PDF Reference 1.3 chap. 5.9)
3983 $this->_newobj();
3984 $this->_out('<</Length 345>>');
3985 $this->_out('stream');
3986 $this->_out('/CIDInit /ProcSet findresource begin');
3987 $this->_out('12 dict begin');
3988 $this->_out('begincmap');
3989 $this->_out('/CIDSystemInfo');
3990 $this->_out('<</Registry (Adobe)');
3991 $this->_out('/Ordering (UCS)');
3992 $this->_out('/Supplement 0');
3993 $this->_out('>> def');
3994 $this->_out('/CMapName /Adobe-Identity-UCS def');
3995 $this->_out('/CMapType 2 def');
3996 $this->_out('1 begincodespacerange');
3997 $this->_out('<0000> <FFFF>');
3998 $this->_out('endcodespacerange');
3999 $this->_out('1 beginbfrange');
4000 $this->_out('<0000> <FFFF> <0000>');
4001 $this->_out('endbfrange');
4002 $this->_out('endcmap');
4003 $this->_out('CMapName currentdict /CMap defineresource pop');
4004 $this->_out('end');
4005 $this->_out('end');
4006 $this->_out('endstream');
4007 $this->_out('endobj');
4009 // CIDSystemInfo dictionary
4010 // A dictionary containing entries that define the character collection of the CIDFont.
4011 $this->_newobj();
4012 $this->_out('<</Registry (Adobe)'); // A string identifying an issuer of character collections
4013 $this->_out('/Ordering (UCS)'); // A string that uniquely names a character collection issued by a specific registry
4014 $this->_out('/Supplement 0'); // The supplement number of the character collection.
4015 $this->_out('>>');
4016 $this->_out('endobj');
4018 // Font descriptor
4019 // A font descriptor describing the CIDFont default metrics other than its glyph widths
4020 $this->_newobj();
4021 $this->_out('<</Type /FontDescriptor');
4022 $this->_out('/FontName /'.$font['name']);
4023 foreach ($font['desc'] as $key => $value) {
4024 $this->_out('/'.$key.' '.$value);
4026 if ($font['file']) {
4027 // A stream containing a TrueType font program
4028 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
4030 $this->_out('>>');
4031 $this->_out('endobj');
4033 // Embed CIDToGIDMap
4034 // A specification of the mapping from CIDs to glyph indices
4035 $this->_newobj();
4036 $ctgfile = $this->_getfontpath().strtolower($font['ctg']);
4037 if(!file_exists($ctgfile)) {
4038 $this->Error('Font file not found: '.$ctgfile);
4040 $size = filesize($ctgfile);
4041 $this->_out('<</Length '.$size.'');
4042 if(substr($ctgfile, -2) == '.z') { // check file extension
4043 /* Decompresses data encoded using the public-domain
4044 zlib/deflate compression method, reproducing the
4045 original text or binary data */
4046 $this->_out('/Filter /FlateDecode');
4048 $this->_out('>>');
4049 $this->_putstream(file_get_contents($ctgfile));
4050 $this->_out('endobj');
4054 * Converts UTF-8 strings to codepoints array.<br>
4055 * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
4056 * Based on: http://www.faqs.org/rfcs/rfc3629.html
4057 * <pre>
4058 * Char. number range | UTF-8 octet sequence
4059 * (hexadecimal) | (binary)
4060 * --------------------+-----------------------------------------------
4061 * 0000 0000-0000 007F | 0xxxxxxx
4062 * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
4063 * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
4064 * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
4065 * ---------------------------------------------------------------------
4067 * ABFN notation:
4068 * ---------------------------------------------------------------------
4069 * UTF8-octets = *( UTF8-char )
4070 * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
4071 * UTF8-1 = %x00-7F
4072 * UTF8-2 = %xC2-DF UTF8-tail
4074 * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
4075 * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
4076 * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
4077 * %xF4 %x80-8F 2( UTF8-tail )
4078 * UTF8-tail = %x80-BF
4079 * ---------------------------------------------------------------------
4080 * </pre>
4081 * @param string $str string to process.
4082 * @return array containing codepoints (UTF-8 characters values)
4083 * @access protected
4084 * @author Nicola Asuni
4085 * @since 1.53.0.TC005 (2005-01-05)
4087 protected function UTF8StringToArray($str) {
4088 if(!$this->isunicode) {
4089 return $str; // string is not in unicode
4091 $unicode = array(); // array containing unicode values
4092 $bytes = array(); // array containing single character byte sequences
4093 $numbytes = 1; // number of octetc needed to represent the UTF-8 character
4095 $str .= ""; // force $str to be a string
4096 $length = strlen($str);
4098 for($i = 0; $i < $length; $i++) {
4099 $char = ord($str{$i}); // get one string character at time
4100 if(count($bytes) == 0) { // get starting octect
4101 if ($char <= 0x7F) {
4102 $unicode[] = $char; // use the character "as is" because is ASCII
4103 $numbytes = 1;
4104 } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
4105 $bytes[] = ($char - 0xC0) << 0x06;
4106 $numbytes = 2;
4107 } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
4108 $bytes[] = ($char - 0xE0) << 0x0C;
4109 $numbytes = 3;
4110 } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
4111 $bytes[] = ($char - 0xF0) << 0x12;
4112 $numbytes = 4;
4113 } else {
4114 // use replacement character for other invalid sequences
4115 $unicode[] = 0xFFFD;
4116 $bytes = array();
4117 $numbytes = 1;
4119 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
4120 $bytes[] = $char - 0x80;
4121 if (count($bytes) == $numbytes) {
4122 // compose UTF-8 bytes to a single unicode value
4123 $char = $bytes[0];
4124 for($j = 1; $j < $numbytes; $j++) {
4125 $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
4127 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
4128 /* The definition of UTF-8 prohibits encoding character numbers between
4129 U+D800 and U+DFFF, which are reserved for use with the UTF-16
4130 encoding form (as surrogate pairs) and do not directly represent
4131 characters. */
4132 $unicode[] = 0xFFFD; // use replacement character
4134 else {
4135 $unicode[] = $char; // add char to array
4137 // reset data for next char
4138 $bytes = array();
4139 $numbytes = 1;
4141 } else {
4142 // use replacement character for other invalid sequences
4143 $unicode[] = 0xFFFD;
4144 $bytes = array();
4145 $numbytes = 1;
4148 return $unicode;
4152 * Converts UTF-8 strings to UTF16-BE.<br>
4153 * @param string $str string to process.
4154 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
4155 * @return string
4156 * @access protected
4157 * @author Nicola Asuni
4158 * @since 1.53.0.TC005 (2005-01-05)
4159 * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
4161 protected function UTF8ToUTF16BE($str, $setbom=true) {
4162 if(!$this->isunicode) {
4163 return $str; // string is not in unicode
4165 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
4166 return $this->arrUTF8ToUTF16BE($unicode, $setbom);
4170 * Converts array of UTF-8 characters to UTF16-BE string.<br>
4171 * Based on: http://www.faqs.org/rfcs/rfc2781.html
4172 * <pre>
4173 * Encoding UTF-16:
4175 * Encoding of a single character from an ISO 10646 character value to
4176 * UTF-16 proceeds as follows. Let U be the character number, no greater
4177 * than 0x10FFFF.
4179 * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
4180 * terminate.
4182 * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
4183 * U' must be less than or equal to 0xFFFFF. That is, U' can be
4184 * represented in 20 bits.
4186 * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
4187 * 0xDC00, respectively. These integers each have 10 bits free to
4188 * encode the character value, for a total of 20 bits.
4190 * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
4191 * bits of W1 and the 10 low-order bits of U' to the 10 low-order
4192 * bits of W2. Terminate.
4194 * Graphically, steps 2 through 4 look like:
4195 * U' = yyyyyyyyyyxxxxxxxxxx
4196 * W1 = 110110yyyyyyyyyy
4197 * W2 = 110111xxxxxxxxxx
4198 * </pre>
4199 * @param array $unicode array containing UTF-8 unicode values
4200 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
4201 * @return string
4202 * @access protected
4203 * @author Nicola Asuni
4204 * @since 2.1.000 (2008-01-08)
4205 * @see UTF8ToUTF16BE()
4207 protected function arrUTF8ToUTF16BE($unicode, $setbom=true) {
4208 $outstr = ""; // string to be returned
4209 if ($setbom) {
4210 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
4212 foreach($unicode as $char) {
4213 if($char == 0xFFFD) {
4214 $outstr .= "\xFF\xFD"; // replacement character
4215 } elseif ($char < 0x10000) {
4216 $outstr .= chr($char >> 0x08);
4217 $outstr .= chr($char & 0xFF);
4218 } else {
4219 $char -= 0x10000;
4220 $w1 = 0xD800 | ($char >> 0x10);
4221 $w2 = 0xDC00 | ($char & 0x3FF);
4222 $outstr .= chr($w1 >> 0x08);
4223 $outstr .= chr($w1 & 0xFF);
4224 $outstr .= chr($w2 >> 0x08);
4225 $outstr .= chr($w2 & 0xFF);
4228 return $outstr;
4230 // ====================================================
4233 * Set header font.
4234 * @param array $font font
4235 * @since 1.1
4237 public function setHeaderFont($font) {
4238 $this->header_font = $font;
4242 * Set footer font.
4243 * @param array $font font
4244 * @since 1.1
4246 public function setFooterFont($font) {
4247 $this->footer_font = $font;
4251 * Set language array.
4252 * @param array $language
4253 * @since 1.1
4255 public function setLanguageArray($language) {
4256 $this->l = $language;
4257 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
4261 * Set document barcode.
4262 * @param string $bc barcode
4264 public function setBarcode($bc="") {
4265 $this->barcode = $bc;
4269 * Print Barcode.
4270 * @param int $x x position in user units
4271 * @param int $y y position in user units
4272 * @param int $w width in user units
4273 * @param int $h height position in user units
4274 * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
4275 * @param string $style barcode style
4276 * @param string $font font for text
4277 * @param int $xres x resolution
4278 * @param string $code code to print
4280 public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
4281 require_once(dirname(__FILE__)."/barcode/barcode.php");
4282 require_once(dirname(__FILE__)."/barcode/i25object.php");
4283 require_once(dirname(__FILE__)."/barcode/c39object.php");
4284 require_once(dirname(__FILE__)."/barcode/c128aobject.php");
4285 require_once(dirname(__FILE__)."/barcode/c128bobject.php");
4286 require_once(dirname(__FILE__)."/barcode/c128cobject.php");
4288 if (empty($code)) {
4289 return;
4292 if (empty($style)) {
4293 $style = BCS_ALIGN_LEFT;
4294 $style |= BCS_IMAGE_PNG;
4295 $style |= BCS_TRANSPARENT;
4296 //$style |= BCS_BORDER;
4297 //$style |= BCS_DRAW_TEXT;
4298 //$style |= BCS_STRETCH_TEXT;
4299 //$style |= BCS_REVERSE_COLOR;
4301 if (empty($font)) {$font = BCD_DEFAULT_FONT;}
4302 if (empty($xres)) {$xres = BCD_DEFAULT_XRES;}
4304 $scale_factor = 1.5 * $xres * $this->k;
4305 $bc_w = round($w * $scale_factor); //width in points
4306 $bc_h = round($h * $scale_factor); //height in points
4308 switch (strtoupper($type)) {
4309 case "I25": {
4310 $obj = new I25Object($bc_w, $bc_h, $style, $code);
4311 break;
4313 case "C128A": {
4314 $obj = new C128AObject($bc_w, $bc_h, $style, $code);
4315 break;
4317 default:
4318 case "C128B": {
4319 $obj = new C128BObject($bc_w, $bc_h, $style, $code);
4320 break;
4322 case "C128C": {
4323 $obj = new C128CObject($bc_w, $bc_h, $style, $code);
4324 break;
4326 case "C39": {
4327 $obj = new C39Object($bc_w, $bc_h, $style, $code);
4328 break;
4332 $obj->SetFont($font);
4333 $obj->DrawObject($xres);
4335 //use a temporary file....
4336 $tmpName = tempnam(K_PATH_CACHE,'img');
4337 imagepng($obj->getImage(), $tmpName);
4338 $this->Image($tmpName, $x, $y, $w, $h, 'png');
4339 $obj->DestroyObject();
4340 unset($obj);
4341 unlink($tmpName);
4345 * Returns the PDF data.
4347 public function getPDFData() {
4348 if($this->state < 3) {
4349 $this->Close();
4351 return $this->buffer;
4354 // --- HTML PARSER FUNCTIONS ---
4357 * Allows to preserve some HTML formatting.<br />
4358 * 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
4359 * @param string $html text to display
4360 * @param boolean $ln if true add a new line after text (default = true)
4361 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
4362 * @param boolean $reseth if true reset the last cell height (default false).
4363 * @param boolean $cell if true add the default cMargin space to each Write.
4365 public function writeHTML($html, $ln=true, $fill=0, $reseth=false, $cell=false) {
4367 // store some variables
4368 $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
4369 //replace carriage returns, newlines and tabs
4370 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
4371 $html = strtr($html, $repTable);
4372 $pattern = '/(<[^>]+>)/Uu';
4373 $a = preg_split($pattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); //explodes the string
4375 if ((empty($this->lasth))OR ($reseth)) {
4376 //set row height
4377 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4380 foreach($a as $key=>$element) {
4381 if (!preg_match($pattern, $element)) {
4382 //Text
4383 if($this->HREF) {
4384 $this->addHtmlLink($this->HREF, $element, $fill);
4385 } elseif($this->tdbegin) {
4386 if((strlen(trim($element)) > 0) AND ($element != "&nbsp;")) {
4387 $this->Cell($this->tdwidth, $this->tdheight, $this->unhtmlentities($element), $this->tableborder, '', $this->tdalign, $this->tdbgcolor);
4388 } elseif($element == "&nbsp;") {
4389 $this->Cell($this->tdwidth, $this->tdheight, '', $this->tableborder, '', $this->tdalign, $this->tdbgcolor);
4391 } else {
4393 $ctmpmargin = $this->cMargin;
4394 if(!$cell) {
4395 $this->cMargin = 0;
4397 $this->Write($this->lasth, stripslashes($this->unhtmlentities($element)), '', $fill, 0);
4398 $this->cMargin = $ctmpmargin;
4400 } else {
4401 $element = substr($element, 1, -1);
4402 //Tag
4403 if($element{0}=='/') {
4404 $this->closedHTMLTagHandler(strtolower(substr($element, 1)));
4406 else {
4407 //Extract attributes
4408 // get tag name
4409 preg_match('/([a-zA-Z0-9]*)/', $element, $tag);
4410 $tag = strtolower($tag[0]);
4411 // get attributes
4412 preg_match_all('/([^=\s]*)=["\']?([^"\']*)["\']?/', $element, $attr_array, PREG_PATTERN_ORDER);
4413 $attr = array(); // reset attribute array
4414 while(list($id,$name)=each($attr_array[1])) {
4415 $attr[strtolower($name)] = $attr_array[2][$id];
4417 $this->openHTMLTagHandler($tag, $attr, $fill);
4421 if ($ln) {
4422 $this->Ln($this->lasth);
4427 * 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 />
4428 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
4429 * @param float $w Cell width. If 0, the cell extends up to the right margin.
4430 * @param float $h Cell minimum height. The cell extends automatically if needed.
4431 * @param float $x upper-left corner X coordinate
4432 * @param float $y upper-left corner Y coordinate
4433 * @param string $html html text to print. Default value: empty string.
4434 * @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>
4435 * @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>
4436 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
4437 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
4438 * @param boolean $reseth if true reset the last cell height (default false).
4439 * @see Cell()
4441 public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=false) {
4443 if ((empty($this->lasth))OR ($reseth)) {
4444 //set row height
4445 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4448 // get current page number
4449 $startpage = $this->page;
4451 if (!empty($y)) {
4452 $this->SetY($y);
4453 } else {
4454 $y = $this->GetY();
4456 if (!empty($x)) {
4457 $this->SetX($x);
4458 } else {
4459 $x = $this->GetX();
4462 if(empty($w)) {
4463 if ($this->rtl) {
4464 $w = $this->x - $this->lMargin;
4465 } else {
4466 $w = $this->w - $this->rMargin - $this->x;
4470 // store original margin values
4471 $lMargin = $this->lMargin;
4472 $rMargin = $this->rMargin;
4474 // set new margin values
4475 if ($this->rtl) {
4476 $this->SetLeftMargin($this->x - $w);
4477 $this->SetRightMargin($this->w - $this->x);
4478 } else {
4479 $this->SetLeftMargin($this->x);
4480 $this->SetRightMargin($this->w - $this->x - $w);
4483 // calculate remaining vertical space on first page ($startpage)
4484 $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin();
4486 // Write HTML text
4487 $this->writeHTML($html, true, $fill, $reseth, true);
4489 // Get end-of-text Y position
4490 $currentY = $this->GetY();
4491 // get latest page number
4492 $endpage = $this->page;
4494 if (!empty($border)) {
4495 // check if a new page has been created
4496 if ($endpage > $startpage) {
4497 // design borders around HTML cells.
4498 for ($page=$startpage; $page<=$endpage; $page++) {
4499 $this->page = $page;
4500 if ($page==$startpage) {
4501 $this->SetY($this->getPageHeight() - $restspace - $this->getBreakMargin());
4502 $h = $restspace - 1;
4503 } elseif ($page==$endpage) {
4504 $this->SetY($this->tMargin); // put cursor at the beginning of text
4505 $h = $currentY - $this->tMargin;
4506 } else {
4507 $this->SetY($this->tMargin); // put cursor at the beginning of text
4508 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
4510 $this->Cell($w, $h, "", $border, 1, '', 0);
4512 } else {
4513 $h = max($h, ($currentY - $y));
4514 $this->SetY($y); // put cursor at the beginning of text
4515 // design a cell around the text
4516 $this->Cell($w, $h, "", $border, 1, '', 0);
4520 // restore original margin values
4521 $this->SetLeftMargin($lMargin);
4522 $this->SetRightMargin($rMargin);
4525 if($ln>0) {
4526 //Go to the beginning of the next line
4527 $this->SetY($currentY);
4528 if($ln == 2) {
4529 $this->SetX($x + $w);
4531 } else {
4532 // go left or right by case
4533 $this->page = $startpage;
4534 $this->y = $y;
4535 $this->SetX($x + $w);
4541 * Process opening tags.
4542 * @param string $tag tag name (in uppercase)
4543 * @param string $attr tag attribute (in uppercase)
4544 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
4545 * @access private
4547 private function openHTMLTagHandler($tag, $attr, $fill=0) {
4548 // check for text direction attribute
4549 if (isset($attr['dir'])) {
4550 $this->tmprtl = $attr['dir']=='rtl' ? 'R' : 'L';
4551 } else {
4552 $this->tmprtl = false;
4554 //Opening tag
4555 switch($tag) {
4556 case 'table': {
4557 if ((isset($attr['border'])) AND ($attr['border'] != '')) {
4558 $this->tableborder = $attr['border'];
4560 else {
4561 $this->tableborder = 0;
4563 break;
4565 case 'tr': {
4566 break;
4568 case 'td':
4569 case 'th': {
4570 if ((isset($attr['width'])) AND ($attr['width'] != '')) {
4571 $this->tdwidth = ($attr['width']/4);
4573 else {
4574 $this->tdwidth = (($this->w - $this->lMargin - $this->rMargin) / $this->default_table_columns);
4576 if ((isset($attr['height'])) AND ($attr['height'] != '')) {
4577 $this->tdheight=($attr['height'] / $this->k);
4579 else {
4580 $this->tdheight = $this->lasth;
4582 if ((isset($attr['align'])) AND ($attr['align'] != '')) {
4583 switch ($attr['align']) {
4584 case 'center': {
4585 $this->tdalign = "C";
4586 break;
4588 case 'right': {
4589 $this->tdalign = "R";
4590 break;
4592 default:
4593 case 'left': {
4594 $this->tdalign = "L";
4595 break;
4598 } else {
4599 if($this->rtl) {
4600 $this->tdalign = "R";
4601 } else {
4602 $this->tdalign = "L";
4605 if ((isset($attr['bgcolor'])) AND ($attr['bgcolor'] != '')) {
4606 $coul = $this->convertColorHexToDec($attr['bgcolor']);
4607 $this->SetFillColor($coul['R'], $coul['G'], $coul['B']);
4608 $this->tdbgcolor=true;
4610 $this->tdbegin=true;
4611 break;
4613 case 'hr': {
4614 $this->Ln();
4615 if ((isset($attr['width'])) AND ($attr['width'] != '')) {
4616 $hrWidth = $attr['width'];
4618 else {
4619 $hrWidth = $this->w - $this->lMargin - $this->rMargin;
4621 $x = $this->GetX();
4622 $y = $this->GetY();
4623 $this->GetLineWidth();
4624 $prevlinewidth = $this->SetLineWidth(0.2);
4625 $this->Line($x, $y, $x + $hrWidth, $y);
4626 $this->SetLineWidth($prevlinewidth);
4627 $this->Ln();
4628 break;
4630 case 'strong': {
4631 $this->setStyle('b', true);
4632 break;
4634 case 'em': {
4635 $this->setStyle('i', true);
4636 break;
4638 case 'b':
4639 case 'i':
4640 case 'u': {
4641 $this->setStyle($tag, true);
4642 break;
4644 case 'a': {
4645 $this->HREF = $attr['href'];
4646 break;
4648 case 'img': {
4649 if(isset($attr['src'])) {
4650 // replace relative path with real server path
4651 if ($attr['src'][0] == '/') {
4652 $attr['src'] = $_SERVER['DOCUMENT_ROOT'].$attr['src'];
4654 $attr['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $attr['src']);
4655 if(!isset($attr['width'])) {
4656 $attr['width'] = 0;
4658 if(!isset($attr['height'])) {
4659 $attr['height'] = 0;
4661 if(!isset($attr['align'])) {
4662 $align = 'N';
4663 } else {
4664 switch($attr['align']) {
4665 case 'top':{
4666 $align = 'T';
4667 break;
4669 case 'middle':{
4670 $align = 'M';
4671 break;
4673 case 'bottom':{
4674 $align = 'B';
4675 break;
4677 default:{
4678 $align = 'N';
4679 break;
4683 $this->Image($attr['src'], $this->GetX(),$this->GetY(), $this->pixelsToMillimeters($attr['width']), $this->pixelsToMillimeters($attr['height']), '', '', $align);
4686 break;
4688 case 'ul': {
4689 $this->listordered = false;
4690 $this->listcount = 0;
4691 break;
4693 case 'ol': {
4694 $this->listordered = true;
4695 $this->listcount = 0;
4696 break;
4698 case 'li': {
4699 $this->Ln();
4700 if ($this->listordered) {
4701 if (isset($attr['value'])) {
4702 $this->listcount = intval($attr['value']);
4704 $this->lispacer = " ".(++$this->listcount).". ";
4705 } else {
4706 //unordered list simbol
4707 $this->lispacer = " - ";
4709 $rtldir = $this->tmprtl;
4710 $this->tmprtl = false;
4711 $this->Write($this->lasth, $this->lispacer, '', $fill);
4712 $this->tmprtl = $rtldir;
4713 break;
4715 case 'blockquote':
4716 case 'br': {
4717 $this->Ln();
4718 if(strlen($this->lispacer) > 0) {
4719 if ($this->rtl) {
4720 $this->x -= $this->GetStringWidth($this->lispacer);
4721 } else {
4722 $this->x += $this->GetStringWidth($this->lispacer);
4725 break;
4727 case 'p': {
4728 $this->Ln();
4729 $this->Ln();
4730 break;
4732 case 'sup': {
4733 $currentFontSize = $this->FontSize;
4734 $this->tempfontsize = $this->FontSizePt;
4735 $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO);
4736 $this->SetXY($this->GetX(), $this->GetY() - (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4737 break;
4739 case 'sub': {
4740 $currentFontSize = $this->FontSize;
4741 $this->tempfontsize = $this->FontSizePt;
4742 $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO);
4743 $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4744 break;
4746 case 'small': {
4747 $currentFontSize = $this->FontSize;
4748 $this->tempfontsize = $this->FontSizePt;
4749 $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO);
4750 $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)/3));
4751 break;
4753 case 'font': {
4754 if (isset($attr['color']) AND $attr['color']!='') {
4755 $coul = $this->convertColorHexToDec($attr['color']);
4756 $this->SetTextColor($coul['R'],$coul['G'],$coul['B']);
4757 $this->issetcolor=true;
4759 if (isset($attr['face']) and in_array(strtolower($attr['face']), $this->fontlist)) {
4760 $this->SetFont(strtolower($attr['face']));
4761 $this->issetfont=true;
4763 if (isset($attr['size'])) {
4764 $headsize = intval($attr['size']);
4765 } else {
4766 $headsize = 0;
4768 $currentFontSize = $this->FontSize;
4769 $this->tempfontsize = $this->FontSizePt;
4770 $this->SetFontSize($this->FontSizePt + $headsize);
4771 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4772 break;
4774 case 'h1':
4775 case 'h2':
4776 case 'h3':
4777 case 'h4':
4778 case 'h5':
4779 case 'h6': {
4780 $headsize = (4 - substr($tag, 1)) * 2;
4781 $currentFontSize = $this->FontSize;
4782 $this->tempfontsize = $this->FontSizePt;
4783 $this->SetFontSize($this->FontSizePt + $headsize);
4784 $this->setStyle('b', true);
4785 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4786 break;
4792 * Process closing tags.
4793 * @param string $tag tag name (in uppercase)
4794 * @access private
4796 private function closedHTMLTagHandler($tag) {
4797 //Closing tag
4798 switch($tag) {
4799 case 'td':
4800 case 'th': {
4801 $this->tdbegin = false;
4802 $this->tdwidth = 0;
4803 $this->tdheight = 0;
4804 if($this->rtl) {
4805 $this->tdalign = "R";
4806 } else {
4807 $this->tdalign = "L";
4809 $this->tdbgcolor = false;
4810 $this->SetFillColor($this->prevFillColor[0], $this->prevFillColor[1], $this->prevFillColor[2]);
4811 break;
4813 case 'tr': {
4814 $this->Ln();
4815 break;
4817 case 'table': {
4818 $this->tableborder=0;
4819 break;
4821 case 'strong': {
4822 $this->setStyle('b', false);
4823 break;
4825 case 'em': {
4826 $this->setStyle('i', false);
4827 break;
4829 case 'b':
4830 case 'i':
4831 case 'u': {
4832 $this->setStyle($tag, false);
4833 break;
4835 case 'a': {
4836 $this->HREF = '';
4837 break;
4839 case 'sup': {
4840 $currentFontSize = $this->FontSize;
4841 $this->SetFontSize($this->tempfontsize);
4842 $this->tempfontsize = $this->FontSizePt;
4843 $this->SetXY($this->GetX(), $this->GetY() - (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4844 break;
4846 case 'sub': {
4847 $currentFontSize = $this->FontSize;
4848 $this->SetFontSize($this->tempfontsize);
4849 $this->tempfontsize = $this->FontSizePt;
4850 $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO)));
4851 break;
4853 case 'small': {
4854 $currentFontSize = $this->FontSize;
4855 $this->SetFontSize($this->tempfontsize);
4856 $this->tempfontsize = $this->FontSizePt;
4857 $this->SetXY($this->GetX(), $this->GetY() - (($this->FontSize - $currentFontSize)/3));
4858 break;
4860 case 'font': {
4861 if ($this->issetcolor == true) {
4862 $this->SetTextColor($this->prevTextColor[0], $this->prevTextColor[1], $this->prevTextColor[2]);
4864 if ($this->issetfont) {
4865 $this->FontFamily = $this->prevFontFamily;
4866 $this->FontStyle = $this->prevFontStyle;
4867 $this->SetFont($this->FontFamily);
4868 $this->issetfont = false;
4870 $currentFontSize = $this->FontSize;
4871 $this->SetFontSize($this->tempfontsize);
4872 $this->tempfontsize = $this->FontSizePt;
4873 //$this->TextColor = $this->prevTextColor;
4874 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4875 break;
4877 case 'p': {
4878 $this->Ln();
4879 $this->Ln();
4880 break;
4882 case 'ul':
4883 case 'ol': {
4884 $this->Ln();
4885 $this->Ln();
4886 break;
4888 case 'li': {
4889 $this->lispacer = "";
4890 break;
4892 case 'h1':
4893 case 'h2':
4894 case 'h3':
4895 case 'h4':
4896 case 'h5':
4897 case 'h6': {
4898 $currentFontSize = $this->FontSize;
4899 $this->SetFontSize($this->tempfontsize);
4900 $this->tempfontsize = $this->FontSizePt;
4901 $this->setStyle('b', false);
4902 $this->Ln();
4903 $this->lasth = $this->FontSize * K_CELL_HEIGHT_RATIO;
4904 break;
4906 default : {
4907 break;
4910 $this->tmprtl = false;
4914 * Sets font style.
4915 * @param string $tag tag name (in lowercase)
4916 * @param boolean $enable
4917 * @access private
4919 private function setStyle($tag, $enable) {
4920 //Modify style and select corresponding font
4921 $this->$tag += ($enable ? 1 : -1);
4922 $style='';
4923 foreach(array('b', 'i', 'u') as $s) {
4924 if($this->$s > 0) {
4925 $style .= $s;
4928 $this->SetFont('', $style);
4932 * Output anchor link.
4933 * @param string $url link URL
4934 * @param string $name link name
4935 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
4936 * @access public
4938 public function addHtmlLink($url, $name, $fill=0) {
4939 //Put a hyperlink
4940 $this->SetTextColor(0, 0, 255);
4941 $this->setStyle('u', true);
4942 $this->Write($this->lasth, $name, $url, $fill);
4943 $this->setStyle('u', false);
4944 $this->SetTextColor(0);
4948 * Returns an associative array (keys: R,G,B) from
4949 * a hex html code (e.g. #3FE5AA).
4950 * @param string $color hexadecimal html color [#rrggbb]
4951 * @return array
4952 * @access private
4954 private function convertColorHexToDec($color = "#000000"){
4955 $tbl_color = array();
4956 $tbl_color['R'] = hexdec(substr($color, 1, 2));
4957 $tbl_color['G'] = hexdec(substr($color, 3, 2));
4958 $tbl_color['B'] = hexdec(substr($color, 5, 2));
4959 return $tbl_color;
4963 * Converts pixels to millimeters in 72 dpi.
4964 * @param int $px pixels
4965 * @return float millimeters
4966 * @access private
4968 private function pixelsToMillimeters($px){
4969 return $px * 25.4 / 72;
4973 * Reverse function for htmlentities.
4974 * Convert entities in UTF-8.
4976 * @param $text_to_convert Text to convert.
4977 * @return string converted
4979 public function unhtmlentities($text_to_convert) {
4980 return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
4983 // ENCRYPTION METHODS ----------------------------------
4984 // SINCE 2.0.000 (2008-01-02)
4986 * Compute encryption key depending on object number where the encrypted data is stored
4987 * @param int $n object number
4988 * @since 2.0.000 (2008-01-02)
4990 protected function _objectkey($n) {
4991 return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);
4995 * Put encryption on PDF document
4996 * @since 2.0.000 (2008-01-02)
4998 protected function _putencryption() {
4999 $this->_out('/Filter /Standard');
5000 $this->_out('/V 1');
5001 $this->_out('/R 2');
5002 $this->_out('/O ('.$this->_escape($this->Ovalue).')');
5003 $this->_out('/U ('.$this->_escape($this->Uvalue).')');
5004 $this->_out('/P '.$this->Pvalue);
5008 * Returns the input text exrypted using RC4 algorithm and the specified key.
5009 * RC4 is the standard encryption algorithm used in PDF format
5010 * @param string $key encryption key
5011 * @param String $text input text to be encrypted
5012 * @return String encrypted text
5013 * @since 2.0.000 (2008-01-02)
5014 * @author Klemen Vodopivec
5016 protected function _RC4($key, $text) {
5017 if ($this->last_rc4_key != $key) {
5018 $k = str_repeat($key, 256/strlen($key)+1);
5019 $rc4 = range(0,255);
5020 $j = 0;
5021 for ($i=0; $i<256; $i++) {
5022 $t = $rc4[$i];
5023 $j = ($j + $t + ord($k{$i})) % 256;
5024 $rc4[$i] = $rc4[$j];
5025 $rc4[$j] = $t;
5027 $this->last_rc4_key = $key;
5028 $this->last_rc4_key_c = $rc4;
5029 } else {
5030 $rc4 = $this->last_rc4_key_c;
5032 $len = strlen($text);
5033 $a = 0;
5034 $b = 0;
5035 $out = '';
5036 for ($i=0; $i<$len; $i++) {
5037 $a = ($a+1)%256;
5038 $t= $rc4[$a];
5039 $b = ($b+$t)%256;
5040 $rc4[$a] = $rc4[$b];
5041 $rc4[$b] = $t;
5042 $k = $rc4[($rc4[$a]+$rc4[$b])%256];
5043 $out.=chr(ord($text{$i}) ^ $k);
5045 return $out;
5049 * Encrypts a string using MD5 and returns it's value as a binary string.
5050 * @param string $str input string
5051 * @return String MD5 encrypted binary string
5052 * @since 2.0.000 (2008-01-02)
5053 * @author Klemen Vodopivec
5055 protected function _md5_16($str) {
5056 return pack('H*',md5($str));
5060 * Compute O value (used for RC4 encryption)
5061 * @param String $user_pass user password
5062 * @param String $owner_pass user password
5063 * @return String O value
5064 * @since 2.0.000 (2008-01-02)
5065 * @author Klemen Vodopivec
5067 protected function _Ovalue($user_pass, $owner_pass) {
5068 $tmp = $this->_md5_16($owner_pass);
5069 $owner_RC4_key = substr($tmp,0,5);
5070 return $this->_RC4($owner_RC4_key, $user_pass);
5074 * Compute U value (used for RC4 encryption)
5075 * @return String U value
5076 * @since 2.0.000 (2008-01-02)
5077 * @author Klemen Vodopivec
5079 protected function _Uvalue() {
5080 return $this->_RC4($this->encryption_key, $this->padding);
5084 * Compute encryption key
5085 * @param String $user_pass user password
5086 * @param String $owner_pass user password
5087 * @param String $protection protection type
5088 * @since 2.0.000 (2008-01-02)
5089 * @author Klemen Vodopivec
5091 protected function _generateencryptionkey($user_pass, $owner_pass, $protection) {
5092 // Pad passwords
5093 $user_pass = substr($user_pass.$this->padding,0,32);
5094 $owner_pass = substr($owner_pass.$this->padding,0,32);
5095 // Compute O value
5096 $this->Ovalue = $this->_Ovalue($user_pass,$owner_pass);
5097 // Compute encyption key
5098 $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
5099 $this->encryption_key = substr($tmp,0,5);
5100 // Compute U value
5101 $this->Uvalue = $this->_Uvalue();
5102 // Compute P value
5103 $this->Pvalue = -(($protection^255)+1);
5107 * Set document protection
5108 * The permission array is composed of values taken from the following ones:
5109 * - copy: copy text and images to the clipboard
5110 * - print: print the document
5111 * - modify: modify it (except for annotations and forms)
5112 * - annot-forms: add annotations and forms
5113 * Remark: the protection against modification is for people who have the full Acrobat product.
5114 * 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.
5115 * 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.
5116 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
5117 * @param String $user_pass user password. Empty by default.
5118 * @param String $owner_pass owner password. If not specified, a random value is used.
5119 * @since 2.0.000 (2008-01-02)
5120 * @author Klemen Vodopivec
5122 public function SetProtection($permissions=array(),$user_pass='',$owner_pass=null) {
5123 $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
5124 $protection = 192;
5125 foreach($permissions as $permission) {
5126 if (!isset($options[$permission])) {
5127 $this->Error('Incorrect permission: '.$permission);
5129 $protection += $options[$permission];
5131 if ($owner_pass === null) {
5132 $owner_pass = uniqid(rand());
5134 $this->encrypted = true;
5135 $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
5138 // END OF ENCRYPTION FUNCTIONS -------------------------
5140 // START TRANSFORMATIONS SECTION -----------------------
5141 // authors: Moritz Wagner, Andreas Wurmser, Nicola Asuni
5144 * Starts a 2D tranformation saving current graphic state.
5145 * This function must be called before scaling, mirroring, translation, rotation and skewing.
5146 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5147 * @since 2.1.000 (2008-01-07)
5148 * @see StartTransform(), StopTransform()
5150 public function StartTransform() {
5151 $this->_out('q');
5155 * Stops a 2D tranformation restoring previous graphic state.
5156 * This function must be called after scaling, mirroring, translation, rotation and skewing.
5157 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5158 * @since 2.1.000 (2008-01-07)
5159 * @see StartTransform(), StopTransform()
5161 public function StopTransform() {
5162 $this->_out('Q');
5165 * Horizontal Scaling.
5166 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5167 * @param int $x abscissa of the scaling center. Default is current x position
5168 * @param int $y ordinate of the scaling center. Default is current y position
5169 * @since 2.1.000 (2008-01-07)
5170 * @see StartTransform(), StopTransform()
5172 public function ScaleX($s_x, $x='', $y=''){
5173 $this->Scale($s_x, 100, $x, $y);
5177 * Vertical Scaling.
5178 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5179 * @param int $x abscissa of the scaling center. Default is current x position
5180 * @param int $y ordinate of the scaling center. Default is current y position
5181 * @since 2.1.000 (2008-01-07)
5182 * @see StartTransform(), StopTransform()
5184 public function ScaleY($s_y, $x='', $y=''){
5185 $this->Scale(100, $s_y, $x, $y);
5189 * Vertical and horizontal proportional Scaling.
5190 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
5191 * @param int $x abscissa of the scaling center. Default is current x position
5192 * @param int $y ordinate of the scaling center. Default is current y position
5193 * @since 2.1.000 (2008-01-07)
5194 * @see StartTransform(), StopTransform()
5196 public function ScaleXY($s, $x='', $y=''){
5197 $this->Scale($s, $s, $x, $y);
5201 * Vertical and horizontal non-proportional Scaling.
5202 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5203 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5204 * @param int $x abscissa of the scaling center. Default is current x position
5205 * @param int $y ordinate of the scaling center. Default is current y position
5206 * @since 2.1.000 (2008-01-07)
5207 * @see StartTransform(), StopTransform()
5209 public function Scale($s_x, $s_y, $x='', $y=''){
5210 if($x === '') {
5211 $x=$this->x;
5213 if($y === '') {
5214 $y=$this->y;
5216 if($this->rtl) {
5217 $x = $this->w - $x;
5219 if($s_x == 0 OR $s_y == 0)
5220 $this->Error('Please use values unequal to zero for Scaling');
5221 $y=($this->h-$y)*$this->k;
5222 $x*=$this->k;
5223 //calculate elements of transformation matrix
5224 $s_x/=100;
5225 $s_y/=100;
5226 $tm[0]=$s_x;
5227 $tm[1]=0;
5228 $tm[2]=0;
5229 $tm[3]=$s_y;
5230 $tm[4]=$x*(1-$s_x);
5231 $tm[5]=$y*(1-$s_y);
5232 //scale the coordinate system
5233 $this->Transform($tm);
5237 * Horizontal Mirroring.
5238 * @param int $x abscissa of the point. Default is current x position
5239 * @since 2.1.000 (2008-01-07)
5240 * @see StartTransform(), StopTransform()
5242 public function MirrorH($x=''){
5243 $this->Scale(-100, 100, $x);
5247 * Verical Mirroring.
5248 * @param int $y ordinate of the point. Default is current y position
5249 * @since 2.1.000 (2008-01-07)
5250 * @see StartTransform(), StopTransform()
5252 public function MirrorV($y=''){
5253 $this->Scale(100, -100, '', $y);
5257 * Point reflection mirroring.
5258 * @param int $x abscissa of the point. Default is current x position
5259 * @param int $y ordinate of the point. Default is current y position
5260 * @since 2.1.000 (2008-01-07)
5261 * @see StartTransform(), StopTransform()
5263 public function MirrorP($x='',$y=''){
5264 $this->Scale(-100, -100, $x, $y);
5268 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
5269 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
5270 * @param int $x abscissa of the point. Default is current x position
5271 * @param int $y ordinate of the point. Default is current y position
5272 * @since 2.1.000 (2008-01-07)
5273 * @see StartTransform(), StopTransform()
5275 public function MirrorL($angle=0, $x='',$y=''){
5276 $this->Scale(-100, 100, $x, $y);
5277 $this->Rotate(-2*($angle-90),$x,$y);
5281 * Translate graphic object horizontally.
5282 * @param int $t_x movement to the right
5283 * @since 2.1.000 (2008-01-07)
5284 * @see StartTransform(), StopTransform()
5286 public function TranslateX($t_x){
5287 $this->Translate($t_x, 0);
5291 * Translate graphic object vertically.
5292 * @param int $t_y movement to the bottom
5293 * @since 2.1.000 (2008-01-07)
5294 * @see StartTransform(), StopTransform()
5296 public function TranslateY($t_y){
5297 $this->Translate(0, $t_y, $x, $y);
5301 * Translate graphic object horizontally and vertically.
5302 * @param int $t_x movement to the right
5303 * @param int $t_y movement to the bottom
5304 * @since 2.1.000 (2008-01-07)
5305 * @see StartTransform(), StopTransform()
5307 public function Translate($t_x, $t_y){
5308 if($this->rtl) {
5309 $t_x = -$t_x;
5311 //calculate elements of transformation matrix
5312 $tm[0]=1;
5313 $tm[1]=0;
5314 $tm[2]=0;
5315 $tm[3]=1;
5316 $tm[4]=$t_x*$this->k;
5317 $tm[5]=-$t_y*$this->k;
5318 //translate the coordinate system
5319 $this->Transform($tm);
5323 * Rotate object.
5324 * @param float $angle angle in degrees for counter-clockwise rotation
5325 * @param int $x abscissa of the rotation center. Default is current x position
5326 * @param int $y ordinate of the rotation center. Default is current y position
5327 * @since 2.1.000 (2008-01-07)
5328 * @see StartTransform(), StopTransform()
5330 public function Rotate($angle, $x='', $y=''){
5331 if($x === '') {
5332 $x=$this->x;
5334 if($y === '') {
5335 $y=$this->y;
5337 if($this->rtl) {
5338 $x = $this->w - $x;
5339 $angle = -$angle;
5341 $y=($this->h-$y)*$this->k;
5342 $x*=$this->k;
5343 //calculate elements of transformation matrix
5344 $tm[0]=cos(deg2rad($angle));
5345 $tm[1]=sin(deg2rad($angle));
5346 $tm[2]=-$tm[1];
5347 $tm[3]=$tm[0];
5348 $tm[4]=$x+$tm[1]*$y-$tm[0]*$x;
5349 $tm[5]=$y-$tm[0]*$y-$tm[1]*$x;
5350 //rotate the coordinate system around ($x,$y)
5351 $this->Transform($tm);
5355 * Skew horizontally.
5356 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
5357 * @param int $x abscissa of the skewing center. default is current x position
5358 * @param int $y ordinate of the skewing center. default is current y position
5359 * @since 2.1.000 (2008-01-07)
5360 * @see StartTransform(), StopTransform()
5362 public function SkewX($angle_x, $x='', $y=''){
5363 $this->Skew($angle_x, 0, $x, $y);
5367 * Skew vertically.
5368 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
5369 * @param int $x abscissa of the skewing center. default is current x position
5370 * @param int $y ordinate of the skewing center. default is current y position
5371 * @since 2.1.000 (2008-01-07)
5372 * @see StartTransform(), StopTransform()
5374 public function SkewY($angle_y, $x='', $y=''){
5375 $this->Skew(0, $angle_y, $x, $y);
5379 * Skew.
5380 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
5381 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
5382 * @param int $x abscissa of the skewing center. default is current x position
5383 * @param int $y ordinate of the skewing center. default is current y position
5384 * @since 2.1.000 (2008-01-07)
5385 * @see StartTransform(), StopTransform()
5387 public function Skew($angle_x, $angle_y, $x='', $y=''){
5388 if($x === '') {
5389 $x=$this->x;
5391 if($y === '') {
5392 $y=$this->y;
5394 if($this->rtl) {
5395 $x = $this->w - $x;
5396 $angle_x = -$angle_x;
5398 if($angle_x <= -90 OR $angle_x >= 90 OR $angle_y <= -90 OR $angle_y >= 90)
5399 $this->Error('Please use values between -90� and 90� for skewing');
5400 $x*=$this->k;
5401 $y=($this->h-$y)*$this->k;
5402 //calculate elements of transformation matrix
5403 $tm[0]=1;
5404 $tm[1]=tan(deg2rad($angle_y));
5405 $tm[2]=tan(deg2rad($angle_x));
5406 $tm[3]=1;
5407 $tm[4]=-$tm[2]*$y;
5408 $tm[5]=-$tm[1]*$x;
5409 //skew the coordinate system
5410 $this->Transform($tm);
5414 * Apply graphic transformations.
5415 * @since 2.1.000 (2008-01-07)
5416 * @see StartTransform(), StopTransform()
5418 protected function Transform($tm){
5419 $this->_out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', $tm[0],$tm[1],$tm[2],$tm[3],$tm[4],$tm[5]));
5422 // END TRANSFORMATIONS SECTION -------------------------
5425 // START GRAPHIC FUNCTIONS SECTION ---------------------
5426 // The following section is based on the code provided by David Hernandez Sanz
5429 * 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.
5430 * @param float $width The width.
5431 * @since 1.0
5432 * @see Line(), Rect(), Cell(), MultiCell()
5434 public function SetLineWidth($width) {
5435 //Set line width
5436 $this->LineWidth=$width;
5437 if($this->page>0) {
5438 $this->_out(sprintf('%.2f w',$width*$this->k));
5443 * Returns the current the line width.
5444 * @return int Line width
5445 * @since 2.1.000 (2008-01-07)
5446 * @see Line(), SetLineWidth()
5448 public function GetLineWidth() {
5449 return $this->LineWidth;
5453 * Set line style.
5455 * @param array $style Line style. Array with keys among the following:
5456 * <ul>
5457 * <li>width (float): Width of the line in user units.</li>
5458 * <li>cap (string): Type of cap to put on the line. Possible values are:
5459 * butt, round, square. The difference between "square" and "butt" is that
5460 * "square" projects a flat end past the end of the line.</li>
5461 * <li>join (string): Type of join. Possible values are: miter, round,
5462 * bevel.</li>
5463 * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
5464 * series of length values, which are the lengths of the on and off dashes.
5465 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
5466 * 1 off, 2 on, 1 off, ...</li>
5467 * <li>phase (integer): Modifier on the dash pattern which is used to shift
5468 * the point at which the pattern starts.</li>
5469 * <li>color (array): Draw color. Format: array(red, green, blue).</li>
5470 * </ul>
5471 * @access public
5472 * @since 2.1.000 (2008-01-08)
5474 public function SetLineStyle($style) {
5475 extract($style);
5476 if (isset($width)) {
5477 $width_prev = $this->LineWidth;
5478 $this->SetLineWidth($width);
5479 $this->LineWidth = $width_prev;
5481 if (isset($cap)) {
5482 $ca = array("butt" => 0, "round"=> 1, "square" => 2);
5483 if (isset($ca[$cap])) {
5484 $this->_out($ca[$cap] . " J");
5487 if (isset($join)) {
5488 $ja = array("miter" => 0, "round" => 1, "bevel" => 2);
5489 if (isset($ja[$join])) {
5490 $this->_out($ja[$join] . " j");
5493 if (isset($dash)) {
5494 $dash_string = "";
5495 if ($dash) {
5496 // phpMyAdmin change
5497 if (preg_match("/^.+,/", $dash)) {
5498 $tab = explode(",", $dash);
5499 } else {
5500 $tab = array($dash);
5502 $dash_string = "";
5503 foreach ($tab as $i => $v) {
5504 if ($i) {
5505 $dash_string .= " ";
5507 $dash_string .= sprintf("%.2f", $v);
5510 if (!isset($phase) OR !$dash) {
5511 $phase = 0;
5513 $this->_out(sprintf("[%s] %.2f d", $dash_string, $phase));
5515 if (isset($color)) {
5516 list($r, $g, $b) = $color;
5517 $this->SetDrawColor($r, $g, $b);
5522 * Set a draw point.
5523 * @param float $x Abscissa of point.
5524 * @param float $y Ordinate of point.
5525 * @access private
5526 * @since 2.1.000 (2008-01-08)
5528 protected function _outPoint($x, $y) {
5529 if($this->rtl) {
5530 $x = $this->w - $x;
5532 $this->_out(sprintf("%.2f %.2f m", $x * $this->k, ($this->h - $y) * $this->k));
5536 * Draws a line from last draw point.
5537 * @param float $x Abscissa of end point.
5538 * @param float $y Ordinate of end point.
5539 * @access private
5540 * @since 2.1.000 (2008-01-08)
5542 protected function _outLine($x, $y) {
5543 if($this->rtl) {
5544 $x = $this->w - $x;
5546 $this->_out(sprintf("%.2f %.2f l", $x * $this->k, ($this->h - $y) * $this->k));
5550 * Draws a rectangle.
5551 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
5552 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
5553 * @param float $w Width.
5554 * @param float $h Height.
5555 * @param string $op options
5556 * @access protected
5557 * @since 2.1.000 (2008-01-08)
5559 protected function _outRect($x, $y, $w, $h, $op) {
5560 if($this->rtl) {
5561 $x = $this->w - $x - $w;
5563 $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op));
5567 * Draws a Bezier curve from last draw point.
5568 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
5569 * @param float $x1 Abscissa of control point 1.
5570 * @param float $y1 Ordinate of control point 1.
5571 * @param float $x2 Abscissa of control point 2.
5572 * @param float $y2 Ordinate of control point 2.
5573 * @param float $x3 Abscissa of end point.
5574 * @param float $y3 Ordinate of end point.
5575 * @access private
5576 * @since 2.1.000 (2008-01-08)
5578 protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
5579 if($this->rtl) {
5580 $x1 = $this->w - $x1;
5581 $x2 = $this->w - $x2;
5582 $x3 = $this->w - $x3;
5584 $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));
5588 * Draws a line between two points.
5589 * @param float $x1 Abscissa of first point.
5590 * @param float $y1 Ordinate of first point.
5591 * @param float $x2 Abscissa of second point.
5592 * @param float $y2 Ordinate of second point.
5593 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5594 * @access public
5595 * @since 1.0
5596 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
5598 public function Line($x1, $y1, $x2, $y2, $style = array()) {
5599 if ($style) {
5600 $this->SetLineStyle($style);
5602 $this->_outPoint($x1, $y1);
5603 $this->_outLine($x2, $y2);
5604 $this->_out(" S");
5608 * Draws a rectangle.
5609 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
5610 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
5611 * @param float $w Width.
5612 * @param float $h Height.
5613 * @param string $style Style of rendering. Possible values are:
5614 * <ul>
5615 * <li>D or empty string: Draw (default).</li>
5616 * <li>F: Fill.</li>
5617 * <li>DF or FD: Draw and fill.</li>
5618 * </ul>
5619 * @param array $border_style Border style of rectangle. Array with keys among the following:
5620 * <ul>
5621 * <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
5622 * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
5623 * </ul>
5624 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
5625 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5626 * @access public
5627 * @since 1.0
5628 * @see SetLineStyle()
5630 public function Rect($x, $y, $w, $h, $style='', $border_style = array(), $fill_color = array()) {
5631 if (!(false === strpos($style, "F")) AND $fill_color) {
5632 list($r, $g, $b) = $fill_color;
5633 $this->SetFillColor($r, $g, $b);
5635 switch ($style) {
5636 case "F": {
5637 $op='f';
5638 $border_style = array();
5639 $this->_outRect($x, $y, $w, $h, $op);
5640 break;
5642 case "DF":
5643 case "FD": {
5644 if (!$border_style OR isset($border_style["all"])) {
5645 $op='B';
5646 if (isset($border_style["all"])) {
5647 $this->SetLineStyle($border_style["all"]);
5648 $border_style = array();
5650 } else {
5651 $op='f';
5653 $this->_outRect($x, $y, $w, $h, $op);
5654 break;
5656 default: {
5657 $op='S';
5658 if (!$border_style OR isset($border_style["all"])) {
5659 if (isset($border_style["all"]) && $border_style["all"]) {
5660 $this->SetLineStyle($border_style["all"]);
5661 $border_style = array();
5663 $this->_outRect($x, $y, $w, $h, $op);
5665 break;
5668 if ($border_style) {
5669 $border_style2 = array();
5670 foreach ($border_style as $line => $value) {
5671 $lenght = strlen($line);
5672 for ($i = 0; $i < $lenght; $i++) {
5673 $border_style2[$line[$i]] = $value;
5676 $border_style = $border_style2;
5677 if (isset($border_style["L"]) && $border_style["L"]) {
5678 $this->Line($x, $y, $x, $y + $h, $border_style["L"]);
5680 if (isset($border_style["T"]) && $border_style["T"]) {
5681 $this->Line($x, $y, $x + $w, $y, $border_style["T"]);
5683 if (isset($border_style["R"]) && $border_style["R"]) {
5684 $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style["R"]);
5686 if (isset($border_style["B"]) && $border_style["B"]) {
5687 $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style["B"]);
5694 * Draws a Bezier curve.
5695 * The Bezier curve is a tangent to the line between the control points at
5696 * either end of the curve.
5697 * @param float $x0 Abscissa of start point.
5698 * @param float $y0 Ordinate of start point.
5699 * @param float $x1 Abscissa of control point 1.
5700 * @param float $y1 Ordinate of control point 1.
5701 * @param float $x2 Abscissa of control point 2.
5702 * @param float $y2 Ordinate of control point 2.
5703 * @param float $x3 Abscissa of end point.
5704 * @param float $y3 Ordinate of end point.
5705 * @param string $style Style of rendering. Possible values are:
5706 * <ul>
5707 * <li>D or empty string: Draw (default).</li>
5708 * <li>F: Fill.</li>
5709 * <li>DF or FD: Draw and fill.</li>
5710 * </ul>
5711 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5712 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5713 * @access public
5714 * @see SetLineStyle()
5715 * @since 2.1.000 (2008-01-08)
5717 public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style = "", $line_style = array(), $fill_color = array()) {
5718 if (!(false === strpos($style, "F")) AND $fill_color) {
5719 list($r, $g, $b) = $fill_color;
5720 $this->SetFillColor($r, $g, $b);
5722 switch ($style) {
5723 case "F": {
5724 $op = "f";
5725 $line_style = array();
5726 break;
5728 case "FD":
5729 case "DF": {
5730 $op = "B";
5731 break;
5733 default: {
5734 $op = "S";
5735 break;
5738 if ($line_style) {
5739 $this->SetLineStyle($line_style);
5741 $this->_outPoint($x0, $y0);
5742 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
5743 $this->_out($op);
5747 * Draws an ellipse.
5748 * An ellipse is formed from n Bezier curves.
5749 * @param float $x0 Abscissa of center point.
5750 * @param float $y0 Ordinate of center point.
5751 * @param float $rx Horizontal radius.
5752 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
5753 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
5754 * @param float $astart: Angle start of draw line. Default value: 0.
5755 * @param float $afinish: Angle finish of draw line. Default value: 360.
5756 * @param string $style Style of rendering. Possible values are:
5757 * <ul>
5758 * <li>D or empty string: Draw (default).</li>
5759 * <li>F: Fill.</li>
5760 * <li>DF or FD: Draw and fill.</li>
5761 * <li>C: Draw close.</li>
5762 * </ul>
5763 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5764 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5765 * @param integer $nc Number of curves used in ellipse. Default value: 8.
5766 * @access public
5767 * @since 2.1.000 (2008-01-08)
5769 public function Ellipse($x0, $y0, $rx, $ry = 0, $angle = 0, $astart = 0, $afinish = 360, $style = "", $line_style = array(), $fill_color = array(), $nc = 8) {
5770 if ($angle) {
5771 $this->StartTransform();
5772 $this->Rotate($angle, $x0, $y0);
5773 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
5774 $this->StopTransform();
5775 return;
5777 if ($rx) {
5778 if (!(false === strpos($style, "F")) AND $fill_color) {
5779 list($r, $g, $b) = $fill_color;
5780 $this->SetFillColor($r, $g, $b);
5782 switch ($style) {
5783 case "F": {
5784 $op = "f";
5785 $line_style = array();
5786 break;
5788 case "FD":
5789 case "DF": {
5790 $op = "B";
5791 break;
5793 case "C": {
5794 $op = "s"; // Small "s" signifies closing the path as well
5795 break;
5797 default: {
5798 $op = "S";
5799 break;
5802 if ($line_style) {
5803 $this->SetLineStyle($line_style);
5805 if (!$ry) {
5806 $ry = $rx;
5808 $rx *= $this->k;
5809 $ry *= $this->k;
5810 if ($nc < 2){
5811 $nc = 2;
5813 $astart = deg2rad((float) $astart);
5814 $afinish = deg2rad((float) $afinish);
5815 $total_angle = $afinish - $astart;
5816 $dt = $total_angle / $nc;
5817 $dtm = $dt/3;
5818 $x0 *= $this->k;
5819 $y0 = ($this->h - $y0) * $this->k;
5820 $t1 = $astart;
5821 $a0 = $x0 + ($rx * cos($t1));
5822 $b0 = $y0 + ($ry * sin($t1));
5823 $c0 = -$rx * sin($t1);
5824 $d0 = $ry * cos($t1);
5825 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
5826 for ($i = 1; $i <= $nc; $i++) {
5827 // Draw this bit of the total curve
5828 $t1 = ($i * $dt) + $astart;
5829 $a1 = $x0 + ($rx * cos($t1));
5830 $b1 = $y0 + ($ry * sin($t1));
5831 $c1 = -$rx * sin($t1);
5832 $d1 = $ry * cos($t1);
5833 $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));
5834 $a0 = $a1;
5835 $b0 = $b1;
5836 $c0 = $c1;
5837 $d0 = $d1;
5839 $this->_out($op);
5844 * Draws a circle.
5845 * A circle is formed from n Bezier curves.
5846 * @param float $x0 Abscissa of center point.
5847 * @param float $y0 Ordinate of center point.
5848 * @param float $r Radius.
5849 * @param float $astart: Angle start of draw line. Default value: 0.
5850 * @param float $afinish: Angle finish of draw line. Default value: 360.
5851 * @param string $style Style of rendering. Possible values are:
5852 * <ul>
5853 * <li>D or empty string: Draw (default).</li>
5854 * <li>F: Fill.</li>
5855 * <li>DF or FD: Draw and fill.</li>
5856 * <li>C: Draw close.</li>
5857 * </ul>
5858 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
5859 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5860 * @param integer $nc Number of curves used in circle. Default value: 8.
5861 * @access public
5862 * @since 2.1.000 (2008-01-08)
5864 public function Circle($x0, $y0, $r, $astart = 0, $afinish = 360, $style = "", $line_style = array(), $fill_color = array(), $nc = 8) {
5865 $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
5869 * Draws a polygon.
5870 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
5871 * @param string $style Style of rendering. Possible values are:
5872 * <ul>
5873 * <li>D or empty string: Draw (default).</li>
5874 * <li>F: Fill.</li>
5875 * <li>DF or FD: Draw and fill.</li>
5876 * </ul>
5877 * @param array $line_style Line style of polygon. Array with keys among the following:
5878 * <ul>
5879 * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
5880 * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
5881 * </ul>
5882 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
5883 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5884 * @access public
5885 * @since 2.1.000 (2008-01-08)
5887 public function Polygon($p, $style = "", $line_style = array(), $fill_color = array()) {
5888 $np = count($p) / 2;
5889 if (!(false === strpos($style, "F")) AND $fill_color) {
5890 list($r, $g, $b) = $fill_color;
5891 $this->SetFillColor($r, $g, $b);
5893 switch ($style) {
5894 case "F": {
5895 $line_style = array();
5896 $op = "f";
5897 break;
5899 case "FD":
5900 case "DF": {
5901 $op = "B";
5902 break;
5904 default: {
5905 $op = "S";
5906 break;
5909 $draw = true;
5910 if ($line_style) {
5911 if (isset($line_style["all"])) {
5912 $this->SetLineStyle($line_style["all"]);
5914 else { // 0 .. (np - 1), op = {B, S}
5915 $draw = false;
5916 if ("B" == $op) {
5917 $op = "f";
5918 $this->_outPoint($p[0], $p[1]);
5919 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
5920 $this->_outLine($p[$i], $p[$i + 1]);
5922 $this->_outLine($p[0], $p[1]);
5923 $this->_out($op);
5925 $p[$np * 2] = $p[0];
5926 $p[($np * 2) + 1] = $p[1];
5927 for ($i = 0; $i < $np; $i++) {
5928 if (isset($line_style[$i])) {
5929 $this->Line($p[$i * 2], $p[($i * 2) + 1], $p[($i * 2) + 2], $p[($i * 2) + 3], $line_style[$i]);
5934 if ($draw) {
5935 $this->_outPoint($p[0], $p[1]);
5936 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
5937 $this->_outLine($p[$i], $p[$i + 1]);
5939 $this->_outLine($p[0], $p[1]);
5940 $this->_out($op);
5945 * Draws a regular polygon.
5946 * @param float $x0 Abscissa of center point.
5947 * @param float $y0 Ordinate of center point.
5948 * @param float $r: Radius of inscribed circle.
5949 * @param integer $ns Number of sides.
5950 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
5951 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
5952 * @param string $style Style of rendering. Possible values are:
5953 * <ul>
5954 * <li>D or empty string: Draw (default).</li>
5955 * <li>F: Fill.</li>
5956 * <li>DF or FD: Draw and fill.</li>
5957 * </ul>
5958 * @param array $line_style Line style of polygon sides. Array with keys among the following:
5959 * <ul>
5960 * <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
5961 * <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
5962 * </ul>
5963 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
5964 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
5965 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
5966 * <ul>
5967 * <li>D or empty string: Draw (default).</li>
5968 * <li>F: Fill.</li>
5969 * <li>DF or FD: Draw and fill.</li>
5970 * </ul>
5971 * @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).
5972 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
5973 * @access public
5974 * @since 2.1.000 (2008-01-08)
5976 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()) {
5977 if (3 > $ns) {
5978 $ns = 3;
5980 if ($draw_circle) {
5981 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
5983 $p = array();
5984 for ($i = 0; $i < $ns; $i++) {
5985 $a = $angle + ($i * 360 / $ns);
5986 $a_rad = deg2rad((float) $a);
5987 $p[] = $x0 + ($r * sin($a_rad));
5988 $p[] = $y0 + ($r * cos($a_rad));
5990 $this->Polygon($p, $style, $line_style, $fill_color);
5994 * Draws a star polygon
5995 * @param float $x0 Abscissa of center point.
5996 * @param float $y0 Ordinate of center point.
5997 * @param float $r Radius of inscribed circle.
5998 * @param integer $nv Number of vertices.
5999 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
6000 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6001 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
6002 * @param string $style Style of rendering. Possible values are:
6003 * <ul>
6004 * <li>D or empty string: Draw (default).</li>
6005 * <li>F: Fill.</li>
6006 * <li>DF or FD: Draw and fill.</li>
6007 * </ul>
6008 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6009 * <ul>
6010 * <li>all: Line style of all sides. Array like for
6011 * {@link SetLineStyle SetLineStyle}.</li>
6012 * <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6013 * </ul>
6014 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6015 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6016 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6017 * <ul>
6018 * <li>D or empty string: Draw (default).</li>
6019 * <li>F: Fill.</li>
6020 * <li>DF or FD: Draw and fill.</li>
6021 * </ul>
6022 * @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).
6023 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6024 * @access public
6025 * @since 2.1.000 (2008-01-08)
6027 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()) {
6028 if (2 > $nv) {
6029 $nv = 2;
6031 if ($draw_circle) {
6032 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6034 $p2 = array();
6035 $visited = array();
6036 for ($i = 0; $i < $nv; $i++) {
6037 $a = $angle + ($i * 360 / $nv);
6038 $a_rad = deg2rad((float) $a);
6039 $p2[] = $x0 + ($r * sin($a_rad));
6040 $p2[] = $y0 + ($r * cos($a_rad));
6041 $visited[] = false;
6043 $p = array();
6044 $i = 0;
6045 do {
6046 $p[] = $p2[$i * 2];
6047 $p[] = $p2[($i * 2) + 1];
6048 $visited[$i] = true;
6049 $i += $ng;
6050 $i %= $nv;
6051 } while (!$visited[$i]);
6052 $this->Polygon($p, $style, $line_style, $fill_color);
6056 * Draws a rounded rectangle.
6057 * @param float $x Abscissa of upper-left corner.
6058 * @param float $y Ordinate of upper-left corner.
6059 * @param float $w Width.
6060 * @param float $h Height.
6061 * @param float $r Radius of the rounded corners.
6062 * @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").
6063 * @param string $style Style of rendering. Possible values are:
6064 * <ul>
6065 * <li>D or empty string: Draw (default).</li>
6066 * <li>F: Fill.</li>
6067 * <li>DF or FD: Draw and fill.</li>
6068 * </ul>
6069 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6070 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6071 * @access public
6072 * @since 2.1.000 (2008-01-08)
6074 public function RoundedRect($x, $y, $w, $h, $r, $round_corner = "1111", $style = "", $border_style = array(), $fill_color = array()) {
6075 if ("0000" == $round_corner) { // Not rounded
6076 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
6077 } else { // Rounded
6078 if (!(false === strpos($style, "F")) AND $fill_color) {
6079 list($red, $g, $b) = $fill_color;
6080 $this->SetFillColor($red, $g, $b);
6082 switch ($style) {
6083 case "F": {
6084 $border_style = array();
6085 $op = "f";
6086 break;
6088 case "FD":
6089 case "DF": {
6090 $op = "B";
6091 break;
6093 default: {
6094 $op = "S";
6095 break;
6098 if ($border_style) {
6099 $this->SetLineStyle($border_style);
6101 $MyArc = 4 / 3 * (sqrt(2) - 1);
6102 $this->_outPoint($x + $r, $y);
6103 $xc = $x + $w - $r;
6104 $yc = $y + $r;
6105 $this->_outLine($xc, $y);
6106 if ($round_corner[0]) {
6107 $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
6108 } else {
6109 $this->_outLine($x + $w, $y);
6111 $xc = $x + $w - $r;
6112 $yc = $y + $h - $r;
6113 $this->_outLine($x + $w, $yc);
6114 if ($round_corner[1]) {
6115 $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
6116 } else {
6117 $this->_outLine($x + $w, $y + $h);
6119 $xc = $x + $r;
6120 $yc = $y + $h - $r;
6121 $this->_outLine($xc, $y + $h);
6122 if ($round_corner[2]) {
6123 $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
6124 } else {
6125 $this->_outLine($x, $y + $h);
6127 $xc = $x + $r;
6128 $yc = $y + $r;
6129 $this->_outLine($x, $yc);
6130 if ($round_corner[3]) {
6131 $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
6132 } else {
6133 $this->_outLine($x, $y);
6134 $this->_outLine($x + $r, $y);
6136 $this->_out($op);
6140 // END GRAPHIC FUNCTIONS SECTION -----------------------
6142 // BIDIRECTIONAL TEXT SECTION --------------------------
6145 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
6146 * @param string $str string to manipulate.
6147 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
6148 * @return string
6149 * @author Nicola Asuni
6150 * @since 2.1.000 (2008-01-08)
6152 protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
6153 global $unicode,$unicode_mirror, $unicode_arlet;
6154 require_once(dirname(__FILE__).'/unicode_data.php');
6156 // paragraph embedding level
6157 $pel = 0;
6158 // max level
6159 $maxlevel = 0;
6161 // check if string contains arabic text
6162 if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
6163 $arabic = true;
6164 } else {
6165 $arabic = false;
6168 // check if string contains RTL text
6169 if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
6170 return $this->UTF8ToUTF16BE($str, false);
6173 // convert string to array of unicode chars
6174 $ta = $this->UTF8StringToArray($str);
6175 // get number of chars
6176 $numchars = count($ta);
6178 if ($forcertl == 'R') {
6179 $pel = 1;
6180 } elseif ($forcertl == 'L') {
6181 $pel = 0;
6182 } else {
6183 // P2. In each paragraph, find the first character of type L, AL, or R.
6184 // 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.
6185 for ($i=0; $i < $numchars; $i++) {
6186 $type = $unicode[$ta[$i]];
6187 if ($type == 'L') {
6188 $pel = 0;
6189 break;
6190 } elseif (($type == 'AL') OR ($type == 'R')) {
6191 $pel = 1;
6192 break;
6197 // Current Embedding Level
6198 $cel = $pel;
6199 // directional override status
6200 $dos = 'N';
6201 $remember = array();
6202 // start-of-level-run
6203 $sor = $pel % 2 ? 'R' : 'L';
6204 $eor = $sor;
6206 //$levels = array(array('level' => $cel, 'sor' => $sor, 'eor' => '', 'chars' => array()));
6207 //$current_level = &$levels[count( $levels )-1];
6209 // Array of characters data
6210 $chardata = Array();
6212 // 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.
6213 // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
6214 for ($i=0; $i < $numchars; $i++) {
6215 if ($ta[$i] == K_RLE) {
6216 // X2. With each RLE, compute the least greater odd embedding level.
6217 // 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.
6218 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6219 $next_level = $cel + ($cel % 2) + 1;
6220 if ($next_level < 62) {
6221 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
6222 $cel = $next_level;
6223 $dos = 'N';
6224 $sor = $eor;
6225 $eor = $cel % 2 ? 'R' : 'L';
6227 } elseif ($ta[$i] == K_LRE) {
6228 // X3. With each LRE, compute the least greater even embedding level.
6229 // 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.
6230 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6231 $next_level = $cel + 2 - ($cel % 2);
6232 if ( $next_level < 62 ) {
6233 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
6234 $cel = $next_level;
6235 $dos = 'N';
6236 $sor = $eor;
6237 $eor = $cel % 2 ? 'R' : 'L';
6239 } elseif ($ta[$i] == K_RLO) {
6240 // X4. With each RLO, compute the least greater odd embedding level.
6241 // 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.
6242 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6243 $next_level = $cel + ($cel % 2) + 1;
6244 if ($next_level < 62) {
6245 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
6246 $cel = $next_level;
6247 $dos = 'R';
6248 $sor = $eor;
6249 $eor = $cel % 2 ? 'R' : 'L';
6251 } elseif ($ta[$i] == K_LRO) {
6252 // X5. With each LRO, compute the least greater even embedding level.
6253 // 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.
6254 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
6255 $next_level = $cel + 2 - ($cel % 2);
6256 if ( $next_level < 62 ) {
6257 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
6258 $cel = $next_level;
6259 $dos = 'L';
6260 $sor = $eor;
6261 $eor = $cel % 2 ? 'R' : 'L';
6263 } elseif ($ta[$i] == K_PDF) {
6264 // 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.
6265 if (count($remember)) {
6266 $last = count($remember ) - 1;
6267 if (($remember[$last]['num'] == K_RLE) OR
6268 ($remember[$last]['num'] == K_LRE) OR
6269 ($remember[$last]['num'] == K_RLO) OR
6270 ($remember[$last]['num'] == K_LRO)) {
6271 $match = array_pop($remember);
6272 $cel = $match['cel'];
6273 $dos = $match['dos'];
6274 $sor = $eor;
6275 $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
6278 } elseif (($ta[$i] != K_RLE) AND
6279 ($ta[$i] != K_LRE) AND
6280 ($ta[$i] != K_RLO) AND
6281 ($ta[$i] != K_LRO) AND
6282 ($ta[$i] != K_PDF)) {
6283 // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
6284 // a. Set the level of the current character to the current embedding level.
6285 // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
6286 if ($dos != 'N') {
6287 $chardir = $dos;
6288 } else {
6289 $chardir = $unicode[$ta[$i]];
6291 // stores string characters and other information
6292 $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
6294 } // end for each char
6296 // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
6297 // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
6298 // 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.
6300 // 3.3.3 Resolving Weak Types
6301 // 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.
6302 // Nonspacing marks are now resolved based on the previous characters.
6303 $numchars = count($chardata);
6305 // 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.
6306 $prevlevel = -1; // track level changes
6307 $levcount = 0; // counts consecutive chars at the same level
6308 for ($i=0; $i < $numchars; $i++) {
6309 if ($chardata[$i]['type'] == 'NSM') {
6310 if ($levcount) {
6311 $chardata[$i]['type'] = $chardata[$i]['sor'];
6312 } elseif ($i > 0) {
6313 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
6316 if ($chardata[$i]['level'] != $prevlevel) {
6317 $levcount = 0;
6318 } else {
6319 $levcount++;
6321 $prevlevel = $chardata[$i]['level'];
6324 // 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.
6325 $prevlevel = -1;
6326 $levcount = 0;
6327 for ($i=0; $i < $numchars; $i++) {
6328 if ($chardata[$i]['char'] == 'EN') {
6329 for ($j=$levcount; $j >= 0; $j--) {
6330 if ($chardata[$j]['type'] == 'AL') {
6331 $chardata[$i]['type'] = 'AN';
6332 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
6333 break;
6337 if ($chardata[$i]['level'] != $prevlevel) {
6338 $levcount = 0;
6339 } else {
6340 $levcount++;
6342 $prevlevel = $chardata[$i]['level'];
6345 // W3. Change all ALs to R.
6346 for ($i=0; $i < $numchars; $i++) {
6347 if ($chardata[$i]['type'] == 'AL') {
6348 $chardata[$i]['type'] = 'R';
6352 // 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.
6353 $prevlevel = -1;
6354 $levcount = 0;
6355 for ($i=0; $i < $numchars; $i++) {
6356 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
6357 if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
6358 $chardata[$i]['type'] = 'EN';
6359 } elseif (($chardata[$i]['type'] == 'CS') 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'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
6362 $chardata[$i]['type'] = 'AN';
6365 if ($chardata[$i]['level'] != $prevlevel) {
6366 $levcount = 0;
6367 } else {
6368 $levcount++;
6370 $prevlevel = $chardata[$i]['level'];
6373 // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
6374 $prevlevel = -1;
6375 $levcount = 0;
6376 for ($i=0; $i < $numchars; $i++) {
6377 if($chardata[$i]['type'] == 'ET') {
6378 if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
6379 $chardata[$i]['type'] = 'EN';
6380 } else {
6381 $j = $i+1;
6382 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
6383 if ($chardata[$j]['type'] == 'EN') {
6384 $chardata[$i]['type'] = 'EN';
6385 break;
6386 } elseif ($chardata[$j]['type'] != 'ET') {
6387 break;
6389 $j++;
6393 if ($chardata[$i]['level'] != $prevlevel) {
6394 $levcount = 0;
6395 } else {
6396 $levcount++;
6398 $prevlevel = $chardata[$i]['level'];
6401 // W6. Otherwise, separators and terminators change to Other Neutral.
6402 $prevlevel = -1;
6403 $levcount = 0;
6404 for ($i=0; $i < $numchars; $i++) {
6405 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
6406 $chardata[$i]['type'] = 'ON';
6408 if ($chardata[$i]['level'] != $prevlevel) {
6409 $levcount = 0;
6410 } else {
6411 $levcount++;
6413 $prevlevel = $chardata[$i]['level'];
6416 //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.
6417 $prevlevel = -1;
6418 $levcount = 0;
6419 for ($i=0; $i < $numchars; $i++) {
6420 if ($chardata[$i]['char'] == 'EN') {
6421 for ($j=$levcount; $j >= 0; $j--) {
6422 if ($chardata[$j]['type'] == 'L') {
6423 $chardata[$i]['type'] = 'L';
6424 } elseif ($chardata[$j]['type'] == 'R') {
6425 break;
6429 if ($chardata[$i]['level'] != $prevlevel) {
6430 $levcount = 0;
6431 } else {
6432 $levcount++;
6434 $prevlevel = $chardata[$i]['level'];
6437 // 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.
6438 $prevlevel = -1;
6439 $levcount = 0;
6440 for ($i=0; $i < $numchars; $i++) {
6441 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
6442 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
6443 $chardata[$i]['type'] = 'L';
6444 } elseif (($chardata[$i]['type'] == 'N') AND
6445 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
6446 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
6447 $chardata[$i]['type'] = 'R';
6448 } elseif ($chardata[$i]['type'] == 'N') {
6449 // N2. Any remaining neutrals take the embedding direction
6450 $chardata[$i]['type'] = $chardata[$i]['sor'];
6452 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
6453 // first char
6454 if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
6455 $chardata[$i]['type'] = 'L';
6456 } elseif (($chardata[$i]['type'] == 'N') AND
6457 (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
6458 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
6459 $chardata[$i]['type'] = 'R';
6460 } elseif ($chardata[$i]['type'] == 'N') {
6461 // N2. Any remaining neutrals take the embedding direction
6462 $chardata[$i]['type'] = $chardata[$i]['sor'];
6464 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
6465 //last char
6466 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
6467 $chardata[$i]['type'] = 'L';
6468 } elseif (($chardata[$i]['type'] == 'N') AND
6469 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
6470 (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
6471 $chardata[$i]['type'] = 'R';
6472 } elseif ($chardata[$i]['type'] == 'N') {
6473 // N2. Any remaining neutrals take the embedding direction
6474 $chardata[$i]['type'] = $chardata[$i]['sor'];
6476 } elseif ($chardata[$i]['type'] == 'N') {
6477 // N2. Any remaining neutrals take the embedding direction
6478 $chardata[$i]['type'] = $chardata[$i]['sor'];
6480 if ($chardata[$i]['level'] != $prevlevel) {
6481 $levcount = 0;
6482 } else {
6483 $levcount++;
6485 $prevlevel = $chardata[$i]['level'];
6488 // 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.
6489 // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
6490 for ($i=0; $i < $numchars; $i++) {
6491 $odd = $chardata[$i]['level'] % 2;
6492 if ($odd) {
6493 if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
6494 $chardata[$i]['level'] += 1;
6496 } else {
6497 if ($chardata[$i]['type'] == 'R') {
6498 $chardata[$i]['level'] += 1;
6499 } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
6500 $chardata[$i]['level'] += 2;
6503 $maxlevel = max($chardata[$i]['level'],$maxlevel);
6506 // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
6507 // 1. Segment separators,
6508 // 2. Paragraph separators,
6509 // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
6510 // 4. Any sequence of white space characters at the end of the line.
6511 for ($i=0; $i < $numchars; $i++) {
6512 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
6513 $chardata[$i]['level'] = $pel;
6514 } elseif ($chardata[$i]['type'] == 'WS') {
6515 $j = $i+1;
6516 while ($j < $numchars) {
6517 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
6518 (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
6519 $chardata[$i]['level'] = $pel;;
6520 break;
6521 } elseif ($chardata[$j]['type'] != 'WS') {
6522 break;
6524 $j++;
6529 // Arabic Shaping
6530 // 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.
6531 if ($arabic) {
6532 for ($i=0; $i < $numchars; $i++) {
6533 if ($unicode[$chardata[$i]['char']] == 'AL') {
6534 if (($i > 0) AND (($i+1) < $numchars) AND
6535 ($unicode[$chardata[($i-1)]['char']] == 'AL') AND
6536 ($unicode[$chardata[($i+1)]['char']] == 'AL') AND
6537 ($chardata[($i-1)]['type'] == $chardata[$i]['type']) AND
6538 ($chardata[($i+1)]['type'] == $chardata[$i]['type'])) {
6539 // medial
6540 if (isset($unicode_arlet[$chardata[$i]['char']][3])) {
6541 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][3];
6543 } elseif ((($i+1) < $numchars) AND
6544 ($unicode[$chardata[($i+1)]['char']] == 'AL') AND
6545 ($chardata[($i+1)]['type'] == $chardata[$i]['type'])) {
6546 // initial
6547 if (isset($unicode_arlet[$chardata[$i]['char']][2])) {
6548 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][2];
6550 } elseif (($i > 0) AND
6551 ($unicode[$chardata[($i-1)]['char']] == 'AL') AND
6552 ($chardata[($i-1)]['type'] == $chardata[$i]['type'])) {
6553 // final
6554 if (isset($unicode_arlet[$chardata[$i]['char']][1])) {
6555 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][1];
6557 } elseif (isset($unicode_arlet[$chardata[$i]['char']][0])) {
6558 // isolated
6559 $chardata[$i]['char'] = $unicode_arlet[$chardata[$i]['char']][0];
6565 // 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.
6566 for ($j=$maxlevel; $j > 0; $j--) {
6567 $ordarray = Array();
6568 $revarr = Array();
6569 $onlevel = false;
6570 for ($i=0; $i < $numchars; $i++) {
6571 if ($chardata[$i]['level'] >= $j) {
6572 $onlevel = true;
6573 if (isset($unicode_mirror[$chardata[$i]['char']])) {
6574 // 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.
6575 $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
6577 $revarr[] = $chardata[$i];
6578 } else {
6579 if($onlevel) {
6580 $revarr = array_reverse($revarr);
6581 $ordarray = array_merge($ordarray, $revarr);
6582 $revarr = Array();
6583 $onlevel = false;
6585 $ordarray[] = $chardata[$i];
6588 if($onlevel) {
6589 $revarr = array_reverse($revarr);
6590 $ordarray = array_merge($ordarray, $revarr);
6592 $chardata = $ordarray;
6595 $ordarray = array();
6596 for ($i=0; $i < $numchars; $i++) {
6597 $ordarray[] = $chardata[$i]['char'];
6600 return $this->arrUTF8ToUTF16BE($ordarray, $setbom);
6603 // END OF BIDIRECTIONAL TEXT SECTION -------------------
6606 * Adds a bookmark.
6607 * @param string $txt bookmark description.
6608 * @param int $level bookmark level.
6609 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
6610 * @access public
6611 * @author Olivier Plathey, Nicola Asuni
6612 * @since 2.1.002 (2008-02-12)
6614 public function Bookmark($txt, $level=0, $y=-1) {
6615 if($y == -1) {
6616 $y = $this->GetY();
6618 $this->outlines[]=array('t'=>$txt,'l'=>$level,'y'=>$y,'p'=>$this->PageNo());
6622 * Create a bookmark PDF string.
6623 * @access private
6624 * @author Olivier Plathey, Nicola Asuni
6625 * @since 2.1.002 (2008-02-12)
6627 private function _putbookmarks() {
6628 $nb = count($this->outlines);
6629 if($nb == 0) {
6630 return;
6632 $lru = array();
6633 $level = 0;
6634 foreach($this->outlines as $i=>$o) {
6635 if($o['l'] > 0) {
6636 $parent = $lru[$o['l'] - 1];
6637 //Set parent and last pointers
6638 $this->outlines[$i]['parent'] = $parent;
6639 $this->outlines[$parent]['last'] = $i;
6640 if($o['l'] > $level) {
6641 //Level increasing: set first pointer
6642 $this->outlines[$parent]['first'] = $i;
6644 } else {
6645 $this->outlines[$i]['parent']=$nb;
6647 if($o['l']<=$level and $i>0) {
6648 //Set prev and next pointers
6649 $prev = $lru[$o['l']];
6650 $this->outlines[$prev]['next'] = $i;
6651 $this->outlines[$i]['prev'] = $prev;
6653 $lru[$o['l']] = $i;
6654 $level = $o['l'];
6656 //Outline items
6657 $n = $this->n+1;
6658 foreach($this->outlines as $i=>$o) {
6659 $this->_newobj();
6660 $this->_out('<</Title '.$this->_textstring($o['t']));
6661 $this->_out('/Parent '.($n+$o['parent']).' 0 R');
6662 if(isset($o['prev']))
6663 $this->_out('/Prev '.($n+$o['prev']).' 0 R');
6664 if(isset($o['next']))
6665 $this->_out('/Next '.($n+$o['next']).' 0 R');
6666 if(isset($o['first']))
6667 $this->_out('/First '.($n+$o['first']).' 0 R');
6668 if(isset($o['last']))
6669 $this->_out('/Last '.($n+$o['last']).' 0 R');
6670 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]',1+2*$o['p'],($this->h-$o['y'])*$this->k));
6671 $this->_out('/Count 0>>');
6672 $this->_out('endobj');
6674 //Outline root
6675 $this->_newobj();
6676 $this->OutlineRoot=$this->n;
6677 $this->_out('<</Type /Outlines /First '.$n.' 0 R');
6678 $this->_out('/Last '.($n+$lru[0]).' 0 R>>');
6679 $this->_out('endobj');
6683 // --- JAVASCRIPT - FORMS ------------------------------
6686 * Adds a javascript
6687 * @access public
6688 * @author Johannes Güntert, Nicola Asuni
6689 * @since 2.1.002 (2008-02-12)
6691 public function IncludeJS($script) {
6692 $this->javascript .= $script;
6696 * Create a javascript PDF string.
6697 * @access private
6698 * @author Johannes Güntert, Nicola Asuni
6699 * @since 2.1.002 (2008-02-12)
6701 private function _putjavascript() {
6702 if (empty($this->javascript)) {
6703 return;
6705 $this->_newobj();
6706 $this->n_js = $this->n;
6707 $this->_out('<<');
6708 $this->_out('/Names [(EmbeddedJS) '.($this->n+1).' 0 R ]');
6709 $this->_out('>>');
6710 $this->_out('endobj');
6711 $this->_newobj();
6712 $this->_out('<<');
6713 $this->_out('/S /JavaScript');
6714 $this->_out('/JS '.$this->_textstring($this->javascript));
6715 $this->_out('>>');
6716 $this->_out('endobj');
6720 * Convert color to javascript color.
6721 * @param string $color color name or #RRGGBB
6722 * @access private
6723 * @author Denis Van Nuffelen, Nicola Asuni
6724 * @since 2.1.002 (2008-02-12)
6726 private function _JScolor($color) {
6727 static $aColors = array('transparent','black','white','red','green','blue','cyan','magenta','yellow','dkGray','gray','ltGray');
6728 if(substr($color,0,1) == '#') {
6729 return sprintf("['RGB',%.3f,%.3f,%.3f]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
6731 if(!in_array($color,$aColors)) {
6732 $this->Error('Invalid color: '.$color);
6734 return 'color.'.$color;
6738 * Adds a javascript form field.
6739 * @param string $type field type
6740 * @param string $name field name
6741 * @param int $x horizontal position
6742 * @param int $y vertical position
6743 * @param int $w width
6744 * @param int $h height
6745 * @param string $prop properties
6746 * @access private
6747 * @author Denis Van Nuffelen, Nicola Asuni
6748 * @since 2.1.002 (2008-02-12)
6750 private function _addfield($type, $name, $x, $y, $w, $h, $prop) {
6751 $k = $this->k;
6752 $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);
6753 $this->javascript .= 'f.textSize='.$this->FontSizePt.';';
6754 if(isset($prop['value'])) {
6755 $this->javascript .= "f.value='".addslashes($prop['value'])."';";
6757 if(isset($prop['TextColor'])) {
6758 $this->javascript .= 'f.textColor='.$this->_JScolor($prop['TextColor']).';';
6760 if(isset($prop['FillColor'])) {
6761 $this->javascript .= 'f.fillColor='.$this->_JScolor($prop['FillColor']).';';
6763 if(isset($prop['BorderColor'])) {
6764 $this->javascript .= 'f.strokeColor='.$this->_JScolor($prop['BorderColor']).';';
6766 if(isset($prop['BorderStyle'])) {
6767 $this->javascript .= "f.borderStyle='".$prop['BorderStyle']."';";
6769 $this->x+=$w;
6773 * Creates a text field
6774 * @param string $name field name
6775 * @param int $w width
6776 * @param int $h height
6777 * @param string $prop properties. The value property allows to set the initial value. The multiline property allows to define the field as multiline.
6778 * @access public
6779 * @author Denis Van Nuffelen, Nicola Asuni
6780 * @since 2.1.002 (2008-02-12)
6782 public function TextField($name, $w, $h, $prop=array()) {
6783 $this->_addfield('text',$name,$this->x,$this->y,$w,$h,$prop);
6784 if(isset($prop['multiline']) AND $prop['multiline']) {
6785 $this->javascript .= 'f.multiline=true;';
6790 * Creates a Combo-box field
6791 * @param string $name field name
6792 * @param int $w width
6793 * @param int $h height
6794 * @param array $values array containing the list of values.
6795 * @param string $prop properties.
6796 * @access public
6797 * @author Denis Van Nuffelen, Nicola Asuni
6798 * @since 2.1.002 (2008-02-12)
6800 public function ComboBox($name, $w, $h, $values, $prop=array()) {
6801 $this->_addfield('combobox',$name,$this->x,$this->y,$w,$h,$prop);
6802 $s = '';
6803 foreach($values as $value) {
6804 $s .= "'".addslashes($value)."',";
6806 $this->javascript .= 'f.setItems(['.substr($s,0,-1).']);';
6810 * Creates a CheckBox field
6811 * @param string $name field name
6812 * @param int $w width
6813 * @param boolean $checked define the initial state (default = false).
6814 * @param string $prop properties.
6815 * @access public
6816 * @author Denis Van Nuffelen, Nicola Asuni
6817 * @since 2.1.002 (2008-02-12)
6819 public function CheckBox($name, $w, $checked=false, $prop=array()) {
6820 $prop['value'] = ($checked ? 'Yes' : 'Off');
6821 if(!isset($prop['BorderColor'])) {
6822 $prop['BorderColor']='black';
6824 $this->_addfield('checkbox',$name,$this->x,$this->y,$w,$w,$prop);
6828 * Creates a button field
6829 * @param string $name field name
6830 * @param int $w width
6831 * @param int $h height
6832 * @param string $caption caption.
6833 * @param string $action action triggered by the button (JavaScript code).
6834 * @param string $prop properties.
6835 * @access public
6836 * @author Denis Van Nuffelen, Nicola Asuni
6837 * @since 2.1.002 (2008-02-12)
6839 public function Button($name, $w, $h, $caption, $action, $prop=array()) {
6840 if(!isset($prop['BorderColor'])) {
6841 $prop['BorderColor']='black';
6843 $prop['BorderStyle']='beveled';
6844 $this->_addfield('button',$name,$this->x,$this->y,$w,$h,$prop);
6845 $this->javascript .= "f.buttonSetCaption('".addslashes($caption)."');";
6846 $this->javascript .= "f.setAction('MouseUp','".addslashes($action)."');";
6847 $this->javascript .= "f.highlight='push';";
6848 $this->javascript .= 'f.print=false;';
6851 // END JAVASCRIPT - FORMS ------------------------------
6853 } // END OF TCPDF CLASS
6855 //Handle special IE contype request
6856 if(isset($_SERVER['HTTP_USER_AGENT']) AND ($_SERVER['HTTP_USER_AGENT']=='contype')) {
6857 header('Content-Type: application/pdf');
6858 exit;
6862 //============================================================+
6863 // END OF FILE
6864 //============================================================+