5 Modification information for LGPL compliance
7 Fri Dec 2 2011 smalyshev - Added unserialize/destruct vulnerability protection
9 Mon May 30 16:16:13 2011 +0300 - alex-vlasov - Bug 41216 - currency is displayed on 2 lines instead of one when printing a quote to PDF
11 r57813 - 2010-08-19 10:34:44 -0700 (Thu, 19 Aug 2010) - kjing - Author: John Mertic <jmertic@sugarcrm.com>
12 Bug 39085 - When loading the opposite search panel via ajax on the ListViews, call the index action instead of the ListView action to avoid touching pre-MVC code by accident.
14 r56990 - 2010-06-16 13:05:36 -0700 (Wed, 16 Jun 2010) - kjing - snapshot "Mango" svn branch to a new one for GitHub sync
16 r56989 - 2010-06-16 13:01:33 -0700 (Wed, 16 Jun 2010) - kjing - defunt "Mango" svn dev branch before github cutover
18 r55980 - 2010-04-19 13:31:28 -0700 (Mon, 19 Apr 2010) - kjing - create Mango (6.1) based on windex
20 r53409 - 2010-01-03 19:31:15 -0800 (Sun, 03 Jan 2010) - roger - merge -r50376:HEAD from fuji_newtag_tmp
22 r51719 - 2009-10-22 10:18:00 -0700 (Thu, 22 Oct 2009) - mitani - Converted to Build 3 tags and updated the build system
24 r51634 - 2009-10-19 13:32:22 -0700 (Mon, 19 Oct 2009) - mitani - Windex is the branch for Sugar Sales 1.0 development
26 r51443 - 2009-10-12 13:34:36 -0700 (Mon, 12 Oct 2009) - jmertic - Bug 33332 - Made application PHP 5.3 compliant with E_DEPRECATED warnings on by:
27 - Changing all ereg function to either preg or simple string based ones
28 - No more references to magic quotes.
29 - Change all the session_unregister() functions to just unset() the correct session variable instead.
31 r50375 - 2009-08-24 18:07:43 -0700 (Mon, 24 Aug 2009) - dwong - branch kobe2 from tokyo r50372
33 r47904 - 2009-06-02 11:54:10 -0700 (Tue, 02 Jun 2009) - jenny - Adding changes that were made to the earlier version of this file to support jpg images.
35 r47900 - 2009-06-02 11:26:55 -0700 (Tue, 02 Jun 2009) - jenny - Updating with changes from bsoufflet.
37 r46662 - 2009-04-29 10:48:07 -0700 (Wed, 29 Apr 2009) - jenny - Invoking native jpg image support which isnt' automatically there.
39 r46617 - 2009-04-28 16:08:45 -0700 (Tue, 28 Apr 2009) - jenny - Fixing a bug in TCPDF that checks to see if the GD library is installed.
41 r46451 - 2009-04-23 16:57:40 -0700 (Thu, 23 Apr 2009) - jenny - tcpdf initial checkin.
47 //============================================================+
48 // File name : tcpdf.php
50 // Last Update : 2009-05-28
51 // Author : Nicola Asuni - info@tecnick.com - http://www.tcpdf.org
53 // License : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
54 // ----------------------------------------------------------------------------
55 // Copyright (C) 2002-2009 Nicola Asuni - Tecnick.com S.r.l.
57 // This program is free software: you can redistribute it and/or modify
58 // it under the terms of the GNU Lesser General Public License as published by
59 // the Free Software Foundation, either version 2.1 of the License, or
60 // (at your option) any later version.
62 // This program is distributed in the hope that it will be useful,
63 // but WITHOUT ANY WARRANTY; without even the implied warranty of
64 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
65 // GNU Lesser General Public License for more details.
67 // You should have received a copy of the GNU Lesser General Public License
68 // along with this program. If not, see <http://www.gnu.org/licenses/>.
70 // See LICENSE.TXT file for more information.
71 // ----------------------------------------------------------------------------
73 // Description : This is a PHP class for generating PDF documents without
74 // requiring external extensions.
77 // This class was originally derived in 2002 from the Public
78 // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
79 // but now is almost entirely rewritten.
82 // * no external libraries are required for the basic functions;
83 // * supports all ISO page formats;
84 // * supports custom page formats, margins and units of measure;
85 // * supports UTF-8 Unicode and Right-To-Left languages;
86 // * supports TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;
87 // * supports document encryption;
88 // * includes methods to publish some XHTML code;
89 // * includes graphic (geometric) and transformation methods;
90 // * includes Javascript and forms support;
91 // * includes a method to print various barcode formats: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS;
92 // * includes methods to set Bookmarks and print a Table of Content;
93 // * includes methods to move and delete pages;
94 // * includes methods for automatic page header and footer management;
95 // * supports automatic page break;
96 // * supports automatic page numbering and page groups;
97 // * supports automatic line break and text justification;
98 // * supports JPEG and PNG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/www/formats.html)
99 // * supports stroke and clipping mode for text;
100 // * supports clipping masks;
101 // * supports Grayscale, RGB, CMYK, Spot Colors and Transparencies;
102 // * supports several annotations, including links, text and file attachments;
103 // * supports page compression (requires zlib extension);
104 // * supports text hyphenation.
105 // * supports transactions to UNDO commands.
107 // -----------------------------------------------------------
110 // Olivier Plathey (http://www.fpdf.org) for original FPDF.
111 // Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support.
112 // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm.
113 // Warren Sherliker (wsherliker@gmail.com) for better image handling.
114 // dullus for text Justification.
115 // Bob Vincent (pillarsdotnet@users.sourceforge.net) for <li> value attribute.
116 // Patrick Benny for text stretch suggestion on Cell().
117 // Johannes G�ntert for JavaScript support.
118 // Denis Van Nuffelen for Dynamic Form.
119 // Jacek Czekaj for multibyte justification
120 // Anthony Ferrara for the reintroduction of legacy image methods.
121 // Sourceforge user 1707880 (hucste) for line-trough mode.
122 // Larry Stanbery for page groups.
123 // Martin Hall-May for transparency.
124 // Aaron C. Spike for Polycurve method.
125 // Mohamad Ali Golkar, Saleh AlMatrafe, Charles Abbott for Arabic and Persian support.
126 // Moritz Wagner and Andreas Wurmser for graphic functions.
127 // Andrew Whitehead for core fonts support.
128 // Esteban Jo�l Mar�n for OpenType font conversion.
129 // Teus Hagen for several suggestions and fixes.
130 // Yukihiro Nakadaira for CID-0 CJK fonts fixes.
131 // Kosmas Papachristos for some CSS improvements.
132 // Marcel Partap for some fixes.
133 // Won Kyu Park for several suggestions, fixes and patches.
134 // Anyone that has reported a bug or sent a suggestion.
135 //============================================================+
138 * This is a PHP class for generating PDF documents without requiring external extensions.<br>
139 * TCPDF project (http://www.tcpdf.org) was originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
140 * <h3>TCPDF main features are:</h3>
142 * <li>no external libraries are required for the basic functions;</li>
143 * <li>supports all ISO page formats;</li>
144 * <li>supports custom page formats, margins and units of measure;</li>
145 * <li>supports UTF-8 Unicode and Right-To-Left languages;</li>
146 * <li>supports TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;</li>
147 * <li>supports document encryption;</li>
148 * <li>includes methods to publish some XHTML code;</li>
149 * <li>includes graphic (geometric) and transformation methods;</li>
150 * <li>includes Javascript and forms support;</li>
151 * <li>includes a method to print various barcode formats: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS;</li>
152 * <li>includes methods to set Bookmarks and print a Table of Content;</li>
153 * <li>includes methods to move and delete pages;</li>
154 * <li>includes methods for automatic page header and footer management;</li>
155 * <li>supports automatic page break;</li>
156 * <li>supports automatic page numbering and page groups;</li>
157 * <li>supports automatic line break and text justification;</li>
158 * <li>supports JPEG and PNG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/www/formats.html)</li>
159 * <li>supports stroke and clipping mode for text;</li>
160 * <li>supports clipping masks;</li>
161 * <li>supports Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
162 * <li>supports several annotations, including links, text and file attachments;</li>
163 * <li>supports page compression (requires zlib extension);</li>
164 * <li>supports text hyphenation.</li>
165 * <li>supports transactions to UNDO commands.</li>
167 * Tools to encode your unicode fonts are on fonts/utils directory.</p>
168 * @package com.tecnick.tcpdf
169 * @abstract Class for generating PDF files on-the-fly without requiring external extensions.
170 * @author Nicola Asuni
171 * @copyright 2002-2009 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
172 * @link http://www.tcpdf.org
173 * @license http://www.gnu.org/copyleft/lesser.html LGPL
178 * main configuration file
180 require_once(dirname(__FILE__).'/config/tcpdf_config.php');
182 // includes some support files
187 require_once(dirname(__FILE__).'/unicode_data.php');
192 require_once(dirname(__FILE__).'/htmlcolors.php');
194 if (!class_exists('TCPDF', false)) {
196 * define default PDF document producer
198 define('PDF_PRODUCER', 'TCPDF 4.6.013 (http://www.tcpdf.org)');
201 * This is a PHP class for generating PDF documents without requiring external extensions.<br>
202 * TCPDF project (http://www.tcpdf.org) has been originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
204 * @package com.tecnick.tcpdf
206 * @author Nicola Asuni - info@tecnick.com
207 * @link http://www.tcpdf.org
208 * @license http://www.gnu.org/copyleft/lesser.html LGPL
212 // protected or Protected properties
215 * @var current page number
221 * @var current object number
227 * @var array of object offsets
233 * @var buffer holding in-memory PDF
239 * @var array containing pages
242 protected $pages = array();
245 * @var current document state
251 * @var compression flag
257 * @var current page orientation (P = Portrait, L = Landscape)
260 protected $CurOrientation;
263 * @var array that stores page dimensions and graphic status.<ul><li>$this->pagedim[$this->page]['w'] => page_width_in_points</li><li>$this->pagedim[$this->page]['h'] => height in points</li><li>$this->pagedim[$this->page]['wk'] => page_width_in_points</li><li>$this->pagedim[$this->page]['hk'] => height</li><li>$this->pagedim[$this->page]['tm'] => top_margin</li><li>$this->pagedim[$this->page]['bm'] => bottom_margin</li><li>$this->pagedim[$this->page]['lm'] => left_margin</li><li>$this->pagedim[$this->page]['rm'] => right_margin</li><li>$this->pagedim[$this->page]['pb'] => auto_page_break</li><li>$this->pagedim[$this->page]['or'] => page_orientation</li><li>$this->pagedim[$this->page]['olm'] => original_left_margin</li><li>$this->pagedim[$this->page]['orm'] => original_right_margin</li></ul>
266 protected $pagedim = array();
269 * @var scale factor (number of points in user unit)
275 * @var width of page format in points
281 * @var height of page format in points
287 * @var current width of page in points
293 * @var current height of page in points
299 * @var current width of page in user unit
305 * @var current height of page in user unit
329 * @var page break margin
335 * @var cell internal padding
342 * @var cell internal padding (previous value)
345 protected $oldcMargin;
348 * @var current horizontal position in user unit for cell positioning
354 * @var current vertical position in user unit for cell positioning
360 * @var height of last cell printed
366 * @var line width in user unit
369 protected $LineWidth;
372 * @var array of standard font names
375 protected $CoreFonts;
378 * @var array of used fonts
381 protected $fonts = array();
384 * @var array of font files
387 protected $FontFiles = array();
390 * @var array of encoding differences
393 protected $diffs = array();
396 * @var array of used images
399 protected $images = array();
402 * @var array of Annotations in pages
405 protected $PageAnnots = array();
408 * @var array of internal links
411 protected $links = array();
414 * @var current font family
417 protected $FontFamily;
420 * @var current font style
423 protected $FontStyle;
426 * @var current font ascent (distance between font top and baseline)
428 * @since 2.8.000 (2007-03-29)
430 protected $FontAscent;
433 * @var current font descent (distance between font bottom and baseline)
435 * @since 2.8.000 (2007-03-29)
437 protected $FontDescent;
440 * @var underlining flag
443 protected $underline;
446 * @var current font info
449 protected $CurrentFont;
452 * @var current font size in points
455 protected $FontSizePt;
458 * @var current font size in user unit
464 * @var commands for drawing color
467 protected $DrawColor;
470 * @var commands for filling color
473 protected $FillColor;
476 * @var commands for text color
479 protected $TextColor;
482 * @var indicates whether fill and text colors are different
485 protected $ColorFlag;
488 * @var automatic page breaking
491 protected $AutoPageBreak;
494 * @var threshold used to trigger page breaks
497 protected $PageBreakTrigger;
500 * @var flag set when processing footer
503 protected $InFooter = false;
506 * @var zoom display mode
512 * @var layout display mode
515 protected $LayoutMode;
521 protected $title = '';
527 protected $subject = '';
533 protected $author = '';
539 protected $keywords = '';
545 protected $creator = '';
548 * @var alias for total number of pages
551 protected $AliasNbPages = '{nb}';
554 * @var alias for page number
557 protected $AliasNumPage = '{pnb}';
560 * @var right-bottom corner X coordinate of inserted image
562 * @author Nicola Asuni
568 * @var right-bottom corner Y coordinate of inserted image
570 * @author Nicola Asuni
576 * @var adjusting factor to convert pixels to user units.
578 * @author Nicola Asuni
581 protected $imgscale = 1;
584 * @var boolean set to true when the input text is unicode (require unicode fonts)
586 * @author Nicola Asuni
589 protected $isunicode = false;
596 protected $PDFVersion = '1.7';
599 // ----------------------
602 * @var Minimum distance between header and top page margin.
605 protected $header_margin;
608 * @var Minimum distance between footer and bottom page margin.
611 protected $footer_margin;
614 * @var original left margin value
616 * @since 1.53.0.TC013
618 protected $original_lMargin;
621 * @var original right margin value
623 * @since 1.53.0.TC013
625 protected $original_rMargin;
631 protected $header_font;
637 protected $footer_font;
640 * @var Language templates.
646 * @var Barcode to print on page footer (only if set).
649 protected $barcode = false;
652 * @var If true prints header
655 protected $print_header = true;
658 * @var If true prints footer.
661 protected $print_footer = true;
664 * @var Header image logo.
667 protected $header_logo = '';
670 * @var Header image logo width in mm.
673 protected $header_logo_width = 30;
676 * @var String to print as title on document header.
679 protected $header_title = '';
682 * @var String to print on document header.
685 protected $header_string = '';
688 * @var Default number of columns for html table.
691 protected $default_table_columns = 4;
694 // variables for html parser
697 * @var HTML PARSER: array to store current link and rendering styles.
700 protected $HREF = array();
703 * @var store a list of available fonts on filesystem.
706 protected $fontlist = array();
709 * @var current foreground color
715 * @var HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
718 protected $listordered = array();
721 * @var HTML PARSER: array count list items on nested lists.
724 protected $listcount = array();
727 * @var HTML PARSER: current list nesting level.
730 protected $listnum = 0;
733 * @var HTML PARSER: indent amount for lists.
736 protected $listindent;
739 * @var current background color
745 * @var Store temporary font size in points.
748 protected $tempfontsize = 10;
751 * @var spacer for LI tags.
754 protected $lispacer = '';
757 * @var default encoding
759 * @since 1.53.0.TC010
761 protected $encoding = 'UTF-8';
764 * @var PHP internal encoding
766 * @since 1.53.0.TC016
768 protected $internal_encoding;
771 * @var indicates if the document language is Right-To-Left
775 protected $rtl = false;
778 * @var used to force RTL or LTR string inversion
782 protected $tmprtl = false;
784 // --- Variables used for document encryption:
787 * Indicates whether document is protected
789 * @since 2.0.000 (2008-01-02)
791 protected $encrypted;
794 * U entry in pdf document
796 * @since 2.0.000 (2008-01-02)
801 * O entry in pdf document
803 * @since 2.0.000 (2008-01-02)
808 * P entry in pdf document
810 * @since 2.0.000 (2008-01-02)
815 * encryption object id
817 * @since 2.0.000 (2008-01-02)
819 protected $enc_obj_id;
822 * last RC4 key encrypted (cached for optimisation)
824 * @since 2.0.000 (2008-01-02)
826 protected $last_rc4_key;
829 * last RC4 computed key
831 * @since 2.0.000 (2008-01-02)
833 protected $last_rc4_key_c;
839 protected $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";
845 protected $encryption_key;
850 * Outlines for bookmark
852 * @since 2.1.002 (2008-02-12)
854 protected $outlines = array();
857 * Outline root for bookmark
859 * @since 2.1.002 (2008-02-12)
861 protected $OutlineRoot;
864 // --- javascript and form ---
869 * @since 2.1.002 (2008-02-12)
871 protected $javascript = '';
876 * @since 2.1.002 (2008-02-12)
883 * @since 2.8.000 (2008-03-19)
885 protected $linethrough;
887 // --- Variables used for User's Rights ---
888 // See PDF reference chapter 8.7 Digital Signatures
891 * If true enables user's rights on PDF reader
893 * @since 2.9.000 (2008-03-26)
898 * Names specifying additional document-wide usage rights for the document.
900 * @since 2.9.000 (2008-03-26)
902 protected $ur_document;
905 * Names specifying additional annotation-related usage rights for the document.
907 * @since 2.9.000 (2008-03-26)
909 protected $ur_annots;
912 * Names specifying additional form-field-related usage rights for the document.
914 * @since 2.9.000 (2008-03-26)
919 * Names specifying additional signature-related usage rights for the document.
921 * @since 2.9.000 (2008-03-26)
923 protected $ur_signature;
926 * Dot Per Inch Document Resolution (do not change)
928 * @since 3.0.000 (2008-03-27)
933 * Array of page numbers were a new page group was started
935 * @since 3.0.000 (2008-03-27)
937 protected $newpagegroup = array();
940 * Contains the number of pages of the groups
942 * @since 3.0.000 (2008-03-27)
944 protected $pagegroups;
947 * Contains the alias of the current page group
949 * @since 3.0.000 (2008-03-27)
951 protected $currpagegroup;
954 * Restrict the rendering of some elements to screen or printout.
956 * @since 3.0.000 (2008-03-27)
958 protected $visibility = 'all';
963 * @since 3.0.000 (2008-03-27)
965 protected $n_ocg_print;
970 * @since 3.0.000 (2008-03-27)
972 protected $n_ocg_view;
975 * Array of transparency objects and parameters.
977 * @since 3.0.000 (2008-03-27)
979 protected $extgstates;
982 * Set the default JPEG compression quality (1-100)
984 * @since 3.0.000 (2008-03-27)
986 protected $jpeg_quality;
989 * Default cell height ratio.
991 * @since 3.0.014 (2008-05-23)
993 protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
996 * PDF viewer preferences.
998 * @since 3.1.000 (2008-06-09)
1000 protected $viewer_preferences;
1003 * A name object specifying how the document should be displayed when opened.
1005 * @since 3.1.000 (2008-06-09)
1007 protected $PageMode;
1010 * Array for storing gradient information.
1012 * @since 3.1.000 (2008-06-09)
1014 protected $gradients = array();
1017 * Array used to store positions inside the pages buffer.
1018 * keys are the page numbers
1020 * @since 3.2.000 (2008-06-26)
1022 protected $intmrk = array();
1025 * Array used to store footer positions of each page.
1027 * @since 3.2.000 (2008-07-01)
1029 protected $footerpos = array();
1033 * Array used to store footer lenght of each page.
1035 * @since 4.0.014 (2008-07-29)
1037 protected $footerlen = array();
1040 * True if a newline is created.
1042 * @since 3.2.000 (2008-07-01)
1044 protected $newline = true;
1047 * End position of the latest inserted line
1049 * @since 3.2.000 (2008-07-01)
1051 protected $endlinex = 0;
1054 * PDF string for last line width
1056 * @since 4.0.006 (2008-07-16)
1058 protected $linestyleWidth = '';
1061 * PDF string for last line width
1063 * @since 4.0.006 (2008-07-16)
1065 protected $linestyleCap = '0 J';
1068 * PDF string for last line width
1070 * @since 4.0.006 (2008-07-16)
1072 protected $linestyleJoin = '0 j';
1075 * PDF string for last line width
1077 * @since 4.0.006 (2008-07-16)
1079 protected $linestyleDash = '[] 0 d';
1082 * True if marked-content sequence is open
1084 * @since 4.0.013 (2008-07-28)
1086 protected $openMarkedContent = false;
1089 * Count the latest inserted vertical spaces on HTML
1091 * @since 4.0.021 (2008-08-24)
1093 protected $htmlvspace = 0;
1096 * Array of Spot colors
1098 * @since 4.0.024 (2008-09-12)
1100 protected $spot_colors = array();
1103 * Symbol used for HTML unordered list items
1105 * @since 4.0.028 (2008-09-26)
1107 protected $lisymbol = '';
1110 * String used to mark the beginning and end of EPS image blocks
1112 * @since 4.1.000 (2008-10-18)
1114 protected $epsmarker = 'x#!#EPS#!#x';
1117 * Array of transformation matrix
1119 * @since 4.2.000 (2008-10-29)
1121 protected $transfmatrix = array();
1124 * Booklet mode for double-sided pages
1126 * @since 4.2.000 (2008-10-29)
1128 protected $booklet = false;
1131 * Epsilon value used for float calculations
1133 * @since 4.2.000 (2008-10-29)
1135 protected $feps = 0.001;
1138 * Array used for custom vertical spaces for HTML tags
1140 * @since 4.2.001 (2008-10-30)
1142 protected $tagvspaces = array();
1145 * @var HTML PARSER: custom indent amount for lists.
1146 * Negative value means disabled.
1148 * @since 4.2.007 (2008-11-12)
1150 protected $customlistindent = -1;
1153 * @var if true keeps the border open for the cell sides that cross the page.
1155 * @since 4.2.010 (2008-11-14)
1157 protected $opencell = true;
1160 * @var array of files to embedd
1162 * @since 4.4.000 (2008-12-07)
1164 protected $embeddedfiles = array();
1167 * @var boolean true when inside html pre tag
1169 * @since 4.4.001 (2008-12-08)
1171 protected $premode = false;
1174 * Array used to store positions of graphics transformation blocks inside the page buffer.
1175 * keys are the page numbers
1177 * @since 4.4.002 (2008-12-09)
1179 protected $transfmrk = array();
1182 * Default color for html links
1184 * @since 4.4.003 (2008-12-09)
1186 protected $htmlLinkColorArray = array(0, 0, 255);
1189 * Default font style to add to html links
1191 * @since 4.4.003 (2008-12-09)
1193 protected $htmlLinkFontStyle = 'U';
1196 * Counts the number of pages.
1198 * @since 4.5.000 (2008-12-31)
1200 protected $numpages = 0;
1203 * Array containing page lenghts in bytes.
1205 * @since 4.5.000 (2008-12-31)
1207 protected $pagelen = array();
1210 * Counts the number of pages.
1212 * @since 4.5.000 (2008-12-31)
1214 protected $numimages = 0;
1217 * Store the image keys.
1219 * @since 4.5.000 (2008-12-31)
1221 protected $imagekeys = array();
1224 * Lenght of the buffer in bytes.
1226 * @since 4.5.000 (2008-12-31)
1228 protected $bufferlen = 0;
1231 * If true enables disk caching.
1233 * @since 4.5.000 (2008-12-31)
1235 protected $diskcache = false;
1238 * Counts the number of fonts.
1240 * @since 4.5.000 (2009-01-02)
1242 protected $numfonts = 0;
1245 * Store the font keys.
1247 * @since 4.5.000 (2009-01-02)
1249 protected $fontkeys = array();
1252 * Store the fage status (true when opened, false when closed).
1254 * @since 4.5.000 (2009-01-02)
1256 protected $pageopen = array();
1259 * Default monospaced font
1261 * @since 4.5.025 (2009-03-10)
1263 protected $default_monospaced_font = 'courier';
1266 * Used to store a cloned copy of the current class object
1268 * @since 4.5.029 (2009-03-19)
1273 * Array used to store the lenghts of cache files
1275 * @since 4.5.029 (2009-03-19)
1277 protected $cache_file_lenght = array();
1280 * Table header content to be repeated on each new page
1282 * @since 4.5.030 (2009-03-20)
1284 protected $thead = '';
1287 * Distance between the top of page and end of table headers on a new page.
1289 * @since 4.5.030 (2009-03-20)
1291 protected $theadMargin = '';
1294 * Cache array for UTF8StringToArray() method.
1296 * @since 4.5.037 (2009-04-07)
1298 protected $cache_UTF8StringToArray = array();
1301 * Maximum size of cache array used for UTF8StringToArray() method.
1303 * @since 4.5.037 (2009-04-07)
1305 protected $cache_maxsize_UTF8StringToArray = 8;
1308 * Current size of cache array used for UTF8StringToArray() method.
1310 * @since 4.5.037 (2009-04-07)
1312 protected $cache_size_UTF8StringToArray = 0;
1315 * If true enables document signing
1317 * @since 4.6.005 (2009-04-24)
1319 protected $sign = false;
1324 * @since 4.6.005 (2009-04-24)
1326 protected $signature_data = array();
1329 * Signature max lenght
1331 * @since 4.6.005 (2009-04-24)
1333 protected $signature_max_lenght = 5120;
1336 * Regular expression used to find blank characters used for word-wrapping.
1338 * @since 4.6.006 (2009-04-28)
1340 protected $re_spaces = '/[\s\p{Z}\p{Lo}]/';
1342 //------------------------------------------------------------
1344 //------------------------------------------------------------
1347 * This is the class constructor.
1348 * It allows to set up the page format, the orientation and
1349 * the measure unit used in all the methods (except for the font sizes).
1351 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
1352 * @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.
1353 * @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>
1354 * @param boolean $unicode TRUE means that the input text is unicode (default = true)
1355 * @param boolean $diskcache if TRUE reduce the RAM memory usage by caching temporary data on filesystem (slower).
1356 * @param String $encoding charset encoding; default is UTF-8
1359 public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false) {
1360 /* Set internal character encoding to ASCII */
1361 if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
1362 $this->internal_encoding = mb_internal_encoding();
1363 mb_internal_encoding('ASCII');
1366 $this->diskcache = $diskcache ? true : false;
1367 // set language direction
1368 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
1369 $this->tmprtl = false;
1372 //Initialization of properties
1373 $this->isunicode = $unicode;
1375 $this->transfmrk[0] = array();
1376 $this->pagedim = array();
1379 $this->pages = array();
1381 $this->fonts = array();
1382 $this->FontFiles = array();
1383 $this->diffs = array();
1384 $this->images = array();
1385 $this->links = array();
1386 $this->gradients = array();
1387 $this->InFooter = false;
1389 $this->FontFamily = 'helvetica';
1390 $this->FontStyle = '';
1391 $this->FontSizePt = 12;
1392 $this->underline = false;
1393 $this->linethrough = false;
1394 $this->DrawColor = '0 G';
1395 $this->FillColor = '0 g';
1396 $this->TextColor = '0 g';
1397 $this->ColorFlag = false;
1398 // encryption values
1399 $this->encrypted = false;
1400 $this->last_rc4_key = '';
1401 $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";
1402 //Standard Unicode fonts
1403 $this->CoreFonts = array(
1404 'courier'=>'Courier',
1405 'courierB'=>'Courier-Bold',
1406 'courierI'=>'Courier-Oblique',
1407 'courierBI'=>'Courier-BoldOblique',
1408 'helvetica'=>'Helvetica',
1409 'helveticaB'=>'Helvetica-Bold',
1410 'helveticaI'=>'Helvetica-Oblique',
1411 'helveticaBI'=>'Helvetica-BoldOblique',
1412 'times'=>'Times-Roman',
1413 'timesB'=>'Times-Bold',
1414 'timesI'=>'Times-Italic',
1415 'timesBI'=>'Times-BoldItalic',
1417 'zapfdingbats'=>'ZapfDingbats'
1420 $this->setPageUnit($unit);
1421 // set page format and orientation
1422 $this->setPageFormat($format, $orientation);
1423 //Page margins (1 cm)
1424 $margin = 28.35 / $this->k;
1425 $this->SetMargins($margin, $margin);
1426 //Interior cell margin
1427 $this->cMargin = $margin / 10;
1428 //Line width (0.2 mm)
1429 $this->LineWidth = 0.57 / $this->k;
1430 $this->linestyleWidth = sprintf('%.2F w', ($this->LineWidth * $this->k));
1431 $this->linestyleCap = '0 J';
1432 $this->linestyleJoin = '0 j';
1433 $this->linestyleDash = '[] 0 d';
1434 //Automatic page break
1435 $this->SetAutoPageBreak(true, (2 * $margin));
1436 //Full width display mode
1437 $this->SetDisplayMode('fullwidth');
1439 $this->SetCompression(true);
1440 //Set default PDF version number
1441 $this->PDFVersion = '1.7';
1442 $this->encoding = $encoding;
1443 $this->HREF = array();
1444 $this->getFontsList();
1445 $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
1446 $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
1447 $this->extgstates = array();
1449 $this->sign = false;
1451 $this->ur_document = '/FullSave';
1452 $this->ur_annots = '/Create/Delete/Modify/Copy/Import/Export';
1453 $this->ur_form = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
1454 $this->ur_signature = '/Modify';
1455 // set default JPEG quality
1456 $this->jpeg_quality = 75;
1457 // initialize some settings
1458 $this->utf8Bidi(array(''), '');
1460 $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
1461 // check if PCRE Unicode support is enabled
1462 if (@preg_match('/\pL/u', 'a') == 1) {
1463 // PCRE unicode support is turned ON
1464 // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
1465 // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
1466 // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
1467 $this->re_spaces = '/[\s\p{Z}\p{Lo}]/';
1469 // PCRE unicode support is turned OFF
1470 $this->re_spaces = '/[\s]/';
1475 * Default destructor.
1477 * @since 1.53.0.TC016
1479 public function __destruct() {
1480 // restore internal encoding
1481 if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
1482 mb_internal_encoding($this->internal_encoding);
1484 // unset all class variables
1485 $this->_destroy(true);
1489 * This is needed to prevent unserialize vulnerability
1491 public function __wakeup()
1493 // clean all properties
1494 foreach(get_object_vars($this) as $k => $v) {
1497 throw new Exception("Not a serializable object");
1501 * Set the units of measure for the document.
1502 * @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.
1504 * @since 3.0.015 (2008-06-06)
1506 public function setPageUnit($unit) {
1508 switch (strtolower($unit)) {
1517 $this->k = $this->dpi / 25.4;
1522 $this->k = $this->dpi / 2.54;
1527 $this->k = $this->dpi;
1532 $this->Error('Incorrect unit: '.$unit);
1536 if (isset($this->CurOrientation)) {
1537 $this->setPageOrientation($this->CurOrientation);
1542 * Set the page format
1543 * @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>
1544 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1546 * @since 3.0.015 (2008-06-06)
1548 public function setPageFormat($format, $orientation='P') {
1550 if (is_string($format)) {
1551 // Page formats (45 standard ISO paper formats and 4 american common formats).
1552 // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm)
1553 switch (strtoupper($format)) {
1554 case '4A0': {$format = array(4767.87,6740.79); break;}
1555 case '2A0': {$format = array(3370.39,4767.87); break;}
1556 case 'A0': {$format = array(2383.94,3370.39); break;}
1557 case 'A1': {$format = array(1683.78,2383.94); break;}
1558 case 'A2': {$format = array(1190.55,1683.78); break;}
1559 case 'A3': {$format = array(841.89,1190.55); break;}
1560 case 'A4': default: {$format = array(595.28,841.89); break;}
1561 case 'A5': {$format = array(419.53,595.28); break;}
1562 case 'A6': {$format = array(297.64,419.53); break;}
1563 case 'A7': {$format = array(209.76,297.64); break;}
1564 case 'A8': {$format = array(147.40,209.76); break;}
1565 case 'A9': {$format = array(104.88,147.40); break;}
1566 case 'A10': {$format = array(73.70,104.88); break;}
1567 case 'B0': {$format = array(2834.65,4008.19); break;}
1568 case 'B1': {$format = array(2004.09,2834.65); break;}
1569 case 'B2': {$format = array(1417.32,2004.09); break;}
1570 case 'B3': {$format = array(1000.63,1417.32); break;}
1571 case 'B4': {$format = array(708.66,1000.63); break;}
1572 case 'B5': {$format = array(498.90,708.66); break;}
1573 case 'B6': {$format = array(354.33,498.90); break;}
1574 case 'B7': {$format = array(249.45,354.33); break;}
1575 case 'B8': {$format = array(175.75,249.45); break;}
1576 case 'B9': {$format = array(124.72,175.75); break;}
1577 case 'B10': {$format = array(87.87,124.72); break;}
1578 case 'C0': {$format = array(2599.37,3676.54); break;}
1579 case 'C1': {$format = array(1836.85,2599.37); break;}
1580 case 'C2': {$format = array(1298.27,1836.85); break;}
1581 case 'C3': {$format = array(918.43,1298.27); break;}
1582 case 'C4': {$format = array(649.13,918.43); break;}
1583 case 'C5': {$format = array(459.21,649.13); break;}
1584 case 'C6': {$format = array(323.15,459.21); break;}
1585 case 'C7': {$format = array(229.61,323.15); break;}
1586 case 'C8': {$format = array(161.57,229.61); break;}
1587 case 'C9': {$format = array(113.39,161.57); break;}
1588 case 'C10': {$format = array(79.37,113.39); break;}
1589 case 'RA0': {$format = array(2437.80,3458.27); break;}
1590 case 'RA1': {$format = array(1729.13,2437.80); break;}
1591 case 'RA2': {$format = array(1218.90,1729.13); break;}
1592 case 'RA3': {$format = array(864.57,1218.90); break;}
1593 case 'RA4': {$format = array(609.45,864.57); break;}
1594 case 'SRA0': {$format = array(2551.18,3628.35); break;}
1595 case 'SRA1': {$format = array(1814.17,2551.18); break;}
1596 case 'SRA2': {$format = array(1275.59,1814.17); break;}
1597 case 'SRA3': {$format = array(907.09,1275.59); break;}
1598 case 'SRA4': {$format = array(637.80,907.09); break;}
1599 case 'LETTER': {$format = array(612.00,792.00); break;}
1600 case 'LEGAL': {$format = array(612.00,1008.00); break;}
1601 case 'EXECUTIVE': {$format = array(521.86,756.00); break;}
1602 case 'FOLIO': {$format = array(612.00,936.00); break;}
1604 $this->fwPt = $format[0];
1605 $this->fhPt = $format[1];
1607 $this->fwPt = $format[0] * $this->k;
1608 $this->fhPt = $format[1] * $this->k;
1610 $this->setPageOrientation($orientation);
1614 * Set page orientation.
1615 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1616 * @param boolean $autopagebreak Boolean indicating if auto-page-break mode should be on or off.
1617 * @param float $bottommargin bottom margin of the page.
1619 * @since 3.0.015 (2008-06-06)
1621 public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
1622 $orientation = strtoupper($orientation);
1623 if (($orientation == 'P') OR ($orientation == 'PORTRAIT')) {
1624 $this->CurOrientation = 'P';
1625 $this->wPt = $this->fwPt;
1626 $this->hPt = $this->fhPt;
1627 } elseif (($orientation == 'L') OR ($orientation == 'LANDSCAPE')) {
1628 $this->CurOrientation = 'L';
1629 $this->wPt = $this->fhPt;
1630 $this->hPt = $this->fwPt;
1632 $this->Error('Incorrect orientation: '.$orientation);
1634 $this->w = $this->wPt / $this->k;
1635 $this->h = $this->hPt / $this->k;
1636 if ($this->empty_string($autopagebreak)) {
1637 if (isset($this->AutoPageBreak)) {
1638 $autopagebreak = $this->AutoPageBreak;
1640 $autopagebreak = true;
1643 if ($this->empty_string($bottommargin)) {
1644 if (isset($this->bMargin)) {
1645 $bottommargin = $this->bMargin;
1647 // default value = 2 cm
1648 $bottommargin = 2 * 28.35 / $this->k;
1651 $this->SetAutoPageBreak($autopagebreak, $bottommargin);
1652 // store page dimensions
1653 $this->pagedim[$this->page] = array('w' => $this->wPt, 'h' => $this->hPt, 'wk' => $this->w, 'hk' => $this->h, 'tm' => $this->tMargin, 'bm' => $bottommargin, 'lm' => $this->lMargin, 'rm' => $this->rMargin, 'pb' => $autopagebreak, 'or' => $this->CurOrientation, 'olm' => $this->original_lMargin, 'orm' => $this->original_rMargin);
1657 * Enable or disable Right-To-Left language mode
1658 * @param Boolean $enable if true enable Right-To-Left language mode.
1660 * @since 2.0.000 (2008-01-03)
1662 public function setRTL($enable) {
1663 $this->rtl = $enable ? true : false;
1664 $this->tmprtl = false;
1668 * Return the RTL status
1671 * @since 4.0.012 (2008-07-24)
1673 public function getRTL() {
1678 * Force temporary RTL language direction
1679 * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL
1681 * @since 2.1.000 (2008-01-09)
1683 public function setTempRTL($mode) {
1688 $this->tmprtl = $mode;
1694 * Set the last cell height.
1695 * @param float $h cell height.
1696 * @author Nicola Asuni
1698 * @since 1.53.0.TC034
1700 public function setLastH($h) {
1705 * Get the last cell height.
1706 * @return last cell height
1708 * @since 4.0.017 (2008-08-05)
1710 public function getLastH() {
1711 return $this->lasth;
1715 * Set the adjusting factor to convert pixels to user units.
1716 * @param float $scale adjusting factor to convert pixels to user units.
1717 * @author Nicola Asuni
1721 public function setImageScale($scale) {
1722 $this->imgscale = $scale;
1726 * Returns the adjusting factor to convert pixels to user units.
1727 * @return float adjusting factor to convert pixels to user units.
1728 * @author Nicola Asuni
1732 public function getImageScale() {
1733 return $this->imgscale;
1737 * Returns an array of page dimensions:
1738 * <ul><li>$this->pagedim[$this->page]['w'] => page_width_in_points</li><li>$this->pagedim[$this->page]['h'] => height in points</li><li>$this->pagedim[$this->page]['wk'] => page_width_in_points</li><li>$this->pagedim[$this->page]['hk'] => height</li><li>$this->pagedim[$this->page]['tm'] => top_margin</li><li>$this->pagedim[$this->page]['bm'] => bottom_margin</li><li>$this->pagedim[$this->page]['lm'] => left_margin</li><li>$this->pagedim[$this->page]['rm'] => right_margin</li><li>$this->pagedim[$this->page]['pb'] => auto_page_break</li><li>$this->pagedim[$this->page]['or'] => page_orientation</li><li>$this->pagedim[$this->page]['olm'] => original_left_margin</li><li>$this->pagedim[$this->page]['orm'] => original_right_margin</li></ul>
1739 * @param int $pagenum page number (empty = current page)
1740 * @return array of page dimensions.
1741 * @author Nicola Asuni
1743 * @since 4.5.027 (2009-03-16)
1745 public function getPageDimensions($pagenum='') {
1746 if (empty($pagenum)) {
1747 $pagenum = $this->page;
1749 return $this->pagedim[$pagenum];
1753 * Returns the page width in units.
1754 * @param int $pagenum page number (empty = current page)
1755 * @return int page width.
1756 * @author Nicola Asuni
1759 * @see getPageDimensions()
1761 public function getPageWidth($pagenum='') {
1762 if (empty($pagenum)) {
1765 return $this->pagedim[$pagenum]['w'];
1769 * Returns the page height in units.
1770 * @param int $pagenum page number (empty = current page)
1771 * @return int page height.
1772 * @author Nicola Asuni
1775 * @see getPageDimensions()
1777 public function getPageHeight($pagenum='') {
1778 if (empty($pagenum)) {
1781 return $this->pagedim[$pagenum]['h'];
1785 * Returns the page break margin.
1786 * @param int $pagenum page number (empty = current page)
1787 * @return int page break margin.
1788 * @author Nicola Asuni
1791 * @see getPageDimensions()
1793 public function getBreakMargin($pagenum='') {
1794 if (empty($pagenum)) {
1795 return $this->bMargin;
1797 return $this->pagedim[$pagenum]['bm'];
1801 * Returns the scale factor (number of points in user unit).
1802 * @return int scale factor.
1803 * @author Nicola Asuni
1807 public function getScaleFactor() {
1812 * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
1813 * @param float $left Left margin.
1814 * @param float $top Top margin.
1815 * @param float $right Right margin. Default value is the left one.
1818 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
1820 public function SetMargins($left, $top, $right=-1) {
1821 //Set left, top and right margins
1822 $this->lMargin = $left;
1823 $this->tMargin = $top;
1827 $this->rMargin = $right;
1831 * 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.
1832 * @param float $margin The margin.
1835 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1837 public function SetLeftMargin($margin) {
1839 $this->lMargin=$margin;
1840 if (($this->page > 0) AND ($this->x < $margin)) {
1846 * Defines the top margin. The method can be called before creating the first page.
1847 * @param float $margin The margin.
1850 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1852 public function SetTopMargin($margin) {
1854 $this->tMargin=$margin;
1855 if (($this->page > 0) AND ($this->y < $margin)) {
1861 * Defines the right margin. The method can be called before creating the first page.
1862 * @param float $margin The margin.
1865 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1867 public function SetRightMargin($margin) {
1868 $this->rMargin=$margin;
1869 if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
1870 $this->x = $this->w - $margin;
1875 * Set the internal Cell padding.
1876 * @param float $pad internal padding.
1878 * @since 2.1.000 (2008-01-09)
1879 * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1881 public function SetCellPadding($pad) {
1882 $this->cMargin = $pad;
1886 * 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.
1887 * @param boolean $auto Boolean indicating if mode should be on or off.
1888 * @param float $margin Distance from the bottom of the page.
1891 * @see Cell(), MultiCell(), AcceptPageBreak()
1893 public function SetAutoPageBreak($auto, $margin=0) {
1894 //Set auto page break mode and triggering margin
1895 $this->AutoPageBreak = $auto;
1896 $this->bMargin = $margin;
1897 $this->PageBreakTrigger = $this->h - $margin;
1901 * Defines the way the document is to be displayed by the viewer.
1902 * @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>
1903 * @param string $layout The page layout. Possible values are:<ul><li>SinglePage Display one page at a time</li><li>OneColumn Display the pages in one column</li><li>TwoColumnLeft Display the pages in two columns, with odd-numbered pages on the left</li><li>TwoColumnRight Display the pages in two columns, with odd-numbered pages on the right</li><li>TwoPageLeft (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the left</li><li>TwoPageRight (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the right</li></ul>
1904 * @param string $mode A name object specifying how the document should be displayed when opened:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>FullScreen Full-screen mode, with no menu bar, window controls, or any other window visible</li><li>UseOC (PDF 1.5) Optional content group panel visible</li><li>UseAttachments (PDF 1.6) Attachments panel visible</li></ul>
1908 public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
1909 //Set display mode in viewer
1910 if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
1911 $this->ZoomMode = $zoom;
1913 $this->Error('Incorrect zoom display mode: '.$zoom);
1918 case 'SinglePage': {
1919 $this->LayoutMode = 'SinglePage';
1924 $this->LayoutMode = 'OneColumn';
1928 case 'TwoColumnLeft': {
1929 $this->LayoutMode = 'TwoColumnLeft';
1932 case 'TwoColumnRight': {
1933 $this->LayoutMode = 'TwoColumnRight';
1936 case 'TwoPageLeft': {
1937 $this->LayoutMode = 'TwoPageLeft';
1940 case 'TwoPageRight': {
1941 $this->LayoutMode = 'TwoPageRight';
1945 $this->LayoutMode = 'SinglePage';
1950 $this->PageMode = 'UseNone';
1953 case 'UseOutlines': {
1954 $this->PageMode = 'UseOutlines';
1958 $this->PageMode = 'UseThumbs';
1961 case 'FullScreen': {
1962 $this->PageMode = 'FullScreen';
1966 $this->PageMode = 'UseOC';
1970 $this->PageMode = 'UseAttachments';
1974 $this->PageMode = 'UseNone';
1980 * 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.
1981 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
1982 * @param boolean $compress Boolean indicating if compression must be enabled.
1986 public function SetCompression($compress) {
1987 //Set page compression
1988 if (function_exists('gzcompress')) {
1989 $this->compress = $compress;
1991 $this->compress = false;
1996 * Defines the title of the document.
1997 * @param string $title The title.
2000 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
2002 public function SetTitle($title) {
2004 $this->title = $title;
2008 * Defines the subject of the document.
2009 * @param string $subject The subject.
2012 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
2014 public function SetSubject($subject) {
2015 //Subject of document
2016 $this->subject = $subject;
2020 * Defines the author of the document.
2021 * @param string $author The name of the author.
2024 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
2026 public function SetAuthor($author) {
2027 //Author of document
2028 $this->author = $author;
2032 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
2033 * @param string $keywords The list of keywords.
2036 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
2038 public function SetKeywords($keywords) {
2039 //Keywords of document
2040 $this->keywords = $keywords;
2044 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
2045 * @param string $creator The name of the creator.
2048 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
2050 public function SetCreator($creator) {
2051 //Creator of document
2052 $this->creator = $creator;
2056 * 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.
2057 * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
2058 * @param string $msg The error message
2062 public function Error($msg) {
2063 // unset all class variables
2064 $this->_destroy(true);
2065 // exit program and print error
2066 die('<strong>TCPDF ERROR: </strong>'.$msg);
2070 * This method begins the generation of the PDF document.
2071 * It is not necessary to call it explicitly because AddPage() does it automatically.
2072 * Note: no page is created by this method
2075 * @see AddPage(), Close()
2077 public function Open() {
2083 * Terminates the PDF document.
2084 * It is not necessary to call this method explicitly because Output() does it automatically.
2085 * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
2088 * @see Open(), Output()
2090 public function Close() {
2091 if ($this->state == 3) {
2094 if ($this->page == 0) {
2101 // unset all class variables (except critical ones)
2102 $this->_destroy(false);
2106 * Move pointer at the specified document page and update page dimensions.
2107 * @param int $pnum page number
2108 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
2110 * @since 2.1.000 (2008-01-07)
2111 * @see getPage(), lastpage(), getNumPages()
2113 public function setPage($pnum, $resetmargins=false) {
2114 if ($pnum == $this->page) {
2117 if (($pnum > 0) AND ($pnum <= $this->numpages)) {
2119 // save current graphic settings
2120 //$gvars = $this->getGraphicVars();
2121 $oldpage = $this->page;
2122 $this->page = $pnum;
2123 $this->wPt = $this->pagedim[$this->page]['w'];
2124 $this->hPt = $this->pagedim[$this->page]['h'];
2125 $this->w = $this->wPt / $this->k;
2126 $this->h = $this->hPt / $this->k;
2127 $this->tMargin = $this->pagedim[$this->page]['tm'];
2128 $this->bMargin = $this->pagedim[$this->page]['bm'];
2129 $this->original_lMargin = $this->pagedim[$this->page]['olm'];
2130 $this->original_rMargin = $this->pagedim[$this->page]['orm'];
2131 $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
2132 $this->CurOrientation = $this->pagedim[$this->page]['or'];
2133 $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
2134 // restore graphic settings
2135 //$this->setGraphicVars($gvars);
2136 if ($resetmargins) {
2137 $this->lMargin = $this->pagedim[$this->page]['olm'];
2138 $this->rMargin = $this->pagedim[$this->page]['orm'];
2139 $this->SetY($this->tMargin);
2141 // account for booklet mode
2142 if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
2143 $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
2144 $this->lMargin += $deltam;
2145 $this->rMargin -= $deltam;
2149 $this->Error('Wrong page number on setPage() function.');
2154 * Reset pointer to the last document page.
2155 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
2157 * @since 2.0.000 (2008-01-04)
2158 * @see setPage(), getPage(), getNumPages()
2160 public function lastPage($resetmargins=false) {
2161 $this->setPage($this->getNumPages(), $resetmargins);
2165 * Get current document page number.
2166 * @return int page number
2168 * @since 2.1.000 (2008-01-07)
2169 * @see setPage(), lastpage(), getNumPages()
2171 public function getPage() {
2177 * Get the total number of insered pages.
2178 * @return int number of pages
2180 * @since 2.1.000 (2008-01-07)
2181 * @see setPage(), getPage(), lastpage()
2183 public function getNumPages() {
2184 return $this->numpages;
2188 * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer (if enabled). Then the page is added, the current position set to the top-left corner according to the left and top margins (or top-right if in RTL mode), and Header() is called to display the header (if enabled).
2189 * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
2190 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
2191 * @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>
2194 * @see startPage(), endPage()
2196 public function AddPage($orientation='', $format='') {
2197 if (!isset($this->original_lMargin)) {
2198 $this->original_lMargin = $this->lMargin;
2200 if (!isset($this->original_rMargin)) {
2201 $this->original_rMargin = $this->rMargin;
2203 // terminate previous page
2206 $this->startPage($orientation, $format);
2210 * Terminate the current page
2212 * @since 4.2.010 (2008-11-14)
2213 * @see startPage(), AddPage()
2215 protected function endPage() {
2216 // check if page is already closed
2217 if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
2220 $this->InFooter = true;
2221 // print page footer
2225 // mark page as closed
2226 $this->pageopen[$this->page] = false;
2227 $this->InFooter = false;
2231 * Starts a new page to the document. The page must be closed using the endPage() function.
2232 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
2233 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
2234 * @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>
2236 * @since 4.2.010 (2008-11-14)
2237 * @see endPage(), AddPage()
2239 protected function startPage($orientation='', $format='') {
2240 if ($this->numpages > $this->page) {
2241 // this page has been already added
2242 $this->setPage($this->page + 1);
2243 $this->SetY($this->tMargin);
2247 if ($this->state == 0) {
2251 $this->swapMargins($this->booklet);
2252 // save current graphic settings
2253 $gvars = $this->getGraphicVars();
2255 $this->_beginpage($orientation, $format);
2256 // mark page as open
2257 $this->pageopen[$this->page] = true;
2258 // restore graphic settings
2259 $this->setGraphicVars($gvars);
2261 $this->setPageMark();
2262 // print page header
2264 // restore graphic settings
2265 $this->setGraphicVars($gvars);
2267 $this->setPageMark();
2268 // print table header (if any)
2269 $this->setTableHeader();
2273 * Set start-writing mark on current page for multicell borders and fills.
2274 * This function must be called after calling Image() function for a background image.
2275 * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
2277 * @since 4.0.016 (2008-07-30)
2279 public function setPageMark() {
2280 $this->intmrk[$this->page] = $this->pagelen[$this->page];
2285 * @param string $ln header image logo
2286 * @param string $lw header image logo width in mm
2287 * @param string $ht string to print as title on document header
2288 * @param string $hs string to print on document header
2291 public function setHeaderData($ln='', $lw=0, $ht='', $hs='') {
2292 $this->header_logo = $ln;
2293 $this->header_logo_width = $lw;
2294 $this->header_title = $ht;
2295 $this->header_string = $hs;
2299 * Returns header data:
2300 * <ul><li>$ret['logo'] = logo image</li><li>$ret['logo_width'] = width of the image logo in user units</li><li>$ret['title'] = header title</li><li>$ret['string'] = header description string</li></ul>
2303 * @since 4.0.012 (2008-07-24)
2305 public function getHeaderData() {
2307 $ret['logo'] = $this->header_logo;
2308 $ret['logo_width'] = $this->header_logo_width;
2309 $ret['title'] = $this->header_title;
2310 $ret['string'] = $this->header_string;
2315 * Set header margin.
2316 * (minimum distance between header and top page margin)
2317 * @param int $hm distance in user units
2320 public function setHeaderMargin($hm=10) {
2321 $this->header_margin = $hm;
2325 * Returns header margin in user units.
2327 * @since 4.0.012 (2008-07-24)
2330 public function getHeaderMargin() {
2331 return $this->header_margin;
2335 * Set footer margin.
2336 * (minimum distance between footer and bottom page margin)
2337 * @param int $fm distance in user units
2340 public function setFooterMargin($fm=10) {
2341 $this->footer_margin = $fm;
2345 * Returns footer margin in user units.
2347 * @since 4.0.012 (2008-07-24)
2350 public function getFooterMargin() {
2351 return $this->footer_margin;
2354 * Set a flag to print page header.
2355 * @param boolean $val set to true to print the page header (default), false otherwise.
2358 public function setPrintHeader($val=true) {
2359 $this->print_header = $val;
2363 * Set a flag to print page footer.
2364 * @param boolean $value set to true to print the page footer (default), false otherwise.
2367 public function setPrintFooter($val=true) {
2368 $this->print_footer = $val;
2372 * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
2376 public function getImageRBX() {
2377 return $this->img_rb_x;
2381 * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
2385 public function getImageRBY() {
2386 return $this->img_rb_y;
2390 * This method is used to render the page header.
2391 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2394 public function Header() {
2395 $ormargins = $this->getOriginalMargins();
2396 $headerfont = $this->getHeaderFont();
2397 $headerdata = $this->getHeaderData();
2398 if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
2399 $this->Image(K_PATH_IMAGES.$headerdata['logo'], $this->GetX(), $this->getHeaderMargin(), $headerdata['logo_width']);
2400 $imgy = $this->getImageRBY();
2402 $imgy = $this->GetY();
2404 $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2);
2405 // set starting margin for text data cell
2406 if ($this->getRTL()) {
2407 $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1);
2409 $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1);
2411 $this->SetTextColor(0, 0, 0);
2413 $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
2414 $this->SetX($header_x);
2415 $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
2417 $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
2418 $this->SetX($header_x);
2419 $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false);
2420 // print an ending header line
2421 $this->SetLineStyle(array('width' => 0.85 / $this->getScaleFactor(), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
2422 $this->SetY((2.835 / $this->getScaleFactor()) + max($imgy, $this->GetY()));
2423 if ($this->getRTL()) {
2424 $this->SetX($ormargins['right']);
2426 $this->SetX($ormargins['left']);
2428 $this->Cell(0, 0, '', 'T', 0, 'C');
2432 * This method is used to render the page footer.
2433 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2436 public function Footer() {
2437 $cur_y = $this->GetY();
2438 $ormargins = $this->getOriginalMargins();
2439 $this->SetTextColor(0, 0, 0);
2440 //set style for cell border
2441 $line_width = 0.85 / $this->getScaleFactor();
2442 $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
2443 //print document barcode
2444 $barcode = $this->getBarcode();
2445 if (!empty($barcode)) {
2446 $this->Ln($line_width);
2447 $barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right'])/3);
2448 $this->write1DBarcode($barcode, 'C128B', $this->GetX(), $cur_y + $line_width, $barcode_width, (($this->getFooterMargin() / 3) - $line_width), 0.3, '', '');
2450 if (empty($this->pagegroups)) {
2451 $pagenumtxt = $this->l['w_page'].' '.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
2453 $pagenumtxt = $this->l['w_page'].' '.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
2455 $this->SetY($cur_y);
2457 if ($this->getRTL()) {
2458 $this->SetX($ormargins['right']);
2459 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
2461 $this->SetX($ormargins['left']);
2462 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R');
2467 * This method is used to render the page header.
2469 * @since 4.0.012 (2008-07-24)
2471 protected function setHeader() {
2472 if ($this->print_header) {
2473 $lasth = $this->lasth;
2475 $this->rMargin = $this->original_rMargin;
2476 $this->lMargin = $this->original_lMargin;
2478 //set current position
2480 $this->SetXY($this->original_rMargin, $this->header_margin);
2482 $this->SetXY($this->original_lMargin, $this->header_margin);
2484 $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
2488 $this->SetXY($this->original_rMargin, $this->tMargin);
2490 $this->SetXY($this->original_lMargin, $this->tMargin);
2493 $this->lasth = $lasth;
2498 * This method is used to render the page footer.
2500 * @since 4.0.012 (2008-07-24)
2502 protected function setFooter() {
2504 // save current graphic settings
2505 $gvars = $this->getGraphicVars();
2507 $this->footerpos[$this->page] = $this->pagelen[$this->page];
2509 if ($this->print_footer) {
2510 $lasth = $this->lasth;
2512 $this->rMargin = $this->original_rMargin;
2513 $this->lMargin = $this->original_lMargin;
2515 //set current position
2516 $footer_y = $this->h - $this->footer_margin;
2518 $this->SetXY($this->original_rMargin, $footer_y);
2520 $this->SetXY($this->original_lMargin, $footer_y);
2522 $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
2526 $this->SetXY($this->original_rMargin, $this->tMargin);
2528 $this->SetXY($this->original_lMargin, $this->tMargin);
2531 $this->lasth = $lasth;
2533 // restore graphic settings
2534 $this->setGraphicVars($gvars);
2535 // calculate footer lenght
2536 $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
2540 * This method is used to render the table header on new page (if any).
2542 * @since 4.5.030 (2009-03-25)
2544 protected function setTableHeader() {
2545 if (!$this->empty_string($this->theadMargin)) {
2546 // restore the original top-margin
2547 $this->tMargin = $this->theadMargin;
2548 $this->pagedim[$this->page]['tm'] = $this->theadMargin;
2549 $this->y = $this->theadMargin;
2551 if (!$this->empty_string($this->thead)) {
2552 // print table header
2553 $this->writeHTML($this->thead, false, false, false, false, '');
2554 // set new top margin to skip the table headers
2555 if (!isset($this->theadMargin) OR ($this->empty_string($this->theadMargin))) {
2556 $this->theadMargin = $this->tMargin;
2558 $this->tMargin = $this->y;
2559 $this->pagedim[$this->page]['tm'] = $this->tMargin;
2564 * Returns the current page number.
2565 * @return int page number
2568 * @see AliasNbPages(), getAliasNbPages()
2570 public function PageNo() {
2575 * Defines a new spot color.
2576 * It can be expressed in RGB components or gray scale.
2577 * The method can be called before the first page is created and the value is retained from page to page.
2578 * @param int $c Cyan color for CMYK. Value between 0 and 255
2579 * @param int $m Magenta color for CMYK. Value between 0 and 255
2580 * @param int $y Yellow color for CMYK. Value between 0 and 255
2581 * @param int $k Key (Black) color for CMYK. Value between 0 and 255
2583 * @since 4.0.024 (2008-09-12)
2584 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2586 public function AddSpotColor($name, $c, $m, $y, $k) {
2587 if (!isset($this->spot_colors[$name])) {
2588 $i = 1 + count($this->spot_colors);
2589 $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k);
2594 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
2595 * It can be expressed in RGB components or gray scale.
2596 * The method can be called before the first page is created and the value is retained from page to page.
2597 * @param array $color array of colors
2599 * @since 3.1.000 (2008-06-11)
2600 * @see SetDrawColor()
2602 public function SetDrawColorArray($color) {
2603 if (isset($color)) {
2604 $color = array_values($color);
2605 $r = isset($color[0]) ? $color[0] : -1;
2606 $g = isset($color[1]) ? $color[1] : -1;
2607 $b = isset($color[2]) ? $color[2] : -1;
2608 $k = isset($color[3]) ? $color[3] : -1;
2610 $this->SetDrawColor($r, $g, $b, $k);
2616 * 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.
2617 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2618 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2619 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2620 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2623 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
2625 public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2626 // set default values
2627 if (!is_numeric($col1)) {
2630 if (!is_numeric($col2)) {
2633 if (!is_numeric($col3)) {
2636 if (!is_numeric($col4)) {
2639 //Set color for all stroking operations
2640 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2642 $this->DrawColor = sprintf('%.3F G', $col1/255);
2643 } elseif ($col4 == -1) {
2645 $this->DrawColor = sprintf('%.3F %.3F %.3F RG', $col1/255, $col2/255, $col3/255);
2648 $this->DrawColor = sprintf('%.3F %.3F %.3F %.3F K', $col1/100, $col2/100, $col3/100, $col4/100);
2650 if ($this->page > 0) {
2651 $this->_out($this->DrawColor);
2656 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
2657 * @param string $name name of the spot color
2658 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2660 * @since 4.0.024 (2008-09-12)
2661 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2663 public function SetDrawSpotColor($name, $tint=100) {
2664 if (!isset($this->spot_colors[$name])) {
2665 $this->Error('Undefined spot color: '.$name);
2667 $this->DrawColor = sprintf('/CS%d CS %.3F SCN', $this->spot_colors[$name]['i'], $tint/100);
2668 if ($this->page > 0) {
2669 $this->_out($this->DrawColor);
2674 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
2675 * It can be expressed in RGB components or gray scale.
2676 * The method can be called before the first page is created and the value is retained from page to page.
2677 * @param array $color array of colors
2679 * @since 3.1.000 (2008-6-11)
2680 * @see SetFillColor()
2682 public function SetFillColorArray($color) {
2683 if (isset($color)) {
2684 $color = array_values($color);
2685 $r = isset($color[0]) ? $color[0] : -1;
2686 $g = isset($color[1]) ? $color[1] : -1;
2687 $b = isset($color[2]) ? $color[2] : -1;
2688 $k = isset($color[3]) ? $color[3] : -1;
2690 $this->SetFillColor($r, $g, $b, $k);
2696 * 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.
2697 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2698 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2699 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2700 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2703 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
2705 public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2706 // set default values
2707 if (!is_numeric($col1)) {
2710 if (!is_numeric($col2)) {
2713 if (!is_numeric($col3)) {
2716 if (!is_numeric($col4)) {
2719 //Set color for all filling operations
2720 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2722 $this->FillColor = sprintf('%.3F g', $col1/255);
2723 $this->bgcolor = array('G' => $col1);
2724 } elseif ($col4 == -1) {
2726 $this->FillColor = sprintf('%.3F %.3F %.3F rg', $col1/255, $col2/255, $col3/255);
2727 $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2730 $this->FillColor = sprintf('%.3F %.3F %.3F %.3F k', $col1/100, $col2/100, $col3/100, $col4/100);
2731 $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2733 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2734 if ($this->page > 0) {
2735 $this->_out($this->FillColor);
2740 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
2741 * @param string $name name of the spot color
2742 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2744 * @since 4.0.024 (2008-09-12)
2745 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
2747 public function SetFillSpotColor($name, $tint=100) {
2748 if (!isset($this->spot_colors[$name])) {
2749 $this->Error('Undefined spot color: '.$name);
2751 $this->FillColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], $tint/100);
2752 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2753 if ($this->page > 0) {
2754 $this->_out($this->FillColor);
2759 * Defines the color used for text. It can be expressed in RGB components or gray scale.
2760 * The method can be called before the first page is created and the value is retained from page to page.
2761 * @param array $color array of colors
2763 * @since 3.1.000 (2008-6-11)
2764 * @see SetFillColor()
2766 public function SetTextColorArray($color) {
2767 if (isset($color)) {
2768 $color = array_values($color);
2769 $r = isset($color[0]) ? $color[0] : -1;
2770 $g = isset($color[1]) ? $color[1] : -1;
2771 $b = isset($color[2]) ? $color[2] : -1;
2772 $k = isset($color[3]) ? $color[3] : -1;
2774 $this->SetTextColor($r, $g, $b, $k);
2780 * 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.
2781 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2782 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2783 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2784 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2787 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
2789 public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2790 // set default values
2791 if (!is_numeric($col1)) {
2794 if (!is_numeric($col2)) {
2797 if (!is_numeric($col3)) {
2800 if (!is_numeric($col4)) {
2803 //Set color for text
2804 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2806 $this->TextColor = sprintf('%.3F g', $col1/255);
2807 $this->fgcolor = array('G' => $col1);
2808 } elseif ($col4 == -1) {
2810 $this->TextColor = sprintf('%.3F %.3F %.3F rg', $col1/255, $col2/255, $col3/255);
2811 $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2814 $this->TextColor = sprintf('%.3F %.3F %.3F %.3F k', $col1/100, $col2/100, $col3/100, $col4/100);
2815 $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2817 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2821 * Defines the spot color used for text.
2822 * @param string $name name of the spot color
2823 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2825 * @since 4.0.024 (2008-09-12)
2826 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
2828 public function SetTextSpotColor($name, $tint=100) {
2829 if (!isset($this->spot_colors[$name])) {
2830 $this->Error('Undefined spot color: '.$name);
2832 $this->TextColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], $tint/100);
2833 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2834 if ($this->page > 0) {
2835 $this->_out($this->TextColor);
2840 * Returns the length of a string in user unit. A font must be selected.<br>
2841 * @param string $s The string whose length is to be computed
2842 * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
2843 * @param string $fontstyle 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><li>D: line trough</li></ul> or any combination. The default value is regular.
2844 * @param float $fontsize Font size in points. The default value is the current size.
2845 * @return int string length
2846 * @author Nicola Asuni
2850 public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0) {
2851 return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $s, $this->tmprtl), $fontname, $fontstyle, $fontsize);
2855 * Returns the string length of an array of chars in user unit. A font must be selected.<br>
2856 * @param string $arr The array of chars whose total length is to be computed
2857 * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
2858 * @param string $fontstyle 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><li>D: line trough</li></ul> or any combination. The default value is regular.
2859 * @param float $fontsize Font size in points. The default value is the current size.
2860 * @return int string length
2861 * @author Nicola Asuni
2863 * @since 2.4.000 (2008-03-06)
2865 public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0) {
2866 // store current values
2867 if (!$this->empty_string($fontname)) {
2868 $prev_FontFamily = $this->FontFamily;
2869 $prev_FontStyle = $this->FontStyle;
2870 $prev_FontSizePt = $this->FontSizePt;
2871 $this->SetFont($fontname, $fontstyle, $fontsize);
2874 foreach ($sa as $char) {
2875 $w += $this->GetCharWidth($char);
2877 // restore previous values
2878 if (!$this->empty_string($fontname)) {
2879 $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt);
2885 * Returns the length of the char in user unit for the current font.<br>
2886 * @param int $char The char code whose length is to be returned
2887 * @return int char width
2888 * @author Nicola Asuni
2890 * @since 2.4.000 (2008-03-06)
2892 public function GetCharWidth($char) {
2894 // SHY character will not be printed
2897 $cw = &$this->CurrentFont['cw'];
2898 if (isset($cw[$char])) {
2900 } elseif (isset($this->CurrentFont['dw'])) {
2902 $w = $this->CurrentFont['dw'];
2903 } elseif (isset($cw[32])) {
2909 return ($w * $this->FontSize / 1000);
2913 * Returns the numbero of characters in a string.
2914 * @param string $s The input string.
2915 * @return int number of characters
2917 * @since 2.0.0001 (2008-01-07)
2919 public function GetNumChars($s) {
2920 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
2921 return count($this->UTF8StringToArray($s));
2927 * Fill the list of available fonts ($this->fontlist).
2929 * @since 4.0.013 (2008-07-28)
2931 protected function getFontsList() {
2932 $fontsdir = opendir($this->_getfontpath());
2933 while (($file = readdir($fontsdir)) !== false) {
2934 if (substr($file, -4) == '.php') {
2935 array_push($this->fontlist, strtolower(basename($file, '.php')));
2938 closedir($fontsdir);
2942 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
2943 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
2944 * 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.
2945 * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
2946 * @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>
2947 * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
2948 * @return array containing the font data, or false in case of error.
2953 public function AddFont($family, $style='', $fontfile='') {
2954 if ($this->empty_string($family)) {
2955 if (!$this->empty_string($this->FontFamily)) {
2956 $family = $this->FontFamily;
2958 $this->Error('Empty font family');
2961 $family = strtolower($family);
2962 if ((!$this->isunicode) AND ($family == 'arial')) {
2963 $family = 'helvetica';
2965 if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
2968 $tempstyle = strtoupper($style);
2971 if (strpos($tempstyle, 'U') !== false) {
2972 $this->underline = true;
2974 $this->underline = false;
2976 // line through (deleted)
2977 if (strpos($tempstyle, 'D') !== false) {
2978 $this->linethrough = true;
2980 $this->linethrough = false;
2983 if (strpos($tempstyle, 'B') !== false) {
2987 if (strpos($tempstyle, 'I') !== false) {
2991 $fontkey = $family.$style;
2992 $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '');
2993 $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
2994 // check if the font has been already added
2995 if ($this->getFontBuffer($fontkey) !== false) {
3004 // get specified font directory (if any)
3006 if (!$this->empty_string($fontfile)) {
3007 $fontdir = dirname($fontfile);
3008 if ($this->empty_string($fontdir) OR ($fontdir == '.')) {
3014 // search and include font file
3015 if ($this->empty_string($fontfile) OR (!file_exists($fontfile))) {
3016 // build a standard filenames for specified font
3017 $fontfile1 = str_replace(' ', '', $family).strtolower($style).'.php';
3018 $fontfile2 = str_replace(' ', '', $family).'.php';
3019 // search files on various directories
3020 if (file_exists($fontdir.$fontfile1)) {
3021 $fontfile = $fontdir.$fontfile1;
3022 } elseif (file_exists($this->_getfontpath().$fontfile1)) {
3023 $fontfile = $this->_getfontpath().$fontfile1;
3024 } elseif (file_exists($fontfile1)) {
3025 $fontfile = $fontfile1;
3026 } elseif (file_exists($fontdir.$fontfile2)) {
3027 $fontfile = $fontdir.$fontfile2;
3028 } elseif (file_exists($this->_getfontpath().$fontfile2)) {
3029 $fontfile = $this->_getfontpath().$fontfile2;
3031 $fontfile = $fontfile2;
3034 // include font file
3035 if (file_exists($fontfile)) {
3038 $this->Error('Could not include font definition file: '.$family.'');
3040 // check font parameters
3041 if ((!isset($type)) OR (!isset($cw))) {
3042 $this->Error('The font definition file has a bad format: '.$fontfile.'');
3044 if (!isset($file)) {
3050 if (!isset($dw) OR $this->empty_string($dw)) {
3051 // set default width
3052 if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
3053 $dw = $desc['MissingWidth'];
3054 } elseif (isset($cw[32])) {
3061 // register CID font (all styles at once)
3062 if ($type == 'cidfont0') {
3063 $file = ''; // not embedded
3064 $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
3065 $sname = $name.$styles[$bistyle];
3066 if ((strpos($bistyle, 'B') !== false) AND (isset($desc['StemV'])) AND ($desc['StemV'] == 70)) {
3067 $desc['StemV'] = 120;
3069 $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => $type, 'name' => $sname, 'desc' => $desc, 'cidinfo' => $cidinfo, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc));
3070 } elseif ($type == 'core') {
3071 $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => 'core', 'name' => $this->CoreFonts[$fontkey], 'up' => -100, 'ut' => 50, 'cw' => $cw, 'dw' => $dw));
3072 } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
3073 $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => $type, 'name' => $name, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'file' => $file, 'enc' => $enc, 'desc' => $desc));
3074 } elseif ($type == 'TrueTypeUnicode') {
3075 $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc, 'file' => $file, 'ctg' => $ctg));
3077 $this->Error('Unknow font type: '.$type.'');
3079 if (isset($diff) AND (!empty($diff))) {
3080 //Search existing encodings
3082 $nb = count($this->diffs);
3083 for ($i=1; $i <= $nb; ++$i) {
3084 if ($this->diffs[$i] == $diff) {
3091 $this->diffs[$d] = $diff;
3093 $this->setFontSubBuffer($fontkey, 'diff', $d);
3095 if (!$this->empty_string($file)) {
3096 if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
3097 $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir);
3098 } elseif ($type != 'core') {
3099 $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir);
3106 * Sets the font used to print character strings.
3107 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
3108 * The method can be called before the first page is created and the font is retained from page to page.
3109 * If you just wish to change the current font size, it is simpler to call SetFontSize().
3110 * 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 />
3111 * @param string $family Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained.
3112 * @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><li>D: line trough</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.
3113 * @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
3114 * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
3117 * @see AddFont(), SetFontSize()
3119 public function SetFont($family, $style='', $size=0, $fontfile='') {
3120 //Select a font; size given in points
3122 $size = $this->FontSizePt;
3124 // try to add font (if not already added)
3125 $fontdata = $this->AddFont($family, $style, $fontfile);
3126 $this->FontFamily = $fontdata['family'];
3127 $this->FontStyle = $fontdata['style'];
3128 $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
3129 $this->SetFontSize($size);
3133 * Defines the size of the current font.
3134 * @param float $size The size (in points)
3139 public function SetFontSize($size) {
3140 //Set font size in points
3141 $this->FontSizePt = $size;
3142 $this->FontSize = $size / $this->k;
3143 if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
3144 $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000;
3146 $this->FontAscent = 0.8 * $this->FontSize;
3148 if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] > 0)) {
3149 $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000;
3151 $this->FontDescent = 0.2 * $this->FontSize;
3153 if (($this->page > 0) AND (isset($this->CurrentFont['i']))) {
3154 $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
3159 * Defines the default monospaced font.
3160 * @param string $font Font name.
3164 public function SetDefaultMonospacedFont($font) {
3165 $this->default_monospaced_font = $font;
3169 * 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 />
3170 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
3173 * @see Cell(), Write(), Image(), Link(), SetLink()
3175 public function AddLink() {
3176 //Create a new internal link
3177 $n = count($this->links) + 1;
3178 $this->links[$n] = array(0, 0);
3183 * Defines the page and position a link points to.
3184 * @param int $link The link identifier returned by AddLink()
3185 * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
3186 * @param int $page Number of target page; -1 indicates the current page. This is the default value
3191 public function SetLink($link, $y=0, $page=-1) {
3196 $page = $this->page;
3198 $this->links[$link] = array($page, $y);
3202 * Puts a link on a rectangular area of the page.
3203 * 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.
3204 * @param float $x Abscissa of the upper-left corner of the rectangle
3205 * @param float $y Ordinate of the upper-left corner of the rectangle
3206 * @param float $w Width of the rectangle
3207 * @param float $h Height of the rectangle
3208 * @param mixed $link URL or identifier returned by AddLink()
3209 * @param int $spaces number of spaces on the text to link
3212 * @see AddLink(), Annotation(), Cell(), Write(), Image()
3214 public function Link($x, $y, $w, $h, $link, $spaces=0) {
3215 $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
3219 * Puts a markup annotation on a rectangular area of the page.
3220 * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
3221 * @param float $x Abscissa of the upper-left corner of the rectangle
3222 * @param float $y Ordinate of the upper-left corner of the rectangle
3223 * @param float $w Width of the rectangle
3224 * @param float $h Height of the rectangle
3225 * @param string $text annotation text or alternate content
3226 * @param array $opt array of options (see section 8.4 of PDF reference 1.7).
3227 * @param int $spaces number of spaces on the text to link
3229 * @since 4.0.018 (2008-08-06)
3231 public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
3232 // recalculate coordinates to account for graphic transformations
3233 if (isset($this->transfmatrix)) {
3234 $maxid = count($this->transfmatrix) - 1;
3235 for ($i=$maxid; $i >= 0; $i--) {
3236 $ctm = $this->transfmatrix[$i];
3237 if (isset($ctm['a'])) {
3239 $y = ($this->h - $y) * $this->k;
3245 $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
3246 $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
3250 $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
3251 $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
3255 $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
3256 $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
3260 $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
3261 $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
3262 // new coordinates (rectangle area)
3263 $x = min($x1, $x2, $x3, $x4);
3264 $y = max($y1, $y2, $y3, $y4);
3265 $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
3266 $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
3268 $y = $this->h - ($y / $this->k);
3272 $this->PageAnnots[$this->page][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
3273 if (($opt['Subtype'] == 'FileAttachment') AND (!$this->empty_string($opt['FS'])) AND file_exists($opt['FS']) AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
3274 $this->embeddedfiles[basename($opt['FS'])] = array('file' => $opt['FS'], 'n' => (count($this->embeddedfiles) + 100000));
3279 * Embedd the attached files.
3280 * @since 4.4.000 (2008-12-07)
3284 protected function _putEmbeddedFiles() {
3285 reset($this->embeddedfiles);
3286 foreach ($this->embeddedfiles as $filename => $filedata) {
3287 $data = file_get_contents($filedata['file']);
3289 if ($this->compress) {
3290 $data = gzcompress($data);
3291 $filter = ' /Filter /FlateDecode';
3293 $this->offsets[$filedata['n']] = $this->bufferlen;
3294 $this->_out($filedata['n'].' 0 obj');
3295 $this->_out('<</Type /EmbeddedFile'.$filter.' /Length '.strlen($data).' >>');
3296 $this->_putstream($data);
3297 $this->_out('endobj');
3302 * Prints a character string.
3303 * The origin is on the left of the first charcter, on the baseline.
3304 * This method allows to place a string precisely on the page.
3305 * @param float $x Abscissa of the origin
3306 * @param float $y Ordinate of the origin
3307 * @param string $txt String to print
3308 * @param int $stroke outline size in points (0 = disable)
3309 * @param boolean $clip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
3312 * @deprecated deprecated since version 4.3.005 (2008-11-25)
3313 * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
3315 public function Text($x, $y, $txt, $stroke=0, $clip=false) {
3318 // bidirectional algorithm (some chars may be changed affecting the line length)
3319 $s = $this->utf8Bidi($this->UTF8StringToArray($txt), $txt, $this->tmprtl);
3320 $l = $this->GetArrStringWidth($s);
3321 $xr = $this->w - $x - $this->GetArrStringWidth($s);
3326 if (($stroke > 0) AND (!$clip)) {
3327 $opt .= '1 Tr '.intval($stroke).' w ';
3328 } elseif (($stroke > 0) AND $clip) {
3329 $opt .= '5 Tr '.intval($stroke).' w ';
3333 $s = sprintf('BT %.2F %.2F Td %s(%s) Tj ET 0 Tr', $xr * $this->k, ($this->h-$y) * $this->k, $opt, $this->_escapetext($txt));
3334 if ($this->underline AND ($txt!='')) {
3335 $s .= ' '.$this->_dounderline($xr, $y, $txt);
3337 if ($this->linethrough AND ($txt!='')) {
3338 $s .= ' '.$this->_dolinethrough($xr, $y, $txt);
3340 if ($this->ColorFlag AND (!$clip)) {
3341 $s='q '.$this->TextColor.' '.$s.' Q';
3347 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
3348 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
3349 * This method is called automatically and should not be called directly by the application.
3353 * @see SetAutoPageBreak()
3355 public function AcceptPageBreak() {
3356 return $this->AutoPageBreak;
3360 * Add page if needed.
3361 * @param float $h Cell height. Default value: 0.
3362 * @param mixed $y starting y position, leave empty for current position.
3363 * @return boolean true in case of page break, false otherwise.
3364 * @since 3.2.000 (2008-07-01)
3367 protected function checkPageBreak($h=0, $y='') {
3368 if ($this->empty_string($y)) {
3371 if ((($y + $h) > $this->PageBreakTrigger) AND (!$this->InFooter) AND ($this->AcceptPageBreak())) {
3372 //Automatic page break
3374 $this->AddPage($this->CurOrientation);
3375 $this->y = $this->tMargin;
3376 $oldpage = $this->page - 1;
3378 if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
3379 $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
3384 if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
3385 $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
3396 * 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 />
3397 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
3398 * @param float $w Cell width. If 0, the cell extends up to the right margin.
3399 * @param float $h Cell height. Default value: 0.
3400 * @param string $txt String to print. Default value: empty string.
3401 * @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>
3402 * @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>
3403 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
3404 * @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>
3405 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3406 * @param mixed $link URL or identifier returned by AddLink().
3407 * @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>
3408 * @param boolean $ignore_min_height if true ignore automatic minimum height value.
3411 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
3413 public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false) {
3414 //$min_cell_height = $this->FontAscent + $this->FontDescent;
3415 $min_cell_height = $this->FontSize * $this->cell_height_ratio;
3416 if ($h < $min_cell_height) {
3417 $h = $min_cell_height;
3419 $this->checkPageBreak($h);
3420 $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height));
3424 * Removes SHY characters from text.
3425 * @param string $txt input string
3426 * @return string without SHY characters.
3428 * @since (4.5.019) 2009-02-28
3430 public function removeSHY($txt='') {
3433 * Name : SOFT HYPHEN, commonly abbreviated as SHY
3434 * HTML Entity (decimal): ­
3435 * HTML Entity (hex): ­
3436 * HTML Entity (named): ­
3437 * How to type in Microsoft Windows: [Alt +00AD] or [Alt 0173]
3438 * UTF-8 (hex): 0xC2 0xAD (c2ad)
3439 * UTF-8 character: chr(194).chr(173)
3441 $txt = preg_replace('/([\\xc2]{1}[\\xad]{1})/', '', $txt);
3442 if (!$this->isunicode) {
3443 $txt = preg_replace('/([\\xad]{1})/', '', $txt);
3449 * Returns the PDF string code to print 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 />
3450 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
3451 * @param float $w Cell width. If 0, the cell extends up to the right margin.
3452 * @param float $h Cell height. Default value: 0.
3453 * @param string $txt String to print. Default value: empty string.
3454 * @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>
3455 * @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>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
3456 * @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>
3457 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3458 * @param mixed $link URL or identifier returned by AddLink().
3459 * @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>
3460 * @param boolean $ignore_min_height if true ignore automatic minimum height value.
3465 protected function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false) {
3466 $txt = $this->removeSHY($txt);
3467 $rs = ''; //string to be returned
3468 if (!$ignore_min_height) {
3469 $min_cell_height = $this->FontSize * $this->cell_height_ratio;
3470 if ($h < $min_cell_height) {
3471 $h = $min_cell_height;
3475 if ($this->empty_string($w) OR ($w <= 0)) {
3477 $w = $this->x - $this->lMargin;
3479 $w = $this->w - $this->rMargin - $this->x;
3483 if (($fill == 1) OR ($border == 1)) {
3485 $op = ($border == 1) ? 'B' : 'f';
3490 $xk = (($this->x - $w) * $k);
3492 $xk = ($this->x * $k);
3494 $s .= sprintf('%.2F %.2F %.2F %.2F re %s ', $xk, (($this->h - $this->y) * $k), ($w * $k), (-$h * $k), $op);
3496 if (is_string($border)) {
3497 $lm = ($this->LineWidth / 2);
3500 if (strpos($border,'L') !== false) {
3502 $xk = ($x - $w) * $k;
3506 $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - $y + $lm) * $k), $xk, (($this->h - ($y + $h + $lm)) * $k));
3508 if (strpos($border,'T') !== false) {
3510 $xk = ($x - $w + $lm) * $k;
3511 $xwk = ($x - $lm) * $k;
3513 $xk = ($x - $lm) * $k;
3514 $xwk = ($x + $w + $lm) * $k;
3516 $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - $y) * $k), $xwk, (($this->h - $y) * $k));
3518 if (strpos($border,'R') !== false) {
3522 $xk = ($x + $w) * $k;
3524 $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - $y + $lm) * $k), $xk, (($this->h - ($y + $h + $lm))* $k));
3526 if (strpos($border,'B') !== false) {
3528 $xk = ($x - $w + $lm) * $k;
3529 $xwk = ($x - $lm) * $k;
3531 $xk = ($x - $lm) * $k;
3532 $xwk = ($x + $w + $lm) * $k;
3534 $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - ($y + $h)) * $k), $xwk, (($this->h - ($y + $h)) * $k));
3539 $width = $this->GetStringWidth($txt);
3540 // ratio between cell lenght and text lenght
3541 $ratio = ($w - (2 * $this->cMargin)) / $width;
3543 // stretch text if required
3544 if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) {
3547 //Calculate character spacing in points
3548 $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1);
3549 //Set character spacing
3550 $rs .= sprintf('BT %.2F Tc ET ', $char_space);
3553 //Calculate horizontal scaling
3554 $horiz_scale = $ratio * 100.0;
3555 //Set horizontal scaling
3556 $rs .= sprintf('BT %.2F Tz ET ', $horiz_scale);
3559 $width = $w - (2 * $this->cMargin);
3563 if ($align == 'L') {
3565 $dx = $w - $width - $this->cMargin;
3567 $dx = $this->cMargin;
3569 } elseif ($align == 'R') {
3571 $dx = $this->cMargin;
3573 $dx = $w - $width - $this->cMargin;
3575 } elseif ($align == 'C') {
3576 $dx = ($w - $width) / 2;
3577 } elseif ($align == 'J') {
3579 $dx = $w - $width - $this->cMargin;
3581 $dx = $this->cMargin;
3584 $dx = $this->cMargin;
3586 if ($this->ColorFlag) {
3587 $s .= 'q '.$this->TextColor.' ';
3589 $txt2 = $this->_escapetext($txt);
3591 $xdk = ($this->x - $dx - $width) * $k;
3593 $xdk = ($this->x + $dx) * $k;
3596 if ($align == 'J') {
3597 // count number of spaces
3598 $ns = substr_count($txt, ' ');
3599 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
3600 // get string width without spaces
3601 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
3602 // calculate average space width
3603 $spacewidth = ($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1) / $this->FontSize / $this->k;
3604 // set word position to be used with TJ operator
3605 $txt2 = str_replace(chr(0).' ', ') '.(-2830 * $spacewidth).' (', $txt2);
3608 $width = $this->GetStringWidth($txt);
3609 $spacewidth = (($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1)) * $this->k;
3610 $rs .= sprintf('BT %.3F Tw ET ', $spacewidth);
3613 // calculate approximate position of the font base line
3614 //$basefonty = $this->y + (($h + $this->FontAscent - $this->FontDescent)/2);
3615 $basefonty = $this->y + ($h/2) + ($this->FontSize/3);
3617 $s .= sprintf('BT %.2F %.2F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
3619 $xdx = $this->x - $dx - $width;
3621 $xdx = $this->x + $dx;
3623 if ($this->underline) {
3624 $s .= ' '.$this->_dounderline($xdx, $basefonty, $txt);
3626 if ($this->linethrough) {
3627 $s .= ' '.$this->_dolinethrough($xdx, $basefonty, $txt);
3629 if ($this->ColorFlag) {
3633 $this->Link($xdx, $this->y + (($h - $this->FontSize)/2), $width, $this->FontSize, $link, substr_count($txt, chr(32)));
3640 // reset text stretching
3642 //Reset character horizontal spacing
3643 $rs .= ' BT 0 Tc ET';
3644 } elseif ($stretch > 0) {
3645 //Reset character horizontal scaling
3646 $rs .= ' BT 100 Tz ET';
3649 // reset word spacing
3650 if (!(($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) AND ($align == 'J')) {
3651 $rs .= ' BT 0 Tw ET';
3655 //Go to the beginning of the next line
3659 $this->x = $this->w - $this->rMargin;
3661 $this->x = $this->lMargin;
3665 // go left or right by case
3672 $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
3678 * This method allows printing text with line breaks.
3679 * 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 />
3680 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
3681 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
3682 * @param float $h Cell minimum height. The cell extends automatically if needed.
3683 * @param string $txt String to print
3684 * @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>
3685 * @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 when $ishtml=false)</li></ul>
3686 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3687 * @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>
3688 * @param int $x x position in user units
3689 * @param int $y y position in user units
3690 * @param boolean $reseth if true reset the last cell height (default true).
3691 * @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>
3692 * @param boolean $ishtml set to true if $txt is HTML content (default = false).
3693 * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
3694 * @param float $maxh maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature. This feature works only when $ishtml=false.
3695 * @return int Return the number of cells or 1 for html mode.
3698 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
3700 public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $addpage=true) {
3701 if ($this->empty_string($this->lasth) OR $reseth) {
3703 $this->lasth = $this->FontSize * $this->cell_height_ratio;
3705 if (!$this->empty_string($y)) {
3710 // should not add page for each cell
3712 // check for page break
3713 $this->checkPageBreak($h);
3716 // get current page number
3717 $startpage = $this->page;
3718 if (!$this->empty_string($x)) {
3723 if ($this->empty_string($w) OR ($w <= 0)) {
3725 $w = $this->x - $this->lMargin;
3727 $w = $this->w - $this->rMargin - $this->x;
3730 // store original margin values
3731 $lMargin = $this->lMargin;
3732 $rMargin = $this->rMargin;
3734 $this->SetRightMargin($this->w - $this->x);
3735 $this->SetLeftMargin($this->x - $w);
3737 $this->SetLeftMargin($this->x);
3738 $this->SetRightMargin($this->w - $this->x - $w);
3742 // Adjust internal padding
3743 if ($this->cMargin < ($this->LineWidth / 2)) {
3744 $this->cMargin = ($this->LineWidth / 2);
3746 // Add top space if needed
3747 if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3748 $this->y += $this->LineWidth / 2;
3751 $this->y += $this->cMargin;
3754 // ******* Write HTML text
3755 $this->writeHTML($txt, true, 0, $reseth, true, $align);
3758 // ******* Write text
3759 $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, false, $maxh);
3762 // add bottom padding
3763 $this->y += $this->cMargin;
3764 // Add bottom space if needed
3765 if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3766 $this->y += $this->LineWidth / 2;
3769 // Get end-of-text Y position
3770 $currentY = $this->y;
3771 // get latest page number
3772 $endpage = $this->page;
3773 // check if a new page has been created
3774 if ($endpage > $startpage) {
3775 // design borders around HTML cells.
3776 for ($page=$startpage; $page <= $endpage; ++$page) {
3777 $this->setPage($page);
3778 if ($page == $startpage) {
3779 $this->y = $starty; // put cursor at the beginning of cell on the first page
3780 $h = $this->getPageHeight() - $starty - $this->getBreakMargin();
3781 $cborder = $this->getBorderMode($border, $position='start');
3782 } elseif ($page == $endpage) {
3783 $this->y = $this->tMargin; // put cursor at the beginning of last page
3784 $h = $currentY - $this->tMargin;
3785 $this->currentY = $currentY;
3786 $cborder = $this->getBorderMode($border, $position='end');
3788 $this->y = $this->tMargin; // put cursor at the beginning of the current page
3789 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
3790 $cborder = $this->getBorderMode($border, $position='middle');
3793 // account for margin changes
3794 if ($page > $startpage) {
3795 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
3796 $nx = $x + ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
3797 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
3798 $nx = $x + ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
3802 $ccode = $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, false);
3803 if ($cborder OR $fill) {
3804 $pagebuff = $this->getPageBuffer($this->page);
3805 $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
3806 $pend = substr($pagebuff, $this->intmrk[$this->page]);
3807 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
3808 $this->intmrk[$this->page] += strlen($ccode."\n");
3812 $h = max($h, ($currentY - $y));
3813 // put cursor at the beginning of text
3816 // design a cell around the text
3817 $ccode = $this->getCellCode($w, $h, '', $border, 1, '', $fill, '', 0, true);
3818 if ($border OR $fill) {
3819 if (end($this->transfmrk[$this->page]) !== false) {
3820 $pagemarkkey = key($this->transfmrk[$this->page]);
3821 $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
3822 } elseif ($this->InFooter) {
3823 $pagemark = &$this->footerpos[$this->page];
3825 $pagemark = &$this->intmrk[$this->page];
3827 $pagebuff = $this->getPageBuffer($this->page);
3828 $pstart = substr($pagebuff, 0, $pagemark);
3829 $pend = substr($pagebuff, $pagemark);
3830 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
3831 $pagemark += strlen($ccode."\n");
3834 // Get end-of-cell Y position
3835 $currentY = $this->GetY();
3836 // restore original margin values
3837 $this->SetLeftMargin($lMargin);
3838 $this->SetRightMargin($rMargin);
3840 //Go to the beginning of the next line
3841 $this->SetY($currentY);
3843 $this->SetX($x + $w);
3846 // go left or right by case
3847 $this->setPage($startpage);
3849 $this->SetX($x + $w);
3855 * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages)
3856 * @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>
3857 * @param string multicell position: 'start', 'middle', 'end'
3858 * @return border mode
3860 * @since 4.4.002 (2008-12-09)
3862 protected function getBorderMode($border, $position='start') {
3863 if ((!$this->opencell) AND ($border == 1)) {
3867 switch ($position) {
3872 if (!(false === strpos($border, 'L'))) {
3875 if (!(false === strpos($border, 'T'))) {
3878 if (!(false === strpos($border, 'R'))) {
3881 if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
3891 if (!(false === strpos($border, 'L'))) {
3894 if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
3897 if (!(false === strpos($border, 'R'))) {
3900 if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
3910 if (!(false === strpos($border, 'L'))) {
3913 if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
3916 if (!(false === strpos($border, 'R'))) {
3919 if (!(false === strpos($border, 'B'))) {
3934 * This method returns the estimated number of lines required to print the text.
3935 * @param string $txt text to print
3936 * @param float $w width of cell. If 0, they extend up to the right margin of the page.
3937 * @return int Return the estimated number of lines.
3941 public function getNumLines($txt, $w=0) {
3943 if ($this->empty_string($w) OR ($w <= 0)) {
3945 $w = $this->x - $this->lMargin;
3947 $w = $this->w - $this->rMargin - $this->x;
3951 $wmax = $w - (2 * $this->cMargin);
3952 // remove carriage returns
3953 $txt = str_replace("\r", '', $txt);
3954 // remove last newline (if any)
3955 if (substr($txt,-1) == "\n") {
3956 $txt = substr($txt, 0, -1);
3958 // divide text in blocks
3959 $txtblocks = explode("\n", $txt);
3961 foreach ($txtblocks as $block) {
3962 // estimate the number of lines
3963 $lines += $this->empty_string($block) ? 1 : (ceil($this->GetStringWidth($block) / $wmax));
3969 * This method prints text from the current position.<br />
3970 * @param float $h Line height
3971 * @param string $txt String to print
3972 * @param mixed $link URL or identifier returned by AddLink()
3973 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
3974 * @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>
3975 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
3976 * @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>
3977 * @param boolean $firstline if true prints only the first line and return the remaining string.
3978 * @param boolean $firstblock if true the string is the starting of a line.
3979 * @param float $maxh maximum height. The remaining unprinted text will be returned. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
3980 * @return mixed Return the number of cells or the remaining string if $firstline = true.
3984 public function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0) {
3985 if (strlen($txt) == 0) {
3988 // remove carriage returns
3989 $s = str_replace("\r", '', $txt);
3991 // check if string contains arabic text
3992 if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
3997 // check if string contains RTL text
3998 if ($arabic OR $this->tmprtl OR preg_match(K_RE_PATTERN_RTL, $txt)) {
4004 $chrwidth = $this->GetCharWidth('.');
4005 // get array of unicode values
4006 $chars = $this->UTF8StringToArray($s);
4007 // get array of chars
4008 $uchars = $this->UTF8ArrayToUniArray($chars);
4009 // get the number of characters
4010 $nb = count($chars);
4011 // replacement for SHY character (minus symbol)
4012 $shy_replacement = 45;
4013 $shy_replacement_char = $this->unichr($shy_replacement);
4014 // widht for SHY replacement
4015 $shy_replacement_width = $this->GetCharWidth($shy_replacement);
4016 // store current position
4020 $maxy = $this->y + $maxh - $h - (2 * $this->cMargin);
4021 // calculate remaining line width ($w)
4023 $w = $this->x - $this->lMargin;
4025 $w = $this->w - $this->rMargin - $this->x;
4028 $wmax = $w - (2 * $this->cMargin);
4029 if ($chrwidth > $wmax) {
4030 // a single character do not fit on column
4033 $i = 0; // character position
4034 $j = 0; // current starting position
4035 $sep = -1; // position of the last blank space
4036 $shy = false; // true if the last blank is a soft hypen (SHY)
4037 $l = 0; // current string lenght
4038 $nl = 0; //number of lines
4040 // for each character
4042 if (($maxh > 0) AND ($this->y >= $maxy) ) {
4045 //Get the current character
4047 if ($c == 10) { // 10 = "\n" = new line
4048 //Explicit line break
4049 if ($align == 'J') {
4058 $tmpstr = $this->UniArrSubString($uchars, $j, $i);
4061 $tmparr = array_slice($chars, $j, $i);
4063 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4065 $linew = $this->GetArrStringWidth($tmparr);
4068 $this->endlinex = $startx - $linew;
4070 $this->endlinex = $startx + $linew;
4073 $tmpcmargin = $this->cMargin;
4078 $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
4081 $this->cMargin = $tmpcmargin;
4082 return ($this->UniArrSubString($uchars, $i));
4089 // account for margin changes
4090 if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
4091 // AcceptPageBreak() may be overriden on extended classed to include margin changes
4092 $this->AcceptPageBreak();
4094 $w = $this->getRemainingWidth();
4095 $wmax = $w - (2 * $this->cMargin);
4097 // 160 is the non-breaking space.
4098 // 173 is SHY (Soft Hypen).
4099 // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
4100 // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
4101 // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
4102 if (($c != 160) AND (($c == 173) OR preg_match($this->re_spaces, $this->unichr($c)))) {
4103 // update last blank space position
4105 // check if is a SHY
4112 // update string length
4113 if ((($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) AND ($arabic)) {
4114 // with bidirectional algorithm some chars may be changed affecting the line length
4115 // *** very slow ***
4116 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), '', $this->tmprtl));
4118 $l += $this->GetCharWidth($c);
4120 if (!$stretch && (($l > $wmax) OR ($shy AND (($l + $shy_replacement_width) > $wmax))) ) {
4121 // we have reached the end of column
4123 // check if the line was already started
4124 if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $chrwidth)))
4125 OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $chrwidth)))) {
4126 // print a void cell and go to next line
4127 $this->Cell($w, $h, '', 0, 1);
4130 return ($this->UniArrSubString($uchars, $j));
4133 // truncate the word because do not fit on column
4134 $tmpstr = $this->UniArrSubString($uchars, $j, $i);
4137 $tmparr = array_slice($chars, $j, $i);
4139 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4141 $linew = $this->GetArrStringWidth($tmparr);
4144 $this->endlinex = $startx - $linew;
4146 $this->endlinex = $startx + $linew;
4149 $tmpcmargin = $this->cMargin;
4154 $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
4157 $this->cMargin = $tmpcmargin;
4158 return ($this->UniArrSubString($uchars, $i));
4165 if ($this->rtl AND (!$firstblock)) {
4171 // add hypen (minus symbol) at the end of the line
4172 $shy_width = $shy_replacement_width;
4174 $shy_char_left = $shy_replacement_char;
4175 $shy_char_right = '';
4177 $shy_char_left = '';
4178 $shy_char_right = $shy_replacement_char;
4182 $shy_char_left = '';
4183 $shy_char_right = '';
4185 $tmpstr = $this->UniArrSubString($uchars, $j, ($sep + $endspace));
4188 $tmparr = array_slice($chars, $j, ($sep + $endspace));
4190 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4192 $linew = $this->GetArrStringWidth($tmparr);
4195 $this->endlinex = $startx - $linew - $shy_width;
4197 $this->endlinex = $startx + $linew + $shy_width;
4200 $tmpcmargin = $this->cMargin;
4206 $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
4209 // return the remaining text
4210 $this->cMargin = $tmpcmargin;
4211 return ($this->UniArrSubString($uchars, ($sep + $endspace)));
4218 // account for margin changes
4219 if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
4220 // AcceptPageBreak() may be overriden on extended classed to include margin changes
4221 $this->AcceptPageBreak();
4223 $w = $this->getRemainingWidth();
4224 $wmax = $w - (2 * $this->cMargin);
4234 } // end while i < nb
4235 // print last substring (if any)
4267 $tmpstr = $this->UniArrSubString($uchars, $j, $nb);
4270 $tmparr = array_slice($chars, $j, $nb);
4272 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4274 $linew = $this->GetArrStringWidth($tmparr);
4277 $this->endlinex = $startx - $linew;
4279 $this->endlinex = $startx + $linew;
4283 $tmpcmargin = $this->cMargin;
4288 $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
4291 $this->cMargin = $tmpcmargin;
4292 return ($this->UniArrSubString($uchars, $nb));
4303 * Returns the remaining width between the current position and margins.
4304 * @return int Return the remaining width
4307 protected function getRemainingWidth() {
4309 return ($this->x - $this->lMargin);
4311 return ($this->w - $this->rMargin - $this->x);
4316 * Extract a slice of the $strarr array and return it as string.
4317 * @param string $strarr The input array of characters.
4318 * @param int $start the starting element of $strarr.
4319 * @param int $end first element that will not be returned.
4320 * @return Return part of a string
4323 public function UTF8ArrSubString($strarr, $start='', $end='') {
4324 if (strlen($start) == 0) {
4327 if (strlen($end) == 0) {
4328 $end = count($strarr);
4331 for ($i=$start; $i < $end; ++$i) {
4332 $string .= $this->unichr($strarr[$i]);
4338 * Extract a slice of the $uniarr array and return it as string.
4339 * @param string $uniarr The input array of characters.
4340 * @param int $start the starting element of $strarr.
4341 * @param int $end first element that will not be returned.
4342 * @return Return part of a string
4344 * @since 4.5.037 (2009-04-07)
4346 public function UniArrSubString($uniarr, $start='', $end='') {
4347 if (strlen($start) == 0) {
4350 if (strlen($end) == 0) {
4351 $end = count($uniarr);
4354 for ($i=$start; $i < $end; ++$i) {
4355 $string .= $uniarr[$i];
4361 * Convert an array of UTF8 values to array of unicode characters
4362 * @param string $ta The input array of UTF8 values.
4363 * @return Return array of unicode characters
4365 * @since 4.5.037 (2009-04-07)
4367 public function UTF8ArrayToUniArray($ta) {
4368 return array_map(array($this, 'unichr'), $ta);
4372 * Returns the unicode caracter specified by UTF-8 code
4373 * @param int $c UTF-8 code
4374 * @return Returns the specified character.
4375 * @author Miguel Perez, Nicola Asuni
4377 * @since 2.3.000 (2008-03-05)
4379 public function unichr($c) {
4380 if (!$this->isunicode) {
4382 } elseif ($c <= 0x7F) {
4385 } elseif ($c <= 0x7FF) {
4387 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
4388 } elseif ($c <= 0xFFFF) {
4390 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
4391 } elseif ($c <= 0x10FFFF) {
4393 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
4400 * Puts an image in the page.
4401 * The upper-left corner must be given.
4402 * The dimensions can be specified in different ways:<ul>
4403 * <li>explicit width and height (expressed in user unit)</li>
4404 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
4405 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
4406 * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
4407 * The format can be specified explicitly or inferred from the file extension.<br />
4408 * It is possible to put a link on the image.<br />
4409 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
4410 * @param string $file Name of the file containing the image.
4411 * @param float $x Abscissa of the upper-left corner.
4412 * @param float $y Ordinate of the upper-left corner.
4413 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
4414 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
4415 * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
4416 * @param mixed $link URL or identifier returned by AddLink().
4417 * @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>
4418 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
4419 * @param int $dpi dot-per-inch resolution used on resize
4420 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
4421 * @param boolean $ismask true if this image is a mask, false otherwise
4422 * @param mixed $imgmask image object returned by this function or false
4423 * @param mixed $border Indicates if borders must be drawn around the image. 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>
4424 * @param boolean $fitbox If true scale image dimensions proportionally to fit within the ($w, $h) box.
4425 * @return image information
4429 * peter d: Upgrading tcpdf to the latest version causes the whole thing to blow up since we have modifications to the original source as well as sugarpdf which
4430 * also extend from this. The only option is to add a workaround for some of the bugs in this function.
4432 public function Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false) {
4439 // get image dimensions
4440 $imsize = @getimagesize($file);
4441 if ($imsize === FALSE) {
4442 // encode spaces on filename
4443 $file = str_replace(' ', '%20', $file);
4444 $imsize = @getimagesize($file);
4445 if ($imsize === FALSE) {
4446 $this->Error('[Image] No such file or directory in '.$file);
4449 // get original image width and height in pixels
4450 list($pixw, $pixh) = $imsize;
4451 // calculate image width and height on document
4452 if (($w <= 0) AND ($h <= 0)) {
4453 // convert image size to document unit
4454 $w = $this->pixelsToUnits($pixw);
4455 $h = $this->pixelsToUnits($pixh);
4456 } elseif ($w <= 0) {
4457 $w = $h * $pixw / $pixh;
4458 } elseif ($h <= 0) {
4459 $h = $w * $pixh / $pixw;
4460 } elseif ($fitbox AND ($w > 0) AND ($h > 0)) {
4461 // scale image dimensions proportionally to fit within the ($w, $h) box
4462 // NOTE: This section doesn't actually work very well, use the resize = true case I added.
4463 if ((($w * $pixh) / ($h * $pixw)) < 1) {
4464 $h = $w * $pixh / $pixw;
4466 $w = $h * $pixw / $pixh;
4468 } else if ($resize) { // Added resize case
4469 // Note: The issue here is that $w and $h represent abstract sizes, we pass it in as pixels,
4470 // but tcpdf treats it as document units.
4471 $wratio = $pixw / $w;
4472 $hratio = $pixh / $h;
4474 // Check if our image exceeds the boundaries of $w and $h
4475 if ($wratio > 1 AND $hratio > 1) {
4476 $favoredRatio = ($wratio > $hratio) ? $wratio : $hratio;
4477 } else if ($wratio > 1) {
4478 $favoredRatio = $wratio;
4479 } else if ($hratio > 1) {
4480 $favoredRatio = $hratio;
4486 // Calculate the new boundaries that also happen to fit the box..
4487 // Dividing by the unit conversion $this->k seems to make the size not blow up
4488 // later down in the code.
4489 $w = $pixw / $favoredRatio / $this->k;
4490 $h = $pixh / $favoredRatio / $this->k;
4492 // calculate new minimum dimensions in pixels
4493 $neww = round($w * $this->k * $dpi / $this->dpi);
4494 $newh = round($h * $this->k * $dpi / $this->dpi);
4496 // check if resize is necessary (resize is used only to reduce the image)
4498 // - commmented out by pete d.
4499 // this is not a good way of checking for resize. and it might overwrite resize if the flag is enabled.
4500 // if (($neww * $newh) >= ($pixw * $pixh)) {
4504 // check if image has been already added on document
4505 if (!in_array($file, $this->imagekeys)) {
4506 //First use of image, get info
4508 $fileinfo = pathinfo($file);
4509 if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
4510 $type = $fileinfo['extension'];
4512 $this->Error('Image file has no extension and no type was specified: '.$file);
4515 $type = strtolower($type);
4516 if ($type == 'jpg') {
4519 $mqr = get_magic_quotes_runtime();
4520 //set_magic_quotes_runtime(0);
4521 // Specific image handlers
4522 $mtd = '_parse'.$type;
4523 // GD image handler function
4524 $gdfunction = 'imagecreatefrom'.$type;
4526 if ((method_exists($this, $mtd)) AND (!($resize AND function_exists($gdfunction)))) {
4527 // TCPDF image functions
4528 $info = $this->$mtd($file);
4529 if ($info == 'pngalpha') {
4530 return $this->ImagePngAlpha($file, $x, $y, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign);
4534 if (function_exists($gdfunction)) {
4536 $img = $gdfunction($file);
4538 $imgr = imagecreatetruecolor($neww, $newh);
4539 imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
4540 $info = $this->_toJPEG($imgr);
4542 $info = $this->_toJPEG($img);
4544 } elseif (extension_loaded('imagick')) {
4545 // ImageMagick library
4546 $img = new Imagick();
4547 $img->readImage($file);
4549 $img->resizeImage($neww, $newh, 10, 1, false);
4551 $img->setCompressionQuality($this->jpeg_quality);
4552 $img->setImageFormat('jpeg');
4553 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
4554 $img->writeImage($tempname);
4555 $info = $this->_parsejpeg($tempname);
4559 else if ($type == 'jpeg') {
4560 $info = $this->_parsejpeg($file);
4566 if ($info === false) {
4567 //If false, we cannot process image
4570 //set_magic_quotes_runtime($mqr);
4573 $info['cs'] = 'DeviceGray';
4575 $info['i'] = $this->numimages + 1;
4576 if ($imgmask !== false) {
4577 $info['masked'] = $imgmask;
4579 // add image to document
4580 $this->setImageBuffer($file, $info);
4582 $info = $this->getImageBuffer($file);
4584 // Check whether we need a new page first as this does not fit
4585 if ($this->checkPageBreak($h, $y)) {
4586 $y = $this->GetY() + $this->cMargin;
4588 // set bottomcoordinates
4589 $this->img_rb_y = $y + $h;
4592 if ($palign == 'L') {
4593 $ximg = $this->lMargin;
4594 // set right side coordinate
4595 $this->img_rb_x = $ximg + $w;
4596 } elseif ($palign == 'C') {
4597 $ximg = ($this->w - $x - $w) / 2;
4598 // set right side coordinate
4599 $this->img_rb_x = $ximg + $w;
4601 $ximg = $this->w - $x - $w;
4602 // set left side coordinate
4603 $this->img_rb_x = $ximg;
4606 if ($palign == 'R') {
4607 $ximg = $this->w - $this->rMargin - $w;
4608 // set left side coordinate
4609 $this->img_rb_x = $ximg;
4610 } elseif ($palign == 'C') {
4611 $ximg = ($this->w - $x - $w) / 2;
4612 // set right side coordinate
4613 $this->img_rb_x = $ximg + $w;
4616 // set right side coordinate
4617 $this->img_rb_x = $ximg + $w;
4621 // embed hidden, ouside the canvas
4622 $xkimg = ($this->pagedim[$this->page]['w'] + 10);
4624 $xkimg = $ximg * $this->k;
4626 $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']));
4627 if (!empty($border)) {
4632 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
4637 $this->Link($ximg, $y, $w, $h, $link, 0);
4639 // set pointer to align the successive text/objects
4643 $this->x = $this->img_rb_x;
4647 $this->y = $y + round($h/2);
4648 $this->x = $this->img_rb_x;
4652 $this->y = $this->img_rb_y;
4653 $this->x = $this->img_rb_x;
4657 $this->SetY($this->img_rb_y);
4664 $this->endlinex = $this->img_rb_x;
4669 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
4670 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
4671 * @param string $file Image file name.
4672 * @param image $image Image object.
4673 * return image JPEG image object.
4676 protected function _toJPEG($image) {
4677 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
4678 imagejpeg($image, $tempname, $this->jpeg_quality);
4679 imagedestroy($image);
4680 $retvars = $this->_parsejpeg($tempname);
4681 // tidy up by removing temporary image
4687 * Extract info from a JPEG file without using the GD library.
4688 * @param string $file image file to parse
4689 * @return array structure containing the image data
4692 protected function _parsejpeg($file) {
4693 $a = getimagesize($file);
4695 $this->Error('Missing or incorrect image file: '.$file);
4698 $this->Error('Not a JPEG file: '.$file);
4700 if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
4701 $colspace = 'DeviceRGB';
4702 } elseif ($a['channels'] == 4) {
4703 $colspace = 'DeviceCMYK';
4705 $colspace = 'DeviceGray';
4707 $bpc = isset($a['bits']) ? $a['bits'] : 8;
4708 $data = file_get_contents($file);
4709 return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
4713 * Extract info from a PNG file without using the GD library.
4714 * @param string $file image file to parse
4715 * @return array structure containing the image data
4718 protected function _parsepng($file) {
4719 $f = fopen($file, 'rb');
4721 $this->Error('Can\'t open image file: '.$file);
4724 if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
4725 $this->Error('Not a PNG file: '.$file);
4729 if (fread($f, 4) != 'IHDR') {
4730 $this->Error('Incorrect PNG file: '.$file);
4732 $w = $this->_freadint($f);
4733 $h = $this->_freadint($f);
4734 $bpc = ord(fread($f, 1));
4736 //$this->Error('16-bit depth not supported: '.$file);
4740 $ct = ord(fread($f, 1));
4742 $colspace = 'DeviceGray';
4743 } elseif ($ct == 2) {
4744 $colspace = 'DeviceRGB';
4745 } elseif ($ct == 3) {
4746 $colspace = 'Indexed';
4752 if (ord(fread($f, 1)) != 0) {
4753 //$this->Error('Unknown compression method: '.$file);
4757 if (ord(fread($f, 1)) != 0) {
4758 //$this->Error('Unknown filter method: '.$file);
4762 if (ord(fread($f, 1)) != 0) {
4763 //$this->Error('Interlacing not supported: '.$file);
4768 $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
4769 //Scan chunks looking for palette, transparency and image data
4774 $n = $this->_freadint($f);
4775 $type = fread($f, 4);
4776 if ($type == 'PLTE') {
4778 $pal = $this->rfread($f, $n);
4780 } elseif ($type == 'tRNS') {
4781 //Read transparency info
4782 $t = $this->rfread($f, $n);
4784 $trns = array(ord(substr($t, 1, 1)));
4785 } elseif ($ct == 2) {
4786 $trns = array(ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1)));
4788 $pos = strpos($t, chr(0));
4789 if ($pos !== false) {
4790 $trns = array($pos);
4794 } elseif ($type == 'IDAT') {
4795 //Read image data block
4796 $data .= $this->rfread($f, $n);
4798 } elseif ($type == 'IEND') {
4801 $this->rfread($f, $n + 4);
4804 if (($colspace == 'Indexed') AND (empty($pal))) {
4805 //$this->Error('Missing palette in '.$file);
4810 return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
4814 * Binary-safe and URL-safe file read.
4815 * Reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met: length bytes have been read; EOF (end of file) is reached.
4816 * @param resource $handle
4817 * @param int $length
4818 * @return Returns the read string or FALSE in case of error.
4819 * @author Nicola Asuni
4821 * @since 4.5.027 (2009-03-16)
4823 protected function rfread($handle, $length) {
4824 $data = fread($handle, $length);
4825 if ($data === false) {
4828 $rest = $length - strlen($data);
4830 $data .= $this->rfread($handle, $rest);
4836 * Extract info from a PNG image with alpha channel using the GD library.
4837 * @param string $file Name of the file containing the image.
4838 * @param float $x Abscissa of the upper-left corner.
4839 * @param float $y Ordinate of the upper-left corner.
4840 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
4841 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
4842 * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
4843 * @param mixed $link URL or identifier returned by AddLink().
4844 * @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>
4845 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
4846 * @param int $dpi dot-per-inch resolution used on resize
4847 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
4848 * @author Valentin Schmidt, Nicola Asuni
4850 * @since 4.3.007 (2008-12-04)
4853 protected function ImagePngAlpha($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
4855 list($wpx, $hpx) = getimagesize($file);
4857 $img = imagecreatefrompng($file);
4858 $imgalpha = imagecreate($wpx, $hpx);
4859 // generate gray scale pallete
4860 for ($c = 0; $c < 256; ++$c) {
4861 ImageColorAllocate($imgalpha, $c, $c, $c);
4863 // extract alpha channel
4864 for ($xpx = 0; $xpx < $wpx; ++$xpx) {
4865 for ($ypx = 0; $ypx < $hpx; ++$ypx) {
4866 $colorindex = imagecolorat($img, $xpx, $ypx);
4867 $col = imagecolorsforindex($img, $colorindex);
4868 imagesetpixel($imgalpha, $xpx, $ypx, $this->getGDgamma((127 - $col['alpha']) * 255 / 127));
4871 // create temp alpha file
4872 $tempfile_alpha = tempnam(K_PATH_CACHE, 'mska_');
4873 imagepng($imgalpha, $tempfile_alpha);
4874 imagedestroy($imgalpha);
4875 // extract image without alpha channel
4876 $imgplain = imagecreatetruecolor($wpx, $hpx);
4877 imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
4878 // create temp image file
4879 $tempfile_plain = tempnam(K_PATH_CACHE, 'mskp_');
4880 imagepng($imgplain, $tempfile_plain);
4881 imagedestroy($imgplain);
4883 $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
4884 // embed image, masked with previously embedded mask
4885 $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
4886 // remove temp files
4887 unlink($tempfile_alpha);
4888 unlink($tempfile_plain);
4892 * Correct the gamma value to be used with GD library
4893 * @param float $v the gamma value to be corrected
4895 * @since 4.3.007 (2008-12-04)
4897 protected function getGDgamma($v) {
4898 return (pow(($v / 255), 2.2) * 255);
4902 * Performs a line break.
4903 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
4904 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
4905 * @param boolean $cell if true add a cMargin to the x coordinate
4910 public function Ln($h='', $cell=false) {
4911 //Line feed; default value is last cell height
4913 $cellmargin = $this->cMargin;
4918 $this->x = $this->w - $this->rMargin - $cellmargin;
4920 $this->x = $this->lMargin + $cellmargin;
4922 if (is_string($h)) {
4923 $this->y += $this->lasth;
4927 $this->newline = true;
4931 * Returns the relative X value of current position.
4932 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
4936 * @see SetX(), GetY(), SetY()
4938 public function GetX() {
4941 return ($this->w - $this->x);
4948 * Returns the absolute X value of current position.
4952 * @see SetX(), GetY(), SetY()
4954 public function GetAbsX() {
4959 * Returns the ordinate of the current position.
4963 * @see SetY(), GetX(), SetX()
4965 public function GetY() {
4971 * Defines the abscissa of the current position.
4972 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
4973 * @param float $x The value of the abscissa.
4976 * @see GetX(), GetY(), SetY(), SetXY()
4978 public function SetX($x) {
4982 $this->x = $this->w - $x;
4990 $this->x = $this->w + $x;
4996 if ($this->x > $this->w) {
4997 $this->x = $this->w;
5002 * Moves the current abscissa back to the left margin and sets the ordinate.
5003 * If the passed value is negative, it is relative to the bottom of the page.
5004 * @param float $y The value of the ordinate.
5005 * @param bool $resetx if true (default) reset the X position.
5008 * @see GetX(), GetY(), SetY(), SetXY()
5010 public function SetY($y, $resetx=true) {
5014 $this->x = $this->w - $this->rMargin;
5016 $this->x = $this->lMargin;
5022 $this->y = $this->h + $y;
5027 if ($this->y > $this->h) {
5028 $this->y = $this->h;
5033 * Defines the abscissa and ordinate of the current position.
5034 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
5035 * @param float $x The value of the abscissa
5036 * @param float $y The value of the ordinate
5039 * @see SetX(), SetY()
5041 public function SetXY($x, $y) {
5042 //Set x and y positions
5048 * Send the document to a given destination: string, local file or browser.
5049 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
5050 * The method first calls Close() if necessary to terminate the document.
5051 * @param string $name The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
5052 * @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 (default). 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>
5057 public function Output($name='doc.pdf', $dest='I') {
5058 //Output PDF to some destination
5059 //Finish document if necessary
5060 if ($this->state < 3) {
5063 //Normalize parameters
5064 if (is_bool($dest)) {
5065 $dest = $dest ? 'D' : 'F';
5067 $dest = strtoupper($dest);
5069 $name = preg_replace('/[\s]+/', '_', $name);
5070 $name = preg_replace('/[^a-zA-Z0-9\._-\x{4e00}-\x{9fa5}]/u', '', $name);
5073 // *** apply digital signature to the document ***
5074 // get the document content
5075 $pdfdoc = $this->getBuffer();
5076 // remove last newline
5077 $pdfdoc = substr($pdfdoc, 0, -1);
5078 // Remove the original buffer
5079 if (isset($this->diskcache) AND $this->diskcache) {
5080 // remove buffer file from cache
5081 unlink($this->buffer);
5083 unset($this->buffer);
5084 // remove filler space
5085 $tmppos = strpos($pdfdoc, '/ByteRange[0 ********** ********** **********]') + 58;
5086 $pdfdoc = substr($pdfdoc, 0, $tmppos).substr($pdfdoc, $tmppos + $this->signature_max_lenght);
5087 // define the ByteRange
5088 $byte_range = array();
5090 $byte_range[1] = $tmppos - 1;
5091 $byte_range[2] = $byte_range[1] + $this->signature_max_lenght;
5092 $byte_range[3] = strlen($pdfdoc) - $byte_range[1];
5093 // replace the ByteRange
5094 $byterange = sprintf('/ByteRange[0 %010u %010u %010u]', $byte_range[1], $byte_range[2], $byte_range[3]);
5095 $pdfdoc = str_replace('/ByteRange[0 ********** ********** **********]', $byterange, $pdfdoc);
5096 // write the document to a temporary folder
5097 $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_');
5098 $f = fopen($tempdoc, 'wb');
5100 $this->Error('Unable to create temporary file: '.$tempdoc);
5102 $pdfdoc_lenght = strlen($pdfdoc);
5103 fwrite($f, $pdfdoc, $pdfdoc_lenght);
5105 // get digital signature.
5106 // IS THE FOLLOWING PROCEDURE CORRECT? THE SIGNED DOCUMENTS ARE NOT VALID!
5107 $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_');
5108 if (empty($this->signature_data['extracerts'])) {
5109 openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
5111 openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED, $this->signature_data['extracerts']);
5115 $signature = file_get_contents($tempsign, false, null, $pdfdoc_lenght);
5117 // extract signature
5118 $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
5119 $tmparr = explode("\n\n", $signature);
5120 $signature = $tmparr[1];
5123 $signature = base64_decode(trim($signature));
5124 // convert signature to hex
5125 $signature = current(unpack('H*', $signature));
5126 $signature = str_pad($signature, $this->signature_max_lenght, '0');
5127 // Add signature to the document
5128 $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).$signature.substr($pdfdoc, (0 - $byte_range[3]));
5129 $this->diskcache = false;
5130 $this->buffer = &$pdfdoc;
5131 $this->bufferlen = strlen($pdfdoc);
5135 // Send PDF to the standard output
5136 if (ob_get_contents()) {
5137 $this->Error('Some data has already been output, can\'t send PDF file');
5139 if (php_sapi_name() != 'cli') {
5140 //We send to a browser
5141 header('Content-Type: application/pdf');
5142 if (headers_sent()) {
5143 $this->Error('Some data has already been output to browser, can\'t send PDF file');
5145 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
5146 header('Pragma: public');
5147 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
5148 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
5149 header('Content-Length: '.$this->bufferlen);
5150 header('Content-Disposition: inline; filename="'.basename($name).'";');
5152 echo $this->getBuffer();
5156 // Download PDF as file
5157 if (ob_get_contents()) {
5158 $this->Error('Some data has already been output, can\'t send PDF file');
5160 header('Content-Description: File Transfer');
5161 if (headers_sent()) {
5162 $this->Error('Some data has already been output to browser, can\'t send PDF file');
5164 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
5165 header('Pragma: public');
5166 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
5167 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
5168 // force download dialog
5169 header('Content-Type: application/force-download');
5170 header('Content-Type: application/octet-stream', false);
5171 header('Content-Type: application/download', false);
5172 header('Content-Type: application/pdf', false);
5173 // use the Content-Disposition header to supply a recommended filename
5174 header('Content-Disposition: attachment; filename="'.basename($name).'";');
5175 header('Content-Transfer-Encoding: binary');
5176 header('Content-Length: '.$this->bufferlen);
5177 echo $this->getBuffer();
5181 // Save PDF to a local file
5182 if ($this->diskcache) {
5183 copy($this->buffer, $name);
5185 $f = fopen($name, 'wb');
5187 $this->Error('Unable to create output file: '.$name);
5189 fwrite($f, $this->getBuffer(), $this->bufferlen);
5195 // Returns PDF as a string
5196 return $this->getBuffer();
5199 $this->Error('Incorrect output destination: '.$dest);
5206 * Unset all class variables except the following critical variables: internal_encoding, state, bufferlen, buffer and diskcache.
5207 * @param boolean $destroyall if true destroys all class variables, otherwise preserves critical variables.
5208 * @param boolean $preserve_objcopy if true preserves the objcopy variable
5210 * @since 4.5.016 (2009-02-24)
5212 public function _destroy($destroyall=false, $preserve_objcopy=false) {
5213 if ($destroyall AND isset($this->diskcache) AND $this->diskcache AND (!$preserve_objcopy) AND (!$this->empty_string($this->buffer))) {
5214 // remove buffer file from cache
5215 unlink($this->buffer);
5217 foreach (array_keys(get_object_vars($this)) as $val) {
5218 if ($destroyall OR (
5219 ($val != 'internal_encoding')
5220 AND ($val != 'state')
5221 AND ($val != 'bufferlen')
5222 AND ($val != 'buffer')
5223 AND ($val != 'diskcache')
5224 AND ($val != 'sign')
5225 AND ($val != 'signature_data')
5226 AND ($val != 'signature_max_lenght')
5228 if (!$preserve_objcopy OR ($val != 'objcopy')) {
5236 * Check for locale-related bug
5239 protected function _dochecks() {
5240 //Check for locale-related bug
5242 $this->Error('Don\'t alter the locale before including class file');
5244 //Check for decimal separator
5245 if (sprintf('%.1F', 1.0) != '1.0') {
5246 setlocale(LC_NUMERIC, 'C');
5255 protected function _getfontpath() {
5256 if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
5257 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
5259 return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
5266 protected function _putpages() {
5267 $nb = $this->numpages;
5268 if (!empty($this->AliasNbPages)) {
5269 $nbs = $this->formatPageNumber($nb);
5270 $nbu = $this->UTF8ToUTF16BE($nbs, false); // replacement for unicode font
5271 $alias_a = $this->_escape($this->AliasNbPages);
5272 $alias_au = $this->_escape('{'.$this->AliasNbPages.'}');
5273 if ($this->isunicode) {
5274 $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
5275 $alias_bu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNbPages.'}'));
5276 $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
5277 $alias_cu = $this->_escape($this->utf8StrRev('{'.$this->AliasNbPages.'}', false, $this->tmprtl));
5280 if (!empty($this->AliasNumPage)) {
5281 $alias_pa = $this->_escape($this->AliasNumPage);
5282 $alias_pau = $this->_escape('{'.$this->AliasNumPage.'}');
5283 if ($this->isunicode) {
5284 $alias_pb = $this->_escape($this->UTF8ToLatin1($this->AliasNumPage));
5285 $alias_pbu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNumPage.'}'));
5286 $alias_pc = $this->_escape($this->utf8StrRev($this->AliasNumPage, false, $this->tmprtl));
5287 $alias_pcu = $this->_escape($this->utf8StrRev('{'.$this->AliasNumPage.'}', false, $this->tmprtl));
5291 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
5292 for ($n=1; $n <= $nb; ++$n) {
5293 $temppage = $this->getPageBuffer($n);
5294 if (!empty($this->pagegroups)) {
5295 if(isset($this->newpagegroup[$n])) {
5299 foreach ($this->pagegroups as $k => $v) {
5300 // replace total pages group numbers
5301 $vs = $this->formatPageNumber($v);
5302 $vu = $this->UTF8ToUTF16BE($vs, false);
5303 $alias_ga = $this->_escape($k);
5304 $alias_gau = $this->_escape('{'.$k.'}');
5305 if ($this->isunicode) {
5306 $alias_gb = $this->_escape($this->UTF8ToLatin1($k));
5307 $alias_gbu = $this->_escape($this->UTF8ToLatin1('{'.$k.'}'));
5308 $alias_gc = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
5309 $alias_gcu = $this->_escape($this->utf8StrRev('{'.$k.'}', false, $this->tmprtl));
5311 $temppage = str_replace($alias_gau, $vu, $temppage);
5312 if ($this->isunicode) {
5313 $temppage = str_replace($alias_gbu, $vu, $temppage);
5314 $temppage = str_replace($alias_gcu, $vu, $temppage);
5315 $temppage = str_replace($alias_gb, $vs, $temppage);
5316 $temppage = str_replace($alias_gc, $vs, $temppage);
5318 $temppage = str_replace($alias_ga, $vs, $temppage);
5319 // replace page group numbers
5320 $pvs = $this->formatPageNumber($pagegroupnum);
5321 $pvu = $this->UTF8ToUTF16BE($pvs, false);
5322 $pk = str_replace('{nb', '{pnb', $k);
5323 $alias_pga = $this->_escape($pk);
5324 $alias_pgau = $this->_escape('{'.$pk.'}');
5325 if ($this->isunicode) {
5326 $alias_pgb = $this->_escape($this->UTF8ToLatin1($pk));
5327 $alias_pgbu = $this->_escape($this->UTF8ToLatin1('{'.$pk.'}'));
5328 $alias_pgc = $this->_escape($this->utf8StrRev($pk, false, $this->tmprtl));
5329 $alias_pgcu = $this->_escape($this->utf8StrRev('{'.$pk.'}', false, $this->tmprtl));
5331 $temppage = str_replace($alias_pgau, $pvu, $temppage);
5332 if ($this->isunicode) {
5333 $temppage = str_replace($alias_pgbu, $pvu, $temppage);
5334 $temppage = str_replace($alias_pgcu, $pvu, $temppage);
5335 $temppage = str_replace($alias_pgb, $pvs, $temppage);
5336 $temppage = str_replace($alias_pgc, $pvs, $temppage);
5338 $temppage = str_replace($alias_pga, $pvs, $temppage);
5341 if (!empty($this->AliasNbPages)) {
5342 // replace total pages number
5343 $temppage = str_replace($alias_au, $nbu, $temppage);
5344 if ($this->isunicode) {
5345 $temppage = str_replace($alias_bu, $nbu, $temppage);
5346 $temppage = str_replace($alias_cu, $nbu, $temppage);
5347 $temppage = str_replace($alias_b, $nbs, $temppage);
5348 $temppage = str_replace($alias_c, $nbs, $temppage);
5350 $temppage = str_replace($alias_a, $nbs, $temppage);
5352 if (!empty($this->AliasNumPage)) {
5353 // replace page number
5354 $pnbs = $this->formatPageNumber($n);
5355 $pnbu = $this->UTF8ToUTF16BE($pnbs, false); // replacement for unicode font
5356 $temppage = str_replace($alias_pau, $pnbu, $temppage);
5357 if ($this->isunicode) {
5358 $temppage = str_replace($alias_pbu, $pnbu, $temppage);
5359 $temppage = str_replace($alias_pcu, $pnbu, $temppage);
5360 $temppage = str_replace($alias_pb, $pnbs, $temppage);
5361 $temppage = str_replace($alias_pc, $pnbs, $temppage);
5363 $temppage = str_replace($alias_pa, $pnbs, $temppage);
5365 $temppage = str_replace($this->epsmarker, '', $temppage);
5366 //$this->setPageBuffer($n, $temppage);
5369 $this->_out('<</Type /Page');
5370 $this->_out('/Parent 1 0 R');
5371 $this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
5372 $this->_out('/Resources 2 0 R');
5373 $this->_putannots($n);
5374 $this->_out('/Contents '.($this->n + 1).' 0 R>>');
5375 $this->_out('endobj');
5377 $p = ($this->compress) ? gzcompress($temppage) : $temppage;
5379 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
5380 $this->_putstream($p);
5381 $this->_out('endobj');
5382 if ($this->diskcache) {
5383 // remove temporary files
5384 unlink($this->pages[$n]);
5388 $this->offsets[1] = $this->bufferlen;
5389 $this->_out('1 0 obj');
5390 $this->_out('<</Type /Pages');
5392 for ($i=0; $i < $nb; ++$i) {
5393 $kids .= (3 + (2 * $i)).' 0 R ';
5395 $this->_out($kids.']');
5396 $this->_out('/Count '.$nb);
5397 //$this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
5399 $this->_out('endobj');
5403 * Output Page Annotations.
5404 * !!! THIS FUNCTION IS NOT YET COMPLETED !!!
5405 * See section 8.4 of PDF reference.
5406 * @param int $n page number
5408 * @author Nicola Asuni
5409 * @since 4.0.018 (2008-08-06)
5411 protected function _putannots($n) {
5412 if (isset($this->PageAnnots[$n])) {
5413 $annots = '/Annots [';
5414 foreach ($this->PageAnnots[$n] as $key => $pl) {
5415 $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
5416 $a = $pl['x'] * $this->k;
5417 $b = $this->pagedim[$n]['h'] - ($pl['y'] * $this->k);
5418 $c = $pl['w'] * $this->k;
5419 $d = $pl['h'] * $this->k;
5420 $rect = sprintf('%.2F %.2F %.2F %.2F', $a, $b, $a+$c, $b-$d);
5422 $annots .= '<</Type /Annot';
5423 $annots .= ' /Subtype /'.$pl['opt']['subtype'];
5424 $annots .= ' /Rect ['.$rect.']';
5425 $annots .= ' /Contents '.$this->_textstring($pl['txt']);
5426 //$annots .= ' /P ';
5427 $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
5428 $annots .= ' /M '.$this->_datastring('D:'.date('YmdHis'));
5429 if (isset($pl['opt']['f'])) {
5431 if (is_array($pl['opt']['f'])) {
5432 foreach ($pl['opt']['f'] as $f) {
5433 switch (strtolower($f)) {
5466 case 'togglenoview': {
5470 case 'lockedcontents': {
5480 $annots .= ' /F '.intval($val);
5482 //$annots .= ' /AP ';
5483 //$annots .= ' /AS ';
5484 $annots .= ' /Border [';
5485 if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
5486 $annots .= intval($pl['opt']['border'][0]).' ';
5487 $annots .= intval($pl['opt']['border'][1]).' ';
5488 $annots .= intval($pl['opt']['border'][2]);
5489 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
5491 foreach ($pl['opt']['border'][3] as $dash) {
5492 $annots .= intval($dash).' ';
5500 if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
5501 $annots .= ' /BS <<Type /Border';
5502 if (isset($pl['opt']['bs']['w'])) {
5503 $annots .= ' /W '.sprintf("%.4F", floatval($pl['opt']['bs']['w']));
5505 $bstyles = array('S', 'D', 'B', 'I', 'U');
5506 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
5507 $annots .= ' /S /'.$pl['opt']['bs']['s'];
5509 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
5511 foreach ($pl['opt']['bs']['d'] as $cord) {
5512 $cord = floatval($cord);
5513 $annots .= sprintf(" %.4F", $cord);
5519 if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
5520 $annots .= ' /BE <<';
5521 $bstyles = array('S', 'C');
5522 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
5523 $annots .= ' /S /'.$pl['opt']['bs']['s'];
5525 $annots .= ' /S /S';
5527 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
5528 $annots .= ' /I '.sprintf(" %.4F", $pl['opt']['be']['i']);
5533 if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
5534 foreach ($pl['opt']['c'] as $col) {
5535 $col = intval($col);
5536 $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
5537 $annots .= sprintf(" %.4F", $color);
5541 //$annots .= ' /StructParent ';
5542 //$annots .= ' /OC ';
5543 $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
5544 if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
5545 // this is a markup type
5546 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
5547 $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
5549 //$annots .= ' /Popup ';
5550 if (isset($pl['opt']['ca'])) {
5551 $annots .= ' /CA '.sprintf("%.4F", floatval($pl['opt']['ca']));
5553 if (isset($pl['opt']['rc'])) {
5554 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
5556 $annots .= ' /CreationDate '.$this->_datastring('D:'.date('YmdHis'));
5557 //$annots .= ' /IRT ';
5558 if (isset($pl['opt']['subj'])) {
5559 $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
5561 //$annots .= ' /RT ';
5562 //$annots .= ' /IT ';
5563 //$annots .= ' /ExData ';
5565 switch (strtolower($pl['opt']['subtype'])) {
5567 if (isset($pl['opt']['open'])) {
5568 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
5570 $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
5571 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5572 $annots .= ' /Name /'.$pl['opt']['name'];
5574 $annots .= ' /Name /Note';
5576 $statemodels = array('Marked', 'Review');
5577 if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
5578 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
5580 $pl['opt']['statemodel'] = 'Marked';
5581 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
5583 if ($pl['opt']['statemodel'] == 'Marked') {
5584 $states = array('Accepted', 'Unmarked');
5586 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
5588 if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
5589 $annots .= ' /State /'.$pl['opt']['state'];
5591 if ($pl['opt']['statemodel'] == 'Marked') {
5592 $annots .= ' /State /Unmarked';
5594 $annots .= ' /State /None';
5600 if(is_string($pl['txt'])) {
5601 // external URI link
5602 $annots .= ' /A <</S /URI /URI '.$this->_datastring($pl['txt']).'>>';
5605 $l = $this->links[$pl['txt']];
5606 $annots .= sprintf(' /Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $l[0])), ($this->pagedim[$l[0]]['h'] - ($l[1] * $this->k)));
5608 $hmodes = array('N', 'I', 'O', 'P');
5609 if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
5610 $annots .= ' /H /'.$pl['opt']['h'];
5612 $annots .= ' /H /I';
5614 //$annots .= ' /PA ';
5615 //$annots .= ' /Quadpoints ';
5619 $annots .= ' /DA '.$this->_textstring($pl['txt']);
5620 if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
5621 $annots .= ' /Q '.intval($pl['opt']['q']);
5623 if (isset($pl['opt']['rc'])) {
5624 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
5626 if (isset($pl['opt']['ds'])) {
5627 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
5629 if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
5630 $annots .= ' /CL [';
5631 foreach ($pl['opt']['cl'] as $cl) {
5632 $annots .= sprintf("%.4F ", $cl * $this->k);
5636 $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
5637 if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
5638 $annots .= ' /IT '.$pl['opt']['it'];
5640 if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
5641 $l = $pl['opt']['rd'][0] * $this->k;
5642 $r = $pl['opt']['rd'][1] * $this->k;
5643 $t = $pl['opt']['rd'][2] * $this->k;
5644 $b = $pl['opt']['rd'][3] * $this->k;
5645 $annots .= ' /RD ['.sprintf('%.2F %.2F %.2F %.2F', $l, $r, $t, $b).']';
5647 //$annots .= ' /LE ';
5650 // ... to be completed ...
5690 case 'fileattachment': {
5691 if (!isset($pl['opt']['fs'])) {
5694 $filename = basename($pl['opt']['fs']);
5695 if (isset($this->embeddedfiles[$filename]['n'])) {
5696 $annots .= ' /FS <</Type /Filespec /F '.$this->_datastring($filename).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
5697 $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
5698 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5699 $annots .= ' /Name /'.$pl['opt']['name'];
5701 $annots .= ' /Name /PushPin';
5707 if (!isset($pl['opt']['sound'])) {
5710 $filename = basename($pl['opt']['sound']);
5711 if (isset($this->embeddedfiles[$filename]['n'])) {
5712 // ... TO BE COMPLETED ...
5713 $iconsapp = array('Speaker', 'Mic');
5714 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5715 $annots .= ' /Name /'.$pl['opt']['name'];
5717 $annots .= ' /Name /Speaker';
5726 if (isset($pl['opt']['h'])) {
5727 $annots .= ' /H '.intval($pl['opt']['h']);
5729 if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk']))) {
5730 $annots .= ' /MK <<';
5731 // ... TO BE COMPLETED ...
5739 case 'printermark': {
5759 $this->_out($annots);
5767 protected function _putfonts() {
5769 foreach ($this->diffs as $diff) {
5772 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
5773 $this->_out('endobj');
5775 $mqr = get_magic_quotes_runtime();
5776 //set_magic_quotes_runtime(0);
5777 foreach ($this->FontFiles as $file => $info) {
5778 // search and get font file to embedd
5779 $fontdir = $info['fontdir'];
5780 $file = strtolower($file);
5782 // search files on various directories
5783 if (file_exists($fontdir.$file)) {
5784 $fontfile = $fontdir.$file;
5785 } elseif (file_exists($this->_getfontpath().$file)) {
5786 $fontfile = $this->_getfontpath().$file;
5787 } elseif (file_exists($file)) {
5790 if (!$this->empty_string($fontfile)) {
5791 $font = file_get_contents($fontfile);
5792 $compressed = (substr($file, -2) == '.z');
5793 if ((!$compressed) AND (isset($info['length2']))) {
5794 $header = (ord($font{0}) == 128);
5796 //Strip first binary header
5797 $font = substr($font, 6);
5799 if ($header AND (ord($font{$info['length1']}) == 128)) {
5800 //Strip second binary header
5801 $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
5805 $this->FontFiles[$file]['n'] = $this->n;
5806 $this->_out('<</Length '.strlen($font));
5808 $this->_out('/Filter /FlateDecode');
5810 $this->_out('/Length1 '.$info['length1']);
5811 if (isset($info['length2'])) {
5812 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
5815 $this->_putstream($font);
5816 $this->_out('endobj');
5819 //set_magic_quotes_runtime($mqr);
5820 foreach ($this->fontkeys as $k) {
5822 $this->setFontSubBuffer($k, 'n', $this->n + 1);
5823 $font = $this->getFontBuffer($k);
5824 $type = $font['type'];
5825 $name = $font['name'];
5826 if ($type == 'core') {
5829 $this->_out('<</Type /Font');
5830 $this->_out('/BaseFont /'.$name);
5831 $this->_out('/Subtype /Type1');
5832 if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
5833 $this->_out('/Encoding /WinAnsiEncoding');
5836 $this->_out('endobj');
5837 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
5838 //Additional Type1 or TrueType font
5840 $this->_out('<</Type /Font');
5841 $this->_out('/BaseFont /'.$name);
5842 $this->_out('/Subtype /'.$type);
5843 $this->_out('/FirstChar 32 /LastChar 255');
5844 $this->_out('/Widths '.($this->n + 1).' 0 R');
5845 $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
5847 if (isset($font['diff'])) {
5848 $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
5850 $this->_out('/Encoding /WinAnsiEncoding');
5854 $this->_out('endobj');
5859 for ($i = 32; $i < 256; ++$i) {
5862 $this->_out($s.']');
5863 $this->_out('endobj');
5866 $s = '<</Type /FontDescriptor /FontName /'.$name;
5867 foreach ($font['desc'] as $k => $v) {
5868 $s .= ' /'.$k.' '.$v.'';
5870 if (!$this->empty_string($font['file'])) {
5871 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
5873 $this->_out($s.'>>');
5874 $this->_out('endobj');
5876 //Allow for additional types
5877 $mtd = '_put'.strtolower($type);
5878 if (!method_exists($this, $mtd)) {
5879 $this->Error('Unsupported font type: '.$type);
5887 * Outputs font widths
5888 * @parameter array $font font data
5889 * @parameter int $cidoffset offset for CID values
5890 * @author Nicola Asuni
5892 * @since 4.4.000 (2008-12-07)
5894 protected function _putfontwidths($font, $cidoffset=0) {
5901 // for each character
5902 foreach ($font['cw'] as $cid => $width) {
5904 if ($width != $font['dw']) {
5905 if ($cid == ($prevcid + 1)) {
5907 if ($width == $prevwidth) {
5908 if ($width == $range[$rangeid][0]) {
5909 $range[$rangeid][] = $width;
5911 array_pop($range[$rangeid]);
5913 $rangeid = $prevcid;
5914 $range[$rangeid] = array();
5915 $range[$rangeid][] = $prevwidth;
5916 $range[$rangeid][] = $width;
5919 $range[$rangeid]['interval'] = true;
5924 $range[$rangeid] = array();
5925 $range[$rangeid][] = $width;
5927 $range[$rangeid][] = $width;
5934 $range[$rangeid] = array();
5935 $range[$rangeid][] = $width;
5939 $prevwidth = $width;
5946 foreach ($range as $k => $ws) {
5948 if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) {
5949 if (isset($range[$k]['interval'])) {
5950 unset($range[$k]['interval']);
5952 $range[$prevk] = array_merge($range[$prevk], $range[$k]);
5958 if (isset($ws['interval'])) {
5964 unset($range[$k]['interval']);
5972 foreach ($range as $k => $ws) {
5973 if (count(array_count_values($ws)) == 1) {
5974 // interval mode is more compact
5975 $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0];
5978 $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
5981 $this->_out('/W ['.$w.' ]');
5985 * Adds unicode fonts.<br>
5986 * Based on PDF Reference 1.3 (section 5)
5987 * @parameter array $font font data
5989 * @author Nicola Asuni
5990 * @since 1.52.0.TC005 (2005-01-05)
5992 protected function _puttruetypeunicode($font) {
5994 // A composite font composed of other fonts, organized hierarchically
5996 $this->_out('<</Type /Font');
5997 $this->_out('/Subtype /Type0');
5998 $this->_out('/BaseFont /'.$font['name'].'');
5999 $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.
6000 $this->_out('/ToUnicode /Identity-H');
6001 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
6003 $this->_out('endobj');
6005 // A CIDFont whose glyph descriptions are based on TrueType font technology
6007 $this->_out('<</Type /Font');
6008 $this->_out('/Subtype /CIDFontType2');
6009 $this->_out('/BaseFont /'.$font['name'].'');
6010 // A dictionary containing entries that define the character collection of the CIDFont.
6011 $cidinfo = '/Registry '.$this->_datastring('Adobe');
6012 $cidinfo .= ' /Ordering '.$this->_datastring('Identity');
6013 $cidinfo .= ' /Supplement 0';
6014 $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
6015 $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
6016 $this->_out('/DW '.$font['dw'].''); // default width
6017 $this->_putfontwidths($font, 0);
6018 $this->_out('/CIDToGIDMap '.($this->n + 2).' 0 R');
6020 $this->_out('endobj');
6022 // A font descriptor describing the CIDFont default metrics other than its glyph widths
6024 $this->_out('<</Type /FontDescriptor');
6025 $this->_out('/FontName /'.$font['name']);
6026 foreach ($font['desc'] as $key => $value) {
6027 $this->_out('/'.$key.' '.$value);
6030 if (!$this->empty_string($font['file'])) {
6031 // A stream containing a TrueType font
6032 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
6033 $fontdir = $this->FontFiles[$font['file']]['fontdir'];
6036 $this->_out('endobj');
6038 if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
6039 // Embed CIDToGIDMap
6040 // A specification of the mapping from CIDs to glyph indices
6041 // search and get CTG font file to embedd
6042 $ctgfile = strtolower($font['ctg']);
6043 // search and get ctg font file to embedd
6045 // search files on various directories
6046 if (file_exists($fontdir.$ctgfile)) {
6047 $fontfile = $fontdir.$ctgfile;
6048 } elseif (file_exists($this->_getfontpath().$ctgfile)) {
6049 $fontfile = $this->_getfontpath().$ctgfile;
6050 } elseif (file_exists($ctgfile)) {
6051 $fontfile = $ctgfile;
6053 if ($this->empty_string($fontfile)) {
6054 $this->Error('Font file not found: '.$ctgfile);
6056 $size = filesize($fontfile);
6057 $this->_out('<</Length '.$size.'');
6058 if (substr($fontfile, -2) == '.z') { // check file extension
6059 // Decompresses data encoded using the public-domain
6060 // zlib/deflate compression method, reproducing the
6061 // original text or binary data
6062 $this->_out('/Filter /FlateDecode');
6065 $this->_putstream(file_get_contents($fontfile));
6067 $this->_out('endobj');
6071 * Output CID-0 fonts.
6072 * @param array $font font data
6074 * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
6075 * @since 3.2.000 (2008-06-23)
6077 protected function _putcidfont0($font) {
6079 if (isset($font['cidinfo']['uni2cid'])) {
6080 // convert unicode to cid.
6081 $uni2cid = $font['cidinfo']['uni2cid'];
6083 foreach ($font['cw'] as $uni => $width) {
6084 if (isset($uni2cid[$uni])) {
6085 $cw[($uni2cid[$uni] + $cidoffset)] = $width;
6086 } elseif ($uni < 256) {
6088 } // else unknown character
6090 $font = array_merge($font, array('cw' => $cw));
6092 $name = $font['name'];
6093 $enc = $font['enc'];
6095 $longname = $name.'-'.$enc;
6100 $this->_out('<</Type /Font');
6101 $this->_out('/BaseFont /'.$longname);
6102 $this->_out('/Subtype /Type0');
6104 $this->_out('/Encoding /'.$enc);
6106 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
6108 $this->_out('endobj');
6110 $this->_out('<</Type /Font');
6111 $this->_out('/BaseFont /'.$name);
6112 $this->_out('/Subtype /CIDFontType0');
6113 $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry']);
6114 $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering']);
6115 $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
6116 $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
6117 $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
6118 $this->_out('/DW '.$font['dw']);
6119 $this->_putfontwidths($font, $cidoffset);
6121 $this->_out('endobj');
6123 $s = '<</Type /FontDescriptor /FontName /'.$name;
6124 foreach ($font['desc'] as $k => $v) {
6125 if ($k != 'Style') {
6126 $s .= ' /'.$k.' '.$v.'';
6129 $this->_out($s.'>>');
6130 $this->_out('endobj');
6137 protected function _putimages() {
6138 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
6139 foreach ($this->imagekeys as $file) {
6140 $info = $this->getImageBuffer($file);
6142 $this->setImageSubBuffer($file, 'n', $this->n);
6143 $this->_out('<</Type /XObject');
6144 $this->_out('/Subtype /Image');
6145 $this->_out('/Width '.$info['w']);
6146 $this->_out('/Height '.$info['h']);
6147 if (isset($info['masked'])) {
6148 $this->_out('/SMask '.($this->n - 1).' 0 R');
6150 if ($info['cs'] == 'Indexed') {
6151 $this->_out('/ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]');
6153 $this->_out('/ColorSpace /'.$info['cs']);
6154 if ($info['cs'] == 'DeviceCMYK') {
6155 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
6158 $this->_out('/BitsPerComponent '.$info['bpc']);
6159 if (isset($info['f'])) {
6160 $this->_out('/Filter /'.$info['f']);
6162 if (isset($info['parms'])) {
6163 $this->_out($info['parms']);
6165 if (isset($info['trns']) AND is_array($info['trns'])) {
6167 $count_info = count($info['trns']);
6168 for ($i=0; $i < $count_info; ++$i) {
6169 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
6171 $this->_out('/Mask ['.$trns.']');
6173 $this->_out('/Length '.strlen($info['data']).'>>');
6174 $this->_putstream($info['data']);
6175 $this->_out('endobj');
6177 if ($info['cs'] == 'Indexed') {
6179 $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
6180 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
6181 $this->_putstream($pal);
6182 $this->_out('endobj');
6188 * Output Spot Colors Resources.
6190 * @since 4.0.024 (2008-09-12)
6192 protected function _putspotcolors() {
6193 foreach ($this->spot_colors as $name => $color) {
6195 $this->spot_colors[$name]['n'] = $this->n;
6196 $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
6197 $this->_out('/DeviceCMYK <<');
6198 $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
6199 $this->_out(sprintf('/C1 [%.4F %.4F %.4F %.4F] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
6200 $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
6201 $this->_out('endobj');
6206 * Output object dictionary for images.
6209 protected function _putxobjectdict() {
6210 foreach ($this->imagekeys as $file) {
6211 $info = $this->getImageBuffer($file);
6212 $this->_out('/I'.$info['i'].' '.$info['n'].' 0 R');
6217 * Output Resources Dictionary.
6220 protected function _putresourcedict() {
6221 $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
6222 $this->_out('/Font <<');
6223 foreach ($this->fontkeys as $fontkey) {
6224 $font = $this->getFontBuffer($fontkey);
6225 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
6228 $this->_out('/XObject <<');
6229 $this->_putxobjectdict();
6232 $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
6234 $this->_out('/ExtGState <<');
6235 foreach ($this->extgstates as $k => $extgstate) {
6236 $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
6240 if (isset($this->gradients) AND (count($this->gradients) > 0)) {
6241 $this->_out('/Shading <<');
6242 foreach ($this->gradients as $id => $grad) {
6243 $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
6248 if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
6249 $this->_out('/ColorSpace <<');
6250 foreach ($this->spot_colors as $color) {
6251 $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
6261 protected function _putresources() {
6262 $this->_putextgstates();
6265 $this->_putimages();
6266 $this->_putspotcolors();
6267 $this->_putshaders();
6268 //Resource dictionary
6269 $this->offsets[2] = $this->bufferlen;
6270 $this->_out('2 0 obj');
6272 $this->_putresourcedict();
6274 $this->_out('endobj');
6275 $this->_putjavascript();
6276 $this->_putbookmarks();
6277 $this->_putEmbeddedFiles();
6279 if ($this->encrypted) {
6281 $this->enc_obj_id = $this->n;
6283 $this->_putencryption();
6285 $this->_out('endobj');
6290 * Adds some Metadata information
6291 * (see Chapter 10.2 of PDF Reference)
6294 protected function _putinfo() {
6295 if (!$this->empty_string($this->title)) {
6296 $this->_out('/Title '.$this->_textstring($this->title));
6298 if (!$this->empty_string($this->author)) {
6299 $this->_out('/Author '.$this->_textstring($this->author));
6301 if (!$this->empty_string($this->subject)) {
6302 $this->_out('/Subject '.$this->_textstring($this->subject));
6304 if (!$this->empty_string($this->keywords)) {
6305 $this->_out('/Keywords '.$this->_textstring($this->keywords));
6307 if (!$this->empty_string($this->creator)) {
6308 $this->_out('/Creator '.$this->_textstring($this->creator));
6310 if (defined('PDF_PRODUCER')) {
6311 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
6313 $this->_out('/CreationDate '.$this->_datastring('D:'.date('YmdHis')));
6314 $this->_out('/ModDate '.$this->_datastring('D:'.date('YmdHis')));
6321 protected function _putcatalog() {
6322 $this->_out('/Type /Catalog');
6323 $this->_out('/Pages 1 0 R');
6324 if ($this->ZoomMode == 'fullpage') {
6325 $this->_out('/OpenAction [3 0 R /Fit]');
6326 } elseif ($this->ZoomMode == 'fullwidth') {
6327 $this->_out('/OpenAction [3 0 R /FitH null]');
6328 } elseif ($this->ZoomMode == 'real') {
6329 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
6330 } elseif (!is_string($this->ZoomMode)) {
6331 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
6333 if (isset($this->LayoutMode) AND (!$this->empty_string($this->LayoutMode))) {
6334 $this->_out('/PageLayout /'.$this->LayoutMode.'');
6336 if (isset($this->PageMode) AND (!$this->empty_string($this->PageMode))) {
6337 $this->_out('/PageMode /'.$this->PageMode);
6339 if (isset($this->l['a_meta_language'])) {
6340 $this->_out('/Lang /'.$this->l['a_meta_language']);
6342 $this->_out('/Names <<');
6343 if (!$this->empty_string($this->javascript)) {
6344 $this->_out('/JavaScript '.($this->n_js).' 0 R');
6347 if (count($this->outlines) > 0) {
6348 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
6349 $this->_out('/PageMode /UseOutlines');
6351 $this->_putviewerpreferences();
6352 $p = $this->n_ocg_print.' 0 R';
6353 $v = $this->n_ocg_view.' 0 R';
6354 $as = '<</Event /Print /OCGs ['.$p.' '.$v.'] /Category [/Print]>> <</Event /View /OCGs ['.$p.' '.$v.'] /Category [/View]>>';
6355 $this->_out('/OCProperties <</OCGs ['.$p.' '.$v.'] /D <</ON ['.$p.'] /OFF ['.$v.'] /AS ['.$as.']>>>>');
6359 * Output viewer preferences.
6360 * @author Nicola asuni
6361 * @since 3.1.000 (2008-06-09)
6364 protected function _putviewerpreferences() {
6365 $this->_out('/ViewerPreferences<<');
6367 $this->_out('/Direction /R2L');
6369 $this->_out('/Direction /L2R');
6371 if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
6372 $this->_out('/HideToolbar true');
6374 if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
6375 $this->_out('/HideMenubar true');
6377 if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
6378 $this->_out('/HideWindowUI true');
6380 if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
6381 $this->_out('/FitWindow true');
6383 if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
6384 $this->_out('/CenterWindow true');
6386 if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
6387 $this->_out('/DisplayDocTitle true');
6389 if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
6390 $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
6392 if (isset($this->viewer_preferences['ViewArea'])) {
6393 $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
6395 if (isset($this->viewer_preferences['ViewClip'])) {
6396 $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
6398 if (isset($this->viewer_preferences['PrintArea'])) {
6399 $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
6401 if (isset($this->viewer_preferences['PrintClip'])) {
6402 $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
6404 if (isset($this->viewer_preferences['PrintScaling'])) {
6405 $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
6407 if (isset($this->viewer_preferences['Duplex']) AND (!$this->empty_string($this->viewer_preferences['Duplex']))) {
6408 $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
6410 if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
6411 if ($this->viewer_preferences['PickTrayByPDFSize']) {
6412 $this->_out('/PickTrayByPDFSize true');
6414 $this->_out('/PickTrayByPDFSize false');
6417 if (isset($this->viewer_preferences['PrintPageRange'])) {
6418 $PrintPageRangeNum = '';
6419 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
6420 $PrintPageRangeNum .= ' '.($v - 1).'';
6422 $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
6424 if (isset($this->viewer_preferences['NumCopies'])) {
6425 $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
6434 protected function _puttrailer() {
6435 $this->_out('/Size '.($this->n + 1));
6436 $this->_out('/Root '.$this->n.' 0 R');
6437 $this->_out('/Info '.($this->n - 1).' 0 R');
6438 if ($this->encrypted) {
6439 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
6440 $this->_out('/ID [()()]');
6445 * Output PDF header.
6448 protected function _putheader() {
6449 $this->_out('%PDF-'.$this->PDFVersion);
6453 * Output end of document (EOF).
6456 protected function _enddoc() {
6458 $this->_putheader();
6460 $this->_putresources();
6466 $this->_out('endobj');
6470 $this->_putcatalog();
6471 $this->_putcertification();
6472 $this->_putuserrights();
6474 $this->_out('endobj');
6476 $o = $this->bufferlen;
6477 $this->_out('xref');
6478 $this->_out('0 '.($this->n + 1));
6479 $this->_out('0000000000 65535 f ');
6480 for ($i=1; $i <= $this->n; ++$i) {
6481 $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
6483 if (isset($this->embeddedfiles) AND count($this->embeddedfiles) > 0) {
6484 $this->_out('100000 '.count($this->embeddedfiles));
6485 foreach ($this->embeddedfiles as $filename => $filedata) {
6486 $this->_out(sprintf('%010d 00000 n ', $this->offsets[$filedata['n']]));
6490 $this->_out('trailer');
6492 $this->_puttrailer();
6494 $this->_out('startxref');
6496 $this->_out('%%EOF');
6497 $this->state = 3; // end-of-doc
6498 if ($this->diskcache) {
6499 // remove temporary files used for images
6500 foreach ($this->imagekeys as $key) {
6501 // remove temporary files
6502 unlink($this->images[$key]);
6504 foreach ($this->fontkeys as $key) {
6505 // remove temporary files
6506 unlink($this->fonts[$key]);
6512 * Initialize a new page.
6513 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
6514 * @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>
6517 protected function _beginpage($orientation='', $format='') {
6519 $this->setPageBuffer($this->page, '');
6520 // initialize array for graphics tranformation positions inside a page buffer
6521 $this->transfmrk[$this->page] = array();
6523 if ($this->empty_string($orientation)) {
6524 if (isset($this->CurOrientation)) {
6525 $orientation = $this->CurOrientation;
6530 if ($this->empty_string($format)) {
6531 $this->setPageOrientation($orientation);
6533 $this->setPageFormat($format, $orientation);
6536 $this->x = $this->w - $this->rMargin;
6538 $this->x = $this->lMargin;
6540 $this->y = $this->tMargin;
6541 if (isset($this->newpagegroup[$this->page])) {
6542 // start a new group
6543 $n = sizeof($this->pagegroups) + 1;
6544 $alias = '{nb'.$n.'}';
6545 $this->pagegroups[$alias] = 1;
6546 $this->currpagegroup = $alias;
6547 } elseif ($this->currpagegroup) {
6548 ++$this->pagegroups[$this->currpagegroup];
6556 protected function _endpage() {
6557 $this->setVisibility('all');
6562 * Begin a new object.
6565 protected function _newobj() {
6567 $this->offsets[$this->n] = $this->bufferlen;
6568 $this->_out($this->n.' 0 obj');
6573 * @param int $x X coordinate
6574 * @param int $y Y coordinate
6575 * @param string $txt text to underline
6578 protected function _dounderline($x, $y, $txt) {
6579 $up = $this->CurrentFont['up'];
6580 $ut = $this->CurrentFont['ut'];
6581 $w = $this->GetStringWidth($txt);
6582 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);
6586 * Line through text.
6587 * @param int $x X coordinate
6588 * @param int $y Y coordinate
6589 * @param string $txt text to linethrough
6592 protected function _dolinethrough($x, $y, $txt) {
6593 $up = $this->CurrentFont['up'];
6594 $ut = $this->CurrentFont['ut'];
6595 $w = $this->GetStringWidth($txt);
6596 return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ($this->h - ($y - ($this->FontSize/2) - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
6600 * Read a 4-byte integer from file.
6601 * @param string $f file name.
6602 * @return 4-byte integer
6605 protected function _freadint($f) {
6606 $a = unpack('Ni', fread($f, 4));
6611 * Add "\" before "\", "(" and ")"
6612 * @param string $s string to escape.
6613 * @return string escaped string.
6616 protected function _escape($s) {
6617 // the chr(13) substitution fixes the Bugs item #1421290.
6618 return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
6622 * Format a date string for meta information
6623 * @param string $s date string to escape.
6624 * @return string escaped string.
6627 protected function _datastring($s) {
6628 if ($this->encrypted) {
6629 $s = $this->_RC4($this->_objectkey($this->n), $s);
6631 return '('. $this->_escape($s).')';
6635 * Format a text string for meta information
6636 * @param string $s string to escape.
6637 * @return string escaped string.
6640 protected function _textstring($s) {
6641 if ($this->isunicode) {
6642 //Convert string to UTF-16BE
6643 $s = $this->UTF8ToUTF16BE($s, true);
6645 return $this->_datastring($s);
6649 * Format a text string
6650 * @param string $s string to escape.
6651 * @return string escaped string.
6654 protected function _escapetext($s) {
6655 if ($this->isunicode) {
6656 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
6657 $s = $this->UTF8ToLatin1($s);
6659 //Convert string to UTF-16BE and reverse RTL language
6660 $s = $this->utf8StrRev($s, false, $this->tmprtl);
6663 return $this->_escape($s);
6668 * @param string $s string to output.
6671 protected function _putstream($s) {
6672 if ($this->encrypted) {
6673 $s = $this->_RC4($this->_objectkey($this->n), $s);
6675 $this->_out('stream');
6677 $this->_out('endstream');
6681 * Output a string to the document.
6682 * @param string $s string to output.
6685 protected function _out($s) {
6686 if ($this->state == 2) {
6687 if ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
6688 // puts data before page footer
6689 $pagebuff = $this->getPageBuffer($this->page);
6690 $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
6691 $footer = substr($pagebuff, -$this->footerlen[$this->page]);
6692 $this->setPageBuffer($this->page, $page.$s."\n".$footer);
6693 // update footer position
6694 $this->footerpos[$this->page] += strlen($s."\n");
6696 $this->setPageBuffer($this->page, $s."\n", true);
6699 $this->setBuffer($s."\n");
6704 * Converts UTF-8 strings to codepoints array.<br>
6705 * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
6706 * Based on: http://www.faqs.org/rfcs/rfc3629.html
6708 * Char. number range | UTF-8 octet sequence
6709 * (hexadecimal) | (binary)
6710 * --------------------+-----------------------------------------------
6711 * 0000 0000-0000 007F | 0xxxxxxx
6712 * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
6713 * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
6714 * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
6715 * ---------------------------------------------------------------------
6718 * ---------------------------------------------------------------------
6719 * UTF8-octets = *( UTF8-char )
6720 * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
6722 * UTF8-2 = %xC2-DF UTF8-tail
6724 * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
6725 * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
6726 * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
6727 * %xF4 %x80-8F 2( UTF8-tail )
6728 * UTF8-tail = %x80-BF
6729 * ---------------------------------------------------------------------
6731 * @param string $str string to process.
6732 * @return array containing codepoints (UTF-8 characters values)
6734 * @author Nicola Asuni
6735 * @since 1.53.0.TC005 (2005-01-05)
6737 protected function UTF8StringToArray($str) {
6738 if (isset($this->cache_UTF8StringToArray['_'.$str])) {
6739 // return cached value
6740 return($this->cache_UTF8StringToArray['_'.$str]);
6743 if ($this->cache_size_UTF8StringToArray >= $this->cache_maxsize_UTF8StringToArray) {
6744 // remove first element
6745 array_shift($this->cache_UTF8StringToArray);
6747 ++$this->cache_size_UTF8StringToArray;
6748 if (!$this->isunicode) {
6749 // split string into array of equivalent codes
6751 $strlen = strlen($str);
6752 for ($i=0; $i < $strlen; ++$i) {
6753 $strarr[] = ord($str{$i});
6755 // insert new value on cache
6756 $this->cache_UTF8StringToArray['_'.$str] = $strarr;
6759 $unicode = array(); // array containing unicode values
6760 $bytes = array(); // array containing single character byte sequences
6761 $numbytes = 1; // number of octetc needed to represent the UTF-8 character
6762 $str .= ''; // force $str to be a string
6763 $length = strlen($str);
6764 for ($i = 0; $i < $length; ++$i) {
6765 $char = ord($str{$i}); // get one string character at time
6766 if (count($bytes) == 0) { // get starting octect
6767 if ($char <= 0x7F) {
6768 $unicode[] = $char; // use the character "as is" because is ASCII
6770 } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
6771 $bytes[] = ($char - 0xC0) << 0x06;
6773 } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
6774 $bytes[] = ($char - 0xE0) << 0x0C;
6776 } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
6777 $bytes[] = ($char - 0xF0) << 0x12;
6780 // use replacement character for other invalid sequences
6781 $unicode[] = 0xFFFD;
6785 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
6786 $bytes[] = $char - 0x80;
6787 if (count($bytes) == $numbytes) {
6788 // compose UTF-8 bytes to a single unicode value
6790 for ($j = 1; $j < $numbytes; ++$j) {
6791 $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
6793 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
6794 /* The definition of UTF-8 prohibits encoding character numbers between
6795 U+D800 and U+DFFF, which are reserved for use with the UTF-16
6796 encoding form (as surrogate pairs) and do not directly represent
6798 $unicode[] = 0xFFFD; // use replacement character
6800 $unicode[] = $char; // add char to array
6802 // reset data for next char
6807 // use replacement character for other invalid sequences
6808 $unicode[] = 0xFFFD;
6813 // insert new value on cache
6814 $this->cache_UTF8StringToArray['_'.$str] = $unicode;
6819 * Converts UTF-8 strings to UTF16-BE.<br>
6820 * @param string $str string to process.
6821 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
6824 * @author Nicola Asuni
6825 * @since 1.53.0.TC005 (2005-01-05)
6826 * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
6828 protected function UTF8ToUTF16BE($str, $setbom=true) {
6829 if (!$this->isunicode) {
6830 return $str; // string is not in unicode
6832 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
6833 return $this->arrUTF8ToUTF16BE($unicode, $setbom);
6837 * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
6838 * @param string $str string to process.
6840 * @author Andrew Whitehead, Nicola Asuni
6842 * @since 3.2.000 (2008-06-23)
6844 protected function UTF8ToLatin1($str) {
6845 global $utf8tolatin;
6846 if (!$this->isunicode) {
6847 return $str; // string is not in unicode
6849 $outstr = ''; // string to be returned
6850 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
6851 foreach ($unicode as $char) {
6853 $outstr .= chr($char);
6854 } elseif (array_key_exists($char, $utf8tolatin)) {
6856 $outstr .= chr($utf8tolatin[$char]);
6857 } elseif ($char == 0xFFFD) {
6867 * Converts array of UTF-8 characters to UTF16-BE string.<br>
6868 * Based on: http://www.faqs.org/rfcs/rfc2781.html
6872 * Encoding of a single character from an ISO 10646 character value to
6873 * UTF-16 proceeds as follows. Let U be the character number, no greater
6876 * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
6879 * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
6880 * U' must be less than or equal to 0xFFFFF. That is, U' can be
6881 * represented in 20 bits.
6883 * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
6884 * 0xDC00, respectively. These integers each have 10 bits free to
6885 * encode the character value, for a total of 20 bits.
6887 * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
6888 * bits of W1 and the 10 low-order bits of U' to the 10 low-order
6889 * bits of W2. Terminate.
6891 * Graphically, steps 2 through 4 look like:
6892 * U' = yyyyyyyyyyxxxxxxxxxx
6893 * W1 = 110110yyyyyyyyyy
6894 * W2 = 110111xxxxxxxxxx
6896 * @param array $unicode array containing UTF-8 unicode values
6897 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
6900 * @author Nicola Asuni
6901 * @since 2.1.000 (2008-01-08)
6902 * @see UTF8ToUTF16BE()
6904 protected function arrUTF8ToUTF16BE($unicode, $setbom=true) {
6905 $outstr = ''; // string to be returned
6907 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
6909 foreach ($unicode as $char) {
6910 if ($char == 0xFFFD) {
6911 $outstr .= "\xFF\xFD"; // replacement character
6912 } elseif ($char < 0x10000) {
6913 $outstr .= chr($char >> 0x08);
6914 $outstr .= chr($char & 0xFF);
6917 $w1 = 0xD800 | ($char >> 0x10);
6918 $w2 = 0xDC00 | ($char & 0x3FF);
6919 $outstr .= chr($w1 >> 0x08);
6920 $outstr .= chr($w1 & 0xFF);
6921 $outstr .= chr($w2 >> 0x08);
6922 $outstr .= chr($w2 & 0xFF);
6927 // ====================================================
6931 * @param array $font font
6935 public function setHeaderFont($font) {
6936 $this->header_font = $font;
6943 * @since 4.0.012 (2008-07-24)
6945 public function getHeaderFont() {
6946 return $this->header_font;
6951 * @param array $font font
6955 public function setFooterFont($font) {
6956 $this->footer_font = $font;
6963 * @since 4.0.012 (2008-07-24)
6965 public function getFooterFont() {
6966 return $this->footer_font;
6970 * Set language array.
6971 * @param array $language
6975 public function setLanguageArray($language) {
6976 $this->l = $language;
6977 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
6981 * Returns the PDF data.
6984 public function getPDFData() {
6985 if ($this->state < 3) {
6988 return $this->buffer;
6992 * Output anchor link.
6993 * @param string $url link URL or internal link (i.e.: <a href="#23">link to page 23</a>)
6994 * @param string $name link name
6995 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
6996 * @param boolean $firstline if true prints only the first line and return the remaining string.
6997 * @param array $color array of RGB text color
6998 * @param string $style font style (U, D, B, I)
6999 * @return the number of cells used or the remaining text if $firstline = true;
7002 public function addHtmlLink($url, $name, $fill=0, $firstline=false, $color='', $style=-1) {
7003 if (!$this->empty_string($url) AND ($url{0} == '#')) {
7004 // convert url to internal link
7005 $page = intval(substr($url, 1));
7006 $url = $this->AddLink();
7007 $this->SetLink($url, 0, $page);
7009 // store current settings
7010 $prevcolor = $this->fgcolor;
7011 $prevstyle = $this->FontStyle;
7012 if (empty($color)) {
7013 $this->SetTextColorArray($this->htmlLinkColorArray);
7015 $this->SetTextColorArray($color);
7018 $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
7020 $this->SetFont('', $this->FontStyle.$style);
7022 $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
7024 $this->SetFont('', $prevstyle);
7025 $this->SetTextColorArray($prevcolor);
7030 * Returns an associative array (keys: R,G,B) from an html color name or a six-digit or three-digit hexadecimal color representation (i.e. #3FE5AA or #7FF).
7031 * @param string $color html color
7032 * @return array RGB color or false in case of error.
7035 public function convertHTMLColorToDec($color='#FFFFFF') {
7037 $returncolor = false;
7038 $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
7039 $color = strtolower($color);
7040 if (strlen($color) == 0) {
7043 if (substr($color, 0, 3) == 'rgb') {
7044 $codes = substr($color, 4);
7045 $codes = str_replace(')', '', $codes);
7046 $returncolor = explode(',', $codes, 3);
7047 return $returncolor;
7049 if (substr($color, 0, 1) != '#') {
7050 // decode color name
7051 if (isset($webcolor[$color])) {
7052 $color_code = $webcolor[$color];
7057 $color_code = substr($color, 1);
7059 switch (strlen($color_code)) {
7061 // three-digit hexadecimal representation
7062 $r = substr($color_code, 0, 1);
7063 $g = substr($color_code, 1, 1);
7064 $b = substr($color_code, 2, 1);
7065 $returncolor['R'] = hexdec($r.$r);
7066 $returncolor['G'] = hexdec($g.$g);
7067 $returncolor['B'] = hexdec($b.$b);
7071 // six-digit hexadecimal representation
7072 $returncolor['R'] = hexdec(substr($color_code, 0, 2));
7073 $returncolor['G'] = hexdec(substr($color_code, 2, 2));
7074 $returncolor['B'] = hexdec(substr($color_code, 4, 2));
7078 return $returncolor;
7082 * Converts pixels to User's Units.
7083 * @param int $px pixels
7084 * @return float value in user's unit
7086 * @see setImageScale(), getImageScale()
7088 public function pixelsToUnits($px) {
7089 return ($px / ($this->imgscale * $this->k));
7093 * Reverse function for htmlentities.
7094 * Convert entities in UTF-8.
7095 * @param $text_to_convert Text to convert.
7096 * @return string converted
7099 public function unhtmlentities($text_to_convert) {
7100 return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
7103 // ENCRYPTION METHODS ----------------------------------
7104 // SINCE 2.0.000 (2008-01-02)
7107 * Compute encryption key depending on object number where the encrypted data is stored
7108 * @param int $n object number
7110 * @since 2.0.000 (2008-01-02)
7112 protected function _objectkey($n) {
7113 return substr($this->_md5_16($this->encryption_key.pack('VXxx', $n)), 0, 10);
7117 * Put encryption on PDF document.
7119 * @since 2.0.000 (2008-01-02)
7121 protected function _putencryption() {
7122 $this->_out('/Filter /Standard');
7123 $this->_out('/V 1');
7124 $this->_out('/R 2');
7125 $this->_out('/O ('.$this->_escape($this->Ovalue).')');
7126 $this->_out('/U ('.$this->_escape($this->Uvalue).')');
7127 $this->_out('/P '.$this->Pvalue);
7131 * Returns the input text exrypted using RC4 algorithm and the specified key.
7132 * RC4 is the standard encryption algorithm used in PDF format
7133 * @param string $key encryption key
7134 * @param String $text input text to be encrypted
7135 * @return String encrypted text
7137 * @since 2.0.000 (2008-01-02)
7138 * @author Klemen Vodopivec
7140 protected function _RC4($key, $text) {
7141 if ($this->last_rc4_key != $key) {
7142 $k = str_repeat($key, ((256 / strlen($key)) + 1));
7143 $rc4 = range(0, 255);
7145 for ($i = 0; $i < 256; ++$i) {
7147 $j = ($j + $t + ord($k{$i})) % 256;
7148 $rc4[$i] = $rc4[$j];
7151 $this->last_rc4_key = $key;
7152 $this->last_rc4_key_c = $rc4;
7154 $rc4 = $this->last_rc4_key_c;
7156 $len = strlen($text);
7160 for ($i = 0; $i < $len; ++$i) {
7161 $a = ($a + 1) % 256;
7163 $b = ($b + $t) % 256;
7164 $rc4[$a] = $rc4[$b];
7166 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
7167 $out .= chr(ord($text{$i}) ^ $k);
7173 * Encrypts a string using MD5 and returns it's value as a binary string.
7174 * @param string $str input string
7175 * @return String MD5 encrypted binary string
7177 * @since 2.0.000 (2008-01-02)
7178 * @author Klemen Vodopivec
7180 protected function _md5_16($str) {
7181 return pack('H*', md5($str));
7185 * Compute O value (used for RC4 encryption)
7186 * @param String $user_pass user password
7187 * @param String $owner_pass user password
7188 * @return String O value
7190 * @since 2.0.000 (2008-01-02)
7191 * @author Klemen Vodopivec
7193 protected function _Ovalue($user_pass, $owner_pass) {
7194 $tmp = $this->_md5_16($owner_pass);
7195 $owner_RC4_key = substr($tmp, 0, 5);
7196 return $this->_RC4($owner_RC4_key, $user_pass);
7200 * Compute U value (used for RC4 encryption)
7201 * @return String U value
7203 * @since 2.0.000 (2008-01-02)
7204 * @author Klemen Vodopivec
7206 protected function _Uvalue() {
7207 return $this->_RC4($this->encryption_key, $this->padding);
7211 * Compute encryption key
7212 * @param String $user_pass user password
7213 * @param String $owner_pass user password
7214 * @param String $protection protection type
7216 * @since 2.0.000 (2008-01-02)
7217 * @author Klemen Vodopivec
7219 protected function _generateencryptionkey($user_pass, $owner_pass, $protection) {
7221 $user_pass = substr($user_pass.$this->padding, 0, 32);
7222 $owner_pass = substr($owner_pass.$this->padding, 0, 32);
7224 $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
7225 // Compute encyption key
7226 $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
7227 $this->encryption_key = substr($tmp, 0, 5);
7229 $this->Uvalue = $this->_Uvalue();
7231 $this->Pvalue = -(($protection^255) + 1);
7235 * Set document protection
7236 * The permission array is composed of values taken from the following ones:
7237 * - copy: copy text and images to the clipboard
7238 * - print: print the document
7239 * - modify: modify it (except for annotations and forms)
7240 * - annot-forms: add annotations and forms
7241 * Remark: the protection against modification is for people who have the full Acrobat product.
7242 * 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.
7243 * 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.
7244 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
7245 * @param String $user_pass user password. Empty by default.
7246 * @param String $owner_pass owner password. If not specified, a random value is used.
7248 * @since 2.0.000 (2008-01-02)
7249 * @author Klemen Vodopivec
7251 public function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
7252 $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
7254 foreach ($permissions as $permission) {
7255 if (!isset($options[$permission])) {
7256 $this->Error('Incorrect permission: '.$permission);
7258 $protection += $options[$permission];
7260 if ($owner_pass === null) {
7261 $owner_pass = uniqid(rand());
7263 $this->encrypted = true;
7264 $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
7267 // END OF ENCRYPTION FUNCTIONS -------------------------
7269 // START TRANSFORMATIONS SECTION -----------------------
7272 * Starts a 2D tranformation saving current graphic state.
7273 * This function must be called before scaling, mirroring, translation, rotation and skewing.
7274 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
7276 * @since 2.1.000 (2008-01-07)
7277 * @see StartTransform(), StopTransform()
7279 public function StartTransform() {
7281 $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
7285 * Stops a 2D tranformation restoring previous graphic state.
7286 * This function must be called after scaling, mirroring, translation, rotation and skewing.
7287 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
7289 * @since 2.1.000 (2008-01-07)
7290 * @see StartTransform(), StopTransform()
7292 public function StopTransform() {
7294 if (isset($this->transfmatrix)) {
7295 array_pop($this->transfmatrix);
7297 array_pop($this->transfmrk[$this->page]);
7300 * Horizontal Scaling.
7301 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
7302 * @param int $x abscissa of the scaling center. Default is current x position
7303 * @param int $y ordinate of the scaling center. Default is current y position
7305 * @since 2.1.000 (2008-01-07)
7306 * @see StartTransform(), StopTransform()
7308 public function ScaleX($s_x, $x='', $y='') {
7309 $this->Scale($s_x, 100, $x, $y);
7314 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
7315 * @param int $x abscissa of the scaling center. Default is current x position
7316 * @param int $y ordinate of the scaling center. Default is current y position
7318 * @since 2.1.000 (2008-01-07)
7319 * @see StartTransform(), StopTransform()
7321 public function ScaleY($s_y, $x='', $y='') {
7322 $this->Scale(100, $s_y, $x, $y);
7326 * Vertical and horizontal proportional Scaling.
7327 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
7328 * @param int $x abscissa of the scaling center. Default is current x position
7329 * @param int $y ordinate of the scaling center. Default is current y position
7331 * @since 2.1.000 (2008-01-07)
7332 * @see StartTransform(), StopTransform()
7334 public function ScaleXY($s, $x='', $y='') {
7335 $this->Scale($s, $s, $x, $y);
7339 * Vertical and horizontal non-proportional Scaling.
7340 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
7341 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
7342 * @param int $x abscissa of the scaling center. Default is current x position
7343 * @param int $y ordinate of the scaling center. Default is current y position
7345 * @since 2.1.000 (2008-01-07)
7346 * @see StartTransform(), StopTransform()
7348 public function Scale($s_x, $s_y, $x='', $y='') {
7358 if (($s_x == 0) OR ($s_y == 0)) {
7359 $this->Error('Please do not use values equal to zero for scaling');
7361 $y = ($this->h - $y) * $this->k;
7363 //calculate elements of transformation matrix
7370 $tm[4] = $x * (1 - $s_x);
7371 $tm[5] = $y * (1 - $s_y);
7372 //scale the coordinate system
7373 $this->Transform($tm);
7377 * Horizontal Mirroring.
7378 * @param int $x abscissa of the point. Default is current x position
7380 * @since 2.1.000 (2008-01-07)
7381 * @see StartTransform(), StopTransform()
7383 public function MirrorH($x='') {
7384 $this->Scale(-100, 100, $x);
7388 * Verical Mirroring.
7389 * @param int $y ordinate of the point. Default is current y position
7391 * @since 2.1.000 (2008-01-07)
7392 * @see StartTransform(), StopTransform()
7394 public function MirrorV($y='') {
7395 $this->Scale(100, -100, '', $y);
7399 * Point reflection mirroring.
7400 * @param int $x abscissa of the point. Default is current x position
7401 * @param int $y ordinate of the point. Default is current y position
7403 * @since 2.1.000 (2008-01-07)
7404 * @see StartTransform(), StopTransform()
7406 public function MirrorP($x='',$y='') {
7407 $this->Scale(-100, -100, $x, $y);
7411 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
7412 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
7413 * @param int $x abscissa of the point. Default is current x position
7414 * @param int $y ordinate of the point. Default is current y position
7416 * @since 2.1.000 (2008-01-07)
7417 * @see StartTransform(), StopTransform()
7419 public function MirrorL($angle=0, $x='',$y='') {
7420 $this->Scale(-100, 100, $x, $y);
7421 $this->Rotate(-2*($angle-90), $x, $y);
7425 * Translate graphic object horizontally.
7426 * @param int $t_x movement to the right (or left for RTL)
7428 * @since 2.1.000 (2008-01-07)
7429 * @see StartTransform(), StopTransform()
7431 public function TranslateX($t_x) {
7432 $this->Translate($t_x, 0);
7436 * Translate graphic object vertically.
7437 * @param int $t_y movement to the bottom
7439 * @since 2.1.000 (2008-01-07)
7440 * @see StartTransform(), StopTransform()
7442 public function TranslateY($t_y) {
7443 $this->Translate(0, $t_y);
7447 * Translate graphic object horizontally and vertically.
7448 * @param int $t_x movement to the right
7449 * @param int $t_y movement to the bottom
7451 * @since 2.1.000 (2008-01-07)
7452 * @see StartTransform(), StopTransform()
7454 public function Translate($t_x, $t_y) {
7458 //calculate elements of transformation matrix
7463 $tm[4] = $t_x * $this->k;
7464 $tm[5] = -$t_y * $this->k;
7465 //translate the coordinate system
7466 $this->Transform($tm);
7471 * @param float $angle angle in degrees for counter-clockwise rotation
7472 * @param int $x abscissa of the rotation center. Default is current x position
7473 * @param int $y ordinate of the rotation center. Default is current y position
7475 * @since 2.1.000 (2008-01-07)
7476 * @see StartTransform(), StopTransform()
7478 public function Rotate($angle, $x='', $y='') {
7489 $y = ($this->h - $y) * $this->k;
7491 //calculate elements of transformation matrix
7492 $tm[0] = cos(deg2rad($angle));
7493 $tm[1] = sin(deg2rad($angle));
7496 $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
7497 $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
7498 //rotate the coordinate system around ($x,$y)
7499 $this->Transform($tm);
7503 * Skew horizontally.
7504 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
7505 * @param int $x abscissa of the skewing center. default is current x position
7506 * @param int $y ordinate of the skewing center. default is current y position
7508 * @since 2.1.000 (2008-01-07)
7509 * @see StartTransform(), StopTransform()
7511 public function SkewX($angle_x, $x='', $y='') {
7512 $this->Skew($angle_x, 0, $x, $y);
7517 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
7518 * @param int $x abscissa of the skewing center. default is current x position
7519 * @param int $y ordinate of the skewing center. default is current y position
7521 * @since 2.1.000 (2008-01-07)
7522 * @see StartTransform(), StopTransform()
7524 public function SkewY($angle_y, $x='', $y='') {
7525 $this->Skew(0, $angle_y, $x, $y);
7530 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
7531 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
7532 * @param int $x abscissa of the skewing center. default is current x position
7533 * @param int $y ordinate of the skewing center. default is current y position
7535 * @since 2.1.000 (2008-01-07)
7536 * @see StartTransform(), StopTransform()
7538 public function Skew($angle_x, $angle_y, $x='', $y='') {
7547 $angle_x = -$angle_x;
7549 if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
7550 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
7553 $y = ($this->h - $y) * $this->k;
7554 //calculate elements of transformation matrix
7556 $tm[1] = tan(deg2rad($angle_y));
7557 $tm[2] = tan(deg2rad($angle_x));
7559 $tm[4] = -$tm[2] * $y;
7560 $tm[5] = -$tm[1] * $x;
7561 //skew the coordinate system
7562 $this->Transform($tm);
7566 * Apply graphic transformations.
7568 * @since 2.1.000 (2008-01-07)
7569 * @see StartTransform(), StopTransform()
7571 protected function Transform($tm) {
7572 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
7573 // store transformation matrix
7574 $this->transfmatrix[] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
7575 // update tranformation mark
7576 if (end($this->transfmrk[$this->page]) !== false) {
7577 $key = key($this->transfmrk[$this->page]);
7578 $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
7582 // END TRANSFORMATIONS SECTION -------------------------
7585 // START GRAPHIC FUNCTIONS SECTION ---------------------
7586 // The following section is based on the code provided by David Hernandez Sanz
7589 * 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.
7590 * @param float $width The width.
7593 * @see Line(), Rect(), Cell(), MultiCell()
7595 public function SetLineWidth($width) {
7597 $this->LineWidth = $width;
7598 $this->linestyleWidth = sprintf('%.2F w', ($width * $this->k));
7599 $this->_out($this->linestyleWidth);
7603 * Returns the current the line width.
7604 * @return int Line width
7606 * @since 2.1.000 (2008-01-07)
7607 * @see Line(), SetLineWidth()
7609 public function GetLineWidth() {
7610 return $this->LineWidth;
7615 * @param array $style Line style. Array with keys among the following:
7617 * <li>width (float): Width of the line in user units.</li>
7618 * <li>cap (string): Type of cap to put on the line. Possible values are:
7619 * butt, round, square. The difference between "square" and "butt" is that
7620 * "square" projects a flat end past the end of the line.</li>
7621 * <li>join (string): Type of join. Possible values are: miter, round,
7623 * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
7624 * series of length values, which are the lengths of the on and off dashes.
7625 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
7626 * 1 off, 2 on, 1 off, ...</li>
7627 * <li>phase (integer): Modifier on the dash pattern which is used to shift
7628 * the point at which the pattern starts.</li>
7629 * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
7632 * @since 2.1.000 (2008-01-08)
7634 public function SetLineStyle($style) {
7636 if (isset($width)) {
7637 $width_prev = $this->LineWidth;
7638 $this->SetLineWidth($width);
7639 $this->LineWidth = $width_prev;
7642 $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
7643 if (isset($ca[$cap])) {
7644 $this->linestyleCap = $ca[$cap].' J';
7645 $this->_out($this->linestyleCap);
7649 $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
7650 if (isset($ja[$join])) {
7651 $this->linestyleJoin = $ja[$join].' j';
7652 $this->_out($this->linestyleJoin);
7658 if (preg_match('/^.+,/', $dash)) {
7659 $tab = explode(',', $dash);
7661 $tab = array($dash);
7664 foreach ($tab as $i => $v) {
7666 $dash_string .= ' ';
7668 $dash_string .= sprintf("%.2F", $v);
7671 if (!isset($phase) OR !$dash) {
7674 $this->linestyleDash = sprintf("[%s] %.2F d", $dash_string, $phase);
7675 $this->_out($this->linestyleDash);
7677 if (isset($color)) {
7678 $this->SetDrawColorArray($color);
7684 * @param float $x Abscissa of point.
7685 * @param float $y Ordinate of point.
7687 * @since 2.1.000 (2008-01-08)
7689 protected function _outPoint($x, $y) {
7693 $this->_out(sprintf("%.2F %.2F m", $x * $this->k, ($this->h - $y) * $this->k));
7697 * Draws a line from last draw point.
7698 * @param float $x Abscissa of end point.
7699 * @param float $y Ordinate of end point.
7701 * @since 2.1.000 (2008-01-08)
7703 protected function _outLine($x, $y) {
7707 $this->_out(sprintf("%.2F %.2F l", $x * $this->k, ($this->h - $y) * $this->k));
7711 * Draws a rectangle.
7712 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
7713 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
7714 * @param float $w Width.
7715 * @param float $h Height.
7716 * @param string $op options
7718 * @since 2.1.000 (2008-01-08)
7720 protected function _outRect($x, $y, $w, $h, $op) {
7722 $x = $this->w - $x - $w;
7724 $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
7728 * Draws a Bezier curve from last draw point.
7729 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
7730 * @param float $x1 Abscissa of control point 1.
7731 * @param float $y1 Ordinate of control point 1.
7732 * @param float $x2 Abscissa of control point 2.
7733 * @param float $y2 Ordinate of control point 2.
7734 * @param float $x3 Abscissa of end point.
7735 * @param float $y3 Ordinate of end point.
7737 * @since 2.1.000 (2008-01-08)
7739 protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
7741 $x1 = $this->w - $x1;
7742 $x2 = $this->w - $x2;
7743 $x3 = $this->w - $x3;
7745 $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));
7749 * Draws a line between two points.
7750 * @param float $x1 Abscissa of first point.
7751 * @param float $y1 Ordinate of first point.
7752 * @param float $x2 Abscissa of second point.
7753 * @param float $y2 Ordinate of second point.
7754 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7757 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
7759 public function Line($x1, $y1, $x2, $y2, $style=array()) {
7761 $this->SetLineStyle($style);
7763 $this->_outPoint($x1, $y1);
7764 $this->_outLine($x2, $y2);
7769 * Draws a rectangle.
7770 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
7771 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
7772 * @param float $w Width.
7773 * @param float $h Height.
7774 * @param string $style Style of rendering. Possible values are:
7776 * <li>D or empty string: Draw (default).</li>
7778 * <li>DF or FD: Draw and fill.</li>
7779 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7780 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7782 * @param array $border_style Border style of rectangle. Array with keys among the following:
7784 * <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
7785 * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
7787 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
7788 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7789 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
7792 * @see SetLineStyle()
7794 public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
7795 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7796 $this->SetFillColorArray($fill_color);
7801 $border_style = array();
7802 $this->_outRect($x, $y, $w, $h, $op);
7807 if ((!$border_style) OR (isset($border_style['all']))) {
7809 if (isset($border_style['all'])) {
7810 $this->SetLineStyle($border_style['all']);
7811 $border_style = array();
7816 $this->_outRect($x, $y, $w, $h, $op);
7821 $this->_outRect($x, $y, $w, $h, $op);
7826 $this->_outRect($x, $y, $w, $h, $op);
7831 if ((!$border_style) OR (isset($border_style['all']))) {
7832 if (isset($border_style['all']) AND $border_style['all']) {
7833 $this->SetLineStyle($border_style['all']);
7834 $border_style = array();
7836 $this->_outRect($x, $y, $w, $h, $op);
7841 if ($border_style) {
7842 $border_style2 = array();
7843 foreach ($border_style as $line => $value) {
7844 $lenght = strlen($line);
7845 for ($i = 0; $i < $lenght; ++$i) {
7846 $border_style2[$line[$i]] = $value;
7849 $border_style = $border_style2;
7850 if (isset($border_style['L']) AND $border_style['L']) {
7851 $this->Line($x, $y, $x, $y + $h, $border_style['L']);
7853 if (isset($border_style['T']) AND $border_style['T']) {
7854 $this->Line($x, $y, $x + $w, $y, $border_style['T']);
7856 if (isset($border_style['R']) AND $border_style['R']) {
7857 $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
7859 if (isset($border_style['B']) AND $border_style['B']) {
7860 $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
7867 * Draws a Bezier curve.
7868 * The Bezier curve is a tangent to the line between the control points at
7869 * either end of the curve.
7870 * @param float $x0 Abscissa of start point.
7871 * @param float $y0 Ordinate of start point.
7872 * @param float $x1 Abscissa of control point 1.
7873 * @param float $y1 Ordinate of control point 1.
7874 * @param float $x2 Abscissa of control point 2.
7875 * @param float $y2 Ordinate of control point 2.
7876 * @param float $x3 Abscissa of end point.
7877 * @param float $y3 Ordinate of end point.
7878 * @param string $style Style of rendering. Possible values are:
7880 * <li>D or empty string: Draw (default).</li>
7882 * <li>DF or FD: Draw and fill.</li>
7883 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7884 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7886 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7887 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
7889 * @see SetLineStyle()
7890 * @since 2.1.000 (2008-01-08)
7892 public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
7893 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7894 $this->SetFillColorArray($fill_color);
7899 $line_style = array();
7921 $this->SetLineStyle($line_style);
7923 $this->_outPoint($x0, $y0);
7924 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
7929 * Draws a poly-Bezier curve.
7930 * Each Bezier curve segment is a tangent to the line between the control points at
7931 * either end of the curve.
7932 * @param float $x0 Abscissa of start point.
7933 * @param float $y0 Ordinate of start point.
7934 * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
7935 * @param string $style Style of rendering. Possible values are:
7937 * <li>D or empty string: Draw (default).</li>
7939 * <li>DF or FD: Draw and fill.</li>
7940 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7941 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7943 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7944 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
7946 * @see SetLineStyle()
7947 * @since 3.0008 (2008-05-12)
7949 public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
7950 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7951 $this->SetFillColorArray($fill_color);
7956 $line_style = array();
7978 $this->SetLineStyle($line_style);
7980 $this->_outPoint($x0, $y0);
7981 foreach ($segments as $segment) {
7982 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
7983 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
7990 * An ellipse is formed from n Bezier curves.
7991 * @param float $x0 Abscissa of center point.
7992 * @param float $y0 Ordinate of center point.
7993 * @param float $rx Horizontal radius.
7994 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
7995 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
7996 * @param float $astart: Angle start of draw line. Default value: 0.
7997 * @param float $afinish: Angle finish of draw line. Default value: 360.
7998 * @param string $style Style of rendering. Possible values are:
8000 * <li>D or empty string: Draw (default).</li>
8002 * <li>DF or FD: Draw and fill.</li>
8003 * <li>C: Draw close.</li>
8004 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8005 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8007 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8008 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
8009 * @param integer $nc Number of curves used in ellipse. Default value: 8.
8011 * @since 2.1.000 (2008-01-08)
8013 public function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
8015 $this->StartTransform();
8016 $this->Rotate($angle, $x0, $y0);
8017 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
8018 $this->StopTransform();
8022 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8023 $this->SetFillColorArray($fill_color);
8028 $line_style = array();
8037 $op = 's'; // Small 's' signifies closing the path as well
8054 $this->SetLineStyle($line_style);
8064 $astart = deg2rad((float) $astart);
8065 $afinish = deg2rad((float) $afinish);
8066 $total_angle = $afinish - $astart;
8067 $dt = $total_angle / $nc;
8070 $y0 = ($this->h - $y0) * $this->k;
8072 $a0 = $x0 + ($rx * cos($t1));
8073 $b0 = $y0 + ($ry * sin($t1));
8074 $c0 = -$rx * sin($t1);
8075 $d0 = $ry * cos($t1);
8076 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
8077 for ($i = 1; $i <= $nc; ++$i) {
8078 // Draw this bit of the total curve
8079 $t1 = ($i * $dt) + $astart;
8080 $a1 = $x0 + ($rx * cos($t1));
8081 $b1 = $y0 + ($ry * sin($t1));
8082 $c1 = -$rx * sin($t1);
8083 $d1 = $ry * cos($t1);
8084 $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));
8096 * A circle is formed from n Bezier curves.
8097 * @param float $x0 Abscissa of center point.
8098 * @param float $y0 Ordinate of center point.
8099 * @param float $r Radius.
8100 * @param float $astart: Angle start of draw line. Default value: 0.
8101 * @param float $afinish: Angle finish of draw line. Default value: 360.
8102 * @param string $style Style of rendering. Possible values are:
8104 * <li>D or empty string: Draw (default).</li>
8106 * <li>DF or FD: Draw and fill.</li>
8107 * <li>C: Draw close.</li>
8108 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8109 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8111 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8112 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8113 * @param integer $nc Number of curves used in circle. Default value: 8.
8115 * @since 2.1.000 (2008-01-08)
8117 public function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
8118 $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
8123 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
8124 * @param string $style Style of rendering. Possible values are:
8126 * <li>D or empty string: Draw (default).</li>
8128 * <li>DF or FD: Draw and fill.</li>
8129 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8130 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8132 * @param array $line_style Line style of polygon. Array with keys among the following:
8134 * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
8135 * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
8137 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
8138 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
8140 * @since 2.1.000 (2008-01-08)
8142 public function Polygon($p, $style='', $line_style=array(), $fill_color=array()) {
8143 $np = count($p) / 2;
8144 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8145 $this->SetFillColorArray($fill_color);
8149 $line_style = array();
8173 if (isset($line_style['all'])) {
8174 $this->SetLineStyle($line_style['all']);
8175 } else { // 0 .. (np - 1), op = {B, S}
8179 $this->_outPoint($p[0], $p[1]);
8180 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
8181 $this->_outLine($p[$i], $p[$i + 1]);
8183 $this->_outLine($p[0], $p[1]);
8186 $p[($np * 2)] = $p[0];
8187 $p[(($np * 2) + 1)] = $p[1];
8188 for ($i = 0; $i < $np; ++$i) {
8189 if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
8190 $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
8196 $this->_outPoint($p[0], $p[1]);
8197 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
8198 $this->_outLine($p[$i], $p[$i + 1]);
8200 $this->_outLine($p[0], $p[1]);
8206 * Draws a regular polygon.
8207 * @param float $x0 Abscissa of center point.
8208 * @param float $y0 Ordinate of center point.
8209 * @param float $r: Radius of inscribed circle.
8210 * @param integer $ns Number of sides.
8211 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
8212 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
8213 * @param string $style Style of rendering. Possible values are:
8215 * <li>D or empty string: Draw (default).</li>
8217 * <li>DF or FD: Draw and fill.</li>
8218 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8219 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8221 * @param array $line_style Line style of polygon sides. Array with keys among the following:
8223 * <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
8224 * <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
8226 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
8227 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8228 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
8230 * <li>D or empty string: Draw (default).</li>
8232 * <li>DF or FD: Draw and fill.</li>
8233 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8234 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8236 * @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).
8237 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
8239 * @since 2.1.000 (2008-01-08)
8241 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()) {
8246 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
8249 for ($i = 0; $i < $ns; ++$i) {
8250 $a = $angle + ($i * 360 / $ns);
8251 $a_rad = deg2rad((float) $a);
8252 $p[] = $x0 + ($r * sin($a_rad));
8253 $p[] = $y0 + ($r * cos($a_rad));
8255 $this->Polygon($p, $style, $line_style, $fill_color);
8259 * Draws a star polygon
8260 * @param float $x0 Abscissa of center point.
8261 * @param float $y0 Ordinate of center point.
8262 * @param float $r Radius of inscribed circle.
8263 * @param integer $nv Number of vertices.
8264 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
8265 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
8266 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
8267 * @param string $style Style of rendering. Possible values are:
8269 * <li>D or empty string: Draw (default).</li>
8271 * <li>DF or FD: Draw and fill.</li>
8272 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8273 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8275 * @param array $line_style Line style of polygon sides. Array with keys among the following:
8277 * <li>all: Line style of all sides. Array like for
8278 * {@link SetLineStyle SetLineStyle}.</li>
8279 * <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
8281 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
8282 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8283 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
8285 * <li>D or empty string: Draw (default).</li>
8287 * <li>DF or FD: Draw and fill.</li>
8288 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8289 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8291 * @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).
8292 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
8294 * @since 2.1.000 (2008-01-08)
8296 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()) {
8301 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
8305 for ($i = 0; $i < $nv; ++$i) {
8306 $a = $angle + ($i * 360 / $nv);
8307 $a_rad = deg2rad((float) $a);
8308 $p2[] = $x0 + ($r * sin($a_rad));
8309 $p2[] = $y0 + ($r * cos($a_rad));
8316 $p[] = $p2[($i * 2) + 1];
8317 $visited[$i] = true;
8320 } while (!$visited[$i]);
8321 $this->Polygon($p, $style, $line_style, $fill_color);
8325 * Draws a rounded rectangle.
8326 * @param float $x Abscissa of upper-left corner.
8327 * @param float $y Ordinate of upper-left corner.
8328 * @param float $w Width.
8329 * @param float $h Height.
8330 * @param float $r Radius of the rounded corners.
8331 * @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").
8332 * @param string $style Style of rendering. Possible values are:
8334 * <li>D or empty string: Draw (default).</li>
8336 * <li>DF or FD: Draw and fill.</li>
8337 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8338 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8340 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8341 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
8343 * @since 2.1.000 (2008-01-08)
8345 public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
8346 if ('0000' == $round_corner) { // Not rounded
8347 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
8349 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8350 $this->SetFillColorArray($fill_color);
8354 $border_style = array();
8376 if ($border_style) {
8377 $this->SetLineStyle($border_style);
8379 $MyArc = 4 / 3 * (sqrt(2) - 1);
8380 $this->_outPoint($x + $r, $y);
8383 $this->_outLine($xc, $y);
8384 if ($round_corner[0]) {
8385 $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
8387 $this->_outLine($x + $w, $y);
8391 $this->_outLine($x + $w, $yc);
8392 if ($round_corner[1]) {
8393 $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
8395 $this->_outLine($x + $w, $y + $h);
8399 $this->_outLine($xc, $y + $h);
8400 if ($round_corner[2]) {
8401 $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
8403 $this->_outLine($x, $y + $h);
8407 $this->_outLine($x, $yc);
8408 if ($round_corner[3]) {
8409 $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
8411 $this->_outLine($x, $y);
8412 $this->_outLine($x + $r, $y);
8418 // END GRAPHIC FUNCTIONS SECTION -----------------------
8420 // BIDIRECTIONAL TEXT SECTION --------------------------
8422 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
8423 * @param string $str string to manipulate.
8424 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
8427 * @author Nicola Asuni
8428 * @since 2.1.000 (2008-01-08)
8430 protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
8431 return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $str, $forcertl), $setbom);
8435 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
8436 * @param array $ta array of characters composing the string.
8437 * @param string $str string to process
8438 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
8440 * @author Nicola Asuni
8442 * @since 2.4.000 (2008-03-06)
8444 protected function utf8Bidi($ta, $str='', $forcertl=false) {
8445 global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
8446 // paragraph embedding level
8450 if ($this->empty_string($str)) {
8451 // create string from array
8452 $str = $this->UTF8ArrSubString($ta);
8454 // check if string contains arabic text
8455 if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
8460 // check if string contains RTL text
8461 if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
8465 // get number of chars
8466 $numchars = count($ta);
8468 if ($forcertl == 'R') {
8470 } elseif ($forcertl == 'L') {
8473 // P2. In each paragraph, find the first character of type L, AL, or R.
8474 // 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.
8475 for ($i=0; $i < $numchars; ++$i) {
8476 $type = $unicode[$ta[$i]];
8480 } elseif (($type == 'AL') OR ($type == 'R')) {
8487 // Current Embedding Level
8489 // directional override status
8491 $remember = array();
8492 // start-of-level-run
8493 $sor = $pel % 2 ? 'R' : 'L';
8496 // Array of characters data
8497 $chardata = Array();
8499 // 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.
8500 // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
8501 for ($i=0; $i < $numchars; ++$i) {
8502 if ($ta[$i] == K_RLE) {
8503 // X2. With each RLE, compute the least greater odd embedding level.
8504 // 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.
8505 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8506 $next_level = $cel + ($cel % 2) + 1;
8507 if ($next_level < 62) {
8508 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
8512 $eor = $cel % 2 ? 'R' : 'L';
8514 } elseif ($ta[$i] == K_LRE) {
8515 // X3. With each LRE, compute the least greater even embedding level.
8516 // 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.
8517 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8518 $next_level = $cel + 2 - ($cel % 2);
8519 if ( $next_level < 62 ) {
8520 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
8524 $eor = $cel % 2 ? 'R' : 'L';
8526 } elseif ($ta[$i] == K_RLO) {
8527 // X4. With each RLO, compute the least greater odd embedding level.
8528 // 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.
8529 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8530 $next_level = $cel + ($cel % 2) + 1;
8531 if ($next_level < 62) {
8532 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
8536 $eor = $cel % 2 ? 'R' : 'L';
8538 } elseif ($ta[$i] == K_LRO) {
8539 // X5. With each LRO, compute the least greater even embedding level.
8540 // 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.
8541 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8542 $next_level = $cel + 2 - ($cel % 2);
8543 if ( $next_level < 62 ) {
8544 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
8548 $eor = $cel % 2 ? 'R' : 'L';
8550 } elseif ($ta[$i] == K_PDF) {
8551 // 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.
8552 if (count($remember)) {
8553 $last = count($remember ) - 1;
8554 if (($remember[$last]['num'] == K_RLE) OR
8555 ($remember[$last]['num'] == K_LRE) OR
8556 ($remember[$last]['num'] == K_RLO) OR
8557 ($remember[$last]['num'] == K_LRO)) {
8558 $match = array_pop($remember);
8559 $cel = $match['cel'];
8560 $dos = $match['dos'];
8562 $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
8565 } elseif (($ta[$i] != K_RLE) AND
8566 ($ta[$i] != K_LRE) AND
8567 ($ta[$i] != K_RLO) AND
8568 ($ta[$i] != K_LRO) AND
8569 ($ta[$i] != K_PDF)) {
8570 // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
8571 // a. Set the level of the current character to the current embedding level.
8572 // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
8576 $chardir = $unicode[$ta[$i]];
8578 // stores string characters and other information
8579 $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
8581 } // end for each char
8583 // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
8584 // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
8585 // 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.
8587 // 3.3.3 Resolving Weak Types
8588 // 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.
8589 // Nonspacing marks are now resolved based on the previous characters.
8590 $numchars = count($chardata);
8592 // 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.
8593 $prevlevel = -1; // track level changes
8594 $levcount = 0; // counts consecutive chars at the same level
8595 for ($i=0; $i < $numchars; ++$i) {
8596 if ($chardata[$i]['type'] == 'NSM') {
8598 $chardata[$i]['type'] = $chardata[$i]['sor'];
8600 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
8603 if ($chardata[$i]['level'] != $prevlevel) {
8608 $prevlevel = $chardata[$i]['level'];
8611 // 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.
8614 for ($i=0; $i < $numchars; ++$i) {
8615 if ($chardata[$i]['char'] == 'EN') {
8616 for ($j=$levcount; $j >= 0; $j--) {
8617 if ($chardata[$j]['type'] == 'AL') {
8618 $chardata[$i]['type'] = 'AN';
8619 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
8624 if ($chardata[$i]['level'] != $prevlevel) {
8629 $prevlevel = $chardata[$i]['level'];
8632 // W3. Change all ALs to R.
8633 for ($i=0; $i < $numchars; ++$i) {
8634 if ($chardata[$i]['type'] == 'AL') {
8635 $chardata[$i]['type'] = 'R';
8639 // 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.
8642 for ($i=0; $i < $numchars; ++$i) {
8643 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8644 if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
8645 $chardata[$i]['type'] = 'EN';
8646 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
8647 $chardata[$i]['type'] = 'EN';
8648 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
8649 $chardata[$i]['type'] = 'AN';
8652 if ($chardata[$i]['level'] != $prevlevel) {
8657 $prevlevel = $chardata[$i]['level'];
8660 // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
8663 for ($i=0; $i < $numchars; ++$i) {
8664 if ($chardata[$i]['type'] == 'ET') {
8665 if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
8666 $chardata[$i]['type'] = 'EN';
8669 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
8670 if ($chardata[$j]['type'] == 'EN') {
8671 $chardata[$i]['type'] = 'EN';
8673 } elseif ($chardata[$j]['type'] != 'ET') {
8680 if ($chardata[$i]['level'] != $prevlevel) {
8685 $prevlevel = $chardata[$i]['level'];
8688 // W6. Otherwise, separators and terminators change to Other Neutral.
8691 for ($i=0; $i < $numchars; ++$i) {
8692 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
8693 $chardata[$i]['type'] = 'ON';
8695 if ($chardata[$i]['level'] != $prevlevel) {
8700 $prevlevel = $chardata[$i]['level'];
8703 //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.
8706 for ($i=0; $i < $numchars; ++$i) {
8707 if ($chardata[$i]['char'] == 'EN') {
8708 for ($j=$levcount; $j >= 0; $j--) {
8709 if ($chardata[$j]['type'] == 'L') {
8710 $chardata[$i]['type'] = 'L';
8711 } elseif ($chardata[$j]['type'] == 'R') {
8716 if ($chardata[$i]['level'] != $prevlevel) {
8721 $prevlevel = $chardata[$i]['level'];
8724 // 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.
8727 for ($i=0; $i < $numchars; ++$i) {
8728 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8729 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
8730 $chardata[$i]['type'] = 'L';
8731 } elseif (($chardata[$i]['type'] == 'N') AND
8732 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
8733 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
8734 $chardata[$i]['type'] = 'R';
8735 } elseif ($chardata[$i]['type'] == 'N') {
8736 // N2. Any remaining neutrals take the embedding direction
8737 $chardata[$i]['type'] = $chardata[$i]['sor'];
8739 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8741 if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
8742 $chardata[$i]['type'] = 'L';
8743 } elseif (($chardata[$i]['type'] == 'N') AND
8744 (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
8745 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
8746 $chardata[$i]['type'] = 'R';
8747 } elseif ($chardata[$i]['type'] == 'N') {
8748 // N2. Any remaining neutrals take the embedding direction
8749 $chardata[$i]['type'] = $chardata[$i]['sor'];
8751 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
8753 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
8754 $chardata[$i]['type'] = 'L';
8755 } elseif (($chardata[$i]['type'] == 'N') AND
8756 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
8757 (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
8758 $chardata[$i]['type'] = 'R';
8759 } elseif ($chardata[$i]['type'] == 'N') {
8760 // N2. Any remaining neutrals take the embedding direction
8761 $chardata[$i]['type'] = $chardata[$i]['sor'];
8763 } elseif ($chardata[$i]['type'] == 'N') {
8764 // N2. Any remaining neutrals take the embedding direction
8765 $chardata[$i]['type'] = $chardata[$i]['sor'];
8767 if ($chardata[$i]['level'] != $prevlevel) {
8772 $prevlevel = $chardata[$i]['level'];
8775 // 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.
8776 // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
8777 for ($i=0; $i < $numchars; ++$i) {
8778 $odd = $chardata[$i]['level'] % 2;
8780 if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
8781 $chardata[$i]['level'] += 1;
8784 if ($chardata[$i]['type'] == 'R') {
8785 $chardata[$i]['level'] += 1;
8786 } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
8787 $chardata[$i]['level'] += 2;
8790 $maxlevel = max($chardata[$i]['level'],$maxlevel);
8793 // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
8794 // 1. Segment separators,
8795 // 2. Paragraph separators,
8796 // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
8797 // 4. Any sequence of white space characters at the end of the line.
8798 for ($i=0; $i < $numchars; ++$i) {
8799 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
8800 $chardata[$i]['level'] = $pel;
8801 } elseif ($chardata[$i]['type'] == 'WS') {
8803 while ($j < $numchars) {
8804 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
8805 (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
8806 $chardata[$i]['level'] = $pel;
8808 } elseif ($chardata[$j]['type'] != 'WS') {
8817 // 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.
8819 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
8820 $alfletter = array(1570,1571,1573,1575);
8821 $chardata2 = $chardata;
8825 for ($i=0; $i < $numchars; ++$i) {
8826 if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
8827 $charAL[$x] = $chardata[$i];
8828 $charAL[$x]['i'] = $i;
8829 $chardata[$i]['x'] = $x;
8834 for ($i=0; $i < $numchars; ++$i) {
8835 $thischar = $chardata[$i];
8837 $prevchar = $chardata[($i-1)];
8841 if (($i+1) < $numchars) {
8842 $nextchar = $chardata[($i+1)];
8846 if ($unicode[$thischar['char']] == 'AL') {
8847 $x = $thischar['x'];
8849 $prevchar = $charAL[($x-1)];
8853 if (($x+1) < $numAL) {
8854 $nextchar = $charAL[($x+1)];
8859 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
8860 $arabicarr = $laa_array;
8863 $prevchar = $charAL[($x-2)];
8868 $arabicarr = $unicode_arlet;
8871 if (($prevchar !== false) AND ($nextchar !== false) AND
8872 (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
8873 (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
8874 ($prevchar['type'] == $thischar['type']) AND
8875 ($nextchar['type'] == $thischar['type']) AND
8876 ($nextchar['char'] != 1567)) {
8877 if (in_array($prevchar['char'], $endedletter)) {
8878 if (isset($arabicarr[$thischar['char']][2])) {
8880 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
8883 if (isset($arabicarr[$thischar['char']][3])) {
8885 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
8888 } elseif (($nextchar !== false) AND
8889 (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
8890 ($nextchar['type'] == $thischar['type']) AND
8891 ($nextchar['char'] != 1567)) {
8892 if (isset($arabicarr[$chardata[$i]['char']][2])) {
8894 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
8896 } elseif ((($prevchar !== false) AND
8897 (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
8898 ($prevchar['type'] == $thischar['type'])) OR
8899 (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
8901 if (($i > 1) AND ($thischar['char'] == 1607) AND
8902 ($chardata[$i-1]['char'] == 1604) AND
8903 ($chardata[$i-2]['char'] == 1604)) {
8905 // mark characters to delete with false
8906 $chardata2[$i-2]['char'] = false;
8907 $chardata2[$i-1]['char'] = false;
8908 $chardata2[$i]['char'] = 65010;
8910 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
8911 if (isset($arabicarr[$thischar['char']][0])) {
8913 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
8916 if (isset($arabicarr[$thischar['char']][1])) {
8918 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
8922 } elseif (isset($arabicarr[$thischar['char']][0])) {
8924 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
8928 // mark characters to delete with false
8929 $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
8931 } // end if AL (Arabic Letter)
8932 } // end for each char
8934 * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
8935 * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
8937 $cw = &$this->CurrentFont['cw'];
8938 for ($i = 0; $i < ($numchars-1); ++$i) {
8939 if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
8940 // check if the subtitution font is defined on current font
8941 if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
8942 $chardata2[$i]['char'] = false;
8943 $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
8947 // remove marked characters
8948 foreach ($chardata2 as $key => $value) {
8949 if ($value['char'] === false) {
8950 unset($chardata2[$key]);
8953 $chardata = array_values($chardata2);
8954 $numchars = count($chardata);
8961 // 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.
8962 for ($j=$maxlevel; $j > 0; $j--) {
8963 $ordarray = Array();
8966 for ($i=0; $i < $numchars; ++$i) {
8967 if ($chardata[$i]['level'] >= $j) {
8969 if (isset($unicode_mirror[$chardata[$i]['char']])) {
8970 // 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.
8971 $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
8973 $revarr[] = $chardata[$i];
8976 $revarr = array_reverse($revarr);
8977 $ordarray = array_merge($ordarray, $revarr);
8981 $ordarray[] = $chardata[$i];
8985 $revarr = array_reverse($revarr);
8986 $ordarray = array_merge($ordarray, $revarr);
8988 $chardata = $ordarray;
8991 $ordarray = array();
8992 for ($i=0; $i < $numchars; ++$i) {
8993 $ordarray[] = $chardata[$i]['char'];
8999 // END OF BIDIRECTIONAL TEXT SECTION -------------------
9003 * @param string $txt bookmark description.
9004 * @param int $level bookmark level (minimum value is 0).
9005 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
9006 * @param int $page target page number (leave empty for current page).
9008 * @author Olivier Plathey, Nicola Asuni
9009 * @since 2.1.002 (2008-02-12)
9011 public function Bookmark($txt, $level=0, $y=-1, $page='') {
9015 if (isset($this->outlines[0])) {
9016 $lastoutline = end($this->outlines);
9017 $maxlevel = $lastoutline['l'] + 1;
9021 if ($level > $maxlevel) {
9028 $page = $this->PageNo();
9030 $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $page);
9034 * Create a bookmark PDF string.
9036 * @author Olivier Plathey, Nicola Asuni
9037 * @since 2.1.002 (2008-02-12)
9039 protected function _putbookmarks() {
9040 $nb = count($this->outlines);
9046 foreach ($this->outlines as $i => $o) {
9048 $parent = $lru[($o['l'] - 1)];
9049 //Set parent and last pointers
9050 $this->outlines[$i]['parent'] = $parent;
9051 $this->outlines[$parent]['last'] = $i;
9052 if ($o['l'] > $level) {
9053 //Level increasing: set first pointer
9054 $this->outlines[$parent]['first'] = $i;
9057 $this->outlines[$i]['parent'] = $nb;
9059 if (($o['l'] <= $level) AND ($i > 0)) {
9060 //Set prev and next pointers
9061 $prev = $lru[$o['l']];
9062 $this->outlines[$prev]['next'] = $i;
9063 $this->outlines[$i]['prev'] = $prev;
9070 foreach ($this->outlines as $i => $o) {
9072 $this->_out('<</Title '.$this->_textstring($o['t']));
9073 $this->_out('/Parent '.($n + $o['parent']).' 0 R');
9074 if (isset($o['prev']))
9075 $this->_out('/Prev '.($n + $o['prev']).' 0 R');
9076 if (isset($o['next']))
9077 $this->_out('/Next '.($n + $o['next']).' 0 R');
9078 if (isset($o['first']))
9079 $this->_out('/First '.($n + $o['first']).' 0 R');
9080 if (isset($o['last']))
9081 $this->_out('/Last '.($n + $o['last']).' 0 R');
9082 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $o['p'])), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k))));
9083 $this->_out('/Count 0>>');
9084 $this->_out('endobj');
9088 $this->OutlineRoot = $this->n;
9089 $this->_out('<</Type /Outlines /First '.$n.' 0 R');
9090 $this->_out('/Last '.($n + $lru[0]).' 0 R>>');
9091 $this->_out('endobj');
9095 // --- JAVASCRIPT - FORMS ------------------------------
9100 * @author Johannes G�ntert, Nicola Asuni
9101 * @since 2.1.002 (2008-02-12)
9103 public function IncludeJS($script) {
9104 $this->javascript .= $script;
9108 * Create a javascript PDF string.
9110 * @author Johannes G�ntert, Nicola Asuni
9111 * @since 2.1.002 (2008-02-12)
9113 protected function _putjavascript() {
9114 if (empty($this->javascript)) {
9117 // the following two lines are uded to avoid form fields duplication after saving
9118 $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
9119 $js2 = "getField('tcpdfdocsaved').value = 'saved';";
9121 $this->n_js = $this->n;
9123 $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
9125 $this->_out('endobj');
9128 $this->_out('/S /JavaScript');
9129 $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
9131 $this->_out('endobj');
9135 * Convert color to javascript color.
9136 * @param string $color color name or #RRGGBB
9138 * @author Denis Van Nuffelen, Nicola Asuni
9139 * @since 2.1.002 (2008-02-12)
9141 protected function _JScolor($color) {
9142 static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
9143 if (substr($color,0,1) == '#') {
9144 return sprintf("['RGB',%.3F,%.3F,%.3F]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
9146 if (!in_array($color,$aColors)) {
9147 $this->Error('Invalid color: '.$color);
9149 return 'color.'.$color;
9153 * Adds a javascript form field.
9154 * @param string $type field type
9155 * @param string $name field name
9156 * @param int $x horizontal position
9157 * @param int $y vertical position
9158 * @param int $w width
9159 * @param int $h height
9160 * @param array $prop array of properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9162 * @author Denis Van Nuffelen, Nicola Asuni
9163 * @since 2.1.002 (2008-02-12)
9165 protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
9169 // the followind avoid fields duplication after saving the document
9170 $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
9172 $this->javascript .= sprintf("f".$name."=this.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)."\n";
9173 $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
9174 while (list($key, $val) = each($prop)) {
9175 if (strcmp(substr($key, -5), 'Color') == 0) {
9176 $val = $this->_JScolor($val);
9178 $val = "'".$val."'";
9180 $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
9187 $this->javascript .= '}';
9191 * Creates a text field
9192 * @param string $name field name
9193 * @param int $w width
9194 * @param int $h height
9195 * @param string $prop properties. The value property allows to set the initial value. The multiline property allows to define the field as multiline. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9197 * @author Denis Van Nuffelen, Nicola Asuni
9198 * @since 2.1.002 (2008-02-12)
9200 public function TextField($name, $w, $h, $prop=array()) {
9201 $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
9205 * Creates a RadioButton field
9206 * @param string $name field name
9207 * @param int $w width
9208 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9210 * @author Nicola Asuni
9211 * @since 2.2.003 (2008-03-03)
9213 public function RadioButton($name, $w, $prop=array()) {
9214 if (!isset($prop['strokeColor'])) {
9215 $prop['strokeColor']='black';
9217 $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
9221 * Creates a List-box field
9222 * @param string $name field name
9223 * @param int $w width
9224 * @param int $h height
9225 * @param array $values array containing the list of values.
9226 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9228 * @author Nicola Asuni
9229 * @since 2.2.003 (2008-03-03)
9231 public function ListBox($name, $w, $h, $values, $prop=array()) {
9232 if (!isset($prop['strokeColor'])) {
9233 $prop['strokeColor'] = 'ltGray';
9235 $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
9237 foreach ($values as $value) {
9238 $s .= "'".addslashes($value)."',";
9240 $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
9244 * Creates a Combo-box field
9245 * @param string $name field name
9246 * @param int $w width
9247 * @param int $h height
9248 * @param array $values array containing the list of values.
9249 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9251 * @author Denis Van Nuffelen, Nicola Asuni
9252 * @since 2.1.002 (2008-02-12)
9254 public function ComboBox($name, $w, $h, $values, $prop=array()) {
9255 $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
9257 foreach ($values as $value) {
9258 $s .= "'".addslashes($value)."',";
9260 $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
9264 * Creates a CheckBox field
9265 * @param string $name field name
9266 * @param int $w width
9267 * @param boolean $checked define the initial state (default = false).
9268 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9270 * @author Denis Van Nuffelen, Nicola Asuni
9271 * @since 2.1.002 (2008-02-12)
9273 public function CheckBox($name, $w, $checked=false, $prop=array()) {
9274 $prop['value'] = ($checked ? 'Yes' : 'Off');
9275 if (!isset($prop['strokeColor'])) {
9276 $prop['strokeColor'] = 'black';
9278 $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
9282 * Creates a button field
9283 * @param string $name field name
9284 * @param int $w width
9285 * @param int $h height
9286 * @param string $caption caption.
9287 * @param string $action action triggered by the button (JavaScript code).
9288 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9290 * @author Denis Van Nuffelen, Nicola Asuni
9291 * @since 2.1.002 (2008-02-12)
9293 public function Button($name, $w, $h, $caption, $action, $prop=array()) {
9294 if (!isset($prop['strokeColor'])) {
9295 $prop['strokeColor'] = 'black';
9297 if (!isset($prop['borderStyle'])) {
9298 $prop['borderStyle'] = 'beveled';
9300 $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
9301 $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
9302 $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
9303 $this->javascript .= 'f'.$name.".highlight='push';\n";
9304 $this->javascript .= 'f'.$name.".print=false;\n";
9307 // END JAVASCRIPT - FORMS ------------------------------
9310 * Enable Write permissions for PDF Reader.
9311 * WARNING: This works only using the Adobe private key with the setSignature() method.
9313 * @author Nicola Asuni
9314 * @since 2.9.000 (2008-03-26)
9316 protected function _putuserrights() {
9317 if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] > 0))) {
9320 $this->_out('/Perms');
9322 $this->_out('/UR3');
9324 $this->_out('/Type/Sig');
9325 $this->_out('/Filter/Adobe.PPKLite');
9326 $this->_out('/SubFilter/adbe.pkcs7.detached');
9327 $this->_out('/ByteRange[0 ********** ********** **********]');
9328 $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
9330 $this->_out('/Reference');
9333 $this->_out('/Type/SigRef');
9334 $this->_out('/TransformMethod/UR3');
9335 $this->_out('/TransformParams');
9337 $this->_out('/Type/TransformParams');
9338 $this->_out('/V/2.2');
9339 if (!$this->empty_string($this->ur_document)) {
9340 $this->_out('/Document['.$this->ur_document.']');
9342 if (!$this->empty_string($this->ur_annots)) {
9343 $this->_out('/Annots['.$this->ur_annots.']');
9345 if (!$this->empty_string($this->ur_form)) {
9346 $this->_out('/Form['.$this->ur_form.']');
9348 if (!$this->empty_string($this->ur_signature)) {
9349 $this->_out('/Signature['.$this->ur_signature.']');
9355 $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
9361 * Add certification signature (DocMDP)
9363 * @author Nicola Asuni
9364 * @since 4.6.008 (2009-05-07)
9366 protected function _putcertification() {
9367 if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] <= 0))) {
9370 $this->_out('/Perms');
9372 $this->_out('/DocMDP');
9374 $this->_out('/Type/Sig');
9375 $this->_out('/Filter/Adobe.PPKLite');
9376 $this->_out('/SubFilter/adbe.pkcs7.detached');
9377 $this->_out('/ByteRange[0 ********** ********** **********]');
9378 $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
9379 $this->_out('/Reference');
9382 $this->_out('/Type/SigRef');
9383 $this->_out('/TransformMethod/DocMDP');
9384 $this->_out('/TransformParams');
9386 $this->_out('/Type/TransformParams');
9387 $this->_out('/V/1.2');
9388 $this->_out('/P '.$this->signature_data['cert_type'].'');
9392 $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
9393 if (isset($this->signature_data['info']['Name']) AND !$this->empty_string($this->signature_data['info']['Name'])) {
9394 $this->_out('/Name '.$this->_textstring($this->signature_data['info']['Name']).'');
9396 if (isset($this->signature_data['info']['Location']) AND !$this->empty_string($this->signature_data['info']['Location'])) {
9397 $this->_out('/Location '.$this->_textstring($this->signature_data['info']['Location']).'');
9399 if (isset($this->signature_data['info']['Reason']) AND !$this->empty_string($this->signature_data['info']['Reason'])) {
9400 $this->_out('/Reason '.$this->_textstring($this->signature_data['info']['Reason']).'');
9402 if (isset($this->signature_data['info']['ContactInfo']) AND !$this->empty_string($this->signature_data['info']['ContactInfo'])) {
9403 $this->_out('/ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo']).'');
9410 * Set User's Rights for PDF Reader
9411 * WARNING: This works only using the Adobe private key with the setSignature() method!.
9412 * Check the PDF Reference 8.7.1 Transform Methods,
9413 * Table 8.105 Entries in the UR transform parameters dictionary
9414 * @param boolean $enable if true enable user's rights on PDF reader
9415 * @param string $document Names specifying additional document-wide usage rights for the document. The only defined value is "/FullSave", which permits a user to save the document along with modified form and/or annotation data.
9416 * @param string $annots Names specifying additional annotation-related usage rights for the document. Valid names in PDF 1.5 and later are /Create/Delete/Modify/Copy/Import/Export, which permit the user to perform the named operation on annotations.
9417 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
9418 * @param string $signature Names specifying additional signature-related usage rights for the document. The only defined value is /Modify, which permits a user to apply a digital signature to an existing signature form field or clear a signed signature form field.
9420 * @author Nicola Asuni
9421 * @since 2.9.000 (2008-03-26)
9423 public function setUserRights(
9425 $document='/FullSave',
9426 $annots='/Create/Delete/Modify/Copy/Import/Export',
9427 $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
9428 $signature='/Modify') {
9429 $this->ur = $enable;
9430 $this->ur_document = $document;
9431 $this->ur_annots = $annots;
9432 $this->ur_form = $form;
9433 $this->ur_signature = $signature;
9437 * Enable document signature (requires the OpenSSL Library).
9438 * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
9439 * @param mixed $signing_cert signing certificate (string or filename prefixed with 'file://')
9440 * @param mixed $private_key private key (string or filename prefixed with 'file://')
9441 * @param string $private_key_password password
9442 * @param string $extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.
9443 * @param int $cert_type The access permissions granted for this document. Valid values shall be: 1 = No changes to the document shall be permitted; any change to the document shall invalidate the signature; 2 = Permitted changes shall be filling in forms, instantiating page templates, and signing; other changes shall invalidate the signature; 3 = Permitted changes shall be the same as for 2, as well as annotation creation, deletion, and modification; other changes shall invalidate the signature.
9444 * @parm array $info array of option information: Name, Location, Reason, ContactInfo.
9446 * @author Nicola Asuni
9447 * @since 4.6.005 (2009-04-24)
9449 public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array()) {
9450 // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.pem -out tcpdf.pem
9452 $this->signature_data = array();
9453 if (strlen($signing_cert) == 0) {
9454 $signing_cert = 'file://'.dirname(__FILE__).'/tcpdf.pem';
9456 if (strlen($private_key) == 0) {
9457 $private_key = $signing_cert;
9459 $this->signature_data['signcert'] = $signing_cert;
9460 $this->signature_data['privkey'] = $private_key;
9461 $this->signature_data['password'] = $private_key_password;
9462 $this->signature_data['extracerts'] = $extracerts;
9463 $this->signature_data['cert_type'] = $cert_type;
9464 $this->signature_data['info'] = array();
9468 * Create a new page group.
9469 * NOTE: call this function before calling AddPage()
9470 * @param int $page starting group page (leave empty for next page).
9472 * @since 3.0.000 (2008-03-27)
9474 public function startPageGroup($page='') {
9476 $page = $this->page + 1;
9478 $this->newpagegroup[$page] = true;
9482 * Defines an alias for the total number of pages.
9483 * It will be substituted as the document is closed.
9484 * @param string $alias The alias.
9487 * @see getAliasNbPages(), PageNo(), Footer()
9489 public function AliasNbPages($alias='{nb}') {
9490 $this->AliasNbPages = $alias;
9494 * Returns the string alias used for the total number of pages.
9495 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9498 * @since 4.0.018 (2008-08-08)
9499 * @see AliasNbPages(), PageNo(), Footer()
9501 public function getAliasNbPages() {
9502 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9503 return '{'.$this->AliasNbPages.'}';
9505 return $this->AliasNbPages;
9509 * Defines an alias for the page number.
9510 * It will be substituted as the document is closed.
9511 * @param string $alias The alias.
9513 * @since 4.5.000 (2009-01-02)
9514 * @see getAliasNbPages(), PageNo(), Footer()
9516 public function AliasNumPage($alias='{pnb}') {
9517 //Define an alias for total number of pages
9518 $this->AliasNumPage = $alias;
9522 * Returns the string alias used for the page number.
9523 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9526 * @since 4.5.000 (2009-01-02)
9527 * @see AliasNbPages(), PageNo(), Footer()
9529 public function getAliasNumPage() {
9530 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9531 return '{'.$this->AliasNumPage.'}';
9533 return $this->AliasNumPage;
9537 * Return the current page in the group.
9538 * @return current page in the group
9540 * @since 3.0.000 (2008-03-27)
9542 public function getGroupPageNo() {
9543 return $this->pagegroups[$this->currpagegroup];
9547 * Returns the current group page number formatted as a string.
9549 * @since 4.3.003 (2008-11-18)
9550 * @see PaneNo(), formatPageNumber()
9552 public function getGroupPageNoFormatted() {
9553 return $this->formatPageNumber($this->getGroupPageNo());
9557 * Return the alias of the current page group
9558 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9559 * (will be replaced by the total number of pages in this group).
9560 * @return alias of the current page group
9562 * @since 3.0.000 (2008-03-27)
9564 public function getPageGroupAlias() {
9565 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9566 return '{'.$this->currpagegroup.'}';
9568 return $this->currpagegroup;
9572 * Return the alias for the page number on the current page group
9573 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9574 * (will be replaced by the total number of pages in this group).
9575 * @return alias of the current page group
9577 * @since 4.5.000 (2009-01-02)
9579 public function getPageNumGroupAlias() {
9580 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9581 return '{'.str_replace('{nb', '{pnb', $this->currpagegroup).'}';
9583 return str_replace('{nb', '{pnb', $this->currpagegroup);
9587 * Format the page numbers.
9588 * This method can be overriden for custom formats.
9589 * @param int $num page number
9591 * @since 4.2.005 (2008-11-06)
9593 protected function formatPageNumber($num) {
9594 return number_format((float)$num, 0, '', '.');
9598 * Format the page numbers on the Table Of Content.
9599 * This method can be overriden for custom formats.
9600 * @param int $num page number
9602 * @since 4.5.001 (2009-01-04)
9605 protected function formatTOCPageNumber($num) {
9606 return number_format((float)$num, 0, '', '.');
9610 * Returns the current page number formatted as a string.
9612 * @since 4.2.005 (2008-11-06)
9613 * @see PaneNo(), formatPageNumber()
9615 public function PageNoFormatted() {
9616 return $this->formatPageNumber($this->PageNo());
9620 * Put visibility settings.
9622 * @since 3.0.000 (2008-03-27)
9624 protected function _putocg() {
9626 $this->n_ocg_print = $this->n;
9627 $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
9628 $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
9629 $this->_out('endobj');
9631 $this->n_ocg_view=$this->n;
9632 $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
9633 $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
9634 $this->_out('endobj');
9638 * Set the visibility of the successive elements.
9639 * This can be useful, for instance, to put a background
9640 * image or color that will show on screen but won't print.
9641 * @param string $v visibility mode. Legal values are: all, print, screen.
9643 * @since 3.0.000 (2008-03-27)
9645 public function setVisibility($v) {
9646 if ($this->openMarkedContent) {
9647 // close existing open marked-content
9649 $this->openMarkedContent = false;
9653 $this->_out('/OC /OC1 BDC');
9654 $this->openMarkedContent = true;
9658 $this->_out('/OC /OC2 BDC');
9659 $this->openMarkedContent = true;
9667 $this->Error('Incorrect visibility: '.$v);
9671 $this->visibility = $v;
9675 * Add transparency parameters to the current extgstate
9676 * @param array $params parameters
9677 * @return the number of extgstates
9679 * @since 3.0.000 (2008-03-27)
9681 protected function addExtGState($parms) {
9682 $n = count($this->extgstates) + 1;
9683 $this->extgstates[$n]['parms'] = $parms;
9689 * @param array $gs extgstate
9691 * @since 3.0.000 (2008-03-27)
9693 protected function setExtGState($gs) {
9694 $this->_out(sprintf('/GS%d gs', $gs));
9698 * Put extgstates for object transparency
9699 * @param array $gs extgstate
9701 * @since 3.0.000 (2008-03-27)
9703 protected function _putextgstates() {
9704 $ne = count($this->extgstates);
9705 for ($i = 1; $i <= $ne; ++$i) {
9707 $this->extgstates[$i]['n'] = $this->n;
9708 $this->_out('<</Type /ExtGState');
9709 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
9710 $this->_out('/'.$k.' '.$v);
9713 $this->_out('endobj');
9718 * Set alpha for stroking (CA) and non-stroking (ca) operations.
9719 * @param float $alpha real value from 0 (transparent) to 1 (opaque)
9720 * @param string $bm blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
9722 * @since 3.0.000 (2008-03-27)
9724 public function setAlpha($alpha, $bm='Normal') {
9725 $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
9726 $this->setExtGState($gs);
9730 * Set the default JPEG compression quality (1-100)
9731 * @param int $quality JPEG quality, integer between 1 and 100
9733 * @since 3.0.000 (2008-03-27)
9735 public function setJPEGQuality($quality) {
9736 if (($quality < 1) OR ($quality > 100)) {
9739 $this->jpeg_quality = intval($quality);
9743 * Set the default number of columns in a row for HTML tables.
9744 * @param int $cols number of columns
9746 * @since 3.0.014 (2008-06-04)
9748 public function setDefaultTableColumns($cols=4) {
9749 $this->default_table_columns = intval($cols);
9753 * Set the height of cell repect font height.
9754 * @param int $h cell proportion respect font height (typical value = 1.25).
9756 * @since 3.0.014 (2008-06-04)
9758 public function setCellHeightRatio($h) {
9759 $this->cell_height_ratio = $h;
9763 * return the height of cell repect font height.
9765 * @since 4.0.012 (2008-07-24)
9767 public function getCellHeightRatio() {
9768 return $this->cell_height_ratio;
9772 * Set the PDF version (check PDF reference for valid values).
9773 * Default value is 1.t
9775 * @since 3.1.000 (2008-06-09)
9777 public function setPDFVersion($version='1.7') {
9778 $this->PDFVersion = $version;
9782 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
9783 * (see Section 8.1 of PDF reference, "Viewer Preferences").
9785 * <li>HideToolbar boolean (Optional) A flag specifying whether to hide the viewer application's tool bars when the document is active. Default value: false.</li>
9786 * <li>HideMenubar boolean (Optional) A flag specifying whether to hide the viewer application's menu bar when the document is active. Default value: false.</li>
9787 * <li>HideWindowUI boolean (Optional) A flag specifying whether to hide user interface elements in the document's window (such as scroll bars and navigation controls), leaving only the document's contents displayed. Default value: false.</li>
9788 * <li>FitWindow boolean (Optional) A flag specifying whether to resize the document's window to fit the size of the first displayed page. Default value: false.</li>
9789 * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
9790 * <li>DisplayDocTitle boolean (Optional; PDF 1.4) A flag specifying whether the window's title bar should display the document title taken from the Title entry of the document information dictionary (see Section 10.2.1, "Document Information Dictionary"). If false, the title bar should instead display the name of the PDF file containing the document. Default value: false.</li>
9791 * <li>NonFullScreenPageMode name (Optional) The document's page mode, specifying how to display the document on exiting full-screen mode:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>UseOC Optional content group panel visible</li><ul>This entry is meaningful only if the value of the PageMode entry in the catalog dictionary (see Section 3.6.1, "Document Catalog") is FullScreen; it is ignored otherwise. Default value: UseNone.</li>
9792 * <li>ViewArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be displayed when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9793 * <li>ViewClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9794 * <li>PrintArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be rendered when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9795 * <li>PrintClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9796 * <li>PrintScaling name (Optional; PDF 1.6) The page scaling option to be selected when a print dialog is displayed for this document. Valid values are: <ul><li>None, which indicates that the print dialog should reflect no page scaling</li><li>AppDefault (default), which indicates that applications should use the current print scaling</li><ul></li>
9797 * <li>Duplex name (Optional; PDF 1.7) The paper handling option to use when printing the file from the print dialog. The following values are valid:<ul><li>Simplex - Print single-sided</li><li>DuplexFlipShortEdge - Duplex and flip on the short edge of the sheet</li><li>DuplexFlipLongEdge - Duplex and flip on the long edge of the sheet</li></ul>Default value: none</li>
9798 * <li>PickTrayByPDFSize boolean (Optional; PDF 1.7) A flag specifying whether the PDF page size is used to select the input paper tray. This setting influences only the preset values used to populate the print dialog presented by a PDF viewer application. If PickTrayByPDFSize is true, the check box in the print dialog associated with input paper tray is checked. Note: This setting has no effect on Mac OS systems, which do not provide the ability to pick the input tray by size.</li>
9799 * <li>PrintPageRange array (Optional; PDF 1.7) The page numbers used to initialize the print dialog box when the file is printed. The first page of the PDF file is denoted by 1. Each pair consists of the first and last pages in the sub-range. An odd number of integers causes this entry to be ignored. Negative numbers cause the entire array to be ignored. Default value: as defined by PDF viewer application</li>
9800 * <li>NumCopies integer (Optional; PDF 1.7) The number of copies to be printed when the print dialog is opened for this file. Supported values are the integers 2 through 5. Values outside this range are ignored. Default value: as defined by PDF viewer application, but typically 1</li>
9802 * @param array $preferences array of options.
9803 * @author Nicola Asuni
9805 * @since 3.1.000 (2008-06-09)
9807 public function setViewerPreferences($preferences) {
9808 $this->viewer_preferences = $preferences;
9812 * Paints a linear colour gradient.
9813 * @param float $x abscissa of the top left corner of the rectangle.
9814 * @param float $y ordinate of the top left corner of the rectangle.
9815 * @param float $w width of the rectangle.
9816 * @param float $h height of the rectangle.
9817 * @param array $col1 first color (RGB components).
9818 * @param array $col2 second color (RGB components).
9819 * @param array $coords array of the form (x1, y1, x2, y2) which defines the gradient vector (see linear_gradient_coords.jpg). The default value is from left to right (x1=0, y1=0, x2=1, y2=0).
9820 * @author Andreas W�rmser, Nicola Asuni
9821 * @since 3.1.000 (2008-06-09)
9824 public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
9825 $this->Clip($x, $y, $w, $h);
9826 $this->Gradient(2, $col1, $col2, $coords);
9830 * Paints a radial colour gradient.
9831 * @param float $x abscissa of the top left corner of the rectangle.
9832 * @param float $y ordinate of the top left corner of the rectangle.
9833 * @param float $w width of the rectangle.
9834 * @param float $h height of the rectangle.
9835 * @param array $col1 first color (RGB components).
9836 * @param array $col2 second color (RGB components).
9837 * @param array $coords array of the form (fx, fy, cx, cy, r) where (fx, fy) is the starting point of the gradient with color1, (cx, cy) is the center of the circle with color2, and r is the radius of the circle (see radial_gradient_coords.jpg). (fx, fy) should be inside the circle, otherwise some areas will not be defined.
9838 * @author Andreas W�rmser, Nicola Asuni
9839 * @since 3.1.000 (2008-06-09)
9842 public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
9843 $this->Clip($x, $y, $w, $h);
9844 $this->Gradient(3, $col1, $col2, $coords);
9848 * Paints a coons patch mesh.
9849 * @param float $x abscissa of the top left corner of the rectangle.
9850 * @param float $y ordinate of the top left corner of the rectangle.
9851 * @param float $w width of the rectangle.
9852 * @param float $h height of the rectangle.
9853 * @param array $col1 first color (lower left corner) (RGB components).
9854 * @param array $col2 second color (lower right corner) (RGB components).
9855 * @param array $col3 third color (upper right corner) (RGB components).
9856 * @param array $col4 fourth color (upper left corner) (RGB components).
9857 * @param array $coords <ul><li>for one patch mesh: array(float x1, float y1, .... float x12, float y12): 12 pairs of coordinates (normally from 0 to 1) which specify the Bezier control points that define the patch. First pair is the lower left edge point, next is its right control point (control point 2). Then the other points are defined in the order: control point 1, edge point, control point 2 going counter-clockwise around the patch. Last (x12, y12) is the first edge point's left control point (control point 1).</li><li>for two or more patch meshes: array[number of patches]: arrays with the following keys for each patch: f: where to put that patch (0 = first patch, 1, 2, 3 = right, top and left of precedent patch - I didn't figure this out completely - just try and error ;-) points: 12 pairs of coordinates of the Bezier control points as above for the first patch, 8 pairs of coordinates for the following patches, ignoring the coordinates already defined by the precedent patch (I also didn't figure out the order of these - also: try and see what's happening) colors: must be 4 colors for the first patch, 2 colors for the following patches</li></ul>
9858 * @param array $coords_min minimum value used by the coordinates. If a coordinate's value is smaller than this it will be cut to coords_min. default: 0
9859 * @param array $coords_max maximum value used by the coordinates. If a coordinate's value is greater than this it will be cut to coords_max. default: 1
9860 * @author Andreas W�rmser, Nicola Asuni
9861 * @since 3.1.000 (2008-06-09)
9864 public function CoonsPatchMesh($x, $y, $w, $h, $col1=array(), $col2=array(), $col3=array(), $col4=array(), $coords=array(0.00,0.0,0.33,0.00,0.67,0.00,1.00,0.00,1.00,0.33,1.00,0.67,1.00,1.00,0.67,1.00,0.33,1.00,0.00,1.00,0.00,0.67,0.00,0.33), $coords_min=0, $coords_max=1) {
9865 $this->Clip($x, $y, $w, $h);
9866 $n = count($this->gradients) + 1;
9867 $this->gradients[$n]['type'] = 6; //coons patch mesh
9868 //check the coords array if it is the simple array or the multi patch array
9869 if (!isset($coords[0]['f'])) {
9870 //simple array -> convert to multi patch array
9871 if (!isset($col1[1])) {
9872 $col1[1] = $col1[2] = $col1[0];
9874 if (!isset($col2[1])) {
9875 $col2[1] = $col2[2] = $col2[0];
9877 if (!isset($col3[1])) {
9878 $col3[1] = $col3[2] = $col3[0];
9880 if (!isset($col4[1])) {
9881 $col4[1] = $col4[2] = $col4[0];
9883 $patch_array[0]['f'] = 0;
9884 $patch_array[0]['points'] = $coords;
9885 $patch_array[0]['colors'][0]['r'] = $col1[0];
9886 $patch_array[0]['colors'][0]['g'] = $col1[1];
9887 $patch_array[0]['colors'][0]['b'] = $col1[2];
9888 $patch_array[0]['colors'][1]['r'] = $col2[0];
9889 $patch_array[0]['colors'][1]['g'] = $col2[1];
9890 $patch_array[0]['colors'][1]['b'] = $col2[2];
9891 $patch_array[0]['colors'][2]['r'] = $col3[0];
9892 $patch_array[0]['colors'][2]['g'] = $col3[1];
9893 $patch_array[0]['colors'][2]['b'] = $col3[2];
9894 $patch_array[0]['colors'][3]['r'] = $col4[0];
9895 $patch_array[0]['colors'][3]['g'] = $col4[1];
9896 $patch_array[0]['colors'][3]['b'] = $col4[2];
9899 $patch_array = $coords;
9901 $bpcd = 65535; //16 BitsPerCoordinate
9902 //build the data stream
9903 $this->gradients[$n]['stream'] = '';
9904 $count_patch = count($patch_array);
9905 for ($i=0; $i < $count_patch; ++$i) {
9906 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
9907 $count_points = count($patch_array[$i]['points']);
9908 for ($j=0; $j < $count_points; ++$j) {
9909 //each point as 16 bit
9910 $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
9911 if ($patch_array[$i]['points'][$j] < 0) {
9912 $patch_array[$i]['points'][$j] = 0;
9914 if ($patch_array[$i]['points'][$j] > $bpcd) {
9915 $patch_array[$i]['points'][$j] = $bpcd;
9917 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
9918 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
9920 $count_cols = count($patch_array[$i]['colors']);
9921 for ($j=0; $j < $count_cols; ++$j) {
9922 //each color component as 8 bit
9923 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
9924 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
9925 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
9928 //paint the gradient
9929 $this->_out('/Sh'.$n.' sh');
9930 //restore previous Graphic State
9935 * Set a rectangular clipping area.
9936 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
9937 * @param float $y ordinate of the top left corner of the rectangle.
9938 * @param float $w width of the rectangle.
9939 * @param float $h height of the rectangle.
9940 * @author Andreas W�rmser, Nicola Asuni
9941 * @since 3.1.000 (2008-06-09)
9944 protected function Clip($x, $y, $w, $h) {
9946 $x = $this->w - $x - $w;
9948 //save current Graphic State
9951 $s .= sprintf(' %.2F %.2F %.2F %.2F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
9952 //set up transformation matrix for gradient
9953 $s .= sprintf(' %.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
9959 * @param int $type type of gradient.
9960 * @param array $col1 first color (RGB components).
9961 * @param array $col2 second color (RGB components).
9962 * @param array $coords array of coordinates.
9963 * @author Andreas W�rmser, Nicola Asuni
9964 * @since 3.1.000 (2008-06-09)
9967 protected function Gradient($type, $col1, $col2, $coords) {
9968 $n = count($this->gradients) + 1;
9969 $this->gradients[$n]['type'] = $type;
9970 if (!isset($col1[1])) {
9971 $col1[1]=$col1[2]=$col1[0];
9973 $this->gradients[$n]['col1'] = sprintf('%.3F %.3F %.3F', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
9974 if (!isset($col2[1])) {
9975 $col2[1] = $col2[2] = $col2[0];
9977 $this->gradients[$n]['col2'] = sprintf('%.3F %.3F %.3F', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
9978 $this->gradients[$n]['coords'] = $coords;
9979 //paint the gradient
9980 $this->_out('/Sh'.$n.' sh');
9981 //restore previous Graphic State
9987 * @author Andreas W�rmser, Nicola Asuni
9988 * @since 3.1.000 (2008-06-09)
9991 function _putshaders() {
9992 foreach ($this->gradients as $id => $grad) {
9993 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
9996 $this->_out('/FunctionType 2');
9997 $this->_out('/Domain [0.0 1.0]');
9998 $this->_out('/C0 ['.$grad['col1'].']');
9999 $this->_out('/C1 ['.$grad['col2'].']');
10000 $this->_out('/N 1');
10002 $this->_out('endobj');
10007 $this->_out('/ShadingType '.$grad['type']);
10008 $this->_out('/ColorSpace /DeviceRGB');
10009 if ($grad['type'] == 2) {
10010 $this->_out(sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
10011 $this->_out('/Function '.$f1.' 0 R');
10012 $this->_out('/Extend [true true] ');
10014 } elseif ($grad['type'] == 3) {
10015 //x0, y0, r0, x1, y1, r1
10016 //at this this time radius of inner circle is 0
10017 $this->_out(sprintf('/Coords [%.3F %.3F 0 %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]));
10018 $this->_out('/Function '.$f1.' 0 R');
10019 $this->_out('/Extend [true true] ');
10021 } elseif ($grad['type'] == 6) {
10022 $this->_out('/BitsPerCoordinate 16');
10023 $this->_out('/BitsPerComponent 8');
10024 $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
10025 $this->_out('/BitsPerFlag 8');
10026 $this->_out('/Length '.strlen($grad['stream']));
10028 $this->_putstream($grad['stream']);
10030 $this->_out('endobj');
10031 $this->gradients[$id]['id'] = $this->n;
10037 * @author Maxime Delorme, Nicola Asuni
10038 * @since 3.1.000 (2008-06-09)
10039 * @access protected
10041 protected function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
10043 $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c', $x1*$this->k, ($h-$y1)*$this->k, $x2*$this->k, ($h-$y2)*$this->k, $x3*$this->k, ($h-$y3)*$this->k));
10047 * Draw the sector of a circle.
10048 * It can be used for instance to render pie charts.
10049 * @param float $xc abscissa of the center.
10050 * @param float $yc ordinate of the center.
10051 * @param float $r radius.
10052 * @param float $a start angle (in degrees).
10053 * @param float $b end angle (in degrees).
10054 * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
10055 * @param float $cw: indicates whether to go clockwise (default: true).
10056 * @param float $o: origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). Default: 90.
10057 * @author Maxime Delorme, Nicola Asuni
10058 * @since 3.1.000 (2008-06-09)
10061 public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
10063 $xc = $this->w - $xc;
10073 $a = ($a % 360) + 360;
10074 $b = ($b % 360) + 360;
10078 $b = $b / 360 * 2 * M_PI;
10079 $a = $a / 360 * 2 * M_PI;
10088 } elseif ($style=='FD' or $style=='DF') {
10094 $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
10096 //first put the center
10097 $this->_out(sprintf('%.2F %.2F m', ($xc)*$k, ($hp-$yc)*$k));
10098 //put the first point
10099 $this->_out(sprintf('%.2F %.2F l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
10101 if ($d < (M_PI/2)) {
10102 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10105 $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
10106 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10109 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10112 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b) );
10115 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10117 //terminate drawing
10122 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
10123 * Only vector drawing is supported, not text or bitmap.
10124 * Although the script was successfully tested with various AI format versions, best results are probably achieved with files that were exported in the AI3 format (tested with Illustrator CS2, Freehand MX and Photoshop CS2).
10125 * @param string $file Name of the file containing the image.
10126 * @param float $x Abscissa of the upper-left corner.
10127 * @param float $y Ordinate of the upper-left corner.
10128 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
10129 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
10130 * @param mixed $link URL or identifier returned by AddLink().
10131 * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
10132 * @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>
10133 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
10134 * @param mixed $border Indicates if borders must be drawn around the image. 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>
10135 * @author Valentin Schmidt, Nicola Asuni
10136 * @since 3.1.000 (2008-06-09)
10139 public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0) {
10147 $data = file_get_contents($file);
10148 if ($data === false) {
10149 $this->Error('EPS file not found: '.$file);
10152 // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
10153 preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
10154 if (count($regs) > 1) {
10155 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
10156 if (strpos($version_str, 'Adobe Illustrator') !== false) {
10157 $versexp = explode(' ', $version_str);
10158 $version = (float)array_pop($versexp);
10159 if ($version >= 9) {
10160 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
10164 // strip binary bytes in front of PS-header
10165 $start = strpos($data, '%!PS-Adobe');
10167 $data = substr($data, $start);
10169 // find BoundingBox params
10170 preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
10171 if (count($regs) > 1) {
10172 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
10174 $this->Error('No BoundingBox found in EPS file: '.$file);
10176 $start = strpos($data, '%%EndSetup');
10177 if ($start === false) {
10178 $start = strpos($data, '%%EndProlog');
10180 if ($start === false) {
10181 $start = strpos($data, '%%BoundingBox');
10183 $data = substr($data, $start);
10184 $end = strpos($data, '%%PageTrailer');
10185 if ($end===false) {
10186 $end = strpos($data, 'showpage');
10189 $data = substr($data, 0, $end);
10192 $scale_x = $w / (($x2 - $x1) / $k);
10194 $scale_y = $h / (($y2 - $y1) / $k);
10196 $scale_y = $scale_x;
10197 $h = ($y2 - $y1) / $k * $scale_y;
10201 $scale_y = $h / (($y2 - $y1) / $k);
10202 $scale_x = $scale_y;
10203 $w = ($x2-$x1) / $k * $scale_x;
10205 $w = ($x2 - $x1) / $k;
10206 $h = ($y2 - $y1) / $k;
10209 // Check whether we need a new page first as this does not fit
10210 if ($this->checkPageBreak($h, $y)) {
10211 $y = $this->GetY() + $this->cMargin;
10213 // set bottomcoordinates
10214 $this->img_rb_y = $y + $h;
10217 if ($palign == 'L') {
10218 $ximg = $this->lMargin;
10219 // set right side coordinate
10220 $this->img_rb_x = $ximg + $w;
10221 } elseif ($palign == 'C') {
10222 $ximg = ($this->w - $x - $w) / 2;
10223 // set right side coordinate
10224 $this->img_rb_x = $ximg + $w;
10226 $ximg = $this->w - $x - $w;
10227 // set left side coordinate
10228 $this->img_rb_x = $ximg;
10231 if ($palign == 'R') {
10232 $ximg = $this->w - $this->rMargin - $w;
10233 // set left side coordinate
10234 $this->img_rb_x = $ximg;
10235 } elseif ($palign == 'C') {
10236 $ximg = ($this->w - $x - $w) / 2;
10237 // set right side coordinate
10238 $this->img_rb_x = $ximg + $w;
10241 // set right side coordinate
10242 $this->img_rb_x = $ximg + $w;
10245 if ($useBoundingBox) {
10246 $dx = $ximg * $k - $x1;
10247 $dy = $y * $k - $y1;
10252 // save the current graphic state
10253 $this->_out('q'.$this->epsmarker);
10255 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
10257 if (isset($scale_x)) {
10258 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
10260 // handle pc/unix/mac line endings
10261 preg_match('/[\r\n]+/s', $data, $regs);
10262 $lines = explode($regs[0], $data);
10264 $cnt = count($lines);
10265 for ($i=0; $i < $cnt; ++$i) {
10266 $line = $lines[$i];
10267 if (($line == '') OR ($line{0} == '%')) {
10270 $len = strlen($line);
10271 $chunks = explode(' ', $line);
10272 $cmd = array_pop($chunks);
10274 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
10275 $b = array_pop($chunks);
10276 $g = array_pop($chunks);
10277 $r = array_pop($chunks);
10278 $this->_out(''.$r.' '.$g.' '.$b.' '.($cmd=='Xa'?'rg':'RG')); //substr($line, 0, -2).'rg' -> in EPS (AI8): c m y k r g b rg!
10300 $this->_out($line);
10303 case 'x': {// custom fill color
10304 list($c,$m,$y,$k) = $chunks;
10305 $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' k');
10308 case 'X': { // custom stroke color
10309 list($c,$m,$y,$k) = $chunks;
10310 $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' K');
10318 $line{$len-1} = strtolower($cmd);
10319 $this->_out($line);
10324 $this->_out($cmd . '*');
10331 $max = min($i+5, $cnt);
10332 for ($j=$i+1; $j < $max; ++$j)
10333 $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
10352 // restore previous graphic state
10353 $this->_out($this->epsmarker.'Q');
10354 if (!empty($border)) {
10359 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
10364 $this->Link($ximg, $y, $w, $h, $link, 0);
10366 // set pointer to align the successive text/objects
10370 $this->x = $this->img_rb_x;
10374 $this->y = $y + round($h/2);
10375 $this->x = $this->img_rb_x;
10379 $this->y = $this->img_rb_y;
10380 $this->x = $this->img_rb_x;
10384 $this->SetY($this->img_rb_y);
10391 $this->endlinex = $this->img_rb_x;
10395 * Set document barcode.
10396 * @param string $bc barcode
10399 public function setBarcode($bc='') {
10400 $this->barcode = $bc;
10404 * Get current barcode.
10407 * @since 4.0.012 (2008-07-24)
10409 public function getBarcode() {
10410 return $this->barcode;
10414 * Print a Linear Barcode.
10415 * @param string $code code to print
10416 * @param string $type type of barcode.
10417 * @param int $x x position in user units
10418 * @param int $y y position in user units
10419 * @param int $w width in user units
10420 * @param int $h height in user units
10421 * @param float $xres width of the smallest bar in user units
10422 * @param array $style array of options:<ul><li>string $style['position'] barcode position inside the specified width: L = left (default for LTR); C = center; R = right (default for RTL); S = stretch</li><li>boolean $style['border'] if true prints a border around the barcode</li><li>int $style['padding'] padding to leave around the barcode in user units</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background or false for transparent</li><li>boolean $style["text"] boolean if true prints text below the barcode</li><li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li><li>int $style['stretchtext']: 0 = disabled; 1 = horizontal scaling only if necessary; 2 = forced horizontal scaling; 3 = character spacing only if necessary; 4 = forced character spacing</li></ul>
10423 * @param string $align Indicates the alignment of the pointer next to barcode insertion relative to barcode 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>
10424 * @author Nicola Asuni
10425 * @since 3.1.000 (2008-06-09)
10428 public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
10429 if ($this->empty_string($code)) {
10432 require_once(dirname(__FILE__).'/barcodes.php');
10433 // save current graphic settings
10434 $gvars = $this->getGraphicVars();
10435 // create new barcode object
10436 $barcodeobj = new TCPDFBarcode($code, $type);
10437 $arrcode = $barcodeobj->getBarcodeArray();
10438 if ($arrcode === false) {
10439 $this->Error('Error in 1D barcode string');
10441 // set default values
10442 if (!isset($style['position'])) {
10444 $style['position'] = 'R';
10446 $style['position'] = 'L';
10449 if (!isset($style['padding'])) {
10450 $style['padding'] = 0;
10452 if (!isset($style['fgcolor'])) {
10453 $style['fgcolor'] = array(0,0,0); // default black
10455 if (!isset($style['bgcolor'])) {
10456 $style['bgcolor'] = false; // default transparent
10458 if (!isset($style['border'])) {
10459 $style['border'] = false;
10461 if (!isset($style['text'])) {
10462 $style['text'] = false;
10465 if ($style['text'] AND isset($style['font'])) {
10466 if (isset($style['fontsize'])) {
10467 $fontsize = $style['fontsize'];
10471 $this->SetFont($style['font'], '', $fontsize);
10473 if (!isset($style['stretchtext'])) {
10474 $style['stretchtext'] = 4;
10476 // set foreground color
10477 $this->SetDrawColorArray($style['fgcolor']);
10478 $this->SetTextColorArray($style['fgcolor']);
10479 if ($this->empty_string($w) OR ($w <= 0)) {
10481 $w = $this->x - $this->lMargin;
10483 $w = $this->w - $this->rMargin - $this->x;
10486 if ($this->empty_string($x)) {
10487 $x = $this->GetX();
10490 $x = $this->w - $x;
10492 if ($this->empty_string($y)) {
10493 $y = $this->GetY();
10495 if ($this->empty_string($xres)) {
10498 $fbw = ($arrcode['maxw'] * $xres) + (2 * $style['padding']);
10499 $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style['padding']);
10500 if ($this->empty_string($h) OR ($h <= 0)) {
10501 $h = 10 + $extraspace;
10503 if ($this->checkPageBreak($h)) {
10506 // maximum bar heigth
10507 $barh = $h - $extraspace;
10508 switch ($style['position']) {
10509 case 'L': { // left
10517 case 'C': { // center
10518 $xdiff = (($w - $fbw) / 2);
10520 $xpos = $x - $w + $xdiff;
10522 $xpos = $x + $xdiff;
10526 case 'R': { // right
10530 $xpos = $x + $w - $fbw;
10534 case 'S': { // stretch
10536 $xres = ($w - (2 * $style['padding'])) / $arrcode['maxw'];
10545 $xpos_rect = $xpos;
10546 $xpos = $xpos_rect + $style['padding'];
10547 $xpos_text = $xpos;
10548 // barcode is always printed in LTR direction
10549 $tempRTL = $this->rtl;
10550 $this->rtl = false;
10551 // print background color
10552 if ($style['bgcolor']) {
10553 $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style['bgcolor']);
10554 } elseif ($style['border']) {
10555 $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
10558 if ($arrcode !== false) {
10559 foreach ($arrcode['bcode'] as $k => $v) {
10560 $bw = ($v['w'] * $xres);
10562 // draw a vertical bar
10563 $ypos = $y + $style['padding'] + ($v['p'] * $barh / $arrcode['maxh']);
10564 $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
10570 if ($style['text']) {
10572 $this->x = $xpos_text;
10573 $this->y = $y + $style['padding'] + $barh;
10574 $this->Cell(($arrcode['maxw'] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style['stretchtext']);
10576 // restore original direction
10577 $this->rtl = $tempRTL;
10578 // restore previous settings
10579 $this->setGraphicVars($gvars);
10580 // set bottomcoordinates
10581 $this->img_rb_y = $y + $h;
10583 // set left side coordinate
10584 $this->img_rb_x = ($this->w - $x - $w);
10586 // set right side coordinate
10587 $this->img_rb_x = $x + $w;
10589 // set pointer to align the successive text/objects
10593 $this->x = $this->img_rb_x;
10597 $this->y = $y + round($h/2);
10598 $this->x = $this->img_rb_x;
10602 $this->y = $this->img_rb_y;
10603 $this->x = $this->img_rb_x;
10607 $this->SetY($this->img_rb_y);
10617 * This function is DEPRECATED, please use the new write1DBarcode() function.
10618 * @param int $x x position in user units
10619 * @param int $y y position in user units
10620 * @param int $w width in user units
10621 * @param int $h height position in user units
10622 * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
10623 * @param string $style barcode style
10624 * @param string $font font for text
10625 * @param int $xres x resolution
10626 * @param string $code code to print
10627 * @deprecated deprecated since version 3.1.000 (2008-06-10)
10629 * @see write1DBarcode()
10631 public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
10632 // convert old settings for the new write1DBarcode() function.
10638 'fgcolor' => array(0,0,0),
10639 'bgcolor' => false,
10646 $newstyle['border'] = true;
10649 $newstyle['bgcolor'] = false;
10652 $newstyle['position'] = 'C';
10653 } elseif ($style & 8) {
10654 $newstyle['position'] = 'L';
10655 } elseif ($style & 16) {
10656 $newstyle['position'] = 'R';
10658 if ($style & 128) {
10659 $newstyle['text'] = true;
10661 if ($style & 256) {
10662 $newstyle['stretchtext'] = 4;
10664 $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
10668 * Print 2D Barcode.
10669 * @param string $code code to print
10670 * @param string $type type of barcode.
10671 * @param int $x x position in user units
10672 * @param int $y y position in user units
10673 * @param int $w width in user units
10674 * @param int $h height in user units
10675 * @param array $style array of options:<ul><li>boolean $style['border'] if true prints a border around the barcode</li><li>int $style['padding'] padding to leave around the barcode in user units</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background or false for transparent</li></ul>
10676 * @param string $align Indicates the alignment of the pointer next to barcode insertion relative to barcode 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>
10677 * @author Nicola Asuni
10678 * @since 4.5.037 (2009-04-07)
10681 public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='') {
10682 if ($this->empty_string($code)) {
10685 require_once(dirname(__FILE__).'/2dbarcodes.php');
10686 // save current graphic settings
10687 $gvars = $this->getGraphicVars();
10688 // create new barcode object
10689 $barcodeobj = new TCPDF2DBarcode($code, $type);
10690 $arrcode = $barcodeobj->getBarcodeArray();
10691 if ($arrcode === false) {
10692 $this->Error('Error in 2D barcode string');
10694 // set default values
10695 if (!isset($style['padding'])) {
10696 $style['padding'] = 0;
10698 if (!isset($style['fgcolor'])) {
10699 $style['fgcolor'] = array(0,0,0); // default black
10701 if (!isset($style['bgcolor'])) {
10702 $style['bgcolor'] = false; // default transparent
10704 if (!isset($style['border'])) {
10705 $style['border'] = false;
10707 // set foreground color
10708 $this->SetDrawColorArray($style['fgcolor']);
10709 if ($this->empty_string($x)) {
10710 $x = $this->GetX();
10713 $x = $this->w - $x;
10715 if ($this->empty_string($y)) {
10716 $y = $this->GetY();
10718 if ($this->empty_string($w) OR ($w <= 0)) {
10720 $w = $x - $this->lMargin;
10722 $w = $this->w - $this->rMargin - $x;
10725 if ($this->empty_string($h) OR ($h <= 0)) {
10726 // 2d barcodes are square by default
10729 if ($this->checkPageBreak($h)) {
10732 // calculate barcode size (excluding padding)
10733 $bw = $w - (2 * $style['padding']);
10734 $bh = $h - (2 * $style['padding']);
10735 // calculate starting coordinates
10741 $xpos += $style['padding'];
10742 $ypos = $y + $style['padding'];
10743 // barcode is always printed in LTR direction
10744 $tempRTL = $this->rtl;
10745 $this->rtl = false;
10746 // print background color
10747 if ($style['bgcolor']) {
10748 $this->Rect($x, $y, $w, $h, 'DF', '', $style['bgcolor']);
10749 } elseif ($style['border']) {
10750 $this->Rect($x, $y, $w, $h, 'D');
10752 // print barcode cells
10753 if ($arrcode !== false) {
10754 $rows = $arrcode['num_rows'];
10755 $cols = $arrcode['num_cols'];
10756 // calculate dimension of single barcode cell
10760 for ($r = 0; $r < $rows; ++$r) {
10763 for ($c = 0; $c < $cols; ++$c) {
10764 if ($arrcode['bcode'][$r][$c] == 1) {
10765 // draw a single barcode cell
10766 $this->Rect($xr, $ypos, $cw, $ch, 'F', array(), $style['fgcolor']);
10773 // restore original direction
10774 $this->rtl = $tempRTL;
10775 // restore previous settings
10776 $this->setGraphicVars($gvars);
10777 // set bottomcoordinates
10778 $this->img_rb_y = $y + $h;
10780 // set left side coordinate
10781 $this->img_rb_x = ($this->w - $x - $w);
10783 // set right side coordinate
10784 $this->img_rb_x = $x + $w;
10786 // set pointer to align the successive text/objects
10790 $this->x = $this->img_rb_x;
10794 $this->y = $y + round($h/2);
10795 $this->x = $this->img_rb_x;
10799 $this->y = $this->img_rb_y;
10800 $this->x = $this->img_rb_x;
10804 $this->SetY($this->img_rb_y);
10814 * Returns an array containing current margins:
10816 <li>$ret['left'] = left margin</li>
10817 <li>$ret['right'] = right margin</li>
10818 <li>$ret['top'] = top margin</li>
10819 <li>$ret['bottom'] = bottom margin</li>
10820 <li>$ret['header'] = header margin</li>
10821 <li>$ret['footer'] = footer margin</li>
10822 <li>$ret['cell'] = cell margin</li>
10824 * @return array containing all margins measures
10826 * @since 3.2.000 (2008-06-23)
10828 public function getMargins() {
10830 'left' => $this->lMargin,
10831 'right' => $this->rMargin,
10832 'top' => $this->tMargin,
10833 'bottom' => $this->bMargin,
10834 'header' => $this->header_margin,
10835 'footer' => $this->footer_margin,
10836 'cell' => $this->cMargin,
10842 * Returns an array containing original margins:
10844 <li>$ret['left'] = left margin</li>
10845 <li>$ret['right'] = right margin</li>
10847 * @return array containing all margins measures
10849 * @since 4.0.012 (2008-07-24)
10851 public function getOriginalMargins() {
10853 'left' => $this->original_lMargin,
10854 'right' => $this->original_rMargin
10860 * Returns the current font size.
10861 * @return current font size
10863 * @since 3.2.000 (2008-06-23)
10865 public function getFontSize() {
10866 return $this->FontSize;
10870 * Returns the current font size in points unit.
10871 * @return current font size in points unit
10873 * @since 3.2.000 (2008-06-23)
10875 public function getFontSizePt() {
10876 return $this->FontSizePt;
10880 * Returns the current font family name.
10881 * @return string current font family name
10883 * @since 4.3.008 (2008-12-05)
10885 public function getFontFamily() {
10886 return $this->FontFamily;
10890 * Returns the current font style.
10891 * @return string current font style
10893 * @since 4.3.008 (2008-12-05)
10895 public function getFontStyle() {
10896 return $this->FontStyle;
10900 * Prints a cell (rectangular area) with optional borders, background color and html text string.
10901 * 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 />
10902 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
10903 * @param float $w Cell width. If 0, the cell extends up to the right margin.
10904 * @param float $h Cell minimum height. The cell extends automatically if needed.
10905 * @param float $x upper-left corner X coordinate
10906 * @param float $y upper-left corner Y coordinate
10907 * @param string $html html text to print. Default value: empty string.
10908 * @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>
10909 * @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>
10910 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
10911 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
10912 * @param boolean $reseth if true reset the last cell height (default true).
10913 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
10914 * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
10916 * @uses MultiCell()
10917 * @see Multicell(), writeHTML()
10919 public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true) {
10920 return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0);
10924 * Returns the HTML DOM array.
10925 * <ul><li>$dom[$key]['tag'] = true if tag, false otherwise;</li><li>$dom[$key]['value'] = tag name or text;</li><li>$dom[$key]['opening'] = true if opening tag, false otherwise;</li><li>$dom[$key]['attribute'] = array of attributes (attribute name is the key);</li><li>$dom[$key]['style'] = array of style attributes (attribute name is the key);</li><li>$dom[$key]['parent'] = id of parent element;</li><li>$dom[$key]['fontname'] = font family name;</li><li>$dom[$key]['fontstyle'] = font style;</li><li>$dom[$key]['fontsize'] = font size in points;</li><li>$dom[$key]['bgcolor'] = RGB array of background color;</li><li>$dom[$key]['fgcolor'] = RGB array of foreground color;</li><li>$dom[$key]['width'] = width in pixels;</li><li>$dom[$key]['height'] = height in pixels;</li><li>$dom[$key]['align'] = text alignment;</li><li>$dom[$key]['cols'] = number of colums in table;</li><li>$dom[$key]['rows'] = number of rows in table;</li></ul>
10926 * @param string $html html code
10928 * @access protected
10929 * @since 3.2.000 (2008-06-20)
10931 protected function getHtmlDomArray($html) {
10932 // remove all unsupported tags (the line below lists all supported tags)
10933 $html = strip_tags($html, '<marker/><a><b><blockquote><br><br/><dd><del><div><dl><dt><em><font><h1><h2><h3><h4><h5><h6><hr><i><img><li><ol><p><pre><small><span><strong><sub><sup><table><tcpdf><td><th><thead><tr><tt><u><ul>');
10934 //replace some blank characters
10935 $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
10936 $html = preg_replace('/<(table|tr|td|th|tcpdf|blockquote|dd|div|dt|h1|h2|h3|h4|h5|h6|br|hr|li|ol|ul|p)([^\>]*)>[\n\r\t]+/', '<\\1\\2>', $html);
10937 $html = preg_replace('@(\r\n|\r)@', "\n", $html);
10938 $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
10939 $html = strtr($html, $repTable);
10940 while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html)) {
10941 // preserve newlines on <pre> tag
10942 $html = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html);
10944 $html = str_replace("\n", ' ', $html);
10945 // remove extra spaces from code
10946 $html = preg_replace('/[\s]+<\/(table|tr|td|th|ul|ol|li)>/', '</\\1>', $html);
10947 $html = preg_replace('/[\s]+<(tr|td|th|ul|ol|li|br)/', '<\\1', $html);
10948 $html = preg_replace('/<\/(table|tr|td|th|blockquote|dd|div|dt|h1|h2|h3|h4|h5|h6|hr|li|ol|ul|p)>[\s]+</', '</\\1><', $html);
10949 $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
10950 $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
10951 $html = preg_replace('/<img/', ' <img', $html);
10952 $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span></span>', $html);
10953 $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
10955 $html = preg_replace('/^[\s]+/', '', $html);
10956 $html = preg_replace('/[\s]+$/', '', $html);
10957 // pattern for generic tag
10958 $tagpattern = '/(<[^>]+>)/';
10959 // explodes the string
10960 $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
10962 $maxel = count($a);
10965 // create an array of elements
10967 $dom[$key] = array();
10968 // set first void element
10969 $dom[$key]['tag'] = false;
10970 $dom[$key]['value'] = '';
10971 $dom[$key]['parent'] = 0;
10972 $dom[$key]['fontname'] = $this->FontFamily;
10973 $dom[$key]['fontstyle'] = $this->FontStyle;
10974 $dom[$key]['fontsize'] = $this->FontSizePt;
10975 $dom[$key]['bgcolor'] = false;
10976 $dom[$key]['fgcolor'] = $this->fgcolor;
10977 $dom[$key]['align'] = '';
10978 $dom[$key]['listtype'] = '';
10979 $thead = false; // true when we are inside the THEAD tag
10982 array_push($level, 0); // root
10983 while ($elkey < $maxel) {
10984 $dom[$key] = array();
10985 $element = $a[$elkey];
10986 $dom[$key]['elkey'] = $elkey;
10987 if (preg_match($tagpattern, $element)) {
10989 $element = substr($element, 1, -1);
10991 preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
10992 $tagname = strtolower($tag[1]);
10993 // check if we are inside a table header
10994 if ($tagname == 'thead') {
10995 if ($element{0} == '/') {
11003 $dom[$key]['tag'] = true;
11004 $dom[$key]['value'] = $tagname;
11005 if ($element{0} == '/') {
11006 // closing html tag
11007 $dom[$key]['opening'] = false;
11008 $dom[$key]['parent'] = end($level);
11010 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
11011 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
11012 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
11013 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
11014 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
11015 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
11016 if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
11017 $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
11019 // set the number of columns in table tag
11020 if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
11021 $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
11023 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
11024 $dom[($dom[$key]['parent'])]['content'] = '';
11025 for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
11026 $dom[($dom[$key]['parent'])]['content'] .= $a[$dom[$i]['elkey']];
11030 // store header rows on a new table
11031 if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] == true)) {
11032 if ($this->empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
11033 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
11035 for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
11036 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
11039 if (($dom[$key]['value'] == 'table') AND (!$this->empty_string($dom[($dom[$key]['parent'])]['thead']))) {
11040 $dom[($dom[$key]['parent'])]['thead'] .= '</table>';
11043 // opening html tag
11044 $dom[$key]['opening'] = true;
11045 $dom[$key]['parent'] = end($level);
11046 if (substr($element, -1, 1) != '/') {
11047 // not self-closing tag
11048 array_push($level, $key);
11049 $dom[$key]['self'] = false;
11051 $dom[$key]['self'] = true;
11053 // copy some values from parent
11056 $parentkey = $dom[$key]['parent'];
11057 $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
11058 $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
11059 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
11060 $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
11061 $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
11062 $dom[$key]['align'] = $dom[$parentkey]['align'];
11063 $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
11066 preg_match_all('/([^=\s]*)=["]?([^"]*)["]?/', $element, $attr_array, PREG_PATTERN_ORDER);
11067 $dom[$key]['attribute'] = array(); // reset attribute array
11068 while (list($id, $name) = each($attr_array[1])) {
11069 $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
11071 // split style attributes
11072 if (isset($dom[$key]['attribute']['style'])) {
11073 // get style attributes
11074 preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
11075 $dom[$key]['style'] = array(); // reset style attribute array
11076 while (list($id, $name) = each($style_array[1])) {
11077 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
11079 // --- get some style attributes ---
11080 if (isset($dom[$key]['style']['font-family'])) {
11082 if (isset($dom[$key]['style']['font-family'])) {
11083 $fontslist = explode(',', strtolower($dom[$key]['style']['font-family']));
11084 foreach ($fontslist as $font) {
11085 $font = trim(strtolower($font));
11086 if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
11087 $dom[$key]['fontname'] = $font;
11094 if (isset($dom[$key]['style']['list-style-type'])) {
11095 $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
11096 if ($dom[$key]['listtype'] == 'inherit') {
11097 $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
11101 if (isset($dom[$key]['style']['font-size'])) {
11102 $fsize = trim($dom[$key]['style']['font-size']);
11106 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
11110 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
11114 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
11118 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
11122 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
11126 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
11130 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
11135 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] - 3;
11139 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] + 3;
11143 $dom[$key]['fontsize'] = $this->getHTMLUnitToUnits($fsize, $dom[$parentkey]['fontsize'], 'pt', true);
11148 if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == 'b')) {
11149 $dom[$key]['fontstyle'] .= 'B';
11151 if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == 'i')) {
11152 $dom[$key]['fontstyle'] .= '"I';
11155 if (isset($dom[$key]['style']['color']) AND (!$this->empty_string($dom[$key]['style']['color']))) {
11156 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
11158 // background color
11159 if (isset($dom[$key]['style']['background-color']) AND (!$this->empty_string($dom[$key]['style']['background-color']))) {
11160 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
11163 if (isset($dom[$key]['style']['text-decoration'])) {
11164 $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
11165 foreach ($decors as $dec) {
11167 if (!$this->empty_string($dec)) {
11168 if ($dec{0} == 'u') {
11169 $dom[$key]['fontstyle'] .= 'U';
11170 } elseif ($dec{0} == 'l') {
11171 $dom[$key]['fontstyle'] .= 'D';
11176 // check for width attribute
11177 if (isset($dom[$key]['style']['width'])) {
11178 $dom[$key]['width'] = $dom[$key]['style']['width'];
11180 // check for height attribute
11181 if (isset($dom[$key]['style']['height'])) {
11182 $dom[$key]['height'] = $dom[$key]['style']['height'];
11184 // check for text alignment
11185 if (isset($dom[$key]['style']['text-align'])) {
11186 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
11188 // check for border attribute
11189 if (isset($dom[$key]['style']['border'])) {
11190 $dom[$key]['attribute']['border'] = $dom[$key]['style']['border'];
11193 // check for font tag
11194 if ($dom[$key]['value'] == 'font') {
11196 if (isset($dom[$key]['attribute']['face'])) {
11197 $fontslist = explode(',', strtolower($dom[$key]['attribute']['face']));
11198 foreach ($fontslist as $font) {
11199 $font = trim(strtolower($font));
11200 if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
11201 $dom[$key]['fontname'] = $font;
11207 if (isset($dom[$key]['attribute']['size'])) {
11209 if ($dom[$key]['attribute']['size']{0} == '+') {
11210 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
11211 } elseif ($dom[$key]['attribute']['size']{0} == '-') {
11212 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
11214 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
11217 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
11221 // force natural alignment for lists
11222 if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
11223 AND (!isset($dom[$key]['align']) OR $this->empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
11225 $dom[$key]['align'] = 'R';
11227 $dom[$key]['align'] = 'L';
11230 if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
11231 $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
11233 if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
11234 $dom[$key]['fontstyle'] .= 'B';
11236 if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
11237 $dom[$key]['fontstyle'] .= 'I';
11239 if ($dom[$key]['value'] == 'u') {
11240 $dom[$key]['fontstyle'] .= 'U';
11242 if ($dom[$key]['value'] == 'del') {
11243 $dom[$key]['fontstyle'] .= 'D';
11245 if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
11246 $dom[$key]['fontname'] = $this->default_monospaced_font;
11248 if (($dom[$key]['value']{0} == 'h') AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
11249 $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
11250 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
11251 $dom[$key]['fontstyle'] .= 'B';
11253 if (($dom[$key]['value'] == 'table')) {
11254 $dom[$key]['rows'] = 0; // number of rows
11255 $dom[$key]['trids'] = array(); // IDs of TR elements
11256 $dom[$key]['thead'] = ''; // table header rows
11258 if (($dom[$key]['value'] == 'tr')) {
11259 $dom[$key]['cols'] = 0;
11260 // store the number of rows on table element
11261 ++$dom[($dom[$key]['parent'])]['rows'];
11262 // store the TR elements IDs on table element
11263 array_push($dom[($dom[$key]['parent'])]['trids'], $key);
11265 $dom[$key]['thead'] = true;
11267 $dom[$key]['thead'] = false;
11270 if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
11271 if (isset($dom[$key]['attribute']['colspan'])) {
11272 $colspan = intval($dom[$key]['attribute']['colspan']);
11276 $dom[$key]['attribute']['colspan'] = $colspan;
11277 $dom[($dom[$key]['parent'])]['cols'] += $colspan;
11279 // set foreground color attribute
11280 if (isset($dom[$key]['attribute']['color']) AND (!$this->empty_string($dom[$key]['attribute']['color']))) {
11281 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
11283 // set background color attribute
11284 if (isset($dom[$key]['attribute']['bgcolor']) AND (!$this->empty_string($dom[$key]['attribute']['bgcolor']))) {
11285 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
11287 // check for width attribute
11288 if (isset($dom[$key]['attribute']['width'])) {
11289 $dom[$key]['width'] = $dom[$key]['attribute']['width'];
11291 // check for height attribute
11292 if (isset($dom[$key]['attribute']['height'])) {
11293 $dom[$key]['height'] = $dom[$key]['attribute']['height'];
11295 // check for text alignment
11296 if (isset($dom[$key]['attribute']['align']) AND (!$this->empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
11297 $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
11299 } // end opening tag
11302 $dom[$key]['tag'] = false;
11303 $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
11304 $dom[$key]['parent'] = end($level);
11313 * Allows to preserve some HTML formatting (limited support).<br />
11314 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
11315 * Supported tags are: a, b, blockquote, br, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, li, ol, p, pre, small, span, strong, sub, sup, table, tcpdf, td, th, thead, tr, tt, u, ul
11316 * @param string $html text to display
11317 * @param boolean $ln if true add a new line after text (default = true)
11318 * @param int $fill Indicates if the background must be painted (true) or transparent (false).
11319 * @param boolean $reseth if true reset the last cell height (default false).
11320 * @param boolean $cell if true add the default cMargin space to each Write (default false).
11321 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
11324 public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
11325 $gvars = $this->getGraphicVars();
11326 // store current values
11327 $prevPage = $this->page;
11328 $prevlMargin = $this->lMargin;
11329 $prevrMargin = $this->rMargin;
11330 $curfontname = $this->FontFamily;
11331 $curfontstyle = $this->FontStyle;
11332 $curfontsize = $this->FontSizePt;
11333 $this->newline = true;
11334 $minstartliney = $this->y;
11336 $startlinepage = $this->page;
11340 $blocktags = array('blockquote','br','dd','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','ul','tcpdf');
11341 $this->premode = false;
11342 if (isset($this->PageAnnots[$this->page])) {
11343 $pask = count($this->PageAnnots[$this->page]);
11347 if (isset($this->footerlen[$this->page])) {
11348 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11350 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11352 $startlinepos = $this->footerpos[$this->page];
11356 $w = $this->x - $this->lMargin;
11358 $w = $this->w - $this->rMargin - $this->x;
11360 $w -= (2 * $this->cMargin);
11363 $this->x -= $this->cMargin;
11365 $this->x += $this->cMargin;
11368 if ($this->customlistindent >= 0) {
11369 $this->listindent = $this->customlistindent;
11371 $this->listindent = $this->GetStringWidth('0000');
11373 $this->listnum = 0;
11374 if (($this->empty_string($this->lasth)) OR ($reseth)) {
11376 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11378 $dom = $this->getHtmlDomArray($html);
11379 $maxel = count($dom);
11381 while ($key < $maxel) {
11382 if ($dom[$key]['tag'] OR ($key == 0)) {
11383 if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
11384 $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
11386 // vertically align image in line
11387 if ((!$this->newline)
11388 AND ($dom[$key]['value'] == 'img')
11389 AND (isset($dom[$key]['attribute']['height']))
11390 AND ($dom[$key]['attribute']['height'] > 0)) {
11391 // get image height
11392 $imgh = $this->getHTMLUnitToUnits($dom[$key]['attribute']['height'], $this->lasth, 'px');
11393 if (!$this->InFooter) {
11394 // check for page break
11395 $this->checkPageBreak($imgh);
11397 if ($this->page > $startlinepage) {
11398 // fix lines splitted over two pages
11399 if (isset($this->footerlen[$startlinepage])) {
11400 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11402 // line to be moved one page forward
11403 $pagebuff = $this->getPageBuffer($startlinepage);
11404 $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
11405 $tstart = substr($pagebuff, 0, $startlinepos);
11406 $tend = substr($this->getPageBuffer($startlinepage), $curpos);
11407 // remove line start from previous page
11408 $this->setPageBuffer($startlinepage, $tstart.''.$tend);
11409 $pagebuff = $this->getPageBuffer($this->page);
11410 $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
11411 $tend = substr($pagebuff, $this->intmrk[$this->page]);
11412 // add line start to current page
11413 $yshift = $minstartliney - $this->y;
11414 $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
11415 $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
11416 // shift the annotations and links
11417 if (isset($this->PageAnnots[$startlinepage])) {
11418 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
11419 if ($pak >= $pask) {
11420 $this->PageAnnots[$this->page][] = $pac;
11421 unset($this->PageAnnots[$startlinepage][$pak]);
11422 $npak = count($this->PageAnnots[$this->page]) - 1;
11423 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
11427 $startlinepos = $this->intmrk[$this->page];
11428 $startlinepage = $this->page;
11429 $startliney = $this->y;
11432 $this->y += (($curfontsize / $this->k) - $imgh);
11433 $minstartliney = min($this->y, $minstartliney);
11435 } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
11436 // account for different font size
11437 $pfontname = $curfontname;
11438 $pfontstyle = $curfontstyle;
11439 $pfontsize = $curfontsize;
11440 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
11441 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
11442 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
11443 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
11444 $this->SetFont($fontname, $fontstyle, $fontsize);
11445 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11446 if (is_numeric($fontsize) AND ($fontsize > 0)
11447 AND is_numeric($curfontsize) AND ($curfontsize > 0)
11448 AND ($fontsize != $curfontsize) AND (!$this->newline)
11449 AND ($key < ($maxel - 1))
11451 if ((!$this->newline) AND ($this->page > $startlinepage)) {
11452 // fix lines splitted over two pages
11453 if (isset($this->footerlen[$startlinepage])) {
11454 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11456 // line to be moved one page forward
11457 $pagebuff = $this->getPageBuffer($startlinepage);
11458 $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
11459 $tstart = substr($pagebuff, 0, $startlinepos);
11460 $tend = substr($this->getPageBuffer($startlinepage), $curpos);
11461 // remove line start from previous page
11462 $this->setPageBuffer($startlinepage, $tstart.''.$tend);
11463 $pagebuff = $this->getPageBuffer($this->page);
11464 $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
11465 $tend = substr($pagebuff, $this->intmrk[$this->page]);
11466 // add line start to current page
11467 $yshift = $minstartliney - $this->y;
11468 $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
11469 $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
11470 // shift the annotations and links
11471 if (isset($this->PageAnnots[$startlinepage])) {
11472 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
11473 if ($pak >= $pask) {
11474 $this->PageAnnots[$this->page][] = $pac;
11475 unset($this->PageAnnots[$startlinepage][$pak]);
11476 $npak = count($this->PageAnnots[$this->page]) - 1;
11477 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
11482 $this->y += (($curfontsize - $fontsize) / $this->k);
11483 $minstartliney = min($this->y, $minstartliney);
11485 $curfontname = $fontname;
11486 $curfontstyle = $fontstyle;
11487 $curfontsize = $fontsize;
11490 if (($plalign == 'J') AND (in_array($dom[$key]['value'], $blocktags))) {
11493 // get current position on page buffer
11494 $curpos = $this->pagelen[$startlinepage];
11495 if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
11496 $this->SetFillColorArray($dom[$key]['bgcolor']);
11499 $wfill = $fill | false;
11501 if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
11502 $this->SetTextColorArray($dom[$key]['fgcolor']);
11504 if (isset($dom[$key]['align'])) {
11505 $lalign = $dom[$key]['align'];
11507 if ($this->empty_string($lalign)) {
11512 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
11514 // we are at the beginning of a new line
11515 if (isset($startlinex)) {
11516 $yshift = $minstartliney - $startliney;
11517 if (($yshift > 0) OR ($this->page > $startlinepage)) {
11520 if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
11521 // the last line must be shifted to be aligned as requested
11522 $linew = abs($this->endlinex - $startlinex);
11523 $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
11524 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
11525 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11526 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
11527 } elseif (isset($opentagpos)) {
11528 $midpos = $opentagpos;
11529 } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
11530 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11531 $midpos = $this->footerpos[$startlinepage];
11536 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
11537 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
11539 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
11542 // calculate shifting amount
11544 if ($this->lMargin != $prevlMargin) {
11545 $tw += ($prevlMargin - $this->lMargin);
11547 if ($this->rMargin != $prevrMargin) {
11548 $tw += ($prevrMargin - $this->rMargin);
11550 $mdiff = abs($tw - $linew);
11552 if ($plalign == 'C') {
11554 $t_x = -($mdiff / 2);
11556 $t_x = ($mdiff / 2);
11558 } elseif (($plalign == 'R') AND (!$this->rtl)) {
11559 // right alignment on LTR document
11561 } elseif (($plalign == 'L') AND ($this->rtl)) {
11562 // left alignment on RTL document
11564 } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
11566 if ($this->rtl OR $this->tmprtl) {
11567 $t_x = $this->lMargin - $this->endlinex;
11572 // escape special characters
11573 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
11574 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
11576 if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
11577 $maxkk = count($lnstring[1]) - 1;
11578 for ($kk=0; $kk <= $maxkk; ++$kk) {
11579 // restore special characters
11580 $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
11581 $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
11582 if ($kk == $maxkk) {
11583 if ($this->rtl OR $this->tmprtl) {
11584 $tvalue = ltrim($lnstring[1][$kk]);
11586 $tvalue = rtrim($lnstring[1][$kk]);
11589 $tvalue = $lnstring[1][$kk];
11591 // count spaces on line
11592 $no += substr_count($lnstring[1][$kk], chr(32));
11593 $ns += substr_count($tvalue, chr(32));
11595 if ($this->rtl OR $this->tmprtl) {
11596 $t_x = $this->lMargin - $this->endlinex - (($no - $ns - 1) * $this->GetStringWidth(chr(32)));
11598 // calculate additional space to add to each space
11599 $spacewidth = (($tw - $linew + (($no - $ns) * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1)) * $this->k;
11600 $spacewidthu = ($tw - $linew + ($no * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1) / $this->FontSize / $this->k;
11606 $prev_epsposbeg = 0;
11608 while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
11609 if ($this->rtl OR $this->tmprtl) {
11610 $spacew = ($spacewidth * ($nsmax - $ns));
11612 $spacew = ($spacewidth * $ns);
11614 $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
11615 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
11616 $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset) + strlen($this->epsmarker.'Q');
11617 if ((($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend))
11618 OR (($epsposbeg === false) AND ($epsposend > 0) AND ($offset < $epsposend))) {
11619 // shift EPS images
11620 $trx = sprintf('1 0 0 1 %.3F 0 cm', $spacew);
11621 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
11622 $pmid_b = substr($pmid, 0, $epsposbeg);
11623 $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
11624 $pmid_e = substr($pmid, $epsposend);
11625 $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
11626 $offset = $epsposend;
11629 $prev_epsposbeg = $epsposbeg;
11631 // shift blocks of code
11632 switch ($strpiece[2][0]) {
11637 // get current X position
11638 preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11639 $currentxpos = $xmatches[1];
11640 if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
11641 if ($strcount == $maxkk) {
11642 if ($this->rtl OR $this->tmprtl) {
11643 $tvalue = $lnstring[1][$strcount];
11645 $tvalue = rtrim($lnstring[1][$strcount]);
11648 $tvalue = $lnstring[1][$strcount];
11650 $ns += substr_count($tvalue, chr(32));
11653 if ($this->rtl OR $this->tmprtl) {
11654 $spacew = ($spacewidth * ($nsmax - $ns));
11657 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11658 create_function('$matches', 'global $spacew;
11659 $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
11660 return "".$newx." ".$matches[2]." x*#!#*x".$matches[3].$matches[4];'), $pmid, 1);
11664 // get current X position
11665 preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11666 $currentxpos = $xmatches[1];
11668 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11669 create_function('$matches', 'global $spacew;
11670 $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
11671 return "".$newx." ".$matches[2]." ".$matches[3]." ".$matches[4]." x*#!#*x".$matches[5].$matches[6];'), $pmid, 1);
11675 // get current X position
11676 preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11677 $currentxpos = $xmatches[1];
11679 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11680 create_function('$matches', 'global $spacew;
11681 $newx1 = sprintf("%.3F",(floatval($matches[1]) + $spacew));
11682 $newx2 = sprintf("%.3F",(floatval($matches[3]) + $spacew));
11683 $newx3 = sprintf("%.3F",(floatval($matches[5]) + $spacew));
11684 return "".$newx1." ".$matches[2]." ".$newx2." ".$matches[4]." ".$newx3." ".$matches[6]." x*#!#*x".$matches[7].$matches[8];'), $pmid, 1);
11688 // shift the annotations and links
11689 if (isset($this->PageAnnots[$this->page])) {
11690 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
11691 if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
11692 $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
11693 $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
11700 $pmid = str_replace('x*#!#*x', '', $pmid);
11701 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
11702 // multibyte characters
11703 $spacew = $spacewidthu;
11705 // escape special characters
11706 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
11707 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
11708 $pmid = preg_replace_callback("/\[\(([^\)]*)\)\]/x",
11709 create_function('$matches', 'global $spacew;
11710 $matches[1] = str_replace("#!#OP#!#", "(", $matches[1]);
11711 $matches[1] = str_replace("#!#CP#!#", ")", $matches[1]);
11712 return "[(".str_replace(chr(0).chr(32), ") ".(-2830 * $spacew)." (", $matches[1]).")]";'), $pmidtemp);
11713 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
11714 $endlinepos = strlen($pstart."\n".$pmid."\n");
11716 // non-unicode (single-byte characters)
11717 $rs = sprintf("%.3F Tw", $spacewidth);
11718 $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
11719 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
11720 $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
11724 if (($t_x != 0) OR ($yshift < 0)) {
11726 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
11727 $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
11728 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
11729 // shift the annotations and links
11730 if (isset($this->PageAnnots[$this->page])) {
11731 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
11732 if ($pak >= $pask) {
11733 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
11734 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
11738 $this->y -= $yshift;
11742 $this->newline = false;
11743 $pbrk = $this->checkPageBreak($this->lasth);
11744 $this->SetFont($fontname, $fontstyle, $fontsize);
11746 $this->SetFillColorArray($this->bgcolor);
11748 $startlinex = $this->x;
11749 $startliney = $this->y;
11750 $minstartliney = $this->y;
11751 $startlinepage = $this->page;
11752 if (isset($endlinepos) AND (!$pbrk)) {
11753 $startlinepos = $endlinepos;
11754 unset($endlinepos);
11756 if (isset($this->footerlen[$this->page])) {
11757 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11759 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11761 $startlinepos = $this->footerpos[$this->page];
11763 $plalign = $lalign;
11764 if (isset($this->PageAnnots[$this->page])) {
11765 $pask = count($this->PageAnnots[$this->page]);
11770 if (isset($opentagpos)) {
11771 unset($opentagpos);
11773 if ($dom[$key]['tag']) {
11774 if ($dom[$key]['opening']) {
11775 if ($dom[$key]['value'] == 'table') {
11777 $wtmp = $this->x - $this->lMargin;
11779 $wtmp = $this->w - $this->rMargin - $this->x;
11781 $wtmp -= (2 * $this->cMargin);
11782 // calculate cell width
11783 if (isset($dom[$key]['width'])) {
11784 $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
11786 $table_width = $wtmp;
11789 // table content is handled in a special way
11790 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
11791 $trid = $dom[$key]['parent'];
11792 $table_el = $dom[$trid]['parent'];
11793 if (!isset($dom[$table_el]['cols'])) {
11794 $dom[$table_el]['cols'] = $trid['cols'];
11796 $oldmargin = $this->cMargin;
11797 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
11798 $currentcmargin = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
11800 $currentcmargin = 0;
11802 $this->cMargin = $currentcmargin;
11803 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
11804 $cellspacing = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'], 1, 'px');
11809 $cellspacingx = -$cellspacing;
11811 $cellspacingx = $cellspacing;
11813 $colspan = $dom[$key]['attribute']['colspan'];
11814 $wtmp = ($colspan * ($table_width / $dom[$table_el]['cols']));
11815 if (isset($dom[$key]['width'])) {
11816 $cellw = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
11820 if (isset($dom[$key]['height'])) {
11821 // minimum cell height
11822 $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
11826 $cellw -= $cellspacing;
11827 if (isset($dom[$key]['content'])) {
11828 $cell_content = $dom[$key]['content'];
11830 $cell_content = ' ';
11832 $tagtype = $dom[$key]['value'];
11834 while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
11835 // move $key index forward
11838 if (!isset($dom[$trid]['startpage'])) {
11839 $dom[$trid]['startpage'] = $this->page;
11841 $this->setPage($dom[$trid]['startpage']);
11843 if (!isset($dom[$trid]['starty'])) {
11844 $dom[$trid]['starty'] = $this->y;
11846 $this->y = $dom[$trid]['starty'];
11848 if (!isset($dom[$trid]['startx'])) {
11849 $dom[$trid]['startx'] = $this->x;
11851 $this->x += ($cellspacingx / 2);
11852 if (isset($dom[$parentid]['attribute']['rowspan'])) {
11853 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
11857 // skip row-spanned cells started on the previous rows
11858 if (isset($dom[$table_el]['rowspans'])) {
11860 $rskmax = count($dom[$table_el]['rowspans']);
11861 while ($rsk < $rskmax) {
11862 $trwsp = $dom[$table_el]['rowspans'][$rsk];
11863 $rsstartx = $trwsp['startx'];
11864 $rsendx = $trwsp['endx'];
11865 // account for margin changes
11866 if ($trwsp['startpage'] < $this->page) {
11867 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
11868 $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
11871 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
11872 $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
11877 if (($trwsp['rowspan'] > 0)
11878 AND ($rsstartx > ($this->x - $cellspacing - $currentcmargin - $this->feps))
11879 AND ($rsstartx < ($this->x + $cellspacing + $currentcmargin + $this->feps))
11880 AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page))) {
11881 // set the starting X position of the current cell
11882 $this->x = $rsendx + $cellspacingx;
11883 if (($trwsp['rowspan'] == 1)
11884 AND (isset($dom[$trid]['endy']))
11885 AND (isset($dom[$trid]['endpage']))
11886 AND ($trwsp['endpage'] == $dom[$trid]['endpage'])) {
11887 // set ending Y position for row
11888 $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
11889 $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
11897 // add rowspan information to table element
11898 if ($rowspan > 1) {
11899 if (isset($this->footerlen[$this->page])) {
11900 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11902 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11904 $trintmrkpos = $this->footerpos[$this->page];
11905 $trsid = array_push($dom[$table_el]['rowspans'], array('trid' => $trid, 'rowspan' => $rowspan, 'mrowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startx' => $this->x, 'starty' => $this->y, 'intmrkpos' => $trintmrkpos));
11907 $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
11908 if ($rowspan > 1) {
11909 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
11911 // push background colors
11912 if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
11913 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
11915 $prevLastH = $this->lasth;
11916 // ****** write the cell content ******
11917 $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
11918 $this->lasth = $prevLastH;
11919 $this->cMargin = $oldmargin;
11920 $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
11921 // update the end of row position
11922 if ($rowspan <= 1) {
11923 if (isset($dom[$trid]['endy'])) {
11924 if ($this->page == $dom[$trid]['endpage']) {
11925 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
11926 } elseif ($this->page > $dom[$trid]['endpage']) {
11927 $dom[$trid]['endy'] = $this->y;
11930 $dom[$trid]['endy'] = $this->y;
11932 if (isset($dom[$trid]['endpage'])) {
11933 $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
11935 $dom[$trid]['endpage'] = $this->page;
11938 // account for row-spanned cells
11939 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
11940 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
11941 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
11943 if (isset($dom[$table_el]['rowspans'])) {
11944 // update endy and endpage on rowspanned cells
11945 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
11946 if ($trwsp['rowspan'] > 0) {
11947 if (isset($dom[$trid]['endpage'])) {
11948 if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
11949 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
11950 } elseif ($trwsp['endpage'] < $dom[$trid]['endpage']) {
11951 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
11952 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
11954 $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
11960 $this->x += ($cellspacingx / 2);
11962 // opening tag (or self-closing tag)
11963 if (!isset($opentagpos)) {
11964 if (!$this->InFooter) {
11965 if (isset($this->footerlen[$this->page])) {
11966 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11968 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11970 $opentagpos = $this->footerpos[$this->page];
11973 $this->openHTMLTagHandler($dom, $key, $cell);
11977 $this->closeHTMLTagHandler($dom, $key, $cell);
11979 } elseif (strlen($dom[$key]['value']) > 0) {
11981 if (!$this->empty_string($this->lispacer)) {
11982 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
11983 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11984 $minstartliney = $this->y;
11985 $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
11986 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
11987 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11988 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
11989 $this->y += (($pfontsize - $curfontsize) / $this->k);
11990 $minstartliney = min($this->y, $minstartliney);
11994 $this->htmlvspace = 0;
11995 if ((!$this->premode) AND ($this->rtl OR $this->tmprtl)) {
11996 // reverse spaces order
11997 $len1 = strlen($dom[$key]['value']);
11998 $lsp = $len1 - strlen(ltrim($dom[$key]['value']));
11999 $rsp = $len1 - strlen(rtrim($dom[$key]['value']));
12002 $tmpstr .= substr($dom[$key]['value'], -$rsp);
12004 $tmpstr .= trim($dom[$key]['value']);
12006 $tmpstr .= substr($dom[$key]['value'], 0, $lsp);
12008 $dom[$key]['value'] = $tmpstr;
12011 if (!$this->premode) {
12012 if (($this->rtl OR $this->tmprtl)) {
12013 $dom[$key]['value'] = rtrim($dom[$key]['value']);
12015 $dom[$key]['value'] = ltrim($dom[$key]['value']);
12019 $firstblock = true;
12021 $firstblock = false;
12024 if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
12026 $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $this->HREF['color'], $this->HREF['style']);
12028 $ctmpmargin = $this->cMargin;
12029 $this->cMargin = 0;
12030 // ****** write only until the end of the line and get the rest ******
12031 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock);
12032 $this->cMargin = $ctmpmargin;
12034 if (strlen($strrest) > 0) {
12035 // store the remaining string on the previous $key position
12036 $this->newline = true;
12039 $this->x -= $this->cMargin;
12041 $this->x += $this->cMargin;
12044 if ($strrest == $dom[$key]['value']) {
12045 // used to avoid infinite loop
12050 $dom[$key]['value'] = ltrim($strrest);
12059 } // end for each $key
12060 // align the last line
12061 if (isset($startlinex)) {
12062 $yshift = $minstartliney - $startliney;
12063 if (($yshift > 0) OR ($this->page > $startlinepage)) {
12066 if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
12067 // the last line must be shifted to be aligned as requested
12068 $linew = abs($this->endlinex - $startlinex);
12069 $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
12070 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
12071 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
12072 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
12073 } elseif (isset($opentagpos)) {
12074 $midpos = $opentagpos;
12075 } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
12076 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
12077 $midpos = $this->footerpos[$startlinepage];
12082 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
12083 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
12085 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
12088 // calculate shifting amount
12090 if ($this->lMargin != $prevlMargin) {
12091 $tw += ($prevlMargin - $this->lMargin);
12093 if ($this->rMargin != $prevrMargin) {
12094 $tw += ($prevrMargin - $this->rMargin);
12096 $mdiff = abs($tw - $linew);
12097 if ($plalign == 'C') {
12099 $t_x = -($mdiff / 2);
12101 $t_x = ($mdiff / 2);
12103 } elseif (($plalign == 'R') AND (!$this->rtl)) {
12104 // right alignment on LTR document
12106 } elseif (($plalign == 'L') AND ($this->rtl)) {
12107 // left alignment on RTL document
12112 if (($t_x != 0) OR ($yshift < 0)) {
12114 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
12115 $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
12116 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
12117 // shift the annotations and links
12118 if (isset($this->PageAnnots[$this->page])) {
12119 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
12120 if ($pak >= $pask) {
12121 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
12122 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
12126 $this->y -= $yshift;
12130 if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
12131 $this->Ln($this->lasth);
12133 // restore previous values
12134 $this->setGraphicVars($gvars);
12135 if ($this->page > $prevPage) {
12136 $this->lMargin = $this->pagedim[$this->page]['olm'];
12137 $this->rMargin = $this->pagedim[$this->page]['orm'];
12143 * Process opening tags.
12144 * @param array $dom html dom array
12145 * @param int $key current element id
12146 * @param boolean $cell if true add the default cMargin space to each new line (default false).
12147 * @access protected
12149 protected function openHTMLTagHandler(&$dom, $key, $cell=false) {
12151 $parent = $dom[($dom[$key]['parent'])];
12152 $firstorlast = ($key == 1);
12153 // check for text direction attribute
12154 if (isset($tag['attribute']['dir'])) {
12155 $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
12157 $this->tmprtl = false;
12160 switch($tag['value']) {
12164 $dom[$key]['rowspans'] = array();
12165 if (!$this->empty_string($dom[$key]['thead'])) {
12166 // set table header
12167 $this->thead = $dom[$key]['thead'];
12169 if (isset($tag['attribute']['cellpadding'])) {
12170 $cp = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
12171 $this->oldcMargin = $this->cMargin;
12172 $this->cMargin = $cp;
12174 if (isset($tag['attribute']['cellspacing'])) {
12175 $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
12177 $this->checkPageBreak((2 * $cp) + (2 * $cs) + $this->lasth);
12181 // array of columns positions
12182 $dom[$key]['cellpos'] = array();
12186 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12187 $this->htmlvspace = 0;
12188 $wtmp = $this->w - $this->lMargin - $this->rMargin;
12189 if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
12190 $hrWidth = $this->getHTMLUnitToUnits($tag['attribute']['width'], $wtmp, 'px');
12194 $x = $this->GetX();
12195 $y = $this->GetY();
12196 $prevlinewidth = $this->GetLineWidth();
12197 $this->Line($x, $y, $x + $hrWidth, $y);
12198 $this->SetLineWidth($prevlinewidth);
12199 $this->addHTMLVertSpace(1, $cell, '', !isset($dom[($key + 1)]), $tag['value'], false);
12203 if (array_key_exists('href', $tag['attribute'])) {
12204 $this->HREF['url'] = $tag['attribute']['href'];
12206 $this->HREF['color'] = $this->htmlLinkColorArray;
12207 $this->HREF['style'] = $this->htmlLinkFontStyle;
12208 if (array_key_exists('style', $tag['attribute'])) {
12209 // get style attributes
12210 preg_match_all('/([^;:\s]*):([^;]*)/', $tag['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
12212 while (list($id, $name) = each($style_array[1])) {
12213 $name = strtolower($name);
12214 $astyle[$name] = trim($style_array[2][$id]);
12216 if (isset($astyle['color'])) {
12217 $this->HREF['color'] = $this->convertHTMLColorToDec($astyle['color']);
12219 if (isset($astyle['text-decoration'])) {
12220 $this->HREF['style'] = '';
12221 $decors = explode(' ', strtolower($astyle['text-decoration']));
12222 foreach ($decors as $dec) {
12224 if (!$this->empty_string($dec)) {
12225 if ($dec{0} == 'u') {
12226 $this->HREF['style'] .= 'U';
12227 } elseif ($dec{0} == 'l') {
12228 $this->HREF['style'] .= 'D';
12237 if (isset($tag['attribute']['src'])) {
12238 // replace relative path with real server path
12239 if ($tag['attribute']['src'][0] == '/') {
12240 $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
12242 $tag['attribute']['src'] = urldecode($tag['attribute']['src']);
12243 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
12244 if (!isset($tag['attribute']['width'])) {
12245 $tag['attribute']['width'] = 0;
12247 if (!isset($tag['attribute']['height'])) {
12248 $tag['attribute']['height'] = 0;
12250 //if (!isset($tag['attribute']['align'])) {
12251 // the only alignment supported is "bottom"
12252 // further development is required for other modes.
12253 $tag['attribute']['align'] = 'bottom';
12255 switch($tag['attribute']['align']) {
12273 $fileinfo = pathinfo($tag['attribute']['src']);
12274 if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
12275 $type = strtolower($fileinfo['extension']);
12278 $xpos = $this->GetX();
12279 if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == ' ')) {
12281 $xpos += $this->GetStringWidth(' ');
12283 $xpos -= $this->GetStringWidth(' ');
12287 if (isset($this->HREF['url']) AND !$this->empty_string($this->HREF['url'])) {
12288 $imglink = $this->HREF['url'];
12289 if ($imglink{0} == '#') {
12290 // convert url to internal link
12291 $page = intval(substr($imglink, 1));
12292 $imglink = $this->AddLink();
12293 $this->SetLink($imglink, 0, $page);
12297 if (isset($tag['attribute']['border']) AND !empty($tag['attribute']['border'])) {
12298 // currently only support 1 (frame) or a combination of 'LTRB'
12299 $border = $tag['attribute']['border'];
12302 if (isset($tag['attribute']['width'])) {
12303 $iw = $this->getHTMLUnitToUnits($tag['attribute']['width'], 1, 'px', false);
12306 if (isset($tag['attribute']['height'])) {
12307 $ih = $this->getHTMLUnitToUnits($tag['attribute']['height'], 1, 'px', false);
12309 if (($type == 'eps') OR ($type == 'ai')) {
12310 $this->ImageEps($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, $imglink, true, $align, '', $border);
12312 $this->Image($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border);
12320 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
12324 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
12333 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12337 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12342 $this->rMargin += $this->listindent;
12344 $this->lMargin += $this->listindent;
12346 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12351 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12352 $this->htmlvspace = 0;
12354 if ($tag['value'] == 'ol') {
12355 $this->listordered[$this->listnum] = true;
12357 $this->listordered[$this->listnum] = false;
12359 if (isset($tag['attribute']['start'])) {
12360 $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
12362 $this->listcount[$this->listnum] = 0;
12365 $this->rMargin += $this->listindent;
12367 $this->lMargin += $this->listindent;
12369 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12370 $this->htmlvspace = 0;
12374 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12375 if ($this->listordered[$this->listnum]) {
12377 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
12378 $this->lispacer = $parent['attribute']['type'];
12379 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
12380 $this->lispacer = $parent['listtype'];
12381 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
12382 $this->lispacer = $this->lisymbol;
12384 $this->lispacer = '#';
12386 ++$this->listcount[$this->listnum];
12387 if (isset($tag['attribute']['value'])) {
12388 $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
12392 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
12393 $this->lispacer = $parent['attribute']['type'];
12394 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
12395 $this->lispacer = $parent['listtype'];
12396 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
12397 $this->lispacer = $this->lisymbol;
12399 $this->lispacer = '!';
12404 case 'blockquote': {
12406 $this->rMargin += $this->listindent;
12408 $this->lMargin += $this->listindent;
12410 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
12414 $this->Ln('', $cell);
12418 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12422 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
12426 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12427 $this->premode = true;
12431 $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
12435 $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
12444 $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], false);
12448 if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
12449 // Special tag used to call TCPDF methods
12450 if (isset($tag['attribute']['method'])) {
12451 $tcpdf_method = $tag['attribute']['method'];
12452 if (method_exists($this, $tcpdf_method)) {
12453 if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
12454 $params = unserialize(urldecode($tag['attribute']['params']));
12455 call_user_func_array(array($this, $tcpdf_method), $params);
12457 $this->$tcpdf_method();
12459 $this->newline = true;
12471 * Process closing tags.
12472 * @param array $dom html dom array
12473 * @param int $key current element id
12474 * @param boolean $cell if true add the default cMargin space to each new line (default false).
12475 * @access protected
12477 protected function closeHTMLTagHandler(&$dom, $key, $cell=false) {
12479 $parent = $dom[($dom[$key]['parent'])];
12480 $firstorlast = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
12482 switch($tag['value']) {
12484 $table_el = $dom[($dom[$key]['parent'])]['parent'];
12485 if(!isset($parent['endy'])) {
12486 $dom[($dom[$key]['parent'])]['endy'] = $this->y;
12487 $parent['endy'] = $this->y;
12489 if(!isset($parent['endpage'])) {
12490 $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
12491 $parent['endpage'] = $this->page;
12493 // update row-spanned cells
12494 if (isset($dom[$table_el]['rowspans'])) {
12495 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12496 $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
12497 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12498 if ($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) {
12499 $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
12500 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) {
12501 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
12502 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
12506 // report new endy and endpage to the rowspanned cells
12507 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12508 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12509 $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
12510 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
12511 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
12512 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
12515 // update remaining rowspanned cells
12516 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12517 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12518 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
12519 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
12523 $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
12524 $this->y = $dom[($dom[$key]['parent'])]['endy'];
12525 if (isset($dom[$table_el]['attribute']['cellspacing'])) {
12526 $cellspacing = $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
12527 $this->y += $cellspacing;
12529 $this->Ln(0, $cell);
12530 $this->x = $parent['startx'];
12531 // account for booklet mode
12532 if ($this->page > $parent['startpage']) {
12533 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
12534 $this->x += ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
12535 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
12536 $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
12543 $table_el = $parent;
12544 if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
12545 OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
12550 // fix bottom line alignment of last line before page break
12551 foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
12552 // update row-spanned cells
12553 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
12554 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
12555 if ($trwsp['trid'] == $trkey) {
12556 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
12558 if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0)) {
12559 $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
12563 if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
12564 $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
12565 $dom[$prevtrkey]['endy'] = $pgendy;
12566 // update row-spanned cells
12567 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
12568 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
12569 if (($trwsp['trid'] == $trkey) AND ($trwsp['mrowspan'] == 1) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
12570 $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
12571 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
12576 $prevtrkey = $trkey;
12577 $table_el = $dom[($dom[$key]['parent'])];
12580 foreach ($table_el['trids'] as $j => $trkey) {
12581 $parent = $dom[$trkey];
12582 // for each cell on the row
12583 foreach ($parent['cellpos'] as $k => $cellpos) {
12584 if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
12585 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
12586 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
12587 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
12588 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
12589 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
12591 $endy = $parent['endy'];
12592 $startpage = $parent['startpage'];
12593 $endpage = $parent['endpage'];
12595 if ($endpage > $startpage) {
12596 // design borders around HTML cells.
12597 for ($page=$startpage; $page <= $endpage; ++$page) {
12598 $this->setPage($page);
12599 if ($page == $startpage) {
12600 $this->y = $parent['starty']; // put cursor at the beginning of row on the first page
12601 $ch = $this->getPageHeight() - $parent['starty'] - $this->getBreakMargin();
12602 $cborder = $this->getBorderMode($border, $position='start');
12603 } elseif ($page == $endpage) {
12604 $this->y = $this->tMargin; // put cursor at the beginning of last page
12605 $ch = $endy - $this->tMargin;
12606 $cborder = $this->getBorderMode($border, $position='end');
12608 $this->y = $this->tMargin; // put cursor at the beginning of the current page
12609 $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
12610 $cborder = $this->getBorderMode($border, $position='middle');
12612 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
12613 $this->SetFillColorArray($cellpos['bgcolor']);
12618 $cw = abs($cellpos['endx'] - $cellpos['startx']);
12619 $this->x = $cellpos['startx'];
12620 // account for margin changes
12621 if ($page > $startpage) {
12622 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
12623 $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
12624 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['lm'] != $this->pagedim[$startpage]['olm'])) {
12625 $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
12628 // design a cell around the text
12629 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $cborder, 1, '', $fill, '', 0, true);
12630 if ($cborder OR $fill) {
12631 $pagebuff = $this->getPageBuffer($this->page);
12632 $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
12633 $pend = substr($pagebuff, $this->intmrk[$this->page]);
12634 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
12635 $this->intmrk[$this->page] += strlen($ccode."\n");
12639 $this->setPage($startpage);
12640 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
12641 $this->SetFillColorArray($cellpos['bgcolor']);
12646 $this->x = $cellpos['startx'];
12647 $this->y = $parent['starty'];
12648 $cw = abs($cellpos['endx'] - $cellpos['startx']);
12649 $ch = $endy - $parent['starty'];
12650 // design a cell around the text
12651 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $border, 1, '', $fill, '', 0, true);
12652 if ($border OR $fill) {
12653 if (end($this->transfmrk[$this->page]) !== false) {
12654 $pagemarkkey = key($this->transfmrk[$this->page]);
12655 $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
12656 } elseif ($this->InFooter) {
12657 $pagemark = &$this->footerpos[$this->page];
12659 $pagemark = &$this->intmrk[$this->page];
12661 $pagebuff = $this->getPageBuffer($this->page);
12662 $pstart = substr($pagebuff, 0, $pagemark);
12663 $pend = substr($pagebuff, $pagemark);
12664 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
12665 $pagemark += strlen($ccode."\n");
12669 if (isset($table_el['attribute']['cellspacing'])) {
12670 $cellspacing = $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
12671 $this->y += $cellspacing;
12673 $this->Ln(0, $cell);
12674 $this->x = $parent['startx'];
12675 if ($endpage > $startpage) {
12676 if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
12677 $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
12678 } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
12679 $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
12683 if (isset($parent['cellpadding'])) {
12684 $this->cMargin = $this->oldcMargin;
12686 $this->lasth = $this->FontSize * $this->cell_height_ratio;
12687 if (!$this->empty_string($this->theadMargin)) {
12688 // restore top margin
12689 $this->tMargin = $this->theadMargin;
12690 $this->pagedim[$this->page]['tm'] = $this->theadMargin;
12692 // reset table header
12694 $this->theadMargin = '';
12702 $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
12706 $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
12710 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
12713 case 'blockquote': {
12715 $this->rMargin -= $this->listindent;
12717 $this->lMargin -= $this->listindent;
12719 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12723 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12727 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
12728 $this->premode = false;
12733 if ($this->listnum <= 0) {
12734 $this->listnum = 0;
12735 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12740 $this->lispacer = '';
12741 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12745 $this->lispacer = '';
12747 $this->rMargin -= $this->listindent;
12749 $this->lMargin -= $this->listindent;
12751 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12757 $this->lispacer = '';
12759 $this->rMargin -= $this->listindent;
12761 $this->lMargin -= $this->listindent;
12763 if ($this->listnum <= 0) {
12764 $this->listnum = 0;
12765 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12767 $this->lasth = $this->FontSize * $this->cell_height_ratio;
12771 $this->lispacer = '';
12772 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12781 $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], true);
12788 $this->tmprtl = false;
12792 * Add vertical spaces if needed.
12793 * @param int $n number of spaces to add
12794 * @param boolean $cell if true add the default cMargin space to each new line (default false).
12795 * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
12796 * @param boolean $firstorlast if true do not print additional empty lines.
12797 * @param string $tag HTML tag to which this space will be applied
12798 * @param boolean $closing true if this space will be applied to a closing tag, false otherwise
12799 * @access protected
12801 protected function addHTMLVertSpace($n, $cell=false, $h='', $firstorlast=false, $tag='', $closing=false) {
12802 if ($firstorlast) {
12803 $this->Ln(0, $cell);
12804 $this->htmlvspace = 0;
12807 if (isset($this->tagvspaces[$tag][intval($closing)]['n'])) {
12808 $n = $this->tagvspaces[$tag][intval($closing)]['n'];
12810 if (isset($this->tagvspaces[$tag][intval($closing)]['h'])) {
12811 $h = $this->tagvspaces[$tag][intval($closing)]['h'];
12813 if (is_string($h)) {
12814 $vsize = $n * $this->lasth;
12818 if ($vsize > $this->htmlvspace) {
12819 $this->Ln(($vsize - $this->htmlvspace), $cell);
12820 $this->htmlvspace = $vsize;
12825 * Set the default bullet to be used as LI bullet symbol
12826 * @param string $symbol character or string to be used (legal values are: '' = automatic, '!' = auto bullet, '#' = auto numbering, 'disc', 'disc', 'circle', 'square', '1', 'decimal', 'decimal-leading-zero', 'i', 'lower-roman', 'I', 'upper-roman', 'a', 'lower-alpha', 'lower-latin', 'A', 'upper-alpha', 'upper-latin', 'lower-greek')
12828 * @since 4.0.028 (2008-09-26)
12830 public function setLIsymbol($symbol='!') {
12831 $symbol = strtolower($symbol);
12841 case 'decimal-leading-zero':
12843 case 'lower-roman':
12845 case 'upper-roman':
12847 case 'lower-alpha':
12848 case 'lower-latin':
12850 case 'upper-alpha':
12851 case 'upper-latin':
12852 case 'lower-greek': {
12853 $this->lisymbol = $symbol;
12857 $this->lisymbol = '';
12863 * Set the booklet mode for double-sided pages.
12864 * @param boolean $booklet true set the booklet mode on, fals eotherwise.
12865 * @param float $inner Inner page margin.
12866 * @param float $outer Outer page margin.
12868 * @since 4.2.000 (2008-10-29)
12870 public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
12871 $this->booklet = $booklet;
12873 $this->lMargin = $inner;
12876 $this->rMargin = $outer;
12881 * Swap the left and right margins.
12882 * @param boolean $reverse if true swap left and right margins.
12883 * @access protected
12884 * @since 4.2.000 (2008-10-29)
12886 protected function swapMargins($reverse=true) {
12888 // swap left and right margins
12889 $mtemp = $this->original_lMargin;
12890 $this->original_lMargin = $this->original_rMargin;
12891 $this->original_rMargin = $mtemp;
12892 $deltam = $this->original_lMargin - $this->original_rMargin;
12893 $this->lMargin += $deltam;
12894 $this->rMargin -= $deltam;
12899 * Set the vertical spaces for HTML tags.
12900 * The array must have the following structure (example):
12901 * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
12902 * The first array level contains the tag names,
12903 * the second level contains 0 for opening tags or 1 for closing tags,
12904 * the third level contains the vertical space unit (h) and the number spaces to add (n).
12905 * If the h parameter is not specified, default values are used.
12906 * @param array $tagvs array of tags and relative vertical spaces.
12908 * @since 4.2.001 (2008-10-30)
12910 public function setHtmlVSpace($tagvs) {
12911 $this->tagvspaces = $tagvs;
12915 * Set custom width for list indentation.
12916 * @param float $width width of the indentation. Use negative value to disable it.
12918 * @since 4.2.007 (2008-11-12)
12920 public function setListIndentWidth($width) {
12921 return $this->customlistindent = floatval($width);
12925 * Set the top/bottom cell sides to be open or closed when the cell cross the page.
12926 * @param boolean $isopen if true keeps the top/bottom border open for the cell sides that cross the page.
12928 * @since 4.2.010 (2008-11-14)
12930 public function setOpenCell($isopen) {
12931 $this->opencell = $isopen;
12935 * Set the color and font style for HTML links.
12936 * @param array $color RGB array of colors
12937 * @param string $fontstyle additional font styles to add
12939 * @since 4.4.003 (2008-12-09)
12941 public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
12942 $this->htmlLinkColorArray = $color;
12943 $this->htmlLinkFontStyle = $fontstyle;
12947 * convert html string containing value and unit of measure to user's units or points.
12948 * @param string $htmlval string containing values and unit
12949 * @param string $refsize reference value in points
12950 * @param string $defaultunit default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
12951 * @param boolean $point if true returns points, otherwise returns value in user's units
12952 * @return float value in user's unit or point if $points=true
12954 * @since 4.4.004 (2008-12-10)
12956 public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
12957 $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
12965 if (in_array($defaultunit, $supportedunits)) {
12966 $unit = $defaultunit;
12968 if (is_numeric($htmlval)) {
12969 $value = floatval($htmlval);
12970 } elseif (preg_match('/([0-9\.]+)/', $htmlval, $mnum)) {
12971 $value = floatval($mnum[1]);
12972 if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
12973 if (in_array($munit[1], $supportedunits)) {
12981 $retval = (($value * $refsize) / 100);
12986 $retval = ($value * $refsize);
12990 $retval = $value * ($refsize / 2);
12995 $retval = ($value * $this->dpi) / $k;
12999 $retval = ($value / 2.54 * $this->dpi) / $k;
13003 $retval = ($value / 25.4 * $this->dpi) / $k;
13007 // one pica is 12 points
13008 $retval = ($value * 12) / $k;
13012 $retval = $value / $k;
13016 $retval = $this->pixelsToUnits($value);
13024 * Returns the Roman representation of an integer number
13025 * @param int number to convert
13026 * @return string roman representation of the specified number
13028 * @since 4.4.004 (2008-12-10)
13030 public function intToRoman($number) {
13032 while ($number >= 1000) {
13036 while ($number >= 900) {
13040 while ($number >= 500) {
13044 while ($number >= 400) {
13048 while ($number >= 100) {
13052 while ($number >= 90) {
13056 while ($number >= 50) {
13060 while ($number >= 40) {
13064 while ($number >= 10) {
13068 while ($number >= 9) {
13072 while ($number >= 5) {
13076 while ($number >= 4) {
13080 while ($number >= 1) {
13088 * Output an HTML list bullet or ordered item symbol
13089 * @param int $listdepth list nesting level
13090 * @param string $listtype type of list
13091 * @param float $size current font size
13092 * @access protected
13093 * @since 4.4.004 (2008-12-10)
13095 protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
13098 $color = $this->fgcolor;
13102 $lspace = $this->GetStringWidth(' ');
13103 if ($listtype == '!') {
13104 // set default list type for unordered list
13105 $deftypes = array('disc', 'circle', 'square');
13106 $listtype = $deftypes[($listdepth - 1) % 3];
13107 } elseif ($listtype == '#') {
13108 // set default list type for ordered list
13109 $listtype = 'decimal';
13111 switch ($listtype) {
13122 $lspace += (2 * $r);
13124 $this->x = $this->w - $this->x - $lspace;
13126 $this->x -= $lspace;
13128 $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, $fill, array('color'=>$color), $color, 8);
13135 $this->x = $this->w - $this->x - $lspace;
13137 $this->x -= $lspace;
13139 $this->Rect($this->x, ($this->y + (($this->lasth - $l)/ 2)), $l, $l, 'F', array(), $color);
13144 // $this->listcount[$this->listnum];
13148 $textitem = $this->listcount[$this->listnum];
13151 case 'decimal-leading-zero': {
13152 $textitem = sprintf("%02d", $this->listcount[$this->listnum]);
13156 case 'lower-roman': {
13157 $textitem = strtolower($this->intToRoman($this->listcount[$this->listnum]));
13161 case 'upper-roman': {
13162 $textitem = $this->intToRoman($this->listcount[$this->listnum]);
13166 case 'lower-alpha':
13167 case 'lower-latin': {
13168 $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
13172 case 'upper-alpha':
13173 case 'upper-latin': {
13174 $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
13177 case 'lower-greek': {
13178 $textitem = $this->unichr(945 + $this->listcount[$this->listnum] - 1);
13182 // Types to be implemented (special handling)
13192 case 'cjk-ideographic': {
13201 case 'hiragana-iroha': {
13204 case 'katakana-iroha': {
13209 $textitem = $this->listcount[$this->listnum];
13212 if (!$this->empty_string($textitem)) {
13213 // print ordered item
13215 $textitem = '.'.$textitem;
13217 $textitem = $textitem.'.';
13219 $lspace += $this->GetStringWidth($textitem);
13221 $this->x += $lspace;
13223 $this->x -= $lspace;
13225 $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
13228 $this->lispacer = '';
13232 * Returns current graphic variables as array.
13233 * @return array graphic variables
13234 * @access protected
13235 * @since 4.2.010 (2008-11-14)
13237 protected function getGraphicVars() {
13239 'FontFamily' => $this->FontFamily,
13240 'FontStyle' => $this->FontStyle,
13241 'FontSizePt' => $this->FontSizePt,
13242 'rMargin' => $this->rMargin,
13243 'lMargin' => $this->lMargin,
13244 'cMargin' => $this->cMargin,
13245 'LineWidth' => $this->LineWidth,
13246 'linestyleWidth' => $this->linestyleWidth,
13247 'linestyleCap' => $this->linestyleCap,
13248 'linestyleJoin' => $this->linestyleJoin,
13249 'linestyleDash' => $this->linestyleDash,
13250 'DrawColor' => $this->DrawColor,
13251 'FillColor' => $this->FillColor,
13252 'TextColor' => $this->TextColor,
13253 'ColorFlag' => $this->ColorFlag,
13254 'bgcolor' => $this->bgcolor,
13255 'fgcolor' => $this->fgcolor,
13256 'htmlvspace' => $this->htmlvspace,
13257 'lasth' => $this->lasth
13263 * Set graphic variables.
13264 * @param $gvars array graphic variables
13265 * @access protected
13266 * @since 4.2.010 (2008-11-14)
13268 protected function setGraphicVars($gvars) {
13269 $this->FontFamily = $gvars['FontFamily'];
13270 $this->FontStyle = $gvars['FontStyle'];
13271 $this->FontSizePt = $gvars['FontSizePt'];
13272 $this->rMargin = $gvars['rMargin'];
13273 $this->lMargin = $gvars['lMargin'];
13274 $this->cMargin = $gvars['cMargin'];
13275 $this->LineWidth = $gvars['LineWidth'];
13276 $this->linestyleWidth = $gvars['linestyleWidth'];
13277 $this->linestyleCap = $gvars['linestyleCap'];
13278 $this->linestyleJoin = $gvars['linestyleJoin'];
13279 $this->linestyleDash = $gvars['linestyleDash'];
13280 $this->DrawColor = $gvars['DrawColor'];
13281 $this->FillColor = $gvars['FillColor'];
13282 $this->TextColor = $gvars['TextColor'];
13283 $this->ColorFlag = $gvars['ColorFlag'];
13284 $this->bgcolor = $gvars['bgcolor'];
13285 $this->fgcolor = $gvars['fgcolor'];
13286 $this->htmlvspace = $gvars['htmlvspace'];
13287 //$this->lasth = $gvars['lasth'];
13288 $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
13289 if (!$this->empty_string($this->FontFamily)) {
13290 $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
13295 * Returns a temporary filename for caching object on filesystem.
13296 * @param string $prefix prefix to add to filename
13297 * return string filename.
13298 * @access protected
13299 * @since 4.5.000 (2008-12-31)
13301 protected function getObjFilename($name) {
13302 return tempnam(K_PATH_CACHE, $name.'_');
13306 * Writes data to a temporary file on filesystem.
13307 * @param string $file file name
13308 * @param mixed $data data to write on file
13309 * @param boolean $append if true append data, false replace.
13310 * @access protected
13311 * @since 4.5.000 (2008-12-31)
13313 protected function writeDiskCache($filename, $data, $append=false) {
13319 $f = @fopen($filename, $fmode);
13321 $this->Error('Unable to write cache file: '.$filename);
13326 // update file lenght (needed for transactions)
13327 if (!isset($this->cache_file_lenght['_'.$filename])) {
13328 $this->cache_file_lenght['_'.$filename] = strlen($data);
13330 $this->cache_file_lenght['_'.$filename] += strlen($data);
13335 * Read data from a temporary file on filesystem.
13336 * @param string $file file name
13337 * @return mixed retrieved data
13338 * @access protected
13339 * @since 4.5.000 (2008-12-31)
13341 protected function readDiskCache($filename) {
13342 return file_get_contents($filename);
13346 * Set buffer content (always append data).
13347 * @param string $data data
13348 * @access protected
13349 * @since 4.5.000 (2009-01-02)
13351 protected function setBuffer($data) {
13352 $this->bufferlen += strlen($data);
13353 if ($this->diskcache) {
13354 if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
13355 $this->buffer = $this->getObjFilename('buffer');
13357 $this->writeDiskCache($this->buffer, $data, true);
13359 $this->buffer .= $data;
13364 * Get buffer content.
13365 * @return string buffer content
13366 * @access protected
13367 * @since 4.5.000 (2009-01-02)
13369 protected function getBuffer() {
13370 if ($this->diskcache) {
13371 return $this->readDiskCache($this->buffer);
13373 return $this->buffer;
13378 * Set page buffer content.
13379 * @param int $page page number
13380 * @param string $data page data
13381 * @param boolean $append if true append data, false replace.
13382 * @access protected
13383 * @since 4.5.000 (2008-12-31)
13385 protected function setPageBuffer($page, $data, $append=false) {
13386 if ($this->diskcache) {
13387 if (!isset($this->pages[$page])) {
13388 $this->pages[$page] = $this->getObjFilename('page'.$page);
13390 $this->writeDiskCache($this->pages[$page], $data, $append);
13393 $this->pages[$page] .= $data;
13395 $this->pages[$page] = $data;
13398 if ($append AND isset($this->pagelen[$page])) {
13399 $this->pagelen[$page] += strlen($data);
13401 $this->pagelen[$page] = strlen($data);
13406 * Get page buffer content.
13407 * @param int $page page number
13408 * @return string page buffer content or false in case of error
13409 * @access protected
13410 * @since 4.5.000 (2008-12-31)
13412 protected function getPageBuffer($page) {
13413 if ($this->diskcache) {
13414 return $this->readDiskCache($this->pages[$page]);
13415 } elseif (isset($this->pages[$page])) {
13416 return $this->pages[$page];
13422 * Set image buffer content.
13423 * @param string $image image key
13424 * @param array $data image data
13425 * @access protected
13426 * @since 4.5.000 (2008-12-31)
13428 protected function setImageBuffer($image, $data) {
13429 if ($this->diskcache) {
13430 if (!isset($this->images[$image])) {
13431 $this->images[$image] = $this->getObjFilename('image'.$image);
13433 $this->writeDiskCache($this->images[$image], serialize($data));
13435 $this->images[$image] = $data;
13437 if (!in_array($image, $this->imagekeys)) {
13438 $this->imagekeys[] = $image;
13440 ++$this->numimages;
13444 * Set image buffer content.
13445 * @param string $image image key
13446 * @param string $key image sub-key
13447 * @param array $data image data
13448 * @access protected
13449 * @since 4.5.000 (2008-12-31)
13451 protected function setImageSubBuffer($image, $key, $data) {
13452 if (!isset($this->images[$image])) {
13453 $this->setImageBuffer($image, array());
13455 if ($this->diskcache) {
13456 $tmpimg = $this->getImageBuffer($image);
13457 $tmpimg[$key] = $data;
13458 $this->writeDiskCache($this->images[$image], serialize($tmpimg));
13460 $this->images[$image][$key] = $data;
13465 * Get page buffer content.
13466 * @param string $image image key
13467 * @return string image buffer content or false in case of error
13468 * @access protected
13469 * @since 4.5.000 (2008-12-31)
13471 protected function getImageBuffer($image) {
13472 if ($this->diskcache AND isset($this->images[$image])) {
13473 return unserialize($this->readDiskCache($this->images[$image]));
13474 } elseif (isset($this->images[$image])) {
13475 return $this->images[$image];
13481 * Set font buffer content.
13482 * @param string $font font key
13483 * @param array $data font data
13484 * @access protected
13485 * @since 4.5.000 (2009-01-02)
13487 protected function setFontBuffer($font, $data) {
13488 if ($this->diskcache) {
13489 if (!isset($this->fonts[$font])) {
13490 $this->fonts[$font] = $this->getObjFilename('font');
13492 $this->writeDiskCache($this->fonts[$font], serialize($data));
13494 $this->fonts[$font] = $data;
13496 if (!in_array($font, $this->fontkeys)) {
13497 $this->fontkeys[] = $font;
13502 * Set font buffer content.
13503 * @param string $font font key
13504 * @param string $key font sub-key
13505 * @param array $data font data
13506 * @access protected
13507 * @since 4.5.000 (2009-01-02)
13509 protected function setFontSubBuffer($font, $key, $data) {
13510 if (!isset($this->fonts[$font])) {
13511 $this->setFontBuffer($font, array());
13513 if ($this->diskcache) {
13514 $tmpfont = $this->getFontBuffer($font);
13515 $tmpfont[$key] = $data;
13516 $this->writeDiskCache($this->fonts[$font], serialize($tmpfont));
13518 $this->fonts[$font][$key] = $data;
13523 * Get font buffer content.
13524 * @param string $font font key
13525 * @return string font buffer content or false in case of error
13526 * @access protected
13527 * @since 4.5.000 (2009-01-02)
13529 protected function getFontBuffer($font) {
13530 if ($this->diskcache AND isset($this->fonts[$font])) {
13531 return unserialize($this->readDiskCache($this->fonts[$font]));
13532 } elseif (isset($this->fonts[$font])) {
13533 return $this->fonts[$font];
13539 * Move a page to a previous position.
13540 * @param int $frompage number of the source page
13541 * @param int $topage number of the destination page (must be less than $frompage)
13542 * @return true in case of success, false in case of error.
13544 * @since 4.5.000 (2009-01-02)
13546 public function movePage($frompage, $topage) {
13547 if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
13550 if ($frompage == $this->page) {
13551 // close the page before moving it
13554 // move all page-related states
13555 $tmppage = $this->pages[$frompage];
13556 $tmppagedim = $this->pagedim[$frompage];
13557 $tmppagelen = $this->pagelen[$frompage];
13558 $tmpintmrk = $this->intmrk[$frompage];
13559 if (isset($this->footerpos[$frompage])) {
13560 $tmpfooterpos = $this->footerpos[$frompage];
13562 if (isset($this->footerlen[$frompage])) {
13563 $tmpfooterlen = $this->footerlen[$frompage];
13565 if (isset($this->transfmrk[$frompage])) {
13566 $tmptransfmrk = $this->transfmrk[$frompage];
13568 if (isset($this->PageAnnots[$frompage])) {
13569 $tmpannots = $this->PageAnnots[$frompage];
13571 if (isset($this->newpagegroup[$frompage])) {
13572 $tmpnewpagegroup = $this->newpagegroup[$frompage];
13574 for ($i = $frompage; $i > $topage; --$i) {
13576 // shift pages down
13577 $this->pages[$i] = $this->pages[$j];
13578 $this->pagedim[$i] = $this->pagedim[$j];
13579 $this->pagelen[$i] = $this->pagelen[$j];
13580 $this->intmrk[$i] = $this->intmrk[$j];
13581 if (isset($this->footerpos[$j])) {
13582 $this->footerpos[$i] = $this->footerpos[$j];
13583 } elseif (isset($this->footerpos[$i])) {
13584 unset($this->footerpos[$i]);
13586 if (isset($this->footerlen[$j])) {
13587 $this->footerlen[$i] = $this->footerlen[$j];
13588 } elseif (isset($this->footerlen[$i])) {
13589 unset($this->footerlen[$i]);
13591 if (isset($this->transfmrk[$j])) {
13592 $this->transfmrk[$i] = $this->transfmrk[$j];
13593 } elseif (isset($this->transfmrk[$i])) {
13594 unset($this->transfmrk[$i]);
13596 if (isset($this->PageAnnots[$j])) {
13597 $this->PageAnnots[$i] = $this->PageAnnots[$j];
13598 } elseif (isset($this->PageAnnots[$i])) {
13599 unset($this->PageAnnots[$i]);
13601 if (isset($this->newpagegroup[$j])) {
13602 $this->newpagegroup[$i] = $this->newpagegroup[$j];
13603 } elseif (isset($this->newpagegroup[$i])) {
13604 unset($this->newpagegroup[$i]);
13607 $this->pages[$topage] = $tmppage;
13608 $this->pagedim[$topage] = $tmppagedim;
13609 $this->pagelen[$topage] = $tmppagelen;
13610 $this->intmrk[$topage] = $tmpintmrk;
13611 if (isset($tmpfooterpos)) {
13612 $this->footerpos[$topage] = $tmpfooterpos;
13613 } elseif (isset($this->footerpos[$topage])) {
13614 unset($this->footerpos[$topage]);
13616 if (isset($tmpfooterlen)) {
13617 $this->footerlen[$topage] = $tmpfooterlen;
13618 } elseif (isset($this->footerlen[$topage])) {
13619 unset($this->footerlen[$topage]);
13621 if (isset($tmptransfmrk)) {
13622 $this->transfmrk[$topage] = $tmptransfmrk;
13623 } elseif (isset($this->transfmrk[$topage])) {
13624 unset($this->transfmrk[$topage]);
13626 if (isset($tmpannots)) {
13627 $this->PageAnnots[$topage] = $tmpannots;
13628 } elseif (isset($this->PageAnnots[$topage])) {
13629 unset($this->PageAnnots[$topage]);
13631 if (isset($tmpnewpagegroup)) {
13632 $this->newpagegroup[$topage] = $tmpnewpagegroup;
13633 } elseif (isset($this->newpagegroup[$topage])) {
13634 unset($this->newpagegroup[$topage]);
13637 $tmpoutlines = $this->outlines;
13638 foreach ($tmpoutlines as $key => $outline) {
13639 if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
13640 $this->outlines[$key]['p'] = $outline['p'] + 1;
13641 } elseif ($outline['p'] == $frompage) {
13642 $this->outlines[$key]['p'] = $topage;
13646 $tmplinks = $this->links;
13647 foreach ($tmplinks as $key => $link) {
13648 if (($link[0] >= $topage) AND ($link[0] < $frompage)) {
13649 $this->links[$key][0] = $link[0] + 1;
13650 } elseif ($link[0] == $frompage) {
13651 $this->links[$key][0] = $topage;
13654 // adjust javascript
13655 $tmpjavascript = $this->javascript;
13656 global $jfrompage, $jtopage;
13657 $jfrompage = $frompage;
13658 $jtopage = $topage;
13659 $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
13660 create_function('$matches', 'global $jfrompage, $jtopage;
13661 $pagenum = intval($matches[3]) + 1;
13662 if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
13663 $newpage = ($pagenum + 1);
13664 } elseif ($pagenum == $jfrompage) {
13665 $newpage = $jtopage;
13667 $newpage = $pagenum;
13670 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
13671 // return to last page
13672 $this->lastPage(true);
13677 * Remove the specified page.
13678 * @param int $page page to remove
13679 * @return true in case of success, false in case of error.
13681 * @since 4.6.004 (2009-04-23)
13683 public function deletePage($page) {
13684 if ($page > $this->numpages) {
13687 // delete current page
13688 unset($this->pages[$page]);
13689 unset($this->pagedim[$page]);
13690 unset($this->pagelen[$page]);
13691 unset($this->intmrk[$page]);
13692 if (isset($this->footerpos[$page])) {
13693 unset($this->footerpos[$page]);
13695 if (isset($this->footerlen[$page])) {
13696 unset($this->footerlen[$page]);
13698 if (isset($this->transfmrk[$page])) {
13699 unset($this->transfmrk[$page]);
13701 if (isset($this->PageAnnots[$page])) {
13702 unset($this->PageAnnots[$page]);
13704 if (isset($this->newpagegroup[$page])) {
13705 unset($this->newpagegroup[$page]);
13707 if (isset($this->pageopen[$page])) {
13708 unset($this->pageopen[$page]);
13710 // update remaining pages
13711 for ($i = $page; $i < $this->numpages; ++$i) {
13714 $this->pages[$i] = $this->pages[$j];
13715 $this->pagedim[$i] = $this->pagedim[$j];
13716 $this->pagelen[$i] = $this->pagelen[$j];
13717 $this->intmrk[$i] = $this->intmrk[$j];
13718 if (isset($this->footerpos[$j])) {
13719 $this->footerpos[$i] = $this->footerpos[$j];
13720 } elseif (isset($this->footerpos[$i])) {
13721 unset($this->footerpos[$i]);
13723 if (isset($this->footerlen[$j])) {
13724 $this->footerlen[$i] = $this->footerlen[$j];
13725 } elseif (isset($this->footerlen[$i])) {
13726 unset($this->footerlen[$i]);
13728 if (isset($this->transfmrk[$j])) {
13729 $this->transfmrk[$i] = $this->transfmrk[$j];
13730 } elseif (isset($this->transfmrk[$i])) {
13731 unset($this->transfmrk[$i]);
13733 if (isset($this->PageAnnots[$j])) {
13734 $this->PageAnnots[$i] = $this->PageAnnots[$j];
13735 } elseif (isset($this->PageAnnots[$i])) {
13736 unset($this->PageAnnots[$i]);
13738 if (isset($this->newpagegroup[$j])) {
13739 $this->newpagegroup[$i] = $this->newpagegroup[$j];
13740 } elseif (isset($this->newpagegroup[$i])) {
13741 unset($this->newpagegroup[$i]);
13743 if (isset($this->pageopen[$j])) {
13744 $this->pageopen[$i] = $this->pageopen[$j];
13745 } elseif (isset($this->pageopen[$i])) {
13746 unset($this->pageopen[$i]);
13749 // remove last page
13750 unset($this->pages[$this->numpages]);
13751 unset($this->pagedim[$this->numpages]);
13752 unset($this->pagelen[$this->numpages]);
13753 unset($this->intmrk[$this->numpages]);
13754 if (isset($this->footerpos[$this->numpages])) {
13755 unset($this->footerpos[$this->numpages]);
13757 if (isset($this->footerlen[$this->numpages])) {
13758 unset($this->footerlen[$this->numpages]);
13760 if (isset($this->transfmrk[$this->numpages])) {
13761 unset($this->transfmrk[$this->numpages]);
13763 if (isset($this->PageAnnots[$this->numpages])) {
13764 unset($this->PageAnnots[$this->numpages]);
13766 if (isset($this->newpagegroup[$this->numpages])) {
13767 unset($this->newpagegroup[$this->numpages]);
13769 if (isset($this->pageopen[$this->numpages])) {
13770 unset($this->pageopen[$this->numpages]);
13773 $this->page = $this->numpages;
13775 $tmpoutlines = $this->outlines;
13776 foreach ($tmpoutlines as $key => $outline) {
13777 if ($outline['p'] > $page) {
13778 $this->outlines[$key]['p'] = $outline['p'] - 1;
13779 } elseif ($outline['p'] == $page) {
13780 unset($this->outlines[$key]);
13784 $tmplinks = $this->links;
13785 foreach ($tmplinks as $key => $link) {
13786 if ($link[0] > $page) {
13787 $this->links[$key][0] = $link[0] - 1;
13788 } elseif ($link[0] == $page) {
13789 unset($this->links[$key]);
13792 // adjust javascript
13793 $tmpjavascript = $this->javascript;
13796 $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
13797 create_function('$matches', 'global $jpage;
13798 $pagenum = intval($matches[3]) + 1;
13799 if ($pagenum >= $jpage) {
13800 $newpage = ($pagenum - 1);
13801 } elseif ($pagenum == $jpage) {
13804 $newpage = $pagenum;
13807 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
13808 // return to last page
13809 $this->lastPage(true);
13814 * Output a Table of Content Index (TOC).
13815 * You can override this method to achieve different styles.
13816 * @param int $page page number where this TOC should be inserted (leave empty for current page).
13817 * @param string $numbersfont set the font for page numbers (please use monospaced font for better alignment).
13818 * @param string $filler string used to fill the space between text and page number.
13820 * @author Nicola Asuni
13821 * @since 4.5.000 (2009-01-02)
13823 public function addTOC($page='', $numbersfont='', $filler='.') {
13824 $fontsize = $this->FontSizePt;
13825 $fontfamily = $this->FontFamily;
13826 $fontstyle = $this->FontStyle;
13827 $w = $this->w - $this->lMargin - $this->rMargin;
13828 $spacer = $this->GetStringWidth(' ') * 4;
13829 $page_first = $this->getPage();
13830 $lmargin = $this->lMargin;
13831 $rmargin = $this->rMargin;
13832 $x_start = $this->GetX();
13833 if ($this->empty_string($numbersfont)) {
13834 $numbersfont = $this->default_monospaced_font;
13836 if ($this->empty_string($filler)) {
13839 if ($this->empty_string($page)) {
13844 foreach ($this->outlines as $key => $outline) {
13852 if ($outline['l'] == 0) {
13853 $this->SetFont($fontfamily, $fontstyle.'B', $fontsize);
13855 $this->SetFont($fontfamily, $fontstyle, $fontsize - $outline['l']);
13857 $indent = ($spacer * $outline['l']);
13859 $this->rMargin += $indent;
13860 $this->x -= $indent;
13862 $this->lMargin += $indent;
13863 $this->x += $indent;
13865 $link = $this->AddLink();
13866 $this->SetLink($link, 0, $outline['p']);
13868 $this->Write(0, $outline['t'], $link, 0, $aligntext, false, 0, false, false, 0);
13869 $this->SetFont($numbersfont, $fontstyle, $fontsize);
13870 if ($this->empty_string($page)) {
13871 $pagenum = $outline['p'];
13873 // placemark to be replaced with the correct number
13874 $pagenum = '{#'.($outline['p']).'}';
13875 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
13876 $pagenum = '{'.$pagenum.'}';
13879 $numwidth = $this->GetStringWidth($pagenum);
13881 $tw = $this->x - $this->lMargin;
13883 $tw = $this->w - $this->rMargin - $this->x;
13885 $fw = $tw - $numwidth - $this->GetStringWidth(' ');
13886 $numfills = floor($fw / $this->GetStringWidth($filler));
13887 if ($numfills > 0) {
13888 $rowfill = str_repeat($filler, $numfills);
13893 $pagenum = $pagenum.$gap.$rowfill.' ';
13895 $pagenum = ' '.$rowfill.$gap.$pagenum;
13897 // write the number
13898 //$this->SetX($x_start);
13899 $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
13900 $this->SetX($x_start);
13901 $this->lMargin = $lmargin;
13902 $this->rMargin = $rmargin;
13904 $page_last = $this->getPage();
13905 $numpages = $page_last - $page_first + 1;
13906 if (!$this->empty_string($page)) {
13907 for ($p = $page_first; $p <= $page_last; ++$p) {
13909 $temppage = $this->getPageBuffer($p);
13910 for ($n = 1; $n <= $this->numpages; ++$n) {
13911 // update page numbers
13914 $alias_a = $this->_escape($k);
13915 $alias_au = $this->_escape('{'.$k.'}');
13916 if ($this->isunicode) {
13917 $alias_b = $this->_escape($this->UTF8ToLatin1($k));
13918 $alias_bu = $this->_escape($this->UTF8ToLatin1($ku));
13919 $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
13920 $alias_cu = $this->_escape($this->utf8StrRev($ku, false, $this->tmprtl));
13923 $np = $n + $numpages;
13927 $ns = $this->formatTOCPageNumber($np);
13929 $sdiff = strlen($k) - strlen($ns) - 1;
13930 $sdiffu = strlen($ku) - strlen($ns) - 1;
13931 $sfill = str_repeat($filler, $sdiff);
13932 $sfillu = str_repeat($filler, $sdiffu);
13934 $ns = $ns.' '.$sfill;
13935 $nu = $nu.' '.$sfillu;
13937 $ns = $sfill.' '.$ns;
13938 $nu = $sfillu.' '.$nu;
13940 $nu = $this->UTF8ToUTF16BE($nu, false);
13941 $temppage = str_replace($alias_au, $nu, $temppage);
13942 if ($this->isunicode) {
13943 $temppage = str_replace($alias_bu, $nu, $temppage);
13944 $temppage = str_replace($alias_cu, $nu, $temppage);
13945 $temppage = str_replace($alias_b, $ns, $temppage);
13946 $temppage = str_replace($alias_c, $ns, $temppage);
13948 $temppage = str_replace($alias_a, $ns, $temppage);
13951 $this->setPageBuffer($p, $temppage);
13954 for ($i = 0; $i < $numpages; ++$i) {
13955 $this->movePage($page_last, $page);
13958 $this->SetFont($fontfamily, $fontstyle, $fontsize);
13962 * Stores a copy of the current TCPDF object used for undo operation.
13964 * @since 4.5.029 (2009-03-19)
13966 public function startTransaction() {
13967 if (isset($this->objcopy)) {
13968 // remove previous copy
13969 $this->commitTransaction();
13971 // clone current object
13972 $this->objcopy = $this->objclone($this);
13976 * Delete the copy of the current TCPDF object used for undo operation.
13978 * @since 4.5.029 (2009-03-19)
13980 public function commitTransaction() {
13981 if (isset($this->objcopy)) {
13982 $this->objcopy->_destroy(true, true);
13983 unset($this->objcopy);
13988 * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
13989 * @return TCPDF object.
13991 * @since 4.5.029 (2009-03-19)
13993 public function rollbackTransaction() {
13994 if (isset($this->objcopy)) {
13995 if (isset($this->objcopy->diskcache) AND $this->objcopy->diskcache) {
13996 // truncate files to previous values
13997 foreach ($this->objcopy->cache_file_lenght as $file => $lenght) {
13998 $file = substr($file, 1);
13999 $handle = fopen($file, 'r+');
14000 ftruncate($handle, $lenght);
14003 $this->_destroy(true, true);
14004 return $this->objcopy;
14010 * Creates a copy of a class object
14011 * @param object $object class object to be cloned
14012 * @return cloned object
14014 * @since 4.5.029 (2009-03-19)
14016 public function objclone($object) {
14017 return @clone($object);
14021 * Determine whether a string is empty.
14022 * @param srting $str string to be checked
14023 * @return boolean true if string is empty
14025 * @since 4.5.044 (2009-04-16)
14027 public function empty_string($str) {
14028 return (is_null($str) OR (is_string($str) AND (strlen($str) == 0)));
14031 } // END OF TCPDF CLASS
14033 //============================================================+
14035 //============================================================+