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 $cborder = $this->getBorderMode($border, $position='end');
3787 $this->y = $this->tMargin; // put cursor at the beginning of the current page
3788 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
3789 $cborder = $this->getBorderMode($border, $position='middle');
3792 // account for margin changes
3793 if ($page > $startpage) {
3794 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
3795 $nx = $x + ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
3796 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
3797 $nx = $x + ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
3801 $ccode = $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, false);
3802 if ($cborder OR $fill) {
3803 $pagebuff = $this->getPageBuffer($this->page);
3804 $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
3805 $pend = substr($pagebuff, $this->intmrk[$this->page]);
3806 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
3807 $this->intmrk[$this->page] += strlen($ccode."\n");
3811 $h = max($h, ($currentY - $y));
3812 // put cursor at the beginning of text
3815 // design a cell around the text
3816 $ccode = $this->getCellCode($w, $h, '', $border, 1, '', $fill, '', 0, true);
3817 if ($border OR $fill) {
3818 if (end($this->transfmrk[$this->page]) !== false) {
3819 $pagemarkkey = key($this->transfmrk[$this->page]);
3820 $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
3821 } elseif ($this->InFooter) {
3822 $pagemark = &$this->footerpos[$this->page];
3824 $pagemark = &$this->intmrk[$this->page];
3826 $pagebuff = $this->getPageBuffer($this->page);
3827 $pstart = substr($pagebuff, 0, $pagemark);
3828 $pend = substr($pagebuff, $pagemark);
3829 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
3830 $pagemark += strlen($ccode."\n");
3833 // Get end-of-cell Y position
3834 $currentY = $this->GetY();
3835 // restore original margin values
3836 $this->SetLeftMargin($lMargin);
3837 $this->SetRightMargin($rMargin);
3839 //Go to the beginning of the next line
3840 $this->SetY($currentY);
3842 $this->SetX($x + $w);
3845 // go left or right by case
3846 $this->setPage($startpage);
3848 $this->SetX($x + $w);
3854 * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages)
3855 * @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>
3856 * @param string multicell position: 'start', 'middle', 'end'
3857 * @return border mode
3859 * @since 4.4.002 (2008-12-09)
3861 protected function getBorderMode($border, $position='start') {
3862 if ((!$this->opencell) AND ($border == 1)) {
3866 switch ($position) {
3871 if (!(false === strpos($border, 'L'))) {
3874 if (!(false === strpos($border, 'T'))) {
3877 if (!(false === strpos($border, 'R'))) {
3880 if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
3890 if (!(false === strpos($border, 'L'))) {
3893 if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
3896 if (!(false === strpos($border, 'R'))) {
3899 if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
3909 if (!(false === strpos($border, 'L'))) {
3912 if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
3915 if (!(false === strpos($border, 'R'))) {
3918 if (!(false === strpos($border, 'B'))) {
3933 * This method returns the estimated number of lines required to print the text.
3934 * @param string $txt text to print
3935 * @param float $w width of cell. If 0, they extend up to the right margin of the page.
3936 * @return int Return the estimated number of lines.
3940 public function getNumLines($txt, $w=0) {
3942 if ($this->empty_string($w) OR ($w <= 0)) {
3944 $w = $this->x - $this->lMargin;
3946 $w = $this->w - $this->rMargin - $this->x;
3950 $wmax = $w - (2 * $this->cMargin);
3951 // remove carriage returns
3952 $txt = str_replace("\r", '', $txt);
3953 // remove last newline (if any)
3954 if (substr($txt,-1) == "\n") {
3955 $txt = substr($txt, 0, -1);
3957 // divide text in blocks
3958 $txtblocks = explode("\n", $txt);
3960 foreach ($txtblocks as $block) {
3961 // estimate the number of lines
3962 $lines += $this->empty_string($block) ? 1 : (ceil($this->GetStringWidth($block) / $wmax));
3968 * This method prints text from the current position.<br />
3969 * @param float $h Line height
3970 * @param string $txt String to print
3971 * @param mixed $link URL or identifier returned by AddLink()
3972 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
3973 * @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>
3974 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
3975 * @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>
3976 * @param boolean $firstline if true prints only the first line and return the remaining string.
3977 * @param boolean $firstblock if true the string is the starting of a line.
3978 * @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.
3979 * @return mixed Return the number of cells or the remaining string if $firstline = true.
3983 public function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0) {
3984 if (strlen($txt) == 0) {
3987 // remove carriage returns
3988 $s = str_replace("\r", '', $txt);
3990 // check if string contains arabic text
3991 if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
3996 // check if string contains RTL text
3997 if ($arabic OR $this->tmprtl OR preg_match(K_RE_PATTERN_RTL, $txt)) {
4003 $chrwidth = $this->GetCharWidth('.');
4004 // get array of unicode values
4005 $chars = $this->UTF8StringToArray($s);
4006 // get array of chars
4007 $uchars = $this->UTF8ArrayToUniArray($chars);
4008 // get the number of characters
4009 $nb = count($chars);
4010 // replacement for SHY character (minus symbol)
4011 $shy_replacement = 45;
4012 $shy_replacement_char = $this->unichr($shy_replacement);
4013 // widht for SHY replacement
4014 $shy_replacement_width = $this->GetCharWidth($shy_replacement);
4015 // store current position
4019 $maxy = $this->y + $maxh - $h - (2 * $this->cMargin);
4020 // calculate remaining line width ($w)
4022 $w = $this->x - $this->lMargin;
4024 $w = $this->w - $this->rMargin - $this->x;
4027 $wmax = $w - (2 * $this->cMargin);
4028 if ($chrwidth > $wmax) {
4029 // a single character do not fit on column
4032 $i = 0; // character position
4033 $j = 0; // current starting position
4034 $sep = -1; // position of the last blank space
4035 $shy = false; // true if the last blank is a soft hypen (SHY)
4036 $l = 0; // current string lenght
4037 $nl = 0; //number of lines
4039 // for each character
4041 if (($maxh > 0) AND ($this->y >= $maxy) ) {
4044 //Get the current character
4046 if ($c == 10) { // 10 = "\n" = new line
4047 //Explicit line break
4048 if ($align == 'J') {
4057 $tmpstr = $this->UniArrSubString($uchars, $j, $i);
4060 $tmparr = array_slice($chars, $j, $i);
4062 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4064 $linew = $this->GetArrStringWidth($tmparr);
4067 $this->endlinex = $startx - $linew;
4069 $this->endlinex = $startx + $linew;
4072 $tmpcmargin = $this->cMargin;
4077 $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
4080 $this->cMargin = $tmpcmargin;
4081 return ($this->UniArrSubString($uchars, $i));
4088 // account for margin changes
4089 if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
4090 // AcceptPageBreak() may be overriden on extended classed to include margin changes
4091 $this->AcceptPageBreak();
4093 $w = $this->getRemainingWidth();
4094 $wmax = $w - (2 * $this->cMargin);
4096 // 160 is the non-breaking space.
4097 // 173 is SHY (Soft Hypen).
4098 // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
4099 // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
4100 // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
4101 if (($c != 160) AND (($c == 173) OR preg_match($this->re_spaces, $this->unichr($c)))) {
4102 // update last blank space position
4104 // check if is a SHY
4111 // update string length
4112 if ((($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) AND ($arabic)) {
4113 // with bidirectional algorithm some chars may be changed affecting the line length
4114 // *** very slow ***
4115 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), '', $this->tmprtl));
4117 $l += $this->GetCharWidth($c);
4119 if (!$stretch && (($l > $wmax) OR ($shy AND (($l + $shy_replacement_width) > $wmax))) ) {
4120 // we have reached the end of column
4122 // check if the line was already started
4123 if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $chrwidth)))
4124 OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $chrwidth)))) {
4125 // print a void cell and go to next line
4126 $this->Cell($w, $h, '', 0, 1);
4129 return ($this->UniArrSubString($uchars, $j));
4132 // truncate the word because do not fit on column
4133 $tmpstr = $this->UniArrSubString($uchars, $j, $i);
4136 $tmparr = array_slice($chars, $j, $i);
4138 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4140 $linew = $this->GetArrStringWidth($tmparr);
4143 $this->endlinex = $startx - $linew;
4145 $this->endlinex = $startx + $linew;
4148 $tmpcmargin = $this->cMargin;
4153 $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
4156 $this->cMargin = $tmpcmargin;
4157 return ($this->UniArrSubString($uchars, $i));
4164 if ($this->rtl AND (!$firstblock)) {
4170 // add hypen (minus symbol) at the end of the line
4171 $shy_width = $shy_replacement_width;
4173 $shy_char_left = $shy_replacement_char;
4174 $shy_char_right = '';
4176 $shy_char_left = '';
4177 $shy_char_right = $shy_replacement_char;
4181 $shy_char_left = '';
4182 $shy_char_right = '';
4184 $tmpstr = $this->UniArrSubString($uchars, $j, ($sep + $endspace));
4187 $tmparr = array_slice($chars, $j, ($sep + $endspace));
4189 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4191 $linew = $this->GetArrStringWidth($tmparr);
4194 $this->endlinex = $startx - $linew - $shy_width;
4196 $this->endlinex = $startx + $linew + $shy_width;
4199 $tmpcmargin = $this->cMargin;
4205 $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
4208 // return the remaining text
4209 $this->cMargin = $tmpcmargin;
4210 return ($this->UniArrSubString($uchars, ($sep + $endspace)));
4217 // account for margin changes
4218 if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
4219 // AcceptPageBreak() may be overriden on extended classed to include margin changes
4220 $this->AcceptPageBreak();
4222 $w = $this->getRemainingWidth();
4223 $wmax = $w - (2 * $this->cMargin);
4233 } // end while i < nb
4234 // print last substring (if any)
4266 $tmpstr = $this->UniArrSubString($uchars, $j, $nb);
4269 $tmparr = array_slice($chars, $j, $nb);
4271 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4273 $linew = $this->GetArrStringWidth($tmparr);
4276 $this->endlinex = $startx - $linew;
4278 $this->endlinex = $startx + $linew;
4282 $tmpcmargin = $this->cMargin;
4287 $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
4290 $this->cMargin = $tmpcmargin;
4291 return ($this->UniArrSubString($uchars, $nb));
4302 * Returns the remaining width between the current position and margins.
4303 * @return int Return the remaining width
4306 protected function getRemainingWidth() {
4308 return ($this->x - $this->lMargin);
4310 return ($this->w - $this->rMargin - $this->x);
4315 * Extract a slice of the $strarr array and return it as string.
4316 * @param string $strarr The input array of characters.
4317 * @param int $start the starting element of $strarr.
4318 * @param int $end first element that will not be returned.
4319 * @return Return part of a string
4322 public function UTF8ArrSubString($strarr, $start='', $end='') {
4323 if (strlen($start) == 0) {
4326 if (strlen($end) == 0) {
4327 $end = count($strarr);
4330 for ($i=$start; $i < $end; ++$i) {
4331 $string .= $this->unichr($strarr[$i]);
4337 * Extract a slice of the $uniarr array and return it as string.
4338 * @param string $uniarr The input array of characters.
4339 * @param int $start the starting element of $strarr.
4340 * @param int $end first element that will not be returned.
4341 * @return Return part of a string
4343 * @since 4.5.037 (2009-04-07)
4345 public function UniArrSubString($uniarr, $start='', $end='') {
4346 if (strlen($start) == 0) {
4349 if (strlen($end) == 0) {
4350 $end = count($uniarr);
4353 for ($i=$start; $i < $end; ++$i) {
4354 $string .= $uniarr[$i];
4360 * Convert an array of UTF8 values to array of unicode characters
4361 * @param string $ta The input array of UTF8 values.
4362 * @return Return array of unicode characters
4364 * @since 4.5.037 (2009-04-07)
4366 public function UTF8ArrayToUniArray($ta) {
4367 return array_map(array($this, 'unichr'), $ta);
4371 * Returns the unicode caracter specified by UTF-8 code
4372 * @param int $c UTF-8 code
4373 * @return Returns the specified character.
4374 * @author Miguel Perez, Nicola Asuni
4376 * @since 2.3.000 (2008-03-05)
4378 public function unichr($c) {
4379 if (!$this->isunicode) {
4381 } elseif ($c <= 0x7F) {
4384 } elseif ($c <= 0x7FF) {
4386 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
4387 } elseif ($c <= 0xFFFF) {
4389 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
4390 } elseif ($c <= 0x10FFFF) {
4392 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
4399 * Puts an image in the page.
4400 * The upper-left corner must be given.
4401 * The dimensions can be specified in different ways:<ul>
4402 * <li>explicit width and height (expressed in user unit)</li>
4403 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
4404 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
4405 * 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;
4406 * The format can be specified explicitly or inferred from the file extension.<br />
4407 * It is possible to put a link on the image.<br />
4408 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
4409 * @param string $file Name of the file containing the image.
4410 * @param float $x Abscissa of the upper-left corner.
4411 * @param float $y Ordinate of the upper-left corner.
4412 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
4413 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
4414 * @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.
4415 * @param mixed $link URL or identifier returned by AddLink().
4416 * @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>
4417 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
4418 * @param int $dpi dot-per-inch resolution used on resize
4419 * @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>
4420 * @param boolean $ismask true if this image is a mask, false otherwise
4421 * @param mixed $imgmask image object returned by this function or false
4422 * @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>
4423 * @param boolean $fitbox If true scale image dimensions proportionally to fit within the ($w, $h) box.
4424 * @return image information
4428 * 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
4429 * also extend from this. The only option is to add a workaround for some of the bugs in this function.
4431 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) {
4438 // get image dimensions
4439 $imsize = @getimagesize($file);
4440 if ($imsize === FALSE) {
4441 // encode spaces on filename
4442 $file = str_replace(' ', '%20', $file);
4443 $imsize = @getimagesize($file);
4444 if ($imsize === FALSE) {
4445 $this->Error('[Image] No such file or directory in '.$file);
4448 // get original image width and height in pixels
4449 list($pixw, $pixh) = $imsize;
4450 // calculate image width and height on document
4451 if (($w <= 0) AND ($h <= 0)) {
4452 // convert image size to document unit
4453 $w = $this->pixelsToUnits($pixw);
4454 $h = $this->pixelsToUnits($pixh);
4455 } elseif ($w <= 0) {
4456 $w = $h * $pixw / $pixh;
4457 } elseif ($h <= 0) {
4458 $h = $w * $pixh / $pixw;
4459 } elseif ($fitbox AND ($w > 0) AND ($h > 0)) {
4460 // scale image dimensions proportionally to fit within the ($w, $h) box
4461 // NOTE: This section doesn't actually work very well, use the resize = true case I added.
4462 if ((($w * $pixh) / ($h * $pixw)) < 1) {
4463 $h = $w * $pixh / $pixw;
4465 $w = $h * $pixw / $pixh;
4467 } else if ($resize) { // Added resize case
4468 // Note: The issue here is that $w and $h represent abstract sizes, we pass it in as pixels,
4469 // but tcpdf treats it as document units.
4470 $wratio = $pixw / $w;
4471 $hratio = $pixh / $h;
4473 // Check if our image exceeds the boundaries of $w and $h
4474 if ($wratio > 1 AND $hratio > 1) {
4475 $favoredRatio = ($wratio > $hratio) ? $wratio : $hratio;
4476 } else if ($wratio > 1) {
4477 $favoredRatio = $wratio;
4478 } else if ($hratio > 1) {
4479 $favoredRatio = $hratio;
4485 // Calculate the new boundaries that also happen to fit the box..
4486 // Dividing by the unit conversion $this->k seems to make the size not blow up
4487 // later down in the code.
4488 $w = $pixw / $favoredRatio / $this->k;
4489 $h = $pixh / $favoredRatio / $this->k;
4491 // calculate new minimum dimensions in pixels
4492 $neww = round($w * $this->k * $dpi / $this->dpi);
4493 $newh = round($h * $this->k * $dpi / $this->dpi);
4495 // check if resize is necessary (resize is used only to reduce the image)
4497 // - commmented out by pete d.
4498 // this is not a good way of checking for resize. and it might overwrite resize if the flag is enabled.
4499 // if (($neww * $newh) >= ($pixw * $pixh)) {
4503 // check if image has been already added on document
4504 if (!in_array($file, $this->imagekeys)) {
4505 //First use of image, get info
4507 $fileinfo = pathinfo($file);
4508 if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
4509 $type = $fileinfo['extension'];
4511 $this->Error('Image file has no extension and no type was specified: '.$file);
4514 $type = strtolower($type);
4515 if ($type == 'jpg') {
4518 $mqr = get_magic_quotes_runtime();
4519 //set_magic_quotes_runtime(0);
4520 // Specific image handlers
4521 $mtd = '_parse'.$type;
4522 // GD image handler function
4523 $gdfunction = 'imagecreatefrom'.$type;
4525 if ((method_exists($this, $mtd)) AND (!($resize AND function_exists($gdfunction)))) {
4526 // TCPDF image functions
4527 $info = $this->$mtd($file);
4528 if ($info == 'pngalpha') {
4529 return $this->ImagePngAlpha($file, $x, $y, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign);
4533 if (function_exists($gdfunction)) {
4535 $img = $gdfunction($file);
4537 $imgr = imagecreatetruecolor($neww, $newh);
4538 imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
4539 $info = $this->_toJPEG($imgr);
4541 $info = $this->_toJPEG($img);
4543 } elseif (extension_loaded('imagick')) {
4544 // ImageMagick library
4545 $img = new Imagick();
4546 $img->readImage($file);
4548 $img->resizeImage($neww, $newh, 10, 1, false);
4550 $img->setCompressionQuality($this->jpeg_quality);
4551 $img->setImageFormat('jpeg');
4552 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
4553 $img->writeImage($tempname);
4554 $info = $this->_parsejpeg($tempname);
4558 else if ($type == 'jpeg') {
4559 $info = $this->_parsejpeg($file);
4565 if ($info === false) {
4566 //If false, we cannot process image
4569 //set_magic_quotes_runtime($mqr);
4572 $info['cs'] = 'DeviceGray';
4574 $info['i'] = $this->numimages + 1;
4575 if ($imgmask !== false) {
4576 $info['masked'] = $imgmask;
4578 // add image to document
4579 $this->setImageBuffer($file, $info);
4581 $info = $this->getImageBuffer($file);
4583 // Check whether we need a new page first as this does not fit
4584 if ($this->checkPageBreak($h, $y)) {
4585 $y = $this->GetY() + $this->cMargin;
4587 // set bottomcoordinates
4588 $this->img_rb_y = $y + $h;
4591 if ($palign == 'L') {
4592 $ximg = $this->lMargin;
4593 // set right side coordinate
4594 $this->img_rb_x = $ximg + $w;
4595 } elseif ($palign == 'C') {
4596 $ximg = ($this->w - $x - $w) / 2;
4597 // set right side coordinate
4598 $this->img_rb_x = $ximg + $w;
4600 $ximg = $this->w - $x - $w;
4601 // set left side coordinate
4602 $this->img_rb_x = $ximg;
4605 if ($palign == 'R') {
4606 $ximg = $this->w - $this->rMargin - $w;
4607 // set left side coordinate
4608 $this->img_rb_x = $ximg;
4609 } elseif ($palign == 'C') {
4610 $ximg = ($this->w - $x - $w) / 2;
4611 // set right side coordinate
4612 $this->img_rb_x = $ximg + $w;
4615 // set right side coordinate
4616 $this->img_rb_x = $ximg + $w;
4620 // embed hidden, ouside the canvas
4621 $xkimg = ($this->pagedim[$this->page]['w'] + 10);
4623 $xkimg = $ximg * $this->k;
4625 $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']));
4626 if (!empty($border)) {
4631 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
4636 $this->Link($ximg, $y, $w, $h, $link, 0);
4638 // set pointer to align the successive text/objects
4642 $this->x = $this->img_rb_x;
4646 $this->y = $y + round($h/2);
4647 $this->x = $this->img_rb_x;
4651 $this->y = $this->img_rb_y;
4652 $this->x = $this->img_rb_x;
4656 $this->SetY($this->img_rb_y);
4663 $this->endlinex = $this->img_rb_x;
4668 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
4669 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
4670 * @param string $file Image file name.
4671 * @param image $image Image object.
4672 * return image JPEG image object.
4675 protected function _toJPEG($image) {
4676 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
4677 imagejpeg($image, $tempname, $this->jpeg_quality);
4678 imagedestroy($image);
4679 $retvars = $this->_parsejpeg($tempname);
4680 // tidy up by removing temporary image
4686 * Extract info from a JPEG file without using the GD library.
4687 * @param string $file image file to parse
4688 * @return array structure containing the image data
4691 protected function _parsejpeg($file) {
4692 $a = getimagesize($file);
4694 $this->Error('Missing or incorrect image file: '.$file);
4697 $this->Error('Not a JPEG file: '.$file);
4699 if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
4700 $colspace = 'DeviceRGB';
4701 } elseif ($a['channels'] == 4) {
4702 $colspace = 'DeviceCMYK';
4704 $colspace = 'DeviceGray';
4706 $bpc = isset($a['bits']) ? $a['bits'] : 8;
4707 $data = file_get_contents($file);
4708 return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
4712 * Extract info from a PNG file without using the GD library.
4713 * @param string $file image file to parse
4714 * @return array structure containing the image data
4717 protected function _parsepng($file) {
4718 $f = fopen($file, 'rb');
4720 $this->Error('Can\'t open image file: '.$file);
4723 if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
4724 $this->Error('Not a PNG file: '.$file);
4728 if (fread($f, 4) != 'IHDR') {
4729 $this->Error('Incorrect PNG file: '.$file);
4731 $w = $this->_freadint($f);
4732 $h = $this->_freadint($f);
4733 $bpc = ord(fread($f, 1));
4735 //$this->Error('16-bit depth not supported: '.$file);
4739 $ct = ord(fread($f, 1));
4741 $colspace = 'DeviceGray';
4742 } elseif ($ct == 2) {
4743 $colspace = 'DeviceRGB';
4744 } elseif ($ct == 3) {
4745 $colspace = 'Indexed';
4751 if (ord(fread($f, 1)) != 0) {
4752 //$this->Error('Unknown compression method: '.$file);
4756 if (ord(fread($f, 1)) != 0) {
4757 //$this->Error('Unknown filter method: '.$file);
4761 if (ord(fread($f, 1)) != 0) {
4762 //$this->Error('Interlacing not supported: '.$file);
4767 $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
4768 //Scan chunks looking for palette, transparency and image data
4773 $n = $this->_freadint($f);
4774 $type = fread($f, 4);
4775 if ($type == 'PLTE') {
4777 $pal = $this->rfread($f, $n);
4779 } elseif ($type == 'tRNS') {
4780 //Read transparency info
4781 $t = $this->rfread($f, $n);
4783 $trns = array(ord(substr($t, 1, 1)));
4784 } elseif ($ct == 2) {
4785 $trns = array(ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1)));
4787 $pos = strpos($t, chr(0));
4788 if ($pos !== false) {
4789 $trns = array($pos);
4793 } elseif ($type == 'IDAT') {
4794 //Read image data block
4795 $data .= $this->rfread($f, $n);
4797 } elseif ($type == 'IEND') {
4800 $this->rfread($f, $n + 4);
4803 if (($colspace == 'Indexed') AND (empty($pal))) {
4804 //$this->Error('Missing palette in '.$file);
4809 return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
4813 * Binary-safe and URL-safe file read.
4814 * 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.
4815 * @param resource $handle
4816 * @param int $length
4817 * @return Returns the read string or FALSE in case of error.
4818 * @author Nicola Asuni
4820 * @since 4.5.027 (2009-03-16)
4822 protected function rfread($handle, $length) {
4823 $data = fread($handle, $length);
4824 if ($data === false) {
4827 $rest = $length - strlen($data);
4829 $data .= $this->rfread($handle, $rest);
4835 * Extract info from a PNG image with alpha channel using the GD library.
4836 * @param string $file Name of the file containing the image.
4837 * @param float $x Abscissa of the upper-left corner.
4838 * @param float $y Ordinate of the upper-left corner.
4839 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
4840 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
4841 * @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.
4842 * @param mixed $link URL or identifier returned by AddLink().
4843 * @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>
4844 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
4845 * @param int $dpi dot-per-inch resolution used on resize
4846 * @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>
4847 * @author Valentin Schmidt, Nicola Asuni
4849 * @since 4.3.007 (2008-12-04)
4852 protected function ImagePngAlpha($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
4854 list($wpx, $hpx) = getimagesize($file);
4856 $img = imagecreatefrompng($file);
4857 $imgalpha = imagecreate($wpx, $hpx);
4858 // generate gray scale pallete
4859 for ($c = 0; $c < 256; ++$c) {
4860 ImageColorAllocate($imgalpha, $c, $c, $c);
4862 // extract alpha channel
4863 for ($xpx = 0; $xpx < $wpx; ++$xpx) {
4864 for ($ypx = 0; $ypx < $hpx; ++$ypx) {
4865 $colorindex = imagecolorat($img, $xpx, $ypx);
4866 $col = imagecolorsforindex($img, $colorindex);
4867 imagesetpixel($imgalpha, $xpx, $ypx, $this->getGDgamma((127 - $col['alpha']) * 255 / 127));
4870 // create temp alpha file
4871 $tempfile_alpha = tempnam(K_PATH_CACHE, 'mska_');
4872 imagepng($imgalpha, $tempfile_alpha);
4873 imagedestroy($imgalpha);
4874 // extract image without alpha channel
4875 $imgplain = imagecreatetruecolor($wpx, $hpx);
4876 imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
4877 // create temp image file
4878 $tempfile_plain = tempnam(K_PATH_CACHE, 'mskp_');
4879 imagepng($imgplain, $tempfile_plain);
4880 imagedestroy($imgplain);
4882 $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
4883 // embed image, masked with previously embedded mask
4884 $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
4885 // remove temp files
4886 unlink($tempfile_alpha);
4887 unlink($tempfile_plain);
4891 * Correct the gamma value to be used with GD library
4892 * @param float $v the gamma value to be corrected
4894 * @since 4.3.007 (2008-12-04)
4896 protected function getGDgamma($v) {
4897 return (pow(($v / 255), 2.2) * 255);
4901 * Performs a line break.
4902 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
4903 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
4904 * @param boolean $cell if true add a cMargin to the x coordinate
4909 public function Ln($h='', $cell=false) {
4910 //Line feed; default value is last cell height
4912 $cellmargin = $this->cMargin;
4917 $this->x = $this->w - $this->rMargin - $cellmargin;
4919 $this->x = $this->lMargin + $cellmargin;
4921 if (is_string($h)) {
4922 $this->y += $this->lasth;
4926 $this->newline = true;
4930 * Returns the relative X value of current position.
4931 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
4935 * @see SetX(), GetY(), SetY()
4937 public function GetX() {
4940 return ($this->w - $this->x);
4947 * Returns the absolute X value of current position.
4951 * @see SetX(), GetY(), SetY()
4953 public function GetAbsX() {
4958 * Returns the ordinate of the current position.
4962 * @see SetY(), GetX(), SetX()
4964 public function GetY() {
4970 * Defines the abscissa of the current position.
4971 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
4972 * @param float $x The value of the abscissa.
4975 * @see GetX(), GetY(), SetY(), SetXY()
4977 public function SetX($x) {
4981 $this->x = $this->w - $x;
4989 $this->x = $this->w + $x;
4995 if ($this->x > $this->w) {
4996 $this->x = $this->w;
5001 * Moves the current abscissa back to the left margin and sets the ordinate.
5002 * If the passed value is negative, it is relative to the bottom of the page.
5003 * @param float $y The value of the ordinate.
5004 * @param bool $resetx if true (default) reset the X position.
5007 * @see GetX(), GetY(), SetY(), SetXY()
5009 public function SetY($y, $resetx=true) {
5013 $this->x = $this->w - $this->rMargin;
5015 $this->x = $this->lMargin;
5021 $this->y = $this->h + $y;
5026 if ($this->y > $this->h) {
5027 $this->y = $this->h;
5032 * Defines the abscissa and ordinate of the current position.
5033 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
5034 * @param float $x The value of the abscissa
5035 * @param float $y The value of the ordinate
5038 * @see SetX(), SetY()
5040 public function SetXY($x, $y) {
5041 //Set x and y positions
5047 * Send the document to a given destination: string, local file or browser.
5048 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
5049 * The method first calls Close() if necessary to terminate the document.
5050 * @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.
5051 * @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>
5056 public function Output($name='doc.pdf', $dest='I') {
5057 //Output PDF to some destination
5058 //Finish document if necessary
5059 if ($this->state < 3) {
5062 //Normalize parameters
5063 if (is_bool($dest)) {
5064 $dest = $dest ? 'D' : 'F';
5066 $dest = strtoupper($dest);
5068 $name = preg_replace('/[\s]+/', '_', $name);
5069 $name = preg_replace('/[^a-zA-Z0-9\._-\x{4e00}-\x{9fa5}]/u', '', $name);
5072 // *** apply digital signature to the document ***
5073 // get the document content
5074 $pdfdoc = $this->getBuffer();
5075 // remove last newline
5076 $pdfdoc = substr($pdfdoc, 0, -1);
5077 // Remove the original buffer
5078 if (isset($this->diskcache) AND $this->diskcache) {
5079 // remove buffer file from cache
5080 unlink($this->buffer);
5082 unset($this->buffer);
5083 // remove filler space
5084 $tmppos = strpos($pdfdoc, '/ByteRange[0 ********** ********** **********]') + 58;
5085 $pdfdoc = substr($pdfdoc, 0, $tmppos).substr($pdfdoc, $tmppos + $this->signature_max_lenght);
5086 // define the ByteRange
5087 $byte_range = array();
5089 $byte_range[1] = $tmppos - 1;
5090 $byte_range[2] = $byte_range[1] + $this->signature_max_lenght;
5091 $byte_range[3] = strlen($pdfdoc) - $byte_range[1];
5092 // replace the ByteRange
5093 $byterange = sprintf('/ByteRange[0 %010u %010u %010u]', $byte_range[1], $byte_range[2], $byte_range[3]);
5094 $pdfdoc = str_replace('/ByteRange[0 ********** ********** **********]', $byterange, $pdfdoc);
5095 // write the document to a temporary folder
5096 $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_');
5097 $f = fopen($tempdoc, 'wb');
5099 $this->Error('Unable to create temporary file: '.$tempdoc);
5101 $pdfdoc_lenght = strlen($pdfdoc);
5102 fwrite($f, $pdfdoc, $pdfdoc_lenght);
5104 // get digital signature.
5105 // IS THE FOLLOWING PROCEDURE CORRECT? THE SIGNED DOCUMENTS ARE NOT VALID!
5106 $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_');
5107 if (empty($this->signature_data['extracerts'])) {
5108 openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
5110 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']);
5114 $signature = file_get_contents($tempsign, false, null, $pdfdoc_lenght);
5116 // extract signature
5117 $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
5118 $tmparr = explode("\n\n", $signature);
5119 $signature = $tmparr[1];
5122 $signature = base64_decode(trim($signature));
5123 // convert signature to hex
5124 $signature = current(unpack('H*', $signature));
5125 $signature = str_pad($signature, $this->signature_max_lenght, '0');
5126 // Add signature to the document
5127 $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).$signature.substr($pdfdoc, (0 - $byte_range[3]));
5128 $this->diskcache = false;
5129 $this->buffer = &$pdfdoc;
5130 $this->bufferlen = strlen($pdfdoc);
5134 // Send PDF to the standard output
5135 if (ob_get_contents()) {
5136 $this->Error('Some data has already been output, can\'t send PDF file');
5138 if (php_sapi_name() != 'cli') {
5139 //We send to a browser
5140 header('Content-Type: application/pdf');
5141 if (headers_sent()) {
5142 $this->Error('Some data has already been output to browser, can\'t send PDF file');
5144 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
5145 header('Pragma: public');
5146 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
5147 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
5148 header('Content-Length: '.$this->bufferlen);
5149 header('Content-Disposition: inline; filename="'.basename($name).'";');
5151 echo $this->getBuffer();
5155 // Download PDF as file
5156 if (ob_get_contents()) {
5157 $this->Error('Some data has already been output, can\'t send PDF file');
5159 header('Content-Description: File Transfer');
5160 if (headers_sent()) {
5161 $this->Error('Some data has already been output to browser, can\'t send PDF file');
5163 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
5164 header('Pragma: public');
5165 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
5166 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
5167 // force download dialog
5168 header('Content-Type: application/force-download');
5169 header('Content-Type: application/octet-stream', false);
5170 header('Content-Type: application/download', false);
5171 header('Content-Type: application/pdf', false);
5172 // use the Content-Disposition header to supply a recommended filename
5173 header('Content-Disposition: attachment; filename="'.basename($name).'";');
5174 header('Content-Transfer-Encoding: binary');
5175 header('Content-Length: '.$this->bufferlen);
5176 echo $this->getBuffer();
5180 // Save PDF to a local file
5181 if ($this->diskcache) {
5182 copy($this->buffer, $name);
5184 $f = fopen($name, 'wb');
5186 $this->Error('Unable to create output file: '.$name);
5188 fwrite($f, $this->getBuffer(), $this->bufferlen);
5194 // Returns PDF as a string
5195 return $this->getBuffer();
5198 $this->Error('Incorrect output destination: '.$dest);
5205 * Unset all class variables except the following critical variables: internal_encoding, state, bufferlen, buffer and diskcache.
5206 * @param boolean $destroyall if true destroys all class variables, otherwise preserves critical variables.
5207 * @param boolean $preserve_objcopy if true preserves the objcopy variable
5209 * @since 4.5.016 (2009-02-24)
5211 public function _destroy($destroyall=false, $preserve_objcopy=false) {
5212 if ($destroyall AND isset($this->diskcache) AND $this->diskcache AND (!$preserve_objcopy) AND (!$this->empty_string($this->buffer))) {
5213 // remove buffer file from cache
5214 unlink($this->buffer);
5216 foreach (array_keys(get_object_vars($this)) as $val) {
5217 if ($destroyall OR (
5218 ($val != 'internal_encoding')
5219 AND ($val != 'state')
5220 AND ($val != 'bufferlen')
5221 AND ($val != 'buffer')
5222 AND ($val != 'diskcache')
5223 AND ($val != 'sign')
5224 AND ($val != 'signature_data')
5225 AND ($val != 'signature_max_lenght')
5227 if (!$preserve_objcopy OR ($val != 'objcopy')) {
5235 * Check for locale-related bug
5238 protected function _dochecks() {
5239 //Check for locale-related bug
5241 $this->Error('Don\'t alter the locale before including class file');
5243 //Check for decimal separator
5244 if (sprintf('%.1F', 1.0) != '1.0') {
5245 setlocale(LC_NUMERIC, 'C');
5254 protected function _getfontpath() {
5255 if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
5256 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
5258 return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
5265 protected function _putpages() {
5266 $nb = $this->numpages;
5267 if (!empty($this->AliasNbPages)) {
5268 $nbs = $this->formatPageNumber($nb);
5269 $nbu = $this->UTF8ToUTF16BE($nbs, false); // replacement for unicode font
5270 $alias_a = $this->_escape($this->AliasNbPages);
5271 $alias_au = $this->_escape('{'.$this->AliasNbPages.'}');
5272 if ($this->isunicode) {
5273 $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
5274 $alias_bu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNbPages.'}'));
5275 $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
5276 $alias_cu = $this->_escape($this->utf8StrRev('{'.$this->AliasNbPages.'}', false, $this->tmprtl));
5279 if (!empty($this->AliasNumPage)) {
5280 $alias_pa = $this->_escape($this->AliasNumPage);
5281 $alias_pau = $this->_escape('{'.$this->AliasNumPage.'}');
5282 if ($this->isunicode) {
5283 $alias_pb = $this->_escape($this->UTF8ToLatin1($this->AliasNumPage));
5284 $alias_pbu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNumPage.'}'));
5285 $alias_pc = $this->_escape($this->utf8StrRev($this->AliasNumPage, false, $this->tmprtl));
5286 $alias_pcu = $this->_escape($this->utf8StrRev('{'.$this->AliasNumPage.'}', false, $this->tmprtl));
5290 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
5291 for ($n=1; $n <= $nb; ++$n) {
5292 $temppage = $this->getPageBuffer($n);
5293 if (!empty($this->pagegroups)) {
5294 if(isset($this->newpagegroup[$n])) {
5298 foreach ($this->pagegroups as $k => $v) {
5299 // replace total pages group numbers
5300 $vs = $this->formatPageNumber($v);
5301 $vu = $this->UTF8ToUTF16BE($vs, false);
5302 $alias_ga = $this->_escape($k);
5303 $alias_gau = $this->_escape('{'.$k.'}');
5304 if ($this->isunicode) {
5305 $alias_gb = $this->_escape($this->UTF8ToLatin1($k));
5306 $alias_gbu = $this->_escape($this->UTF8ToLatin1('{'.$k.'}'));
5307 $alias_gc = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
5308 $alias_gcu = $this->_escape($this->utf8StrRev('{'.$k.'}', false, $this->tmprtl));
5310 $temppage = str_replace($alias_gau, $vu, $temppage);
5311 if ($this->isunicode) {
5312 $temppage = str_replace($alias_gbu, $vu, $temppage);
5313 $temppage = str_replace($alias_gcu, $vu, $temppage);
5314 $temppage = str_replace($alias_gb, $vs, $temppage);
5315 $temppage = str_replace($alias_gc, $vs, $temppage);
5317 $temppage = str_replace($alias_ga, $vs, $temppage);
5318 // replace page group numbers
5319 $pvs = $this->formatPageNumber($pagegroupnum);
5320 $pvu = $this->UTF8ToUTF16BE($pvs, false);
5321 $pk = str_replace('{nb', '{pnb', $k);
5322 $alias_pga = $this->_escape($pk);
5323 $alias_pgau = $this->_escape('{'.$pk.'}');
5324 if ($this->isunicode) {
5325 $alias_pgb = $this->_escape($this->UTF8ToLatin1($pk));
5326 $alias_pgbu = $this->_escape($this->UTF8ToLatin1('{'.$pk.'}'));
5327 $alias_pgc = $this->_escape($this->utf8StrRev($pk, false, $this->tmprtl));
5328 $alias_pgcu = $this->_escape($this->utf8StrRev('{'.$pk.'}', false, $this->tmprtl));
5330 $temppage = str_replace($alias_pgau, $pvu, $temppage);
5331 if ($this->isunicode) {
5332 $temppage = str_replace($alias_pgbu, $pvu, $temppage);
5333 $temppage = str_replace($alias_pgcu, $pvu, $temppage);
5334 $temppage = str_replace($alias_pgb, $pvs, $temppage);
5335 $temppage = str_replace($alias_pgc, $pvs, $temppage);
5337 $temppage = str_replace($alias_pga, $pvs, $temppage);
5340 if (!empty($this->AliasNbPages)) {
5341 // replace total pages number
5342 $temppage = str_replace($alias_au, $nbu, $temppage);
5343 if ($this->isunicode) {
5344 $temppage = str_replace($alias_bu, $nbu, $temppage);
5345 $temppage = str_replace($alias_cu, $nbu, $temppage);
5346 $temppage = str_replace($alias_b, $nbs, $temppage);
5347 $temppage = str_replace($alias_c, $nbs, $temppage);
5349 $temppage = str_replace($alias_a, $nbs, $temppage);
5351 if (!empty($this->AliasNumPage)) {
5352 // replace page number
5353 $pnbs = $this->formatPageNumber($n);
5354 $pnbu = $this->UTF8ToUTF16BE($pnbs, false); // replacement for unicode font
5355 $temppage = str_replace($alias_pau, $pnbu, $temppage);
5356 if ($this->isunicode) {
5357 $temppage = str_replace($alias_pbu, $pnbu, $temppage);
5358 $temppage = str_replace($alias_pcu, $pnbu, $temppage);
5359 $temppage = str_replace($alias_pb, $pnbs, $temppage);
5360 $temppage = str_replace($alias_pc, $pnbs, $temppage);
5362 $temppage = str_replace($alias_pa, $pnbs, $temppage);
5364 $temppage = str_replace($this->epsmarker, '', $temppage);
5365 //$this->setPageBuffer($n, $temppage);
5368 $this->_out('<</Type /Page');
5369 $this->_out('/Parent 1 0 R');
5370 $this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
5371 $this->_out('/Resources 2 0 R');
5372 $this->_putannots($n);
5373 $this->_out('/Contents '.($this->n + 1).' 0 R>>');
5374 $this->_out('endobj');
5376 $p = ($this->compress) ? gzcompress($temppage) : $temppage;
5378 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
5379 $this->_putstream($p);
5380 $this->_out('endobj');
5381 if ($this->diskcache) {
5382 // remove temporary files
5383 unlink($this->pages[$n]);
5387 $this->offsets[1] = $this->bufferlen;
5388 $this->_out('1 0 obj');
5389 $this->_out('<</Type /Pages');
5391 for ($i=0; $i < $nb; ++$i) {
5392 $kids .= (3 + (2 * $i)).' 0 R ';
5394 $this->_out($kids.']');
5395 $this->_out('/Count '.$nb);
5396 //$this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
5398 $this->_out('endobj');
5402 * Output Page Annotations.
5403 * !!! THIS FUNCTION IS NOT YET COMPLETED !!!
5404 * See section 8.4 of PDF reference.
5405 * @param int $n page number
5407 * @author Nicola Asuni
5408 * @since 4.0.018 (2008-08-06)
5410 protected function _putannots($n) {
5411 if (isset($this->PageAnnots[$n])) {
5412 $annots = '/Annots [';
5413 foreach ($this->PageAnnots[$n] as $key => $pl) {
5414 $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
5415 $a = $pl['x'] * $this->k;
5416 $b = $this->pagedim[$n]['h'] - ($pl['y'] * $this->k);
5417 $c = $pl['w'] * $this->k;
5418 $d = $pl['h'] * $this->k;
5419 $rect = sprintf('%.2F %.2F %.2F %.2F', $a, $b, $a+$c, $b-$d);
5421 $annots .= '<</Type /Annot';
5422 $annots .= ' /Subtype /'.$pl['opt']['subtype'];
5423 $annots .= ' /Rect ['.$rect.']';
5424 $annots .= ' /Contents '.$this->_textstring($pl['txt']);
5425 //$annots .= ' /P ';
5426 $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
5427 $annots .= ' /M '.$this->_datastring('D:'.date('YmdHis'));
5428 if (isset($pl['opt']['f'])) {
5430 if (is_array($pl['opt']['f'])) {
5431 foreach ($pl['opt']['f'] as $f) {
5432 switch (strtolower($f)) {
5465 case 'togglenoview': {
5469 case 'lockedcontents': {
5479 $annots .= ' /F '.intval($val);
5481 //$annots .= ' /AP ';
5482 //$annots .= ' /AS ';
5483 $annots .= ' /Border [';
5484 if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
5485 $annots .= intval($pl['opt']['border'][0]).' ';
5486 $annots .= intval($pl['opt']['border'][1]).' ';
5487 $annots .= intval($pl['opt']['border'][2]);
5488 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
5490 foreach ($pl['opt']['border'][3] as $dash) {
5491 $annots .= intval($dash).' ';
5499 if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
5500 $annots .= ' /BS <<Type /Border';
5501 if (isset($pl['opt']['bs']['w'])) {
5502 $annots .= ' /W '.sprintf("%.4F", floatval($pl['opt']['bs']['w']));
5504 $bstyles = array('S', 'D', 'B', 'I', 'U');
5505 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
5506 $annots .= ' /S /'.$pl['opt']['bs']['s'];
5508 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
5510 foreach ($pl['opt']['bs']['d'] as $cord) {
5511 $cord = floatval($cord);
5512 $annots .= sprintf(" %.4F", $cord);
5518 if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
5519 $annots .= ' /BE <<';
5520 $bstyles = array('S', 'C');
5521 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
5522 $annots .= ' /S /'.$pl['opt']['bs']['s'];
5524 $annots .= ' /S /S';
5526 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
5527 $annots .= ' /I '.sprintf(" %.4F", $pl['opt']['be']['i']);
5532 if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
5533 foreach ($pl['opt']['c'] as $col) {
5534 $col = intval($col);
5535 $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
5536 $annots .= sprintf(" %.4F", $color);
5540 //$annots .= ' /StructParent ';
5541 //$annots .= ' /OC ';
5542 $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
5543 if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
5544 // this is a markup type
5545 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
5546 $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
5548 //$annots .= ' /Popup ';
5549 if (isset($pl['opt']['ca'])) {
5550 $annots .= ' /CA '.sprintf("%.4F", floatval($pl['opt']['ca']));
5552 if (isset($pl['opt']['rc'])) {
5553 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
5555 $annots .= ' /CreationDate '.$this->_datastring('D:'.date('YmdHis'));
5556 //$annots .= ' /IRT ';
5557 if (isset($pl['opt']['subj'])) {
5558 $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
5560 //$annots .= ' /RT ';
5561 //$annots .= ' /IT ';
5562 //$annots .= ' /ExData ';
5564 switch (strtolower($pl['opt']['subtype'])) {
5566 if (isset($pl['opt']['open'])) {
5567 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
5569 $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
5570 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5571 $annots .= ' /Name /'.$pl['opt']['name'];
5573 $annots .= ' /Name /Note';
5575 $statemodels = array('Marked', 'Review');
5576 if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
5577 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
5579 $pl['opt']['statemodel'] = 'Marked';
5580 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
5582 if ($pl['opt']['statemodel'] == 'Marked') {
5583 $states = array('Accepted', 'Unmarked');
5585 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
5587 if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
5588 $annots .= ' /State /'.$pl['opt']['state'];
5590 if ($pl['opt']['statemodel'] == 'Marked') {
5591 $annots .= ' /State /Unmarked';
5593 $annots .= ' /State /None';
5599 if(is_string($pl['txt'])) {
5600 // external URI link
5601 $annots .= ' /A <</S /URI /URI '.$this->_datastring($pl['txt']).'>>';
5604 $l = $this->links[$pl['txt']];
5605 $annots .= sprintf(' /Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $l[0])), ($this->pagedim[$l[0]]['h'] - ($l[1] * $this->k)));
5607 $hmodes = array('N', 'I', 'O', 'P');
5608 if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
5609 $annots .= ' /H /'.$pl['opt']['h'];
5611 $annots .= ' /H /I';
5613 //$annots .= ' /PA ';
5614 //$annots .= ' /Quadpoints ';
5618 $annots .= ' /DA '.$this->_textstring($pl['txt']);
5619 if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
5620 $annots .= ' /Q '.intval($pl['opt']['q']);
5622 if (isset($pl['opt']['rc'])) {
5623 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
5625 if (isset($pl['opt']['ds'])) {
5626 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
5628 if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
5629 $annots .= ' /CL [';
5630 foreach ($pl['opt']['cl'] as $cl) {
5631 $annots .= sprintf("%.4F ", $cl * $this->k);
5635 $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
5636 if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
5637 $annots .= ' /IT '.$pl['opt']['it'];
5639 if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
5640 $l = $pl['opt']['rd'][0] * $this->k;
5641 $r = $pl['opt']['rd'][1] * $this->k;
5642 $t = $pl['opt']['rd'][2] * $this->k;
5643 $b = $pl['opt']['rd'][3] * $this->k;
5644 $annots .= ' /RD ['.sprintf('%.2F %.2F %.2F %.2F', $l, $r, $t, $b).']';
5646 //$annots .= ' /LE ';
5649 // ... to be completed ...
5689 case 'fileattachment': {
5690 if (!isset($pl['opt']['fs'])) {
5693 $filename = basename($pl['opt']['fs']);
5694 if (isset($this->embeddedfiles[$filename]['n'])) {
5695 $annots .= ' /FS <</Type /Filespec /F '.$this->_datastring($filename).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
5696 $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
5697 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5698 $annots .= ' /Name /'.$pl['opt']['name'];
5700 $annots .= ' /Name /PushPin';
5706 if (!isset($pl['opt']['sound'])) {
5709 $filename = basename($pl['opt']['sound']);
5710 if (isset($this->embeddedfiles[$filename]['n'])) {
5711 // ... TO BE COMPLETED ...
5712 $iconsapp = array('Speaker', 'Mic');
5713 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5714 $annots .= ' /Name /'.$pl['opt']['name'];
5716 $annots .= ' /Name /Speaker';
5725 if (isset($pl['opt']['h'])) {
5726 $annots .= ' /H '.intval($pl['opt']['h']);
5728 if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk']))) {
5729 $annots .= ' /MK <<';
5730 // ... TO BE COMPLETED ...
5738 case 'printermark': {
5758 $this->_out($annots);
5766 protected function _putfonts() {
5768 foreach ($this->diffs as $diff) {
5771 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
5772 $this->_out('endobj');
5774 $mqr = get_magic_quotes_runtime();
5775 //set_magic_quotes_runtime(0);
5776 foreach ($this->FontFiles as $file => $info) {
5777 // search and get font file to embedd
5778 $fontdir = $info['fontdir'];
5779 $file = strtolower($file);
5781 // search files on various directories
5782 if (file_exists($fontdir.$file)) {
5783 $fontfile = $fontdir.$file;
5784 } elseif (file_exists($this->_getfontpath().$file)) {
5785 $fontfile = $this->_getfontpath().$file;
5786 } elseif (file_exists($file)) {
5789 if (!$this->empty_string($fontfile)) {
5790 $font = file_get_contents($fontfile);
5791 $compressed = (substr($file, -2) == '.z');
5792 if ((!$compressed) AND (isset($info['length2']))) {
5793 $header = (ord($font{0}) == 128);
5795 //Strip first binary header
5796 $font = substr($font, 6);
5798 if ($header AND (ord($font{$info['length1']}) == 128)) {
5799 //Strip second binary header
5800 $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
5804 $this->FontFiles[$file]['n'] = $this->n;
5805 $this->_out('<</Length '.strlen($font));
5807 $this->_out('/Filter /FlateDecode');
5809 $this->_out('/Length1 '.$info['length1']);
5810 if (isset($info['length2'])) {
5811 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
5814 $this->_putstream($font);
5815 $this->_out('endobj');
5818 //set_magic_quotes_runtime($mqr);
5819 foreach ($this->fontkeys as $k) {
5821 $this->setFontSubBuffer($k, 'n', $this->n + 1);
5822 $font = $this->getFontBuffer($k);
5823 $type = $font['type'];
5824 $name = $font['name'];
5825 if ($type == 'core') {
5828 $this->_out('<</Type /Font');
5829 $this->_out('/BaseFont /'.$name);
5830 $this->_out('/Subtype /Type1');
5831 if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
5832 $this->_out('/Encoding /WinAnsiEncoding');
5835 $this->_out('endobj');
5836 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
5837 //Additional Type1 or TrueType font
5839 $this->_out('<</Type /Font');
5840 $this->_out('/BaseFont /'.$name);
5841 $this->_out('/Subtype /'.$type);
5842 $this->_out('/FirstChar 32 /LastChar 255');
5843 $this->_out('/Widths '.($this->n + 1).' 0 R');
5844 $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
5846 if (isset($font['diff'])) {
5847 $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
5849 $this->_out('/Encoding /WinAnsiEncoding');
5853 $this->_out('endobj');
5858 for ($i = 32; $i < 256; ++$i) {
5861 $this->_out($s.']');
5862 $this->_out('endobj');
5865 $s = '<</Type /FontDescriptor /FontName /'.$name;
5866 foreach ($font['desc'] as $k => $v) {
5867 $s .= ' /'.$k.' '.$v.'';
5869 if (!$this->empty_string($font['file'])) {
5870 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
5872 $this->_out($s.'>>');
5873 $this->_out('endobj');
5875 //Allow for additional types
5876 $mtd = '_put'.strtolower($type);
5877 if (!method_exists($this, $mtd)) {
5878 $this->Error('Unsupported font type: '.$type);
5886 * Outputs font widths
5887 * @parameter array $font font data
5888 * @parameter int $cidoffset offset for CID values
5889 * @author Nicola Asuni
5891 * @since 4.4.000 (2008-12-07)
5893 protected function _putfontwidths($font, $cidoffset=0) {
5900 // for each character
5901 foreach ($font['cw'] as $cid => $width) {
5903 if ($width != $font['dw']) {
5904 if ($cid == ($prevcid + 1)) {
5906 if ($width == $prevwidth) {
5907 if ($width == $range[$rangeid][0]) {
5908 $range[$rangeid][] = $width;
5910 array_pop($range[$rangeid]);
5912 $rangeid = $prevcid;
5913 $range[$rangeid] = array();
5914 $range[$rangeid][] = $prevwidth;
5915 $range[$rangeid][] = $width;
5918 $range[$rangeid]['interval'] = true;
5923 $range[$rangeid] = array();
5924 $range[$rangeid][] = $width;
5926 $range[$rangeid][] = $width;
5933 $range[$rangeid] = array();
5934 $range[$rangeid][] = $width;
5938 $prevwidth = $width;
5945 foreach ($range as $k => $ws) {
5947 if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) {
5948 if (isset($range[$k]['interval'])) {
5949 unset($range[$k]['interval']);
5951 $range[$prevk] = array_merge($range[$prevk], $range[$k]);
5957 if (isset($ws['interval'])) {
5963 unset($range[$k]['interval']);
5971 foreach ($range as $k => $ws) {
5972 if (count(array_count_values($ws)) == 1) {
5973 // interval mode is more compact
5974 $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0];
5977 $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
5980 $this->_out('/W ['.$w.' ]');
5984 * Adds unicode fonts.<br>
5985 * Based on PDF Reference 1.3 (section 5)
5986 * @parameter array $font font data
5988 * @author Nicola Asuni
5989 * @since 1.52.0.TC005 (2005-01-05)
5991 protected function _puttruetypeunicode($font) {
5993 // A composite font composed of other fonts, organized hierarchically
5995 $this->_out('<</Type /Font');
5996 $this->_out('/Subtype /Type0');
5997 $this->_out('/BaseFont /'.$font['name'].'');
5998 $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.
5999 $this->_out('/ToUnicode /Identity-H');
6000 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
6002 $this->_out('endobj');
6004 // A CIDFont whose glyph descriptions are based on TrueType font technology
6006 $this->_out('<</Type /Font');
6007 $this->_out('/Subtype /CIDFontType2');
6008 $this->_out('/BaseFont /'.$font['name'].'');
6009 // A dictionary containing entries that define the character collection of the CIDFont.
6010 $cidinfo = '/Registry '.$this->_datastring('Adobe');
6011 $cidinfo .= ' /Ordering '.$this->_datastring('Identity');
6012 $cidinfo .= ' /Supplement 0';
6013 $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
6014 $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
6015 $this->_out('/DW '.$font['dw'].''); // default width
6016 $this->_putfontwidths($font, 0);
6017 $this->_out('/CIDToGIDMap '.($this->n + 2).' 0 R');
6019 $this->_out('endobj');
6021 // A font descriptor describing the CIDFont default metrics other than its glyph widths
6023 $this->_out('<</Type /FontDescriptor');
6024 $this->_out('/FontName /'.$font['name']);
6025 foreach ($font['desc'] as $key => $value) {
6026 $this->_out('/'.$key.' '.$value);
6029 if (!$this->empty_string($font['file'])) {
6030 // A stream containing a TrueType font
6031 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
6032 $fontdir = $this->FontFiles[$font['file']]['fontdir'];
6035 $this->_out('endobj');
6037 if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
6038 // Embed CIDToGIDMap
6039 // A specification of the mapping from CIDs to glyph indices
6040 // search and get CTG font file to embedd
6041 $ctgfile = strtolower($font['ctg']);
6042 // search and get ctg font file to embedd
6044 // search files on various directories
6045 if (file_exists($fontdir.$ctgfile)) {
6046 $fontfile = $fontdir.$ctgfile;
6047 } elseif (file_exists($this->_getfontpath().$ctgfile)) {
6048 $fontfile = $this->_getfontpath().$ctgfile;
6049 } elseif (file_exists($ctgfile)) {
6050 $fontfile = $ctgfile;
6052 if ($this->empty_string($fontfile)) {
6053 $this->Error('Font file not found: '.$ctgfile);
6055 $size = filesize($fontfile);
6056 $this->_out('<</Length '.$size.'');
6057 if (substr($fontfile, -2) == '.z') { // check file extension
6058 // Decompresses data encoded using the public-domain
6059 // zlib/deflate compression method, reproducing the
6060 // original text or binary data
6061 $this->_out('/Filter /FlateDecode');
6064 $this->_putstream(file_get_contents($fontfile));
6066 $this->_out('endobj');
6070 * Output CID-0 fonts.
6071 * @param array $font font data
6073 * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
6074 * @since 3.2.000 (2008-06-23)
6076 protected function _putcidfont0($font) {
6078 if (isset($font['cidinfo']['uni2cid'])) {
6079 // convert unicode to cid.
6080 $uni2cid = $font['cidinfo']['uni2cid'];
6082 foreach ($font['cw'] as $uni => $width) {
6083 if (isset($uni2cid[$uni])) {
6084 $cw[($uni2cid[$uni] + $cidoffset)] = $width;
6085 } elseif ($uni < 256) {
6087 } // else unknown character
6089 $font = array_merge($font, array('cw' => $cw));
6091 $name = $font['name'];
6092 $enc = $font['enc'];
6094 $longname = $name.'-'.$enc;
6099 $this->_out('<</Type /Font');
6100 $this->_out('/BaseFont /'.$longname);
6101 $this->_out('/Subtype /Type0');
6103 $this->_out('/Encoding /'.$enc);
6105 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
6107 $this->_out('endobj');
6109 $this->_out('<</Type /Font');
6110 $this->_out('/BaseFont /'.$name);
6111 $this->_out('/Subtype /CIDFontType0');
6112 $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry']);
6113 $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering']);
6114 $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
6115 $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
6116 $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
6117 $this->_out('/DW '.$font['dw']);
6118 $this->_putfontwidths($font, $cidoffset);
6120 $this->_out('endobj');
6122 $s = '<</Type /FontDescriptor /FontName /'.$name;
6123 foreach ($font['desc'] as $k => $v) {
6124 if ($k != 'Style') {
6125 $s .= ' /'.$k.' '.$v.'';
6128 $this->_out($s.'>>');
6129 $this->_out('endobj');
6136 protected function _putimages() {
6137 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
6138 foreach ($this->imagekeys as $file) {
6139 $info = $this->getImageBuffer($file);
6141 $this->setImageSubBuffer($file, 'n', $this->n);
6142 $this->_out('<</Type /XObject');
6143 $this->_out('/Subtype /Image');
6144 $this->_out('/Width '.$info['w']);
6145 $this->_out('/Height '.$info['h']);
6146 if (isset($info['masked'])) {
6147 $this->_out('/SMask '.($this->n - 1).' 0 R');
6149 if ($info['cs'] == 'Indexed') {
6150 $this->_out('/ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]');
6152 $this->_out('/ColorSpace /'.$info['cs']);
6153 if ($info['cs'] == 'DeviceCMYK') {
6154 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
6157 $this->_out('/BitsPerComponent '.$info['bpc']);
6158 if (isset($info['f'])) {
6159 $this->_out('/Filter /'.$info['f']);
6161 if (isset($info['parms'])) {
6162 $this->_out($info['parms']);
6164 if (isset($info['trns']) AND is_array($info['trns'])) {
6166 $count_info = count($info['trns']);
6167 for ($i=0; $i < $count_info; ++$i) {
6168 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
6170 $this->_out('/Mask ['.$trns.']');
6172 $this->_out('/Length '.strlen($info['data']).'>>');
6173 $this->_putstream($info['data']);
6174 $this->_out('endobj');
6176 if ($info['cs'] == 'Indexed') {
6178 $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
6179 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
6180 $this->_putstream($pal);
6181 $this->_out('endobj');
6187 * Output Spot Colors Resources.
6189 * @since 4.0.024 (2008-09-12)
6191 protected function _putspotcolors() {
6192 foreach ($this->spot_colors as $name => $color) {
6194 $this->spot_colors[$name]['n'] = $this->n;
6195 $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
6196 $this->_out('/DeviceCMYK <<');
6197 $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
6198 $this->_out(sprintf('/C1 [%.4F %.4F %.4F %.4F] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
6199 $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
6200 $this->_out('endobj');
6205 * Output object dictionary for images.
6208 protected function _putxobjectdict() {
6209 foreach ($this->imagekeys as $file) {
6210 $info = $this->getImageBuffer($file);
6211 $this->_out('/I'.$info['i'].' '.$info['n'].' 0 R');
6216 * Output Resources Dictionary.
6219 protected function _putresourcedict() {
6220 $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
6221 $this->_out('/Font <<');
6222 foreach ($this->fontkeys as $fontkey) {
6223 $font = $this->getFontBuffer($fontkey);
6224 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
6227 $this->_out('/XObject <<');
6228 $this->_putxobjectdict();
6231 $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
6233 $this->_out('/ExtGState <<');
6234 foreach ($this->extgstates as $k => $extgstate) {
6235 $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
6239 if (isset($this->gradients) AND (count($this->gradients) > 0)) {
6240 $this->_out('/Shading <<');
6241 foreach ($this->gradients as $id => $grad) {
6242 $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
6247 if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
6248 $this->_out('/ColorSpace <<');
6249 foreach ($this->spot_colors as $color) {
6250 $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
6260 protected function _putresources() {
6261 $this->_putextgstates();
6264 $this->_putimages();
6265 $this->_putspotcolors();
6266 $this->_putshaders();
6267 //Resource dictionary
6268 $this->offsets[2] = $this->bufferlen;
6269 $this->_out('2 0 obj');
6271 $this->_putresourcedict();
6273 $this->_out('endobj');
6274 $this->_putjavascript();
6275 $this->_putbookmarks();
6276 $this->_putEmbeddedFiles();
6278 if ($this->encrypted) {
6280 $this->enc_obj_id = $this->n;
6282 $this->_putencryption();
6284 $this->_out('endobj');
6289 * Adds some Metadata information
6290 * (see Chapter 10.2 of PDF Reference)
6293 protected function _putinfo() {
6294 if (!$this->empty_string($this->title)) {
6295 $this->_out('/Title '.$this->_textstring($this->title));
6297 if (!$this->empty_string($this->author)) {
6298 $this->_out('/Author '.$this->_textstring($this->author));
6300 if (!$this->empty_string($this->subject)) {
6301 $this->_out('/Subject '.$this->_textstring($this->subject));
6303 if (!$this->empty_string($this->keywords)) {
6304 $this->_out('/Keywords '.$this->_textstring($this->keywords));
6306 if (!$this->empty_string($this->creator)) {
6307 $this->_out('/Creator '.$this->_textstring($this->creator));
6309 if (defined('PDF_PRODUCER')) {
6310 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
6312 $this->_out('/CreationDate '.$this->_datastring('D:'.date('YmdHis')));
6313 $this->_out('/ModDate '.$this->_datastring('D:'.date('YmdHis')));
6320 protected function _putcatalog() {
6321 $this->_out('/Type /Catalog');
6322 $this->_out('/Pages 1 0 R');
6323 if ($this->ZoomMode == 'fullpage') {
6324 $this->_out('/OpenAction [3 0 R /Fit]');
6325 } elseif ($this->ZoomMode == 'fullwidth') {
6326 $this->_out('/OpenAction [3 0 R /FitH null]');
6327 } elseif ($this->ZoomMode == 'real') {
6328 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
6329 } elseif (!is_string($this->ZoomMode)) {
6330 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
6332 if (isset($this->LayoutMode) AND (!$this->empty_string($this->LayoutMode))) {
6333 $this->_out('/PageLayout /'.$this->LayoutMode.'');
6335 if (isset($this->PageMode) AND (!$this->empty_string($this->PageMode))) {
6336 $this->_out('/PageMode /'.$this->PageMode);
6338 if (isset($this->l['a_meta_language'])) {
6339 $this->_out('/Lang /'.$this->l['a_meta_language']);
6341 $this->_out('/Names <<');
6342 if (!$this->empty_string($this->javascript)) {
6343 $this->_out('/JavaScript '.($this->n_js).' 0 R');
6346 if (count($this->outlines) > 0) {
6347 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
6348 $this->_out('/PageMode /UseOutlines');
6350 $this->_putviewerpreferences();
6351 $p = $this->n_ocg_print.' 0 R';
6352 $v = $this->n_ocg_view.' 0 R';
6353 $as = '<</Event /Print /OCGs ['.$p.' '.$v.'] /Category [/Print]>> <</Event /View /OCGs ['.$p.' '.$v.'] /Category [/View]>>';
6354 $this->_out('/OCProperties <</OCGs ['.$p.' '.$v.'] /D <</ON ['.$p.'] /OFF ['.$v.'] /AS ['.$as.']>>>>');
6358 * Output viewer preferences.
6359 * @author Nicola asuni
6360 * @since 3.1.000 (2008-06-09)
6363 protected function _putviewerpreferences() {
6364 $this->_out('/ViewerPreferences<<');
6366 $this->_out('/Direction /R2L');
6368 $this->_out('/Direction /L2R');
6370 if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
6371 $this->_out('/HideToolbar true');
6373 if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
6374 $this->_out('/HideMenubar true');
6376 if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
6377 $this->_out('/HideWindowUI true');
6379 if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
6380 $this->_out('/FitWindow true');
6382 if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
6383 $this->_out('/CenterWindow true');
6385 if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
6386 $this->_out('/DisplayDocTitle true');
6388 if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
6389 $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
6391 if (isset($this->viewer_preferences['ViewArea'])) {
6392 $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
6394 if (isset($this->viewer_preferences['ViewClip'])) {
6395 $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
6397 if (isset($this->viewer_preferences['PrintArea'])) {
6398 $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
6400 if (isset($this->viewer_preferences['PrintClip'])) {
6401 $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
6403 if (isset($this->viewer_preferences['PrintScaling'])) {
6404 $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
6406 if (isset($this->viewer_preferences['Duplex']) AND (!$this->empty_string($this->viewer_preferences['Duplex']))) {
6407 $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
6409 if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
6410 if ($this->viewer_preferences['PickTrayByPDFSize']) {
6411 $this->_out('/PickTrayByPDFSize true');
6413 $this->_out('/PickTrayByPDFSize false');
6416 if (isset($this->viewer_preferences['PrintPageRange'])) {
6417 $PrintPageRangeNum = '';
6418 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
6419 $PrintPageRangeNum .= ' '.($v - 1).'';
6421 $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
6423 if (isset($this->viewer_preferences['NumCopies'])) {
6424 $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
6433 protected function _puttrailer() {
6434 $this->_out('/Size '.($this->n + 1));
6435 $this->_out('/Root '.$this->n.' 0 R');
6436 $this->_out('/Info '.($this->n - 1).' 0 R');
6437 if ($this->encrypted) {
6438 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
6439 $this->_out('/ID [()()]');
6444 * Output PDF header.
6447 protected function _putheader() {
6448 $this->_out('%PDF-'.$this->PDFVersion);
6452 * Output end of document (EOF).
6455 protected function _enddoc() {
6457 $this->_putheader();
6459 $this->_putresources();
6465 $this->_out('endobj');
6469 $this->_putcatalog();
6470 $this->_putcertification();
6471 $this->_putuserrights();
6473 $this->_out('endobj');
6475 $o = $this->bufferlen;
6476 $this->_out('xref');
6477 $this->_out('0 '.($this->n + 1));
6478 $this->_out('0000000000 65535 f ');
6479 for ($i=1; $i <= $this->n; ++$i) {
6480 $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
6482 if (isset($this->embeddedfiles) AND count($this->embeddedfiles) > 0) {
6483 $this->_out('100000 '.count($this->embeddedfiles));
6484 foreach ($this->embeddedfiles as $filename => $filedata) {
6485 $this->_out(sprintf('%010d 00000 n ', $this->offsets[$filedata['n']]));
6489 $this->_out('trailer');
6491 $this->_puttrailer();
6493 $this->_out('startxref');
6495 $this->_out('%%EOF');
6496 $this->state = 3; // end-of-doc
6497 if ($this->diskcache) {
6498 // remove temporary files used for images
6499 foreach ($this->imagekeys as $key) {
6500 // remove temporary files
6501 unlink($this->images[$key]);
6503 foreach ($this->fontkeys as $key) {
6504 // remove temporary files
6505 unlink($this->fonts[$key]);
6511 * Initialize a new page.
6512 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
6513 * @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>
6516 protected function _beginpage($orientation='', $format='') {
6518 $this->setPageBuffer($this->page, '');
6519 // initialize array for graphics tranformation positions inside a page buffer
6520 $this->transfmrk[$this->page] = array();
6522 if ($this->empty_string($orientation)) {
6523 if (isset($this->CurOrientation)) {
6524 $orientation = $this->CurOrientation;
6529 if ($this->empty_string($format)) {
6530 $this->setPageOrientation($orientation);
6532 $this->setPageFormat($format, $orientation);
6535 $this->x = $this->w - $this->rMargin;
6537 $this->x = $this->lMargin;
6539 $this->y = $this->tMargin;
6540 if (isset($this->newpagegroup[$this->page])) {
6541 // start a new group
6542 $n = sizeof($this->pagegroups) + 1;
6543 $alias = '{nb'.$n.'}';
6544 $this->pagegroups[$alias] = 1;
6545 $this->currpagegroup = $alias;
6546 } elseif ($this->currpagegroup) {
6547 ++$this->pagegroups[$this->currpagegroup];
6555 protected function _endpage() {
6556 $this->setVisibility('all');
6561 * Begin a new object.
6564 protected function _newobj() {
6566 $this->offsets[$this->n] = $this->bufferlen;
6567 $this->_out($this->n.' 0 obj');
6572 * @param int $x X coordinate
6573 * @param int $y Y coordinate
6574 * @param string $txt text to underline
6577 protected function _dounderline($x, $y, $txt) {
6578 $up = $this->CurrentFont['up'];
6579 $ut = $this->CurrentFont['ut'];
6580 $w = $this->GetStringWidth($txt);
6581 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);
6585 * Line through text.
6586 * @param int $x X coordinate
6587 * @param int $y Y coordinate
6588 * @param string $txt text to linethrough
6591 protected function _dolinethrough($x, $y, $txt) {
6592 $up = $this->CurrentFont['up'];
6593 $ut = $this->CurrentFont['ut'];
6594 $w = $this->GetStringWidth($txt);
6595 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);
6599 * Read a 4-byte integer from file.
6600 * @param string $f file name.
6601 * @return 4-byte integer
6604 protected function _freadint($f) {
6605 $a = unpack('Ni', fread($f, 4));
6610 * Add "\" before "\", "(" and ")"
6611 * @param string $s string to escape.
6612 * @return string escaped string.
6615 protected function _escape($s) {
6616 // the chr(13) substitution fixes the Bugs item #1421290.
6617 return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
6621 * Format a date string for meta information
6622 * @param string $s date string to escape.
6623 * @return string escaped string.
6626 protected function _datastring($s) {
6627 if ($this->encrypted) {
6628 $s = $this->_RC4($this->_objectkey($this->n), $s);
6630 return '('. $this->_escape($s).')';
6634 * Format a text string for meta information
6635 * @param string $s string to escape.
6636 * @return string escaped string.
6639 protected function _textstring($s) {
6640 if ($this->isunicode) {
6641 //Convert string to UTF-16BE
6642 $s = $this->UTF8ToUTF16BE($s, true);
6644 return $this->_datastring($s);
6648 * Format a text string
6649 * @param string $s string to escape.
6650 * @return string escaped string.
6653 protected function _escapetext($s) {
6654 if ($this->isunicode) {
6655 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
6656 $s = $this->UTF8ToLatin1($s);
6658 //Convert string to UTF-16BE and reverse RTL language
6659 $s = $this->utf8StrRev($s, false, $this->tmprtl);
6662 return $this->_escape($s);
6667 * @param string $s string to output.
6670 protected function _putstream($s) {
6671 if ($this->encrypted) {
6672 $s = $this->_RC4($this->_objectkey($this->n), $s);
6674 $this->_out('stream');
6676 $this->_out('endstream');
6680 * Output a string to the document.
6681 * @param string $s string to output.
6684 protected function _out($s) {
6685 if ($this->state == 2) {
6686 if ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
6687 // puts data before page footer
6688 $pagebuff = $this->getPageBuffer($this->page);
6689 $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
6690 $footer = substr($pagebuff, -$this->footerlen[$this->page]);
6691 $this->setPageBuffer($this->page, $page.$s."\n".$footer);
6692 // update footer position
6693 $this->footerpos[$this->page] += strlen($s."\n");
6695 $this->setPageBuffer($this->page, $s."\n", true);
6698 $this->setBuffer($s."\n");
6703 * Converts UTF-8 strings to codepoints array.<br>
6704 * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
6705 * Based on: http://www.faqs.org/rfcs/rfc3629.html
6707 * Char. number range | UTF-8 octet sequence
6708 * (hexadecimal) | (binary)
6709 * --------------------+-----------------------------------------------
6710 * 0000 0000-0000 007F | 0xxxxxxx
6711 * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
6712 * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
6713 * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
6714 * ---------------------------------------------------------------------
6717 * ---------------------------------------------------------------------
6718 * UTF8-octets = *( UTF8-char )
6719 * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
6721 * UTF8-2 = %xC2-DF UTF8-tail
6723 * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
6724 * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
6725 * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
6726 * %xF4 %x80-8F 2( UTF8-tail )
6727 * UTF8-tail = %x80-BF
6728 * ---------------------------------------------------------------------
6730 * @param string $str string to process.
6731 * @return array containing codepoints (UTF-8 characters values)
6733 * @author Nicola Asuni
6734 * @since 1.53.0.TC005 (2005-01-05)
6736 protected function UTF8StringToArray($str) {
6737 if (isset($this->cache_UTF8StringToArray['_'.$str])) {
6738 // return cached value
6739 return($this->cache_UTF8StringToArray['_'.$str]);
6742 if ($this->cache_size_UTF8StringToArray >= $this->cache_maxsize_UTF8StringToArray) {
6743 // remove first element
6744 array_shift($this->cache_UTF8StringToArray);
6746 ++$this->cache_size_UTF8StringToArray;
6747 if (!$this->isunicode) {
6748 // split string into array of equivalent codes
6750 $strlen = strlen($str);
6751 for ($i=0; $i < $strlen; ++$i) {
6752 $strarr[] = ord($str{$i});
6754 // insert new value on cache
6755 $this->cache_UTF8StringToArray['_'.$str] = $strarr;
6758 $unicode = array(); // array containing unicode values
6759 $bytes = array(); // array containing single character byte sequences
6760 $numbytes = 1; // number of octetc needed to represent the UTF-8 character
6761 $str .= ''; // force $str to be a string
6762 $length = strlen($str);
6763 for ($i = 0; $i < $length; ++$i) {
6764 $char = ord($str{$i}); // get one string character at time
6765 if (count($bytes) == 0) { // get starting octect
6766 if ($char <= 0x7F) {
6767 $unicode[] = $char; // use the character "as is" because is ASCII
6769 } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
6770 $bytes[] = ($char - 0xC0) << 0x06;
6772 } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
6773 $bytes[] = ($char - 0xE0) << 0x0C;
6775 } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
6776 $bytes[] = ($char - 0xF0) << 0x12;
6779 // use replacement character for other invalid sequences
6780 $unicode[] = 0xFFFD;
6784 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
6785 $bytes[] = $char - 0x80;
6786 if (count($bytes) == $numbytes) {
6787 // compose UTF-8 bytes to a single unicode value
6789 for ($j = 1; $j < $numbytes; ++$j) {
6790 $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
6792 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
6793 /* The definition of UTF-8 prohibits encoding character numbers between
6794 U+D800 and U+DFFF, which are reserved for use with the UTF-16
6795 encoding form (as surrogate pairs) and do not directly represent
6797 $unicode[] = 0xFFFD; // use replacement character
6799 $unicode[] = $char; // add char to array
6801 // reset data for next char
6806 // use replacement character for other invalid sequences
6807 $unicode[] = 0xFFFD;
6812 // insert new value on cache
6813 $this->cache_UTF8StringToArray['_'.$str] = $unicode;
6818 * Converts UTF-8 strings to UTF16-BE.<br>
6819 * @param string $str string to process.
6820 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
6823 * @author Nicola Asuni
6824 * @since 1.53.0.TC005 (2005-01-05)
6825 * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
6827 protected function UTF8ToUTF16BE($str, $setbom=true) {
6828 if (!$this->isunicode) {
6829 return $str; // string is not in unicode
6831 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
6832 return $this->arrUTF8ToUTF16BE($unicode, $setbom);
6836 * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
6837 * @param string $str string to process.
6839 * @author Andrew Whitehead, Nicola Asuni
6841 * @since 3.2.000 (2008-06-23)
6843 protected function UTF8ToLatin1($str) {
6844 global $utf8tolatin;
6845 if (!$this->isunicode) {
6846 return $str; // string is not in unicode
6848 $outstr = ''; // string to be returned
6849 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
6850 foreach ($unicode as $char) {
6852 $outstr .= chr($char);
6853 } elseif (array_key_exists($char, $utf8tolatin)) {
6855 $outstr .= chr($utf8tolatin[$char]);
6856 } elseif ($char == 0xFFFD) {
6866 * Converts array of UTF-8 characters to UTF16-BE string.<br>
6867 * Based on: http://www.faqs.org/rfcs/rfc2781.html
6871 * Encoding of a single character from an ISO 10646 character value to
6872 * UTF-16 proceeds as follows. Let U be the character number, no greater
6875 * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
6878 * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
6879 * U' must be less than or equal to 0xFFFFF. That is, U' can be
6880 * represented in 20 bits.
6882 * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
6883 * 0xDC00, respectively. These integers each have 10 bits free to
6884 * encode the character value, for a total of 20 bits.
6886 * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
6887 * bits of W1 and the 10 low-order bits of U' to the 10 low-order
6888 * bits of W2. Terminate.
6890 * Graphically, steps 2 through 4 look like:
6891 * U' = yyyyyyyyyyxxxxxxxxxx
6892 * W1 = 110110yyyyyyyyyy
6893 * W2 = 110111xxxxxxxxxx
6895 * @param array $unicode array containing UTF-8 unicode values
6896 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
6899 * @author Nicola Asuni
6900 * @since 2.1.000 (2008-01-08)
6901 * @see UTF8ToUTF16BE()
6903 protected function arrUTF8ToUTF16BE($unicode, $setbom=true) {
6904 $outstr = ''; // string to be returned
6906 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
6908 foreach ($unicode as $char) {
6909 if ($char == 0xFFFD) {
6910 $outstr .= "\xFF\xFD"; // replacement character
6911 } elseif ($char < 0x10000) {
6912 $outstr .= chr($char >> 0x08);
6913 $outstr .= chr($char & 0xFF);
6916 $w1 = 0xD800 | ($char >> 0x10);
6917 $w2 = 0xDC00 | ($char & 0x3FF);
6918 $outstr .= chr($w1 >> 0x08);
6919 $outstr .= chr($w1 & 0xFF);
6920 $outstr .= chr($w2 >> 0x08);
6921 $outstr .= chr($w2 & 0xFF);
6926 // ====================================================
6930 * @param array $font font
6934 public function setHeaderFont($font) {
6935 $this->header_font = $font;
6942 * @since 4.0.012 (2008-07-24)
6944 public function getHeaderFont() {
6945 return $this->header_font;
6950 * @param array $font font
6954 public function setFooterFont($font) {
6955 $this->footer_font = $font;
6962 * @since 4.0.012 (2008-07-24)
6964 public function getFooterFont() {
6965 return $this->footer_font;
6969 * Set language array.
6970 * @param array $language
6974 public function setLanguageArray($language) {
6975 $this->l = $language;
6976 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
6980 * Returns the PDF data.
6983 public function getPDFData() {
6984 if ($this->state < 3) {
6987 return $this->buffer;
6991 * Output anchor link.
6992 * @param string $url link URL or internal link (i.e.: <a href="#23">link to page 23</a>)
6993 * @param string $name link name
6994 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
6995 * @param boolean $firstline if true prints only the first line and return the remaining string.
6996 * @param array $color array of RGB text color
6997 * @param string $style font style (U, D, B, I)
6998 * @return the number of cells used or the remaining text if $firstline = true;
7001 public function addHtmlLink($url, $name, $fill=0, $firstline=false, $color='', $style=-1) {
7002 if (!$this->empty_string($url) AND ($url{0} == '#')) {
7003 // convert url to internal link
7004 $page = intval(substr($url, 1));
7005 $url = $this->AddLink();
7006 $this->SetLink($url, 0, $page);
7008 // store current settings
7009 $prevcolor = $this->fgcolor;
7010 $prevstyle = $this->FontStyle;
7011 if (empty($color)) {
7012 $this->SetTextColorArray($this->htmlLinkColorArray);
7014 $this->SetTextColorArray($color);
7017 $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
7019 $this->SetFont('', $this->FontStyle.$style);
7021 $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
7023 $this->SetFont('', $prevstyle);
7024 $this->SetTextColorArray($prevcolor);
7029 * 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).
7030 * @param string $color html color
7031 * @return array RGB color or false in case of error.
7034 public function convertHTMLColorToDec($color='#FFFFFF') {
7036 $returncolor = false;
7037 $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
7038 $color = strtolower($color);
7039 if (strlen($color) == 0) {
7042 if (substr($color, 0, 3) == 'rgb') {
7043 $codes = substr($color, 4);
7044 $codes = str_replace(')', '', $codes);
7045 $returncolor = explode(',', $codes, 3);
7046 return $returncolor;
7048 if (substr($color, 0, 1) != '#') {
7049 // decode color name
7050 if (isset($webcolor[$color])) {
7051 $color_code = $webcolor[$color];
7056 $color_code = substr($color, 1);
7058 switch (strlen($color_code)) {
7060 // three-digit hexadecimal representation
7061 $r = substr($color_code, 0, 1);
7062 $g = substr($color_code, 1, 1);
7063 $b = substr($color_code, 2, 1);
7064 $returncolor['R'] = hexdec($r.$r);
7065 $returncolor['G'] = hexdec($g.$g);
7066 $returncolor['B'] = hexdec($b.$b);
7070 // six-digit hexadecimal representation
7071 $returncolor['R'] = hexdec(substr($color_code, 0, 2));
7072 $returncolor['G'] = hexdec(substr($color_code, 2, 2));
7073 $returncolor['B'] = hexdec(substr($color_code, 4, 2));
7077 return $returncolor;
7081 * Converts pixels to User's Units.
7082 * @param int $px pixels
7083 * @return float value in user's unit
7085 * @see setImageScale(), getImageScale()
7087 public function pixelsToUnits($px) {
7088 return ($px / ($this->imgscale * $this->k));
7092 * Reverse function for htmlentities.
7093 * Convert entities in UTF-8.
7094 * @param $text_to_convert Text to convert.
7095 * @return string converted
7098 public function unhtmlentities($text_to_convert) {
7099 return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
7102 // ENCRYPTION METHODS ----------------------------------
7103 // SINCE 2.0.000 (2008-01-02)
7106 * Compute encryption key depending on object number where the encrypted data is stored
7107 * @param int $n object number
7109 * @since 2.0.000 (2008-01-02)
7111 protected function _objectkey($n) {
7112 return substr($this->_md5_16($this->encryption_key.pack('VXxx', $n)), 0, 10);
7116 * Put encryption on PDF document.
7118 * @since 2.0.000 (2008-01-02)
7120 protected function _putencryption() {
7121 $this->_out('/Filter /Standard');
7122 $this->_out('/V 1');
7123 $this->_out('/R 2');
7124 $this->_out('/O ('.$this->_escape($this->Ovalue).')');
7125 $this->_out('/U ('.$this->_escape($this->Uvalue).')');
7126 $this->_out('/P '.$this->Pvalue);
7130 * Returns the input text exrypted using RC4 algorithm and the specified key.
7131 * RC4 is the standard encryption algorithm used in PDF format
7132 * @param string $key encryption key
7133 * @param String $text input text to be encrypted
7134 * @return String encrypted text
7136 * @since 2.0.000 (2008-01-02)
7137 * @author Klemen Vodopivec
7139 protected function _RC4($key, $text) {
7140 if ($this->last_rc4_key != $key) {
7141 $k = str_repeat($key, ((256 / strlen($key)) + 1));
7142 $rc4 = range(0, 255);
7144 for ($i = 0; $i < 256; ++$i) {
7146 $j = ($j + $t + ord($k{$i})) % 256;
7147 $rc4[$i] = $rc4[$j];
7150 $this->last_rc4_key = $key;
7151 $this->last_rc4_key_c = $rc4;
7153 $rc4 = $this->last_rc4_key_c;
7155 $len = strlen($text);
7159 for ($i = 0; $i < $len; ++$i) {
7160 $a = ($a + 1) % 256;
7162 $b = ($b + $t) % 256;
7163 $rc4[$a] = $rc4[$b];
7165 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
7166 $out .= chr(ord($text{$i}) ^ $k);
7172 * Encrypts a string using MD5 and returns it's value as a binary string.
7173 * @param string $str input string
7174 * @return String MD5 encrypted binary string
7176 * @since 2.0.000 (2008-01-02)
7177 * @author Klemen Vodopivec
7179 protected function _md5_16($str) {
7180 return pack('H*', md5($str));
7184 * Compute O value (used for RC4 encryption)
7185 * @param String $user_pass user password
7186 * @param String $owner_pass user password
7187 * @return String O value
7189 * @since 2.0.000 (2008-01-02)
7190 * @author Klemen Vodopivec
7192 protected function _Ovalue($user_pass, $owner_pass) {
7193 $tmp = $this->_md5_16($owner_pass);
7194 $owner_RC4_key = substr($tmp, 0, 5);
7195 return $this->_RC4($owner_RC4_key, $user_pass);
7199 * Compute U value (used for RC4 encryption)
7200 * @return String U value
7202 * @since 2.0.000 (2008-01-02)
7203 * @author Klemen Vodopivec
7205 protected function _Uvalue() {
7206 return $this->_RC4($this->encryption_key, $this->padding);
7210 * Compute encryption key
7211 * @param String $user_pass user password
7212 * @param String $owner_pass user password
7213 * @param String $protection protection type
7215 * @since 2.0.000 (2008-01-02)
7216 * @author Klemen Vodopivec
7218 protected function _generateencryptionkey($user_pass, $owner_pass, $protection) {
7220 $user_pass = substr($user_pass.$this->padding, 0, 32);
7221 $owner_pass = substr($owner_pass.$this->padding, 0, 32);
7223 $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
7224 // Compute encyption key
7225 $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
7226 $this->encryption_key = substr($tmp, 0, 5);
7228 $this->Uvalue = $this->_Uvalue();
7230 $this->Pvalue = -(($protection^255) + 1);
7234 * Set document protection
7235 * The permission array is composed of values taken from the following ones:
7236 * - copy: copy text and images to the clipboard
7237 * - print: print the document
7238 * - modify: modify it (except for annotations and forms)
7239 * - annot-forms: add annotations and forms
7240 * Remark: the protection against modification is for people who have the full Acrobat product.
7241 * 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.
7242 * 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.
7243 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
7244 * @param String $user_pass user password. Empty by default.
7245 * @param String $owner_pass owner password. If not specified, a random value is used.
7247 * @since 2.0.000 (2008-01-02)
7248 * @author Klemen Vodopivec
7250 public function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
7251 $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
7253 foreach ($permissions as $permission) {
7254 if (!isset($options[$permission])) {
7255 $this->Error('Incorrect permission: '.$permission);
7257 $protection += $options[$permission];
7259 if ($owner_pass === null) {
7260 $owner_pass = uniqid(rand());
7262 $this->encrypted = true;
7263 $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
7266 // END OF ENCRYPTION FUNCTIONS -------------------------
7268 // START TRANSFORMATIONS SECTION -----------------------
7271 * Starts a 2D tranformation saving current graphic state.
7272 * This function must be called before scaling, mirroring, translation, rotation and skewing.
7273 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
7275 * @since 2.1.000 (2008-01-07)
7276 * @see StartTransform(), StopTransform()
7278 public function StartTransform() {
7280 $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
7284 * Stops a 2D tranformation restoring previous graphic state.
7285 * This function must be called after scaling, mirroring, translation, rotation and skewing.
7286 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
7288 * @since 2.1.000 (2008-01-07)
7289 * @see StartTransform(), StopTransform()
7291 public function StopTransform() {
7293 if (isset($this->transfmatrix)) {
7294 array_pop($this->transfmatrix);
7296 array_pop($this->transfmrk[$this->page]);
7299 * Horizontal Scaling.
7300 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
7301 * @param int $x abscissa of the scaling center. Default is current x position
7302 * @param int $y ordinate of the scaling center. Default is current y position
7304 * @since 2.1.000 (2008-01-07)
7305 * @see StartTransform(), StopTransform()
7307 public function ScaleX($s_x, $x='', $y='') {
7308 $this->Scale($s_x, 100, $x, $y);
7313 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
7314 * @param int $x abscissa of the scaling center. Default is current x position
7315 * @param int $y ordinate of the scaling center. Default is current y position
7317 * @since 2.1.000 (2008-01-07)
7318 * @see StartTransform(), StopTransform()
7320 public function ScaleY($s_y, $x='', $y='') {
7321 $this->Scale(100, $s_y, $x, $y);
7325 * Vertical and horizontal proportional Scaling.
7326 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
7327 * @param int $x abscissa of the scaling center. Default is current x position
7328 * @param int $y ordinate of the scaling center. Default is current y position
7330 * @since 2.1.000 (2008-01-07)
7331 * @see StartTransform(), StopTransform()
7333 public function ScaleXY($s, $x='', $y='') {
7334 $this->Scale($s, $s, $x, $y);
7338 * Vertical and horizontal non-proportional Scaling.
7339 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
7340 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
7341 * @param int $x abscissa of the scaling center. Default is current x position
7342 * @param int $y ordinate of the scaling center. Default is current y position
7344 * @since 2.1.000 (2008-01-07)
7345 * @see StartTransform(), StopTransform()
7347 public function Scale($s_x, $s_y, $x='', $y='') {
7357 if (($s_x == 0) OR ($s_y == 0)) {
7358 $this->Error('Please do not use values equal to zero for scaling');
7360 $y = ($this->h - $y) * $this->k;
7362 //calculate elements of transformation matrix
7369 $tm[4] = $x * (1 - $s_x);
7370 $tm[5] = $y * (1 - $s_y);
7371 //scale the coordinate system
7372 $this->Transform($tm);
7376 * Horizontal Mirroring.
7377 * @param int $x abscissa of the point. Default is current x position
7379 * @since 2.1.000 (2008-01-07)
7380 * @see StartTransform(), StopTransform()
7382 public function MirrorH($x='') {
7383 $this->Scale(-100, 100, $x);
7387 * Verical Mirroring.
7388 * @param int $y ordinate of the point. Default is current y position
7390 * @since 2.1.000 (2008-01-07)
7391 * @see StartTransform(), StopTransform()
7393 public function MirrorV($y='') {
7394 $this->Scale(100, -100, '', $y);
7398 * Point reflection mirroring.
7399 * @param int $x abscissa of the point. Default is current x position
7400 * @param int $y ordinate of the point. Default is current y position
7402 * @since 2.1.000 (2008-01-07)
7403 * @see StartTransform(), StopTransform()
7405 public function MirrorP($x='',$y='') {
7406 $this->Scale(-100, -100, $x, $y);
7410 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
7411 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
7412 * @param int $x abscissa of the point. Default is current x position
7413 * @param int $y ordinate of the point. Default is current y position
7415 * @since 2.1.000 (2008-01-07)
7416 * @see StartTransform(), StopTransform()
7418 public function MirrorL($angle=0, $x='',$y='') {
7419 $this->Scale(-100, 100, $x, $y);
7420 $this->Rotate(-2*($angle-90), $x, $y);
7424 * Translate graphic object horizontally.
7425 * @param int $t_x movement to the right (or left for RTL)
7427 * @since 2.1.000 (2008-01-07)
7428 * @see StartTransform(), StopTransform()
7430 public function TranslateX($t_x) {
7431 $this->Translate($t_x, 0);
7435 * Translate graphic object vertically.
7436 * @param int $t_y movement to the bottom
7438 * @since 2.1.000 (2008-01-07)
7439 * @see StartTransform(), StopTransform()
7441 public function TranslateY($t_y) {
7442 $this->Translate(0, $t_y);
7446 * Translate graphic object horizontally and vertically.
7447 * @param int $t_x movement to the right
7448 * @param int $t_y movement to the bottom
7450 * @since 2.1.000 (2008-01-07)
7451 * @see StartTransform(), StopTransform()
7453 public function Translate($t_x, $t_y) {
7457 //calculate elements of transformation matrix
7462 $tm[4] = $t_x * $this->k;
7463 $tm[5] = -$t_y * $this->k;
7464 //translate the coordinate system
7465 $this->Transform($tm);
7470 * @param float $angle angle in degrees for counter-clockwise rotation
7471 * @param int $x abscissa of the rotation center. Default is current x position
7472 * @param int $y ordinate of the rotation center. Default is current y position
7474 * @since 2.1.000 (2008-01-07)
7475 * @see StartTransform(), StopTransform()
7477 public function Rotate($angle, $x='', $y='') {
7488 $y = ($this->h - $y) * $this->k;
7490 //calculate elements of transformation matrix
7491 $tm[0] = cos(deg2rad($angle));
7492 $tm[1] = sin(deg2rad($angle));
7495 $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
7496 $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
7497 //rotate the coordinate system around ($x,$y)
7498 $this->Transform($tm);
7502 * Skew horizontally.
7503 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
7504 * @param int $x abscissa of the skewing center. default is current x position
7505 * @param int $y ordinate of the skewing center. default is current y position
7507 * @since 2.1.000 (2008-01-07)
7508 * @see StartTransform(), StopTransform()
7510 public function SkewX($angle_x, $x='', $y='') {
7511 $this->Skew($angle_x, 0, $x, $y);
7516 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
7517 * @param int $x abscissa of the skewing center. default is current x position
7518 * @param int $y ordinate of the skewing center. default is current y position
7520 * @since 2.1.000 (2008-01-07)
7521 * @see StartTransform(), StopTransform()
7523 public function SkewY($angle_y, $x='', $y='') {
7524 $this->Skew(0, $angle_y, $x, $y);
7529 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
7530 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
7531 * @param int $x abscissa of the skewing center. default is current x position
7532 * @param int $y ordinate of the skewing center. default is current y position
7534 * @since 2.1.000 (2008-01-07)
7535 * @see StartTransform(), StopTransform()
7537 public function Skew($angle_x, $angle_y, $x='', $y='') {
7546 $angle_x = -$angle_x;
7548 if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
7549 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
7552 $y = ($this->h - $y) * $this->k;
7553 //calculate elements of transformation matrix
7555 $tm[1] = tan(deg2rad($angle_y));
7556 $tm[2] = tan(deg2rad($angle_x));
7558 $tm[4] = -$tm[2] * $y;
7559 $tm[5] = -$tm[1] * $x;
7560 //skew the coordinate system
7561 $this->Transform($tm);
7565 * Apply graphic transformations.
7567 * @since 2.1.000 (2008-01-07)
7568 * @see StartTransform(), StopTransform()
7570 protected function Transform($tm) {
7571 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
7572 // store transformation matrix
7573 $this->transfmatrix[] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
7574 // update tranformation mark
7575 if (end($this->transfmrk[$this->page]) !== false) {
7576 $key = key($this->transfmrk[$this->page]);
7577 $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
7581 // END TRANSFORMATIONS SECTION -------------------------
7584 // START GRAPHIC FUNCTIONS SECTION ---------------------
7585 // The following section is based on the code provided by David Hernandez Sanz
7588 * 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.
7589 * @param float $width The width.
7592 * @see Line(), Rect(), Cell(), MultiCell()
7594 public function SetLineWidth($width) {
7596 $this->LineWidth = $width;
7597 $this->linestyleWidth = sprintf('%.2F w', ($width * $this->k));
7598 $this->_out($this->linestyleWidth);
7602 * Returns the current the line width.
7603 * @return int Line width
7605 * @since 2.1.000 (2008-01-07)
7606 * @see Line(), SetLineWidth()
7608 public function GetLineWidth() {
7609 return $this->LineWidth;
7614 * @param array $style Line style. Array with keys among the following:
7616 * <li>width (float): Width of the line in user units.</li>
7617 * <li>cap (string): Type of cap to put on the line. Possible values are:
7618 * butt, round, square. The difference between "square" and "butt" is that
7619 * "square" projects a flat end past the end of the line.</li>
7620 * <li>join (string): Type of join. Possible values are: miter, round,
7622 * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
7623 * series of length values, which are the lengths of the on and off dashes.
7624 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
7625 * 1 off, 2 on, 1 off, ...</li>
7626 * <li>phase (integer): Modifier on the dash pattern which is used to shift
7627 * the point at which the pattern starts.</li>
7628 * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
7631 * @since 2.1.000 (2008-01-08)
7633 public function SetLineStyle($style) {
7635 if (isset($width)) {
7636 $width_prev = $this->LineWidth;
7637 $this->SetLineWidth($width);
7638 $this->LineWidth = $width_prev;
7641 $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
7642 if (isset($ca[$cap])) {
7643 $this->linestyleCap = $ca[$cap].' J';
7644 $this->_out($this->linestyleCap);
7648 $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
7649 if (isset($ja[$join])) {
7650 $this->linestyleJoin = $ja[$join].' j';
7651 $this->_out($this->linestyleJoin);
7657 if (preg_match('/^.+,/', $dash)) {
7658 $tab = explode(',', $dash);
7660 $tab = array($dash);
7663 foreach ($tab as $i => $v) {
7665 $dash_string .= ' ';
7667 $dash_string .= sprintf("%.2F", $v);
7670 if (!isset($phase) OR !$dash) {
7673 $this->linestyleDash = sprintf("[%s] %.2F d", $dash_string, $phase);
7674 $this->_out($this->linestyleDash);
7676 if (isset($color)) {
7677 $this->SetDrawColorArray($color);
7683 * @param float $x Abscissa of point.
7684 * @param float $y Ordinate of point.
7686 * @since 2.1.000 (2008-01-08)
7688 protected function _outPoint($x, $y) {
7692 $this->_out(sprintf("%.2F %.2F m", $x * $this->k, ($this->h - $y) * $this->k));
7696 * Draws a line from last draw point.
7697 * @param float $x Abscissa of end point.
7698 * @param float $y Ordinate of end point.
7700 * @since 2.1.000 (2008-01-08)
7702 protected function _outLine($x, $y) {
7706 $this->_out(sprintf("%.2F %.2F l", $x * $this->k, ($this->h - $y) * $this->k));
7710 * Draws a rectangle.
7711 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
7712 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
7713 * @param float $w Width.
7714 * @param float $h Height.
7715 * @param string $op options
7717 * @since 2.1.000 (2008-01-08)
7719 protected function _outRect($x, $y, $w, $h, $op) {
7721 $x = $this->w - $x - $w;
7723 $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
7727 * Draws a Bezier curve from last draw point.
7728 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
7729 * @param float $x1 Abscissa of control point 1.
7730 * @param float $y1 Ordinate of control point 1.
7731 * @param float $x2 Abscissa of control point 2.
7732 * @param float $y2 Ordinate of control point 2.
7733 * @param float $x3 Abscissa of end point.
7734 * @param float $y3 Ordinate of end point.
7736 * @since 2.1.000 (2008-01-08)
7738 protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
7740 $x1 = $this->w - $x1;
7741 $x2 = $this->w - $x2;
7742 $x3 = $this->w - $x3;
7744 $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));
7748 * Draws a line between two points.
7749 * @param float $x1 Abscissa of first point.
7750 * @param float $y1 Ordinate of first point.
7751 * @param float $x2 Abscissa of second point.
7752 * @param float $y2 Ordinate of second point.
7753 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7756 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
7758 public function Line($x1, $y1, $x2, $y2, $style=array()) {
7760 $this->SetLineStyle($style);
7762 $this->_outPoint($x1, $y1);
7763 $this->_outLine($x2, $y2);
7768 * Draws a rectangle.
7769 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
7770 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
7771 * @param float $w Width.
7772 * @param float $h Height.
7773 * @param string $style Style of rendering. Possible values are:
7775 * <li>D or empty string: Draw (default).</li>
7777 * <li>DF or FD: Draw and fill.</li>
7778 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7779 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7781 * @param array $border_style Border style of rectangle. Array with keys among the following:
7783 * <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
7784 * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
7786 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
7787 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7788 * @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).
7791 * @see SetLineStyle()
7793 public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
7794 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7795 $this->SetFillColorArray($fill_color);
7800 $border_style = array();
7801 $this->_outRect($x, $y, $w, $h, $op);
7806 if ((!$border_style) OR (isset($border_style['all']))) {
7808 if (isset($border_style['all'])) {
7809 $this->SetLineStyle($border_style['all']);
7810 $border_style = array();
7815 $this->_outRect($x, $y, $w, $h, $op);
7820 $this->_outRect($x, $y, $w, $h, $op);
7825 $this->_outRect($x, $y, $w, $h, $op);
7830 if ((!$border_style) OR (isset($border_style['all']))) {
7831 if (isset($border_style['all']) AND $border_style['all']) {
7832 $this->SetLineStyle($border_style['all']);
7833 $border_style = array();
7835 $this->_outRect($x, $y, $w, $h, $op);
7840 if ($border_style) {
7841 $border_style2 = array();
7842 foreach ($border_style as $line => $value) {
7843 $lenght = strlen($line);
7844 for ($i = 0; $i < $lenght; ++$i) {
7845 $border_style2[$line[$i]] = $value;
7848 $border_style = $border_style2;
7849 if (isset($border_style['L']) AND $border_style['L']) {
7850 $this->Line($x, $y, $x, $y + $h, $border_style['L']);
7852 if (isset($border_style['T']) AND $border_style['T']) {
7853 $this->Line($x, $y, $x + $w, $y, $border_style['T']);
7855 if (isset($border_style['R']) AND $border_style['R']) {
7856 $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
7858 if (isset($border_style['B']) AND $border_style['B']) {
7859 $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
7866 * Draws a Bezier curve.
7867 * The Bezier curve is a tangent to the line between the control points at
7868 * either end of the curve.
7869 * @param float $x0 Abscissa of start point.
7870 * @param float $y0 Ordinate of start point.
7871 * @param float $x1 Abscissa of control point 1.
7872 * @param float $y1 Ordinate of control point 1.
7873 * @param float $x2 Abscissa of control point 2.
7874 * @param float $y2 Ordinate of control point 2.
7875 * @param float $x3 Abscissa of end point.
7876 * @param float $y3 Ordinate of end point.
7877 * @param string $style Style of rendering. Possible values are:
7879 * <li>D or empty string: Draw (default).</li>
7881 * <li>DF or FD: Draw and fill.</li>
7882 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7883 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7885 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7886 * @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).
7888 * @see SetLineStyle()
7889 * @since 2.1.000 (2008-01-08)
7891 public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
7892 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7893 $this->SetFillColorArray($fill_color);
7898 $line_style = array();
7920 $this->SetLineStyle($line_style);
7922 $this->_outPoint($x0, $y0);
7923 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
7928 * Draws a poly-Bezier curve.
7929 * Each Bezier curve segment is a tangent to the line between the control points at
7930 * either end of the curve.
7931 * @param float $x0 Abscissa of start point.
7932 * @param float $y0 Ordinate of start point.
7933 * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
7934 * @param string $style Style of rendering. Possible values are:
7936 * <li>D or empty string: Draw (default).</li>
7938 * <li>DF or FD: Draw and fill.</li>
7939 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7940 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7942 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7943 * @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).
7945 * @see SetLineStyle()
7946 * @since 3.0008 (2008-05-12)
7948 public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
7949 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7950 $this->SetFillColorArray($fill_color);
7955 $line_style = array();
7977 $this->SetLineStyle($line_style);
7979 $this->_outPoint($x0, $y0);
7980 foreach ($segments as $segment) {
7981 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
7982 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
7989 * An ellipse is formed from n Bezier curves.
7990 * @param float $x0 Abscissa of center point.
7991 * @param float $y0 Ordinate of center point.
7992 * @param float $rx Horizontal radius.
7993 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
7994 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
7995 * @param float $astart: Angle start of draw line. Default value: 0.
7996 * @param float $afinish: Angle finish of draw line. Default value: 360.
7997 * @param string $style Style of rendering. Possible values are:
7999 * <li>D or empty string: Draw (default).</li>
8001 * <li>DF or FD: Draw and fill.</li>
8002 * <li>C: Draw close.</li>
8003 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8004 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8006 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8007 * @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).
8008 * @param integer $nc Number of curves used in ellipse. Default value: 8.
8010 * @since 2.1.000 (2008-01-08)
8012 public function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
8014 $this->StartTransform();
8015 $this->Rotate($angle, $x0, $y0);
8016 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
8017 $this->StopTransform();
8021 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8022 $this->SetFillColorArray($fill_color);
8027 $line_style = array();
8036 $op = 's'; // Small 's' signifies closing the path as well
8053 $this->SetLineStyle($line_style);
8063 $astart = deg2rad((float) $astart);
8064 $afinish = deg2rad((float) $afinish);
8065 $total_angle = $afinish - $astart;
8066 $dt = $total_angle / $nc;
8069 $y0 = ($this->h - $y0) * $this->k;
8071 $a0 = $x0 + ($rx * cos($t1));
8072 $b0 = $y0 + ($ry * sin($t1));
8073 $c0 = -$rx * sin($t1);
8074 $d0 = $ry * cos($t1);
8075 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
8076 for ($i = 1; $i <= $nc; ++$i) {
8077 // Draw this bit of the total curve
8078 $t1 = ($i * $dt) + $astart;
8079 $a1 = $x0 + ($rx * cos($t1));
8080 $b1 = $y0 + ($ry * sin($t1));
8081 $c1 = -$rx * sin($t1);
8082 $d1 = $ry * cos($t1);
8083 $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));
8095 * A circle is formed from n Bezier curves.
8096 * @param float $x0 Abscissa of center point.
8097 * @param float $y0 Ordinate of center point.
8098 * @param float $r Radius.
8099 * @param float $astart: Angle start of draw line. Default value: 0.
8100 * @param float $afinish: Angle finish of draw line. Default value: 360.
8101 * @param string $style Style of rendering. Possible values are:
8103 * <li>D or empty string: Draw (default).</li>
8105 * <li>DF or FD: Draw and fill.</li>
8106 * <li>C: Draw close.</li>
8107 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8108 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8110 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8111 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8112 * @param integer $nc Number of curves used in circle. Default value: 8.
8114 * @since 2.1.000 (2008-01-08)
8116 public function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
8117 $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
8122 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
8123 * @param string $style Style of rendering. Possible values are:
8125 * <li>D or empty string: Draw (default).</li>
8127 * <li>DF or FD: Draw and fill.</li>
8128 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8129 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8131 * @param array $line_style Line style of polygon. Array with keys among the following:
8133 * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
8134 * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
8136 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
8137 * @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).
8139 * @since 2.1.000 (2008-01-08)
8141 public function Polygon($p, $style='', $line_style=array(), $fill_color=array()) {
8142 $np = count($p) / 2;
8143 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8144 $this->SetFillColorArray($fill_color);
8148 $line_style = array();
8172 if (isset($line_style['all'])) {
8173 $this->SetLineStyle($line_style['all']);
8174 } else { // 0 .. (np - 1), op = {B, S}
8178 $this->_outPoint($p[0], $p[1]);
8179 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
8180 $this->_outLine($p[$i], $p[$i + 1]);
8182 $this->_outLine($p[0], $p[1]);
8185 $p[($np * 2)] = $p[0];
8186 $p[(($np * 2) + 1)] = $p[1];
8187 for ($i = 0; $i < $np; ++$i) {
8188 if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
8189 $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
8195 $this->_outPoint($p[0], $p[1]);
8196 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
8197 $this->_outLine($p[$i], $p[$i + 1]);
8199 $this->_outLine($p[0], $p[1]);
8205 * Draws a regular polygon.
8206 * @param float $x0 Abscissa of center point.
8207 * @param float $y0 Ordinate of center point.
8208 * @param float $r: Radius of inscribed circle.
8209 * @param integer $ns Number of sides.
8210 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
8211 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
8212 * @param string $style Style of rendering. Possible values are:
8214 * <li>D or empty string: Draw (default).</li>
8216 * <li>DF or FD: Draw and fill.</li>
8217 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8218 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8220 * @param array $line_style Line style of polygon sides. Array with keys among the following:
8222 * <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
8223 * <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
8225 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
8226 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8227 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
8229 * <li>D or empty string: Draw (default).</li>
8231 * <li>DF or FD: Draw and fill.</li>
8232 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8233 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8235 * @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).
8236 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
8238 * @since 2.1.000 (2008-01-08)
8240 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()) {
8245 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
8248 for ($i = 0; $i < $ns; ++$i) {
8249 $a = $angle + ($i * 360 / $ns);
8250 $a_rad = deg2rad((float) $a);
8251 $p[] = $x0 + ($r * sin($a_rad));
8252 $p[] = $y0 + ($r * cos($a_rad));
8254 $this->Polygon($p, $style, $line_style, $fill_color);
8258 * Draws a star polygon
8259 * @param float $x0 Abscissa of center point.
8260 * @param float $y0 Ordinate of center point.
8261 * @param float $r Radius of inscribed circle.
8262 * @param integer $nv Number of vertices.
8263 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
8264 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
8265 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
8266 * @param string $style Style of rendering. Possible values are:
8268 * <li>D or empty string: Draw (default).</li>
8270 * <li>DF or FD: Draw and fill.</li>
8271 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8272 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8274 * @param array $line_style Line style of polygon sides. Array with keys among the following:
8276 * <li>all: Line style of all sides. Array like for
8277 * {@link SetLineStyle SetLineStyle}.</li>
8278 * <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
8280 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
8281 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8282 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
8284 * <li>D or empty string: Draw (default).</li>
8286 * <li>DF or FD: Draw and fill.</li>
8287 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8288 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8290 * @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).
8291 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
8293 * @since 2.1.000 (2008-01-08)
8295 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()) {
8300 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
8304 for ($i = 0; $i < $nv; ++$i) {
8305 $a = $angle + ($i * 360 / $nv);
8306 $a_rad = deg2rad((float) $a);
8307 $p2[] = $x0 + ($r * sin($a_rad));
8308 $p2[] = $y0 + ($r * cos($a_rad));
8315 $p[] = $p2[($i * 2) + 1];
8316 $visited[$i] = true;
8319 } while (!$visited[$i]);
8320 $this->Polygon($p, $style, $line_style, $fill_color);
8324 * Draws a rounded rectangle.
8325 * @param float $x Abscissa of upper-left corner.
8326 * @param float $y Ordinate of upper-left corner.
8327 * @param float $w Width.
8328 * @param float $h Height.
8329 * @param float $r Radius of the rounded corners.
8330 * @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").
8331 * @param string $style Style of rendering. Possible values are:
8333 * <li>D or empty string: Draw (default).</li>
8335 * <li>DF or FD: Draw and fill.</li>
8336 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8337 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8339 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8340 * @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).
8342 * @since 2.1.000 (2008-01-08)
8344 public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
8345 if ('0000' == $round_corner) { // Not rounded
8346 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
8348 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8349 $this->SetFillColorArray($fill_color);
8353 $border_style = array();
8375 if ($border_style) {
8376 $this->SetLineStyle($border_style);
8378 $MyArc = 4 / 3 * (sqrt(2) - 1);
8379 $this->_outPoint($x + $r, $y);
8382 $this->_outLine($xc, $y);
8383 if ($round_corner[0]) {
8384 $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
8386 $this->_outLine($x + $w, $y);
8390 $this->_outLine($x + $w, $yc);
8391 if ($round_corner[1]) {
8392 $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
8394 $this->_outLine($x + $w, $y + $h);
8398 $this->_outLine($xc, $y + $h);
8399 if ($round_corner[2]) {
8400 $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
8402 $this->_outLine($x, $y + $h);
8406 $this->_outLine($x, $yc);
8407 if ($round_corner[3]) {
8408 $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
8410 $this->_outLine($x, $y);
8411 $this->_outLine($x + $r, $y);
8417 // END GRAPHIC FUNCTIONS SECTION -----------------------
8419 // BIDIRECTIONAL TEXT SECTION --------------------------
8421 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
8422 * @param string $str string to manipulate.
8423 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
8426 * @author Nicola Asuni
8427 * @since 2.1.000 (2008-01-08)
8429 protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
8430 return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $str, $forcertl), $setbom);
8434 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
8435 * @param array $ta array of characters composing the string.
8436 * @param string $str string to process
8437 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
8439 * @author Nicola Asuni
8441 * @since 2.4.000 (2008-03-06)
8443 protected function utf8Bidi($ta, $str='', $forcertl=false) {
8444 global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
8445 // paragraph embedding level
8449 if ($this->empty_string($str)) {
8450 // create string from array
8451 $str = $this->UTF8ArrSubString($ta);
8453 // check if string contains arabic text
8454 if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
8459 // check if string contains RTL text
8460 if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
8464 // get number of chars
8465 $numchars = count($ta);
8467 if ($forcertl == 'R') {
8469 } elseif ($forcertl == 'L') {
8472 // P2. In each paragraph, find the first character of type L, AL, or R.
8473 // 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.
8474 for ($i=0; $i < $numchars; ++$i) {
8475 $type = $unicode[$ta[$i]];
8479 } elseif (($type == 'AL') OR ($type == 'R')) {
8486 // Current Embedding Level
8488 // directional override status
8490 $remember = array();
8491 // start-of-level-run
8492 $sor = $pel % 2 ? 'R' : 'L';
8495 // Array of characters data
8496 $chardata = Array();
8498 // 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.
8499 // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
8500 for ($i=0; $i < $numchars; ++$i) {
8501 if ($ta[$i] == K_RLE) {
8502 // X2. With each RLE, compute the least greater odd embedding level.
8503 // 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.
8504 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8505 $next_level = $cel + ($cel % 2) + 1;
8506 if ($next_level < 62) {
8507 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
8511 $eor = $cel % 2 ? 'R' : 'L';
8513 } elseif ($ta[$i] == K_LRE) {
8514 // X3. With each LRE, compute the least greater even embedding level.
8515 // 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.
8516 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8517 $next_level = $cel + 2 - ($cel % 2);
8518 if ( $next_level < 62 ) {
8519 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
8523 $eor = $cel % 2 ? 'R' : 'L';
8525 } elseif ($ta[$i] == K_RLO) {
8526 // X4. With each RLO, compute the least greater odd embedding level.
8527 // 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.
8528 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8529 $next_level = $cel + ($cel % 2) + 1;
8530 if ($next_level < 62) {
8531 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
8535 $eor = $cel % 2 ? 'R' : 'L';
8537 } elseif ($ta[$i] == K_LRO) {
8538 // X5. With each LRO, compute the least greater even embedding level.
8539 // 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.
8540 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8541 $next_level = $cel + 2 - ($cel % 2);
8542 if ( $next_level < 62 ) {
8543 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
8547 $eor = $cel % 2 ? 'R' : 'L';
8549 } elseif ($ta[$i] == K_PDF) {
8550 // 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.
8551 if (count($remember)) {
8552 $last = count($remember ) - 1;
8553 if (($remember[$last]['num'] == K_RLE) OR
8554 ($remember[$last]['num'] == K_LRE) OR
8555 ($remember[$last]['num'] == K_RLO) OR
8556 ($remember[$last]['num'] == K_LRO)) {
8557 $match = array_pop($remember);
8558 $cel = $match['cel'];
8559 $dos = $match['dos'];
8561 $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
8564 } elseif (($ta[$i] != K_RLE) AND
8565 ($ta[$i] != K_LRE) AND
8566 ($ta[$i] != K_RLO) AND
8567 ($ta[$i] != K_LRO) AND
8568 ($ta[$i] != K_PDF)) {
8569 // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
8570 // a. Set the level of the current character to the current embedding level.
8571 // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
8575 $chardir = $unicode[$ta[$i]];
8577 // stores string characters and other information
8578 $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
8580 } // end for each char
8582 // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
8583 // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
8584 // 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.
8586 // 3.3.3 Resolving Weak Types
8587 // 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.
8588 // Nonspacing marks are now resolved based on the previous characters.
8589 $numchars = count($chardata);
8591 // 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.
8592 $prevlevel = -1; // track level changes
8593 $levcount = 0; // counts consecutive chars at the same level
8594 for ($i=0; $i < $numchars; ++$i) {
8595 if ($chardata[$i]['type'] == 'NSM') {
8597 $chardata[$i]['type'] = $chardata[$i]['sor'];
8599 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
8602 if ($chardata[$i]['level'] != $prevlevel) {
8607 $prevlevel = $chardata[$i]['level'];
8610 // 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.
8613 for ($i=0; $i < $numchars; ++$i) {
8614 if ($chardata[$i]['char'] == 'EN') {
8615 for ($j=$levcount; $j >= 0; $j--) {
8616 if ($chardata[$j]['type'] == 'AL') {
8617 $chardata[$i]['type'] = 'AN';
8618 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
8623 if ($chardata[$i]['level'] != $prevlevel) {
8628 $prevlevel = $chardata[$i]['level'];
8631 // W3. Change all ALs to R.
8632 for ($i=0; $i < $numchars; ++$i) {
8633 if ($chardata[$i]['type'] == 'AL') {
8634 $chardata[$i]['type'] = 'R';
8638 // 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.
8641 for ($i=0; $i < $numchars; ++$i) {
8642 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8643 if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
8644 $chardata[$i]['type'] = 'EN';
8645 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
8646 $chardata[$i]['type'] = 'EN';
8647 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
8648 $chardata[$i]['type'] = 'AN';
8651 if ($chardata[$i]['level'] != $prevlevel) {
8656 $prevlevel = $chardata[$i]['level'];
8659 // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
8662 for ($i=0; $i < $numchars; ++$i) {
8663 if ($chardata[$i]['type'] == 'ET') {
8664 if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
8665 $chardata[$i]['type'] = 'EN';
8668 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
8669 if ($chardata[$j]['type'] == 'EN') {
8670 $chardata[$i]['type'] = 'EN';
8672 } elseif ($chardata[$j]['type'] != 'ET') {
8679 if ($chardata[$i]['level'] != $prevlevel) {
8684 $prevlevel = $chardata[$i]['level'];
8687 // W6. Otherwise, separators and terminators change to Other Neutral.
8690 for ($i=0; $i < $numchars; ++$i) {
8691 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
8692 $chardata[$i]['type'] = 'ON';
8694 if ($chardata[$i]['level'] != $prevlevel) {
8699 $prevlevel = $chardata[$i]['level'];
8702 //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.
8705 for ($i=0; $i < $numchars; ++$i) {
8706 if ($chardata[$i]['char'] == 'EN') {
8707 for ($j=$levcount; $j >= 0; $j--) {
8708 if ($chardata[$j]['type'] == 'L') {
8709 $chardata[$i]['type'] = 'L';
8710 } elseif ($chardata[$j]['type'] == 'R') {
8715 if ($chardata[$i]['level'] != $prevlevel) {
8720 $prevlevel = $chardata[$i]['level'];
8723 // 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.
8726 for ($i=0; $i < $numchars; ++$i) {
8727 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8728 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
8729 $chardata[$i]['type'] = 'L';
8730 } elseif (($chardata[$i]['type'] == 'N') AND
8731 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
8732 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
8733 $chardata[$i]['type'] = 'R';
8734 } elseif ($chardata[$i]['type'] == 'N') {
8735 // N2. Any remaining neutrals take the embedding direction
8736 $chardata[$i]['type'] = $chardata[$i]['sor'];
8738 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8740 if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
8741 $chardata[$i]['type'] = 'L';
8742 } elseif (($chardata[$i]['type'] == 'N') AND
8743 (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
8744 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
8745 $chardata[$i]['type'] = 'R';
8746 } elseif ($chardata[$i]['type'] == 'N') {
8747 // N2. Any remaining neutrals take the embedding direction
8748 $chardata[$i]['type'] = $chardata[$i]['sor'];
8750 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
8752 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
8753 $chardata[$i]['type'] = 'L';
8754 } elseif (($chardata[$i]['type'] == 'N') AND
8755 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
8756 (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
8757 $chardata[$i]['type'] = 'R';
8758 } elseif ($chardata[$i]['type'] == 'N') {
8759 // N2. Any remaining neutrals take the embedding direction
8760 $chardata[$i]['type'] = $chardata[$i]['sor'];
8762 } elseif ($chardata[$i]['type'] == 'N') {
8763 // N2. Any remaining neutrals take the embedding direction
8764 $chardata[$i]['type'] = $chardata[$i]['sor'];
8766 if ($chardata[$i]['level'] != $prevlevel) {
8771 $prevlevel = $chardata[$i]['level'];
8774 // 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.
8775 // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
8776 for ($i=0; $i < $numchars; ++$i) {
8777 $odd = $chardata[$i]['level'] % 2;
8779 if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
8780 $chardata[$i]['level'] += 1;
8783 if ($chardata[$i]['type'] == 'R') {
8784 $chardata[$i]['level'] += 1;
8785 } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
8786 $chardata[$i]['level'] += 2;
8789 $maxlevel = max($chardata[$i]['level'],$maxlevel);
8792 // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
8793 // 1. Segment separators,
8794 // 2. Paragraph separators,
8795 // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
8796 // 4. Any sequence of white space characters at the end of the line.
8797 for ($i=0; $i < $numchars; ++$i) {
8798 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
8799 $chardata[$i]['level'] = $pel;
8800 } elseif ($chardata[$i]['type'] == 'WS') {
8802 while ($j < $numchars) {
8803 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
8804 (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
8805 $chardata[$i]['level'] = $pel;
8807 } elseif ($chardata[$j]['type'] != 'WS') {
8816 // 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.
8818 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
8819 $alfletter = array(1570,1571,1573,1575);
8820 $chardata2 = $chardata;
8824 for ($i=0; $i < $numchars; ++$i) {
8825 if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
8826 $charAL[$x] = $chardata[$i];
8827 $charAL[$x]['i'] = $i;
8828 $chardata[$i]['x'] = $x;
8833 for ($i=0; $i < $numchars; ++$i) {
8834 $thischar = $chardata[$i];
8836 $prevchar = $chardata[($i-1)];
8840 if (($i+1) < $numchars) {
8841 $nextchar = $chardata[($i+1)];
8845 if ($unicode[$thischar['char']] == 'AL') {
8846 $x = $thischar['x'];
8848 $prevchar = $charAL[($x-1)];
8852 if (($x+1) < $numAL) {
8853 $nextchar = $charAL[($x+1)];
8858 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
8859 $arabicarr = $laa_array;
8862 $prevchar = $charAL[($x-2)];
8867 $arabicarr = $unicode_arlet;
8870 if (($prevchar !== false) AND ($nextchar !== false) AND
8871 (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
8872 (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
8873 ($prevchar['type'] == $thischar['type']) AND
8874 ($nextchar['type'] == $thischar['type']) AND
8875 ($nextchar['char'] != 1567)) {
8876 if (in_array($prevchar['char'], $endedletter)) {
8877 if (isset($arabicarr[$thischar['char']][2])) {
8879 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
8882 if (isset($arabicarr[$thischar['char']][3])) {
8884 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
8887 } elseif (($nextchar !== false) AND
8888 (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
8889 ($nextchar['type'] == $thischar['type']) AND
8890 ($nextchar['char'] != 1567)) {
8891 if (isset($arabicarr[$chardata[$i]['char']][2])) {
8893 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
8895 } elseif ((($prevchar !== false) AND
8896 (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
8897 ($prevchar['type'] == $thischar['type'])) OR
8898 (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
8900 if (($i > 1) AND ($thischar['char'] == 1607) AND
8901 ($chardata[$i-1]['char'] == 1604) AND
8902 ($chardata[$i-2]['char'] == 1604)) {
8904 // mark characters to delete with false
8905 $chardata2[$i-2]['char'] = false;
8906 $chardata2[$i-1]['char'] = false;
8907 $chardata2[$i]['char'] = 65010;
8909 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
8910 if (isset($arabicarr[$thischar['char']][0])) {
8912 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
8915 if (isset($arabicarr[$thischar['char']][1])) {
8917 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
8921 } elseif (isset($arabicarr[$thischar['char']][0])) {
8923 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
8927 // mark characters to delete with false
8928 $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
8930 } // end if AL (Arabic Letter)
8931 } // end for each char
8933 * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
8934 * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
8936 $cw = &$this->CurrentFont['cw'];
8937 for ($i = 0; $i < ($numchars-1); ++$i) {
8938 if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
8939 // check if the subtitution font is defined on current font
8940 if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
8941 $chardata2[$i]['char'] = false;
8942 $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
8946 // remove marked characters
8947 foreach ($chardata2 as $key => $value) {
8948 if ($value['char'] === false) {
8949 unset($chardata2[$key]);
8952 $chardata = array_values($chardata2);
8953 $numchars = count($chardata);
8960 // 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.
8961 for ($j=$maxlevel; $j > 0; $j--) {
8962 $ordarray = Array();
8965 for ($i=0; $i < $numchars; ++$i) {
8966 if ($chardata[$i]['level'] >= $j) {
8968 if (isset($unicode_mirror[$chardata[$i]['char']])) {
8969 // 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.
8970 $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
8972 $revarr[] = $chardata[$i];
8975 $revarr = array_reverse($revarr);
8976 $ordarray = array_merge($ordarray, $revarr);
8980 $ordarray[] = $chardata[$i];
8984 $revarr = array_reverse($revarr);
8985 $ordarray = array_merge($ordarray, $revarr);
8987 $chardata = $ordarray;
8990 $ordarray = array();
8991 for ($i=0; $i < $numchars; ++$i) {
8992 $ordarray[] = $chardata[$i]['char'];
8998 // END OF BIDIRECTIONAL TEXT SECTION -------------------
9002 * @param string $txt bookmark description.
9003 * @param int $level bookmark level (minimum value is 0).
9004 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
9005 * @param int $page target page number (leave empty for current page).
9007 * @author Olivier Plathey, Nicola Asuni
9008 * @since 2.1.002 (2008-02-12)
9010 public function Bookmark($txt, $level=0, $y=-1, $page='') {
9014 if (isset($this->outlines[0])) {
9015 $lastoutline = end($this->outlines);
9016 $maxlevel = $lastoutline['l'] + 1;
9020 if ($level > $maxlevel) {
9027 $page = $this->PageNo();
9029 $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $page);
9033 * Create a bookmark PDF string.
9035 * @author Olivier Plathey, Nicola Asuni
9036 * @since 2.1.002 (2008-02-12)
9038 protected function _putbookmarks() {
9039 $nb = count($this->outlines);
9045 foreach ($this->outlines as $i => $o) {
9047 $parent = $lru[($o['l'] - 1)];
9048 //Set parent and last pointers
9049 $this->outlines[$i]['parent'] = $parent;
9050 $this->outlines[$parent]['last'] = $i;
9051 if ($o['l'] > $level) {
9052 //Level increasing: set first pointer
9053 $this->outlines[$parent]['first'] = $i;
9056 $this->outlines[$i]['parent'] = $nb;
9058 if (($o['l'] <= $level) AND ($i > 0)) {
9059 //Set prev and next pointers
9060 $prev = $lru[$o['l']];
9061 $this->outlines[$prev]['next'] = $i;
9062 $this->outlines[$i]['prev'] = $prev;
9069 foreach ($this->outlines as $i => $o) {
9071 $this->_out('<</Title '.$this->_textstring($o['t']));
9072 $this->_out('/Parent '.($n + $o['parent']).' 0 R');
9073 if (isset($o['prev']))
9074 $this->_out('/Prev '.($n + $o['prev']).' 0 R');
9075 if (isset($o['next']))
9076 $this->_out('/Next '.($n + $o['next']).' 0 R');
9077 if (isset($o['first']))
9078 $this->_out('/First '.($n + $o['first']).' 0 R');
9079 if (isset($o['last']))
9080 $this->_out('/Last '.($n + $o['last']).' 0 R');
9081 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $o['p'])), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k))));
9082 $this->_out('/Count 0>>');
9083 $this->_out('endobj');
9087 $this->OutlineRoot = $this->n;
9088 $this->_out('<</Type /Outlines /First '.$n.' 0 R');
9089 $this->_out('/Last '.($n + $lru[0]).' 0 R>>');
9090 $this->_out('endobj');
9094 // --- JAVASCRIPT - FORMS ------------------------------
9099 * @author Johannes G�ntert, Nicola Asuni
9100 * @since 2.1.002 (2008-02-12)
9102 public function IncludeJS($script) {
9103 $this->javascript .= $script;
9107 * Create a javascript PDF string.
9109 * @author Johannes G�ntert, Nicola Asuni
9110 * @since 2.1.002 (2008-02-12)
9112 protected function _putjavascript() {
9113 if (empty($this->javascript)) {
9116 // the following two lines are uded to avoid form fields duplication after saving
9117 $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
9118 $js2 = "getField('tcpdfdocsaved').value = 'saved';";
9120 $this->n_js = $this->n;
9122 $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
9124 $this->_out('endobj');
9127 $this->_out('/S /JavaScript');
9128 $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
9130 $this->_out('endobj');
9134 * Convert color to javascript color.
9135 * @param string $color color name or #RRGGBB
9137 * @author Denis Van Nuffelen, Nicola Asuni
9138 * @since 2.1.002 (2008-02-12)
9140 protected function _JScolor($color) {
9141 static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
9142 if (substr($color,0,1) == '#') {
9143 return sprintf("['RGB',%.3F,%.3F,%.3F]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
9145 if (!in_array($color,$aColors)) {
9146 $this->Error('Invalid color: '.$color);
9148 return 'color.'.$color;
9152 * Adds a javascript form field.
9153 * @param string $type field type
9154 * @param string $name field name
9155 * @param int $x horizontal position
9156 * @param int $y vertical position
9157 * @param int $w width
9158 * @param int $h height
9159 * @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>
9161 * @author Denis Van Nuffelen, Nicola Asuni
9162 * @since 2.1.002 (2008-02-12)
9164 protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
9168 // the followind avoid fields duplication after saving the document
9169 $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
9171 $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";
9172 $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
9173 while (list($key, $val) = each($prop)) {
9174 if (strcmp(substr($key, -5), 'Color') == 0) {
9175 $val = $this->_JScolor($val);
9177 $val = "'".$val."'";
9179 $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
9186 $this->javascript .= '}';
9190 * Creates a text field
9191 * @param string $name field name
9192 * @param int $w width
9193 * @param int $h height
9194 * @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>
9196 * @author Denis Van Nuffelen, Nicola Asuni
9197 * @since 2.1.002 (2008-02-12)
9199 public function TextField($name, $w, $h, $prop=array()) {
9200 $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
9204 * Creates a RadioButton field
9205 * @param string $name field name
9206 * @param int $w width
9207 * @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>
9209 * @author Nicola Asuni
9210 * @since 2.2.003 (2008-03-03)
9212 public function RadioButton($name, $w, $prop=array()) {
9213 if (!isset($prop['strokeColor'])) {
9214 $prop['strokeColor']='black';
9216 $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
9220 * Creates a List-box field
9221 * @param string $name field name
9222 * @param int $w width
9223 * @param int $h height
9224 * @param array $values array containing the list of values.
9225 * @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>
9227 * @author Nicola Asuni
9228 * @since 2.2.003 (2008-03-03)
9230 public function ListBox($name, $w, $h, $values, $prop=array()) {
9231 if (!isset($prop['strokeColor'])) {
9232 $prop['strokeColor'] = 'ltGray';
9234 $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
9236 foreach ($values as $value) {
9237 $s .= "'".addslashes($value)."',";
9239 $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
9243 * Creates a Combo-box field
9244 * @param string $name field name
9245 * @param int $w width
9246 * @param int $h height
9247 * @param array $values array containing the list of values.
9248 * @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>
9250 * @author Denis Van Nuffelen, Nicola Asuni
9251 * @since 2.1.002 (2008-02-12)
9253 public function ComboBox($name, $w, $h, $values, $prop=array()) {
9254 $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
9256 foreach ($values as $value) {
9257 $s .= "'".addslashes($value)."',";
9259 $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
9263 * Creates a CheckBox field
9264 * @param string $name field name
9265 * @param int $w width
9266 * @param boolean $checked define the initial state (default = false).
9267 * @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>
9269 * @author Denis Van Nuffelen, Nicola Asuni
9270 * @since 2.1.002 (2008-02-12)
9272 public function CheckBox($name, $w, $checked=false, $prop=array()) {
9273 $prop['value'] = ($checked ? 'Yes' : 'Off');
9274 if (!isset($prop['strokeColor'])) {
9275 $prop['strokeColor'] = 'black';
9277 $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
9281 * Creates a button field
9282 * @param string $name field name
9283 * @param int $w width
9284 * @param int $h height
9285 * @param string $caption caption.
9286 * @param string $action action triggered by the button (JavaScript code).
9287 * @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>
9289 * @author Denis Van Nuffelen, Nicola Asuni
9290 * @since 2.1.002 (2008-02-12)
9292 public function Button($name, $w, $h, $caption, $action, $prop=array()) {
9293 if (!isset($prop['strokeColor'])) {
9294 $prop['strokeColor'] = 'black';
9296 if (!isset($prop['borderStyle'])) {
9297 $prop['borderStyle'] = 'beveled';
9299 $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
9300 $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
9301 $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
9302 $this->javascript .= 'f'.$name.".highlight='push';\n";
9303 $this->javascript .= 'f'.$name.".print=false;\n";
9306 // END JAVASCRIPT - FORMS ------------------------------
9309 * Enable Write permissions for PDF Reader.
9310 * WARNING: This works only using the Adobe private key with the setSignature() method.
9312 * @author Nicola Asuni
9313 * @since 2.9.000 (2008-03-26)
9315 protected function _putuserrights() {
9316 if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] > 0))) {
9319 $this->_out('/Perms');
9321 $this->_out('/UR3');
9323 $this->_out('/Type/Sig');
9324 $this->_out('/Filter/Adobe.PPKLite');
9325 $this->_out('/SubFilter/adbe.pkcs7.detached');
9326 $this->_out('/ByteRange[0 ********** ********** **********]');
9327 $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
9329 $this->_out('/Reference');
9332 $this->_out('/Type/SigRef');
9333 $this->_out('/TransformMethod/UR3');
9334 $this->_out('/TransformParams');
9336 $this->_out('/Type/TransformParams');
9337 $this->_out('/V/2.2');
9338 if (!$this->empty_string($this->ur_document)) {
9339 $this->_out('/Document['.$this->ur_document.']');
9341 if (!$this->empty_string($this->ur_annots)) {
9342 $this->_out('/Annots['.$this->ur_annots.']');
9344 if (!$this->empty_string($this->ur_form)) {
9345 $this->_out('/Form['.$this->ur_form.']');
9347 if (!$this->empty_string($this->ur_signature)) {
9348 $this->_out('/Signature['.$this->ur_signature.']');
9354 $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
9360 * Add certification signature (DocMDP)
9362 * @author Nicola Asuni
9363 * @since 4.6.008 (2009-05-07)
9365 protected function _putcertification() {
9366 if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] <= 0))) {
9369 $this->_out('/Perms');
9371 $this->_out('/DocMDP');
9373 $this->_out('/Type/Sig');
9374 $this->_out('/Filter/Adobe.PPKLite');
9375 $this->_out('/SubFilter/adbe.pkcs7.detached');
9376 $this->_out('/ByteRange[0 ********** ********** **********]');
9377 $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
9378 $this->_out('/Reference');
9381 $this->_out('/Type/SigRef');
9382 $this->_out('/TransformMethod/DocMDP');
9383 $this->_out('/TransformParams');
9385 $this->_out('/Type/TransformParams');
9386 $this->_out('/V/1.2');
9387 $this->_out('/P '.$this->signature_data['cert_type'].'');
9391 $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
9392 if (isset($this->signature_data['info']['Name']) AND !$this->empty_string($this->signature_data['info']['Name'])) {
9393 $this->_out('/Name '.$this->_textstring($this->signature_data['info']['Name']).'');
9395 if (isset($this->signature_data['info']['Location']) AND !$this->empty_string($this->signature_data['info']['Location'])) {
9396 $this->_out('/Location '.$this->_textstring($this->signature_data['info']['Location']).'');
9398 if (isset($this->signature_data['info']['Reason']) AND !$this->empty_string($this->signature_data['info']['Reason'])) {
9399 $this->_out('/Reason '.$this->_textstring($this->signature_data['info']['Reason']).'');
9401 if (isset($this->signature_data['info']['ContactInfo']) AND !$this->empty_string($this->signature_data['info']['ContactInfo'])) {
9402 $this->_out('/ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo']).'');
9409 * Set User's Rights for PDF Reader
9410 * WARNING: This works only using the Adobe private key with the setSignature() method!.
9411 * Check the PDF Reference 8.7.1 Transform Methods,
9412 * Table 8.105 Entries in the UR transform parameters dictionary
9413 * @param boolean $enable if true enable user's rights on PDF reader
9414 * @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.
9415 * @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.
9416 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
9417 * @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.
9419 * @author Nicola Asuni
9420 * @since 2.9.000 (2008-03-26)
9422 public function setUserRights(
9424 $document='/FullSave',
9425 $annots='/Create/Delete/Modify/Copy/Import/Export',
9426 $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
9427 $signature='/Modify') {
9428 $this->ur = $enable;
9429 $this->ur_document = $document;
9430 $this->ur_annots = $annots;
9431 $this->ur_form = $form;
9432 $this->ur_signature = $signature;
9436 * Enable document signature (requires the OpenSSL Library).
9437 * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
9438 * @param mixed $signing_cert signing certificate (string or filename prefixed with 'file://')
9439 * @param mixed $private_key private key (string or filename prefixed with 'file://')
9440 * @param string $private_key_password password
9441 * @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.
9442 * @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.
9443 * @parm array $info array of option information: Name, Location, Reason, ContactInfo.
9445 * @author Nicola Asuni
9446 * @since 4.6.005 (2009-04-24)
9448 public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array()) {
9449 // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.pem -out tcpdf.pem
9451 $this->signature_data = array();
9452 if (strlen($signing_cert) == 0) {
9453 $signing_cert = 'file://'.dirname(__FILE__).'/tcpdf.pem';
9455 if (strlen($private_key) == 0) {
9456 $private_key = $signing_cert;
9458 $this->signature_data['signcert'] = $signing_cert;
9459 $this->signature_data['privkey'] = $private_key;
9460 $this->signature_data['password'] = $private_key_password;
9461 $this->signature_data['extracerts'] = $extracerts;
9462 $this->signature_data['cert_type'] = $cert_type;
9463 $this->signature_data['info'] = array();
9467 * Create a new page group.
9468 * NOTE: call this function before calling AddPage()
9469 * @param int $page starting group page (leave empty for next page).
9471 * @since 3.0.000 (2008-03-27)
9473 public function startPageGroup($page='') {
9475 $page = $this->page + 1;
9477 $this->newpagegroup[$page] = true;
9481 * Defines an alias for the total number of pages.
9482 * It will be substituted as the document is closed.
9483 * @param string $alias The alias.
9486 * @see getAliasNbPages(), PageNo(), Footer()
9488 public function AliasNbPages($alias='{nb}') {
9489 $this->AliasNbPages = $alias;
9493 * Returns the string alias used for the total number of pages.
9494 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9497 * @since 4.0.018 (2008-08-08)
9498 * @see AliasNbPages(), PageNo(), Footer()
9500 public function getAliasNbPages() {
9501 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9502 return '{'.$this->AliasNbPages.'}';
9504 return $this->AliasNbPages;
9508 * Defines an alias for the page number.
9509 * It will be substituted as the document is closed.
9510 * @param string $alias The alias.
9512 * @since 4.5.000 (2009-01-02)
9513 * @see getAliasNbPages(), PageNo(), Footer()
9515 public function AliasNumPage($alias='{pnb}') {
9516 //Define an alias for total number of pages
9517 $this->AliasNumPage = $alias;
9521 * Returns the string alias used for the page number.
9522 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9525 * @since 4.5.000 (2009-01-02)
9526 * @see AliasNbPages(), PageNo(), Footer()
9528 public function getAliasNumPage() {
9529 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9530 return '{'.$this->AliasNumPage.'}';
9532 return $this->AliasNumPage;
9536 * Return the current page in the group.
9537 * @return current page in the group
9539 * @since 3.0.000 (2008-03-27)
9541 public function getGroupPageNo() {
9542 return $this->pagegroups[$this->currpagegroup];
9546 * Returns the current group page number formatted as a string.
9548 * @since 4.3.003 (2008-11-18)
9549 * @see PaneNo(), formatPageNumber()
9551 public function getGroupPageNoFormatted() {
9552 return $this->formatPageNumber($this->getGroupPageNo());
9556 * Return the alias of the current page group
9557 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9558 * (will be replaced by the total number of pages in this group).
9559 * @return alias of the current page group
9561 * @since 3.0.000 (2008-03-27)
9563 public function getPageGroupAlias() {
9564 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9565 return '{'.$this->currpagegroup.'}';
9567 return $this->currpagegroup;
9571 * Return the alias for the page number on the current page group
9572 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9573 * (will be replaced by the total number of pages in this group).
9574 * @return alias of the current page group
9576 * @since 4.5.000 (2009-01-02)
9578 public function getPageNumGroupAlias() {
9579 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9580 return '{'.str_replace('{nb', '{pnb', $this->currpagegroup).'}';
9582 return str_replace('{nb', '{pnb', $this->currpagegroup);
9586 * Format the page numbers.
9587 * This method can be overriden for custom formats.
9588 * @param int $num page number
9590 * @since 4.2.005 (2008-11-06)
9592 protected function formatPageNumber($num) {
9593 return number_format((float)$num, 0, '', '.');
9597 * Format the page numbers on the Table Of Content.
9598 * This method can be overriden for custom formats.
9599 * @param int $num page number
9601 * @since 4.5.001 (2009-01-04)
9604 protected function formatTOCPageNumber($num) {
9605 return number_format((float)$num, 0, '', '.');
9609 * Returns the current page number formatted as a string.
9611 * @since 4.2.005 (2008-11-06)
9612 * @see PaneNo(), formatPageNumber()
9614 public function PageNoFormatted() {
9615 return $this->formatPageNumber($this->PageNo());
9619 * Put visibility settings.
9621 * @since 3.0.000 (2008-03-27)
9623 protected function _putocg() {
9625 $this->n_ocg_print = $this->n;
9626 $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
9627 $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
9628 $this->_out('endobj');
9630 $this->n_ocg_view=$this->n;
9631 $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
9632 $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
9633 $this->_out('endobj');
9637 * Set the visibility of the successive elements.
9638 * This can be useful, for instance, to put a background
9639 * image or color that will show on screen but won't print.
9640 * @param string $v visibility mode. Legal values are: all, print, screen.
9642 * @since 3.0.000 (2008-03-27)
9644 public function setVisibility($v) {
9645 if ($this->openMarkedContent) {
9646 // close existing open marked-content
9648 $this->openMarkedContent = false;
9652 $this->_out('/OC /OC1 BDC');
9653 $this->openMarkedContent = true;
9657 $this->_out('/OC /OC2 BDC');
9658 $this->openMarkedContent = true;
9666 $this->Error('Incorrect visibility: '.$v);
9670 $this->visibility = $v;
9674 * Add transparency parameters to the current extgstate
9675 * @param array $params parameters
9676 * @return the number of extgstates
9678 * @since 3.0.000 (2008-03-27)
9680 protected function addExtGState($parms) {
9681 $n = count($this->extgstates) + 1;
9682 $this->extgstates[$n]['parms'] = $parms;
9688 * @param array $gs extgstate
9690 * @since 3.0.000 (2008-03-27)
9692 protected function setExtGState($gs) {
9693 $this->_out(sprintf('/GS%d gs', $gs));
9697 * Put extgstates for object transparency
9698 * @param array $gs extgstate
9700 * @since 3.0.000 (2008-03-27)
9702 protected function _putextgstates() {
9703 $ne = count($this->extgstates);
9704 for ($i = 1; $i <= $ne; ++$i) {
9706 $this->extgstates[$i]['n'] = $this->n;
9707 $this->_out('<</Type /ExtGState');
9708 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
9709 $this->_out('/'.$k.' '.$v);
9712 $this->_out('endobj');
9717 * Set alpha for stroking (CA) and non-stroking (ca) operations.
9718 * @param float $alpha real value from 0 (transparent) to 1 (opaque)
9719 * @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
9721 * @since 3.0.000 (2008-03-27)
9723 public function setAlpha($alpha, $bm='Normal') {
9724 $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
9725 $this->setExtGState($gs);
9729 * Set the default JPEG compression quality (1-100)
9730 * @param int $quality JPEG quality, integer between 1 and 100
9732 * @since 3.0.000 (2008-03-27)
9734 public function setJPEGQuality($quality) {
9735 if (($quality < 1) OR ($quality > 100)) {
9738 $this->jpeg_quality = intval($quality);
9742 * Set the default number of columns in a row for HTML tables.
9743 * @param int $cols number of columns
9745 * @since 3.0.014 (2008-06-04)
9747 public function setDefaultTableColumns($cols=4) {
9748 $this->default_table_columns = intval($cols);
9752 * Set the height of cell repect font height.
9753 * @param int $h cell proportion respect font height (typical value = 1.25).
9755 * @since 3.0.014 (2008-06-04)
9757 public function setCellHeightRatio($h) {
9758 $this->cell_height_ratio = $h;
9762 * return the height of cell repect font height.
9764 * @since 4.0.012 (2008-07-24)
9766 public function getCellHeightRatio() {
9767 return $this->cell_height_ratio;
9771 * Set the PDF version (check PDF reference for valid values).
9772 * Default value is 1.t
9774 * @since 3.1.000 (2008-06-09)
9776 public function setPDFVersion($version='1.7') {
9777 $this->PDFVersion = $version;
9781 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
9782 * (see Section 8.1 of PDF reference, "Viewer Preferences").
9784 * <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>
9785 * <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>
9786 * <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>
9787 * <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>
9788 * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
9789 * <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>
9790 * <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>
9791 * <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>
9792 * <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>
9793 * <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>
9794 * <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>
9795 * <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>
9796 * <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>
9797 * <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>
9798 * <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>
9799 * <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>
9801 * @param array $preferences array of options.
9802 * @author Nicola Asuni
9804 * @since 3.1.000 (2008-06-09)
9806 public function setViewerPreferences($preferences) {
9807 $this->viewer_preferences = $preferences;
9811 * Paints a linear colour gradient.
9812 * @param float $x abscissa of the top left corner of the rectangle.
9813 * @param float $y ordinate of the top left corner of the rectangle.
9814 * @param float $w width of the rectangle.
9815 * @param float $h height of the rectangle.
9816 * @param array $col1 first color (RGB components).
9817 * @param array $col2 second color (RGB components).
9818 * @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).
9819 * @author Andreas W�rmser, Nicola Asuni
9820 * @since 3.1.000 (2008-06-09)
9823 public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
9824 $this->Clip($x, $y, $w, $h);
9825 $this->Gradient(2, $col1, $col2, $coords);
9829 * Paints a radial colour gradient.
9830 * @param float $x abscissa of the top left corner of the rectangle.
9831 * @param float $y ordinate of the top left corner of the rectangle.
9832 * @param float $w width of the rectangle.
9833 * @param float $h height of the rectangle.
9834 * @param array $col1 first color (RGB components).
9835 * @param array $col2 second color (RGB components).
9836 * @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.
9837 * @author Andreas W�rmser, Nicola Asuni
9838 * @since 3.1.000 (2008-06-09)
9841 public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
9842 $this->Clip($x, $y, $w, $h);
9843 $this->Gradient(3, $col1, $col2, $coords);
9847 * Paints a coons patch mesh.
9848 * @param float $x abscissa of the top left corner of the rectangle.
9849 * @param float $y ordinate of the top left corner of the rectangle.
9850 * @param float $w width of the rectangle.
9851 * @param float $h height of the rectangle.
9852 * @param array $col1 first color (lower left corner) (RGB components).
9853 * @param array $col2 second color (lower right corner) (RGB components).
9854 * @param array $col3 third color (upper right corner) (RGB components).
9855 * @param array $col4 fourth color (upper left corner) (RGB components).
9856 * @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>
9857 * @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
9858 * @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
9859 * @author Andreas W�rmser, Nicola Asuni
9860 * @since 3.1.000 (2008-06-09)
9863 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) {
9864 $this->Clip($x, $y, $w, $h);
9865 $n = count($this->gradients) + 1;
9866 $this->gradients[$n]['type'] = 6; //coons patch mesh
9867 //check the coords array if it is the simple array or the multi patch array
9868 if (!isset($coords[0]['f'])) {
9869 //simple array -> convert to multi patch array
9870 if (!isset($col1[1])) {
9871 $col1[1] = $col1[2] = $col1[0];
9873 if (!isset($col2[1])) {
9874 $col2[1] = $col2[2] = $col2[0];
9876 if (!isset($col3[1])) {
9877 $col3[1] = $col3[2] = $col3[0];
9879 if (!isset($col4[1])) {
9880 $col4[1] = $col4[2] = $col4[0];
9882 $patch_array[0]['f'] = 0;
9883 $patch_array[0]['points'] = $coords;
9884 $patch_array[0]['colors'][0]['r'] = $col1[0];
9885 $patch_array[0]['colors'][0]['g'] = $col1[1];
9886 $patch_array[0]['colors'][0]['b'] = $col1[2];
9887 $patch_array[0]['colors'][1]['r'] = $col2[0];
9888 $patch_array[0]['colors'][1]['g'] = $col2[1];
9889 $patch_array[0]['colors'][1]['b'] = $col2[2];
9890 $patch_array[0]['colors'][2]['r'] = $col3[0];
9891 $patch_array[0]['colors'][2]['g'] = $col3[1];
9892 $patch_array[0]['colors'][2]['b'] = $col3[2];
9893 $patch_array[0]['colors'][3]['r'] = $col4[0];
9894 $patch_array[0]['colors'][3]['g'] = $col4[1];
9895 $patch_array[0]['colors'][3]['b'] = $col4[2];
9898 $patch_array = $coords;
9900 $bpcd = 65535; //16 BitsPerCoordinate
9901 //build the data stream
9902 $this->gradients[$n]['stream'] = '';
9903 $count_patch = count($patch_array);
9904 for ($i=0; $i < $count_patch; ++$i) {
9905 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
9906 $count_points = count($patch_array[$i]['points']);
9907 for ($j=0; $j < $count_points; ++$j) {
9908 //each point as 16 bit
9909 $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
9910 if ($patch_array[$i]['points'][$j] < 0) {
9911 $patch_array[$i]['points'][$j] = 0;
9913 if ($patch_array[$i]['points'][$j] > $bpcd) {
9914 $patch_array[$i]['points'][$j] = $bpcd;
9916 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
9917 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
9919 $count_cols = count($patch_array[$i]['colors']);
9920 for ($j=0; $j < $count_cols; ++$j) {
9921 //each color component as 8 bit
9922 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
9923 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
9924 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
9927 //paint the gradient
9928 $this->_out('/Sh'.$n.' sh');
9929 //restore previous Graphic State
9934 * Set a rectangular clipping area.
9935 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
9936 * @param float $y ordinate of the top left corner of the rectangle.
9937 * @param float $w width of the rectangle.
9938 * @param float $h height of the rectangle.
9939 * @author Andreas W�rmser, Nicola Asuni
9940 * @since 3.1.000 (2008-06-09)
9943 protected function Clip($x, $y, $w, $h) {
9945 $x = $this->w - $x - $w;
9947 //save current Graphic State
9950 $s .= sprintf(' %.2F %.2F %.2F %.2F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
9951 //set up transformation matrix for gradient
9952 $s .= sprintf(' %.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
9958 * @param int $type type of gradient.
9959 * @param array $col1 first color (RGB components).
9960 * @param array $col2 second color (RGB components).
9961 * @param array $coords array of coordinates.
9962 * @author Andreas W�rmser, Nicola Asuni
9963 * @since 3.1.000 (2008-06-09)
9966 protected function Gradient($type, $col1, $col2, $coords) {
9967 $n = count($this->gradients) + 1;
9968 $this->gradients[$n]['type'] = $type;
9969 if (!isset($col1[1])) {
9970 $col1[1]=$col1[2]=$col1[0];
9972 $this->gradients[$n]['col1'] = sprintf('%.3F %.3F %.3F', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
9973 if (!isset($col2[1])) {
9974 $col2[1] = $col2[2] = $col2[0];
9976 $this->gradients[$n]['col2'] = sprintf('%.3F %.3F %.3F', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
9977 $this->gradients[$n]['coords'] = $coords;
9978 //paint the gradient
9979 $this->_out('/Sh'.$n.' sh');
9980 //restore previous Graphic State
9986 * @author Andreas W�rmser, Nicola Asuni
9987 * @since 3.1.000 (2008-06-09)
9990 function _putshaders() {
9991 foreach ($this->gradients as $id => $grad) {
9992 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
9995 $this->_out('/FunctionType 2');
9996 $this->_out('/Domain [0.0 1.0]');
9997 $this->_out('/C0 ['.$grad['col1'].']');
9998 $this->_out('/C1 ['.$grad['col2'].']');
9999 $this->_out('/N 1');
10001 $this->_out('endobj');
10006 $this->_out('/ShadingType '.$grad['type']);
10007 $this->_out('/ColorSpace /DeviceRGB');
10008 if ($grad['type'] == 2) {
10009 $this->_out(sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
10010 $this->_out('/Function '.$f1.' 0 R');
10011 $this->_out('/Extend [true true] ');
10013 } elseif ($grad['type'] == 3) {
10014 //x0, y0, r0, x1, y1, r1
10015 //at this this time radius of inner circle is 0
10016 $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]));
10017 $this->_out('/Function '.$f1.' 0 R');
10018 $this->_out('/Extend [true true] ');
10020 } elseif ($grad['type'] == 6) {
10021 $this->_out('/BitsPerCoordinate 16');
10022 $this->_out('/BitsPerComponent 8');
10023 $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
10024 $this->_out('/BitsPerFlag 8');
10025 $this->_out('/Length '.strlen($grad['stream']));
10027 $this->_putstream($grad['stream']);
10029 $this->_out('endobj');
10030 $this->gradients[$id]['id'] = $this->n;
10036 * @author Maxime Delorme, Nicola Asuni
10037 * @since 3.1.000 (2008-06-09)
10038 * @access protected
10040 protected function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
10042 $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));
10046 * Draw the sector of a circle.
10047 * It can be used for instance to render pie charts.
10048 * @param float $xc abscissa of the center.
10049 * @param float $yc ordinate of the center.
10050 * @param float $r radius.
10051 * @param float $a start angle (in degrees).
10052 * @param float $b end angle (in degrees).
10053 * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
10054 * @param float $cw: indicates whether to go clockwise (default: true).
10055 * @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.
10056 * @author Maxime Delorme, Nicola Asuni
10057 * @since 3.1.000 (2008-06-09)
10060 public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
10062 $xc = $this->w - $xc;
10072 $a = ($a % 360) + 360;
10073 $b = ($b % 360) + 360;
10077 $b = $b / 360 * 2 * M_PI;
10078 $a = $a / 360 * 2 * M_PI;
10087 } elseif ($style=='FD' or $style=='DF') {
10093 $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
10095 //first put the center
10096 $this->_out(sprintf('%.2F %.2F m', ($xc)*$k, ($hp-$yc)*$k));
10097 //put the first point
10098 $this->_out(sprintf('%.2F %.2F l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
10100 if ($d < (M_PI/2)) {
10101 $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));
10104 $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
10105 $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));
10108 $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));
10111 $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) );
10114 $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));
10116 //terminate drawing
10121 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
10122 * Only vector drawing is supported, not text or bitmap.
10123 * 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).
10124 * @param string $file Name of the file containing the image.
10125 * @param float $x Abscissa of the upper-left corner.
10126 * @param float $y Ordinate of the upper-left corner.
10127 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
10128 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
10129 * @param mixed $link URL or identifier returned by AddLink().
10130 * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
10131 * @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>
10132 * @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>
10133 * @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>
10134 * @author Valentin Schmidt, Nicola Asuni
10135 * @since 3.1.000 (2008-06-09)
10138 public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0) {
10146 $data = file_get_contents($file);
10147 if ($data === false) {
10148 $this->Error('EPS file not found: '.$file);
10151 // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
10152 preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
10153 if (count($regs) > 1) {
10154 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
10155 if (strpos($version_str, 'Adobe Illustrator') !== false) {
10156 $versexp = explode(' ', $version_str);
10157 $version = (float)array_pop($versexp);
10158 if ($version >= 9) {
10159 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
10163 // strip binary bytes in front of PS-header
10164 $start = strpos($data, '%!PS-Adobe');
10166 $data = substr($data, $start);
10168 // find BoundingBox params
10169 preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
10170 if (count($regs) > 1) {
10171 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
10173 $this->Error('No BoundingBox found in EPS file: '.$file);
10175 $start = strpos($data, '%%EndSetup');
10176 if ($start === false) {
10177 $start = strpos($data, '%%EndProlog');
10179 if ($start === false) {
10180 $start = strpos($data, '%%BoundingBox');
10182 $data = substr($data, $start);
10183 $end = strpos($data, '%%PageTrailer');
10184 if ($end===false) {
10185 $end = strpos($data, 'showpage');
10188 $data = substr($data, 0, $end);
10191 $scale_x = $w / (($x2 - $x1) / $k);
10193 $scale_y = $h / (($y2 - $y1) / $k);
10195 $scale_y = $scale_x;
10196 $h = ($y2 - $y1) / $k * $scale_y;
10200 $scale_y = $h / (($y2 - $y1) / $k);
10201 $scale_x = $scale_y;
10202 $w = ($x2-$x1) / $k * $scale_x;
10204 $w = ($x2 - $x1) / $k;
10205 $h = ($y2 - $y1) / $k;
10208 // Check whether we need a new page first as this does not fit
10209 if ($this->checkPageBreak($h, $y)) {
10210 $y = $this->GetY() + $this->cMargin;
10212 // set bottomcoordinates
10213 $this->img_rb_y = $y + $h;
10216 if ($palign == 'L') {
10217 $ximg = $this->lMargin;
10218 // set right side coordinate
10219 $this->img_rb_x = $ximg + $w;
10220 } elseif ($palign == 'C') {
10221 $ximg = ($this->w - $x - $w) / 2;
10222 // set right side coordinate
10223 $this->img_rb_x = $ximg + $w;
10225 $ximg = $this->w - $x - $w;
10226 // set left side coordinate
10227 $this->img_rb_x = $ximg;
10230 if ($palign == 'R') {
10231 $ximg = $this->w - $this->rMargin - $w;
10232 // set left side coordinate
10233 $this->img_rb_x = $ximg;
10234 } elseif ($palign == 'C') {
10235 $ximg = ($this->w - $x - $w) / 2;
10236 // set right side coordinate
10237 $this->img_rb_x = $ximg + $w;
10240 // set right side coordinate
10241 $this->img_rb_x = $ximg + $w;
10244 if ($useBoundingBox) {
10245 $dx = $ximg * $k - $x1;
10246 $dy = $y * $k - $y1;
10251 // save the current graphic state
10252 $this->_out('q'.$this->epsmarker);
10254 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
10256 if (isset($scale_x)) {
10257 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
10259 // handle pc/unix/mac line endings
10260 preg_match('/[\r\n]+/s', $data, $regs);
10261 $lines = explode($regs[0], $data);
10263 $cnt = count($lines);
10264 for ($i=0; $i < $cnt; ++$i) {
10265 $line = $lines[$i];
10266 if (($line == '') OR ($line{0} == '%')) {
10269 $len = strlen($line);
10270 $chunks = explode(' ', $line);
10271 $cmd = array_pop($chunks);
10273 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
10274 $b = array_pop($chunks);
10275 $g = array_pop($chunks);
10276 $r = array_pop($chunks);
10277 $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!
10299 $this->_out($line);
10302 case 'x': {// custom fill color
10303 list($c,$m,$y,$k) = $chunks;
10304 $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' k');
10307 case 'X': { // custom stroke color
10308 list($c,$m,$y,$k) = $chunks;
10309 $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' K');
10317 $line{$len-1} = strtolower($cmd);
10318 $this->_out($line);
10323 $this->_out($cmd . '*');
10330 $max = min($i+5, $cnt);
10331 for ($j=$i+1; $j < $max; ++$j)
10332 $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
10351 // restore previous graphic state
10352 $this->_out($this->epsmarker.'Q');
10353 if (!empty($border)) {
10358 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
10363 $this->Link($ximg, $y, $w, $h, $link, 0);
10365 // set pointer to align the successive text/objects
10369 $this->x = $this->img_rb_x;
10373 $this->y = $y + round($h/2);
10374 $this->x = $this->img_rb_x;
10378 $this->y = $this->img_rb_y;
10379 $this->x = $this->img_rb_x;
10383 $this->SetY($this->img_rb_y);
10390 $this->endlinex = $this->img_rb_x;
10394 * Set document barcode.
10395 * @param string $bc barcode
10398 public function setBarcode($bc='') {
10399 $this->barcode = $bc;
10403 * Get current barcode.
10406 * @since 4.0.012 (2008-07-24)
10408 public function getBarcode() {
10409 return $this->barcode;
10413 * Print a Linear Barcode.
10414 * @param string $code code to print
10415 * @param string $type type of barcode.
10416 * @param int $x x position in user units
10417 * @param int $y y position in user units
10418 * @param int $w width in user units
10419 * @param int $h height in user units
10420 * @param float $xres width of the smallest bar in user units
10421 * @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>
10422 * @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>
10423 * @author Nicola Asuni
10424 * @since 3.1.000 (2008-06-09)
10427 public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
10428 if ($this->empty_string($code)) {
10431 require_once(dirname(__FILE__).'/barcodes.php');
10432 // save current graphic settings
10433 $gvars = $this->getGraphicVars();
10434 // create new barcode object
10435 $barcodeobj = new TCPDFBarcode($code, $type);
10436 $arrcode = $barcodeobj->getBarcodeArray();
10437 if ($arrcode === false) {
10438 $this->Error('Error in 1D barcode string');
10440 // set default values
10441 if (!isset($style['position'])) {
10443 $style['position'] = 'R';
10445 $style['position'] = 'L';
10448 if (!isset($style['padding'])) {
10449 $style['padding'] = 0;
10451 if (!isset($style['fgcolor'])) {
10452 $style['fgcolor'] = array(0,0,0); // default black
10454 if (!isset($style['bgcolor'])) {
10455 $style['bgcolor'] = false; // default transparent
10457 if (!isset($style['border'])) {
10458 $style['border'] = false;
10460 if (!isset($style['text'])) {
10461 $style['text'] = false;
10464 if ($style['text'] AND isset($style['font'])) {
10465 if (isset($style['fontsize'])) {
10466 $fontsize = $style['fontsize'];
10470 $this->SetFont($style['font'], '', $fontsize);
10472 if (!isset($style['stretchtext'])) {
10473 $style['stretchtext'] = 4;
10475 // set foreground color
10476 $this->SetDrawColorArray($style['fgcolor']);
10477 $this->SetTextColorArray($style['fgcolor']);
10478 if ($this->empty_string($w) OR ($w <= 0)) {
10480 $w = $this->x - $this->lMargin;
10482 $w = $this->w - $this->rMargin - $this->x;
10485 if ($this->empty_string($x)) {
10486 $x = $this->GetX();
10489 $x = $this->w - $x;
10491 if ($this->empty_string($y)) {
10492 $y = $this->GetY();
10494 if ($this->empty_string($xres)) {
10497 $fbw = ($arrcode['maxw'] * $xres) + (2 * $style['padding']);
10498 $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style['padding']);
10499 if ($this->empty_string($h) OR ($h <= 0)) {
10500 $h = 10 + $extraspace;
10502 if ($this->checkPageBreak($h)) {
10505 // maximum bar heigth
10506 $barh = $h - $extraspace;
10507 switch ($style['position']) {
10508 case 'L': { // left
10516 case 'C': { // center
10517 $xdiff = (($w - $fbw) / 2);
10519 $xpos = $x - $w + $xdiff;
10521 $xpos = $x + $xdiff;
10525 case 'R': { // right
10529 $xpos = $x + $w - $fbw;
10533 case 'S': { // stretch
10535 $xres = ($w - (2 * $style['padding'])) / $arrcode['maxw'];
10544 $xpos_rect = $xpos;
10545 $xpos = $xpos_rect + $style['padding'];
10546 $xpos_text = $xpos;
10547 // barcode is always printed in LTR direction
10548 $tempRTL = $this->rtl;
10549 $this->rtl = false;
10550 // print background color
10551 if ($style['bgcolor']) {
10552 $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style['bgcolor']);
10553 } elseif ($style['border']) {
10554 $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
10557 if ($arrcode !== false) {
10558 foreach ($arrcode['bcode'] as $k => $v) {
10559 $bw = ($v['w'] * $xres);
10561 // draw a vertical bar
10562 $ypos = $y + $style['padding'] + ($v['p'] * $barh / $arrcode['maxh']);
10563 $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
10569 if ($style['text']) {
10571 $this->x = $xpos_text;
10572 $this->y = $y + $style['padding'] + $barh;
10573 $this->Cell(($arrcode['maxw'] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style['stretchtext']);
10575 // restore original direction
10576 $this->rtl = $tempRTL;
10577 // restore previous settings
10578 $this->setGraphicVars($gvars);
10579 // set bottomcoordinates
10580 $this->img_rb_y = $y + $h;
10582 // set left side coordinate
10583 $this->img_rb_x = ($this->w - $x - $w);
10585 // set right side coordinate
10586 $this->img_rb_x = $x + $w;
10588 // set pointer to align the successive text/objects
10592 $this->x = $this->img_rb_x;
10596 $this->y = $y + round($h/2);
10597 $this->x = $this->img_rb_x;
10601 $this->y = $this->img_rb_y;
10602 $this->x = $this->img_rb_x;
10606 $this->SetY($this->img_rb_y);
10616 * This function is DEPRECATED, please use the new write1DBarcode() function.
10617 * @param int $x x position in user units
10618 * @param int $y y position in user units
10619 * @param int $w width in user units
10620 * @param int $h height position in user units
10621 * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
10622 * @param string $style barcode style
10623 * @param string $font font for text
10624 * @param int $xres x resolution
10625 * @param string $code code to print
10626 * @deprecated deprecated since version 3.1.000 (2008-06-10)
10628 * @see write1DBarcode()
10630 public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
10631 // convert old settings for the new write1DBarcode() function.
10637 'fgcolor' => array(0,0,0),
10638 'bgcolor' => false,
10645 $newstyle['border'] = true;
10648 $newstyle['bgcolor'] = false;
10651 $newstyle['position'] = 'C';
10652 } elseif ($style & 8) {
10653 $newstyle['position'] = 'L';
10654 } elseif ($style & 16) {
10655 $newstyle['position'] = 'R';
10657 if ($style & 128) {
10658 $newstyle['text'] = true;
10660 if ($style & 256) {
10661 $newstyle['stretchtext'] = 4;
10663 $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
10667 * Print 2D Barcode.
10668 * @param string $code code to print
10669 * @param string $type type of barcode.
10670 * @param int $x x position in user units
10671 * @param int $y y position in user units
10672 * @param int $w width in user units
10673 * @param int $h height in user units
10674 * @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>
10675 * @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>
10676 * @author Nicola Asuni
10677 * @since 4.5.037 (2009-04-07)
10680 public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='') {
10681 if ($this->empty_string($code)) {
10684 require_once(dirname(__FILE__).'/2dbarcodes.php');
10685 // save current graphic settings
10686 $gvars = $this->getGraphicVars();
10687 // create new barcode object
10688 $barcodeobj = new TCPDF2DBarcode($code, $type);
10689 $arrcode = $barcodeobj->getBarcodeArray();
10690 if ($arrcode === false) {
10691 $this->Error('Error in 2D barcode string');
10693 // set default values
10694 if (!isset($style['padding'])) {
10695 $style['padding'] = 0;
10697 if (!isset($style['fgcolor'])) {
10698 $style['fgcolor'] = array(0,0,0); // default black
10700 if (!isset($style['bgcolor'])) {
10701 $style['bgcolor'] = false; // default transparent
10703 if (!isset($style['border'])) {
10704 $style['border'] = false;
10706 // set foreground color
10707 $this->SetDrawColorArray($style['fgcolor']);
10708 if ($this->empty_string($x)) {
10709 $x = $this->GetX();
10712 $x = $this->w - $x;
10714 if ($this->empty_string($y)) {
10715 $y = $this->GetY();
10717 if ($this->empty_string($w) OR ($w <= 0)) {
10719 $w = $x - $this->lMargin;
10721 $w = $this->w - $this->rMargin - $x;
10724 if ($this->empty_string($h) OR ($h <= 0)) {
10725 // 2d barcodes are square by default
10728 if ($this->checkPageBreak($h)) {
10731 // calculate barcode size (excluding padding)
10732 $bw = $w - (2 * $style['padding']);
10733 $bh = $h - (2 * $style['padding']);
10734 // calculate starting coordinates
10740 $xpos += $style['padding'];
10741 $ypos = $y + $style['padding'];
10742 // barcode is always printed in LTR direction
10743 $tempRTL = $this->rtl;
10744 $this->rtl = false;
10745 // print background color
10746 if ($style['bgcolor']) {
10747 $this->Rect($x, $y, $w, $h, 'DF', '', $style['bgcolor']);
10748 } elseif ($style['border']) {
10749 $this->Rect($x, $y, $w, $h, 'D');
10751 // print barcode cells
10752 if ($arrcode !== false) {
10753 $rows = $arrcode['num_rows'];
10754 $cols = $arrcode['num_cols'];
10755 // calculate dimension of single barcode cell
10759 for ($r = 0; $r < $rows; ++$r) {
10762 for ($c = 0; $c < $cols; ++$c) {
10763 if ($arrcode['bcode'][$r][$c] == 1) {
10764 // draw a single barcode cell
10765 $this->Rect($xr, $ypos, $cw, $ch, 'F', array(), $style['fgcolor']);
10772 // restore original direction
10773 $this->rtl = $tempRTL;
10774 // restore previous settings
10775 $this->setGraphicVars($gvars);
10776 // set bottomcoordinates
10777 $this->img_rb_y = $y + $h;
10779 // set left side coordinate
10780 $this->img_rb_x = ($this->w - $x - $w);
10782 // set right side coordinate
10783 $this->img_rb_x = $x + $w;
10785 // set pointer to align the successive text/objects
10789 $this->x = $this->img_rb_x;
10793 $this->y = $y + round($h/2);
10794 $this->x = $this->img_rb_x;
10798 $this->y = $this->img_rb_y;
10799 $this->x = $this->img_rb_x;
10803 $this->SetY($this->img_rb_y);
10813 * Returns an array containing current margins:
10815 <li>$ret['left'] = left margin</li>
10816 <li>$ret['right'] = right margin</li>
10817 <li>$ret['top'] = top margin</li>
10818 <li>$ret['bottom'] = bottom margin</li>
10819 <li>$ret['header'] = header margin</li>
10820 <li>$ret['footer'] = footer margin</li>
10821 <li>$ret['cell'] = cell margin</li>
10823 * @return array containing all margins measures
10825 * @since 3.2.000 (2008-06-23)
10827 public function getMargins() {
10829 'left' => $this->lMargin,
10830 'right' => $this->rMargin,
10831 'top' => $this->tMargin,
10832 'bottom' => $this->bMargin,
10833 'header' => $this->header_margin,
10834 'footer' => $this->footer_margin,
10835 'cell' => $this->cMargin,
10841 * Returns an array containing original margins:
10843 <li>$ret['left'] = left margin</li>
10844 <li>$ret['right'] = right margin</li>
10846 * @return array containing all margins measures
10848 * @since 4.0.012 (2008-07-24)
10850 public function getOriginalMargins() {
10852 'left' => $this->original_lMargin,
10853 'right' => $this->original_rMargin
10859 * Returns the current font size.
10860 * @return current font size
10862 * @since 3.2.000 (2008-06-23)
10864 public function getFontSize() {
10865 return $this->FontSize;
10869 * Returns the current font size in points unit.
10870 * @return current font size in points unit
10872 * @since 3.2.000 (2008-06-23)
10874 public function getFontSizePt() {
10875 return $this->FontSizePt;
10879 * Returns the current font family name.
10880 * @return string current font family name
10882 * @since 4.3.008 (2008-12-05)
10884 public function getFontFamily() {
10885 return $this->FontFamily;
10889 * Returns the current font style.
10890 * @return string current font style
10892 * @since 4.3.008 (2008-12-05)
10894 public function getFontStyle() {
10895 return $this->FontStyle;
10899 * Prints a cell (rectangular area) with optional borders, background color and html text string.
10900 * 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 />
10901 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
10902 * @param float $w Cell width. If 0, the cell extends up to the right margin.
10903 * @param float $h Cell minimum height. The cell extends automatically if needed.
10904 * @param float $x upper-left corner X coordinate
10905 * @param float $y upper-left corner Y coordinate
10906 * @param string $html html text to print. Default value: empty string.
10907 * @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>
10908 * @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>
10909 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
10910 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
10911 * @param boolean $reseth if true reset the last cell height (default true).
10912 * @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>
10913 * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
10915 * @uses MultiCell()
10916 * @see Multicell(), writeHTML()
10918 public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true) {
10919 return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0);
10923 * Returns the HTML DOM array.
10924 * <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>
10925 * @param string $html html code
10927 * @access protected
10928 * @since 3.2.000 (2008-06-20)
10930 protected function getHtmlDomArray($html) {
10931 // remove all unsupported tags (the line below lists all supported tags)
10932 $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>');
10933 //replace some blank characters
10934 $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
10935 $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);
10936 $html = preg_replace('@(\r\n|\r)@', "\n", $html);
10937 $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
10938 $html = strtr($html, $repTable);
10939 while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html)) {
10940 // preserve newlines on <pre> tag
10941 $html = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html);
10943 $html = str_replace("\n", ' ', $html);
10944 // remove extra spaces from code
10945 $html = preg_replace('/[\s]+<\/(table|tr|td|th|ul|ol|li)>/', '</\\1>', $html);
10946 $html = preg_replace('/[\s]+<(tr|td|th|ul|ol|li|br)/', '<\\1', $html);
10947 $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);
10948 $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
10949 $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
10950 $html = preg_replace('/<img/', ' <img', $html);
10951 $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span></span>', $html);
10952 $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
10954 $html = preg_replace('/^[\s]+/', '', $html);
10955 $html = preg_replace('/[\s]+$/', '', $html);
10956 // pattern for generic tag
10957 $tagpattern = '/(<[^>]+>)/';
10958 // explodes the string
10959 $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
10961 $maxel = count($a);
10964 // create an array of elements
10966 $dom[$key] = array();
10967 // set first void element
10968 $dom[$key]['tag'] = false;
10969 $dom[$key]['value'] = '';
10970 $dom[$key]['parent'] = 0;
10971 $dom[$key]['fontname'] = $this->FontFamily;
10972 $dom[$key]['fontstyle'] = $this->FontStyle;
10973 $dom[$key]['fontsize'] = $this->FontSizePt;
10974 $dom[$key]['bgcolor'] = false;
10975 $dom[$key]['fgcolor'] = $this->fgcolor;
10976 $dom[$key]['align'] = '';
10977 $dom[$key]['listtype'] = '';
10978 $thead = false; // true when we are inside the THEAD tag
10981 array_push($level, 0); // root
10982 while ($elkey < $maxel) {
10983 $dom[$key] = array();
10984 $element = $a[$elkey];
10985 $dom[$key]['elkey'] = $elkey;
10986 if (preg_match($tagpattern, $element)) {
10988 $element = substr($element, 1, -1);
10990 preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
10991 $tagname = strtolower($tag[1]);
10992 // check if we are inside a table header
10993 if ($tagname == 'thead') {
10994 if ($element{0} == '/') {
11002 $dom[$key]['tag'] = true;
11003 $dom[$key]['value'] = $tagname;
11004 if ($element{0} == '/') {
11005 // closing html tag
11006 $dom[$key]['opening'] = false;
11007 $dom[$key]['parent'] = end($level);
11009 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
11010 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
11011 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
11012 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
11013 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
11014 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
11015 if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
11016 $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
11018 // set the number of columns in table tag
11019 if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
11020 $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
11022 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
11023 $dom[($dom[$key]['parent'])]['content'] = '';
11024 for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
11025 $dom[($dom[$key]['parent'])]['content'] .= $a[$dom[$i]['elkey']];
11029 // store header rows on a new table
11030 if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] == true)) {
11031 if ($this->empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
11032 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
11034 for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
11035 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
11038 if (($dom[$key]['value'] == 'table') AND (!$this->empty_string($dom[($dom[$key]['parent'])]['thead']))) {
11039 $dom[($dom[$key]['parent'])]['thead'] .= '</table>';
11042 // opening html tag
11043 $dom[$key]['opening'] = true;
11044 $dom[$key]['parent'] = end($level);
11045 if (substr($element, -1, 1) != '/') {
11046 // not self-closing tag
11047 array_push($level, $key);
11048 $dom[$key]['self'] = false;
11050 $dom[$key]['self'] = true;
11052 // copy some values from parent
11055 $parentkey = $dom[$key]['parent'];
11056 $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
11057 $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
11058 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
11059 $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
11060 $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
11061 $dom[$key]['align'] = $dom[$parentkey]['align'];
11062 $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
11065 preg_match_all('/([^=\s]*)=["]?([^"]*)["]?/', $element, $attr_array, PREG_PATTERN_ORDER);
11066 $dom[$key]['attribute'] = array(); // reset attribute array
11067 while (list($id, $name) = each($attr_array[1])) {
11068 $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
11070 // split style attributes
11071 if (isset($dom[$key]['attribute']['style'])) {
11072 // get style attributes
11073 preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
11074 $dom[$key]['style'] = array(); // reset style attribute array
11075 while (list($id, $name) = each($style_array[1])) {
11076 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
11078 // --- get some style attributes ---
11079 if (isset($dom[$key]['style']['font-family'])) {
11081 if (isset($dom[$key]['style']['font-family'])) {
11082 $fontslist = explode(',', strtolower($dom[$key]['style']['font-family']));
11083 foreach ($fontslist as $font) {
11084 $font = trim(strtolower($font));
11085 if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
11086 $dom[$key]['fontname'] = $font;
11093 if (isset($dom[$key]['style']['list-style-type'])) {
11094 $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
11095 if ($dom[$key]['listtype'] == 'inherit') {
11096 $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
11100 if (isset($dom[$key]['style']['font-size'])) {
11101 $fsize = trim($dom[$key]['style']['font-size']);
11105 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
11109 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
11113 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
11117 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
11121 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
11125 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
11129 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
11134 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] - 3;
11138 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] + 3;
11142 $dom[$key]['fontsize'] = $this->getHTMLUnitToUnits($fsize, $dom[$parentkey]['fontsize'], 'pt', true);
11147 if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == 'b')) {
11148 $dom[$key]['fontstyle'] .= 'B';
11150 if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == 'i')) {
11151 $dom[$key]['fontstyle'] .= '"I';
11154 if (isset($dom[$key]['style']['color']) AND (!$this->empty_string($dom[$key]['style']['color']))) {
11155 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
11157 // background color
11158 if (isset($dom[$key]['style']['background-color']) AND (!$this->empty_string($dom[$key]['style']['background-color']))) {
11159 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
11162 if (isset($dom[$key]['style']['text-decoration'])) {
11163 $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
11164 foreach ($decors as $dec) {
11166 if (!$this->empty_string($dec)) {
11167 if ($dec{0} == 'u') {
11168 $dom[$key]['fontstyle'] .= 'U';
11169 } elseif ($dec{0} == 'l') {
11170 $dom[$key]['fontstyle'] .= 'D';
11175 // check for width attribute
11176 if (isset($dom[$key]['style']['width'])) {
11177 $dom[$key]['width'] = $dom[$key]['style']['width'];
11179 // check for height attribute
11180 if (isset($dom[$key]['style']['height'])) {
11181 $dom[$key]['height'] = $dom[$key]['style']['height'];
11183 // check for text alignment
11184 if (isset($dom[$key]['style']['text-align'])) {
11185 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
11187 // check for border attribute
11188 if (isset($dom[$key]['style']['border'])) {
11189 $dom[$key]['attribute']['border'] = $dom[$key]['style']['border'];
11192 // check for font tag
11193 if ($dom[$key]['value'] == 'font') {
11195 if (isset($dom[$key]['attribute']['face'])) {
11196 $fontslist = explode(',', strtolower($dom[$key]['attribute']['face']));
11197 foreach ($fontslist as $font) {
11198 $font = trim(strtolower($font));
11199 if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
11200 $dom[$key]['fontname'] = $font;
11206 if (isset($dom[$key]['attribute']['size'])) {
11208 if ($dom[$key]['attribute']['size']{0} == '+') {
11209 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
11210 } elseif ($dom[$key]['attribute']['size']{0} == '-') {
11211 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
11213 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
11216 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
11220 // force natural alignment for lists
11221 if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
11222 AND (!isset($dom[$key]['align']) OR $this->empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
11224 $dom[$key]['align'] = 'R';
11226 $dom[$key]['align'] = 'L';
11229 if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
11230 $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
11232 if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
11233 $dom[$key]['fontstyle'] .= 'B';
11235 if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
11236 $dom[$key]['fontstyle'] .= 'I';
11238 if ($dom[$key]['value'] == 'u') {
11239 $dom[$key]['fontstyle'] .= 'U';
11241 if ($dom[$key]['value'] == 'del') {
11242 $dom[$key]['fontstyle'] .= 'D';
11244 if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
11245 $dom[$key]['fontname'] = $this->default_monospaced_font;
11247 if (($dom[$key]['value']{0} == 'h') AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
11248 $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
11249 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
11250 $dom[$key]['fontstyle'] .= 'B';
11252 if (($dom[$key]['value'] == 'table')) {
11253 $dom[$key]['rows'] = 0; // number of rows
11254 $dom[$key]['trids'] = array(); // IDs of TR elements
11255 $dom[$key]['thead'] = ''; // table header rows
11257 if (($dom[$key]['value'] == 'tr')) {
11258 $dom[$key]['cols'] = 0;
11259 // store the number of rows on table element
11260 ++$dom[($dom[$key]['parent'])]['rows'];
11261 // store the TR elements IDs on table element
11262 array_push($dom[($dom[$key]['parent'])]['trids'], $key);
11264 $dom[$key]['thead'] = true;
11266 $dom[$key]['thead'] = false;
11269 if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
11270 if (isset($dom[$key]['attribute']['colspan'])) {
11271 $colspan = intval($dom[$key]['attribute']['colspan']);
11275 $dom[$key]['attribute']['colspan'] = $colspan;
11276 $dom[($dom[$key]['parent'])]['cols'] += $colspan;
11278 // set foreground color attribute
11279 if (isset($dom[$key]['attribute']['color']) AND (!$this->empty_string($dom[$key]['attribute']['color']))) {
11280 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
11282 // set background color attribute
11283 if (isset($dom[$key]['attribute']['bgcolor']) AND (!$this->empty_string($dom[$key]['attribute']['bgcolor']))) {
11284 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
11286 // check for width attribute
11287 if (isset($dom[$key]['attribute']['width'])) {
11288 $dom[$key]['width'] = $dom[$key]['attribute']['width'];
11290 // check for height attribute
11291 if (isset($dom[$key]['attribute']['height'])) {
11292 $dom[$key]['height'] = $dom[$key]['attribute']['height'];
11294 // check for text alignment
11295 if (isset($dom[$key]['attribute']['align']) AND (!$this->empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
11296 $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
11298 } // end opening tag
11301 $dom[$key]['tag'] = false;
11302 $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
11303 $dom[$key]['parent'] = end($level);
11312 * Allows to preserve some HTML formatting (limited support).<br />
11313 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
11314 * 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
11315 * @param string $html text to display
11316 * @param boolean $ln if true add a new line after text (default = true)
11317 * @param int $fill Indicates if the background must be painted (true) or transparent (false).
11318 * @param boolean $reseth if true reset the last cell height (default false).
11319 * @param boolean $cell if true add the default cMargin space to each Write (default false).
11320 * @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>
11323 public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
11324 $gvars = $this->getGraphicVars();
11325 // store current values
11326 $prevPage = $this->page;
11327 $prevlMargin = $this->lMargin;
11328 $prevrMargin = $this->rMargin;
11329 $curfontname = $this->FontFamily;
11330 $curfontstyle = $this->FontStyle;
11331 $curfontsize = $this->FontSizePt;
11332 $this->newline = true;
11333 $minstartliney = $this->y;
11335 $startlinepage = $this->page;
11339 $blocktags = array('blockquote','br','dd','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','ul','tcpdf');
11340 $this->premode = false;
11341 if (isset($this->PageAnnots[$this->page])) {
11342 $pask = count($this->PageAnnots[$this->page]);
11346 if (isset($this->footerlen[$this->page])) {
11347 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11349 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11351 $startlinepos = $this->footerpos[$this->page];
11355 $w = $this->x - $this->lMargin;
11357 $w = $this->w - $this->rMargin - $this->x;
11359 $w -= (2 * $this->cMargin);
11362 $this->x -= $this->cMargin;
11364 $this->x += $this->cMargin;
11367 if ($this->customlistindent >= 0) {
11368 $this->listindent = $this->customlistindent;
11370 $this->listindent = $this->GetStringWidth('0000');
11372 $this->listnum = 0;
11373 if (($this->empty_string($this->lasth)) OR ($reseth)) {
11375 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11377 $dom = $this->getHtmlDomArray($html);
11378 $maxel = count($dom);
11380 while ($key < $maxel) {
11381 if ($dom[$key]['tag'] OR ($key == 0)) {
11382 if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
11383 $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
11385 // vertically align image in line
11386 if ((!$this->newline)
11387 AND ($dom[$key]['value'] == 'img')
11388 AND (isset($dom[$key]['attribute']['height']))
11389 AND ($dom[$key]['attribute']['height'] > 0)) {
11390 // get image height
11391 $imgh = $this->getHTMLUnitToUnits($dom[$key]['attribute']['height'], $this->lasth, 'px');
11392 if (!$this->InFooter) {
11393 // check for page break
11394 $this->checkPageBreak($imgh);
11396 if ($this->page > $startlinepage) {
11397 // fix lines splitted over two pages
11398 if (isset($this->footerlen[$startlinepage])) {
11399 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11401 // line to be moved one page forward
11402 $pagebuff = $this->getPageBuffer($startlinepage);
11403 $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
11404 $tstart = substr($pagebuff, 0, $startlinepos);
11405 $tend = substr($this->getPageBuffer($startlinepage), $curpos);
11406 // remove line start from previous page
11407 $this->setPageBuffer($startlinepage, $tstart.''.$tend);
11408 $pagebuff = $this->getPageBuffer($this->page);
11409 $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
11410 $tend = substr($pagebuff, $this->intmrk[$this->page]);
11411 // add line start to current page
11412 $yshift = $minstartliney - $this->y;
11413 $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
11414 $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
11415 // shift the annotations and links
11416 if (isset($this->PageAnnots[$startlinepage])) {
11417 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
11418 if ($pak >= $pask) {
11419 $this->PageAnnots[$this->page][] = $pac;
11420 unset($this->PageAnnots[$startlinepage][$pak]);
11421 $npak = count($this->PageAnnots[$this->page]) - 1;
11422 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
11426 $startlinepos = $this->intmrk[$this->page];
11427 $startlinepage = $this->page;
11428 $startliney = $this->y;
11431 $this->y += (($curfontsize / $this->k) - $imgh);
11432 $minstartliney = min($this->y, $minstartliney);
11434 } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
11435 // account for different font size
11436 $pfontname = $curfontname;
11437 $pfontstyle = $curfontstyle;
11438 $pfontsize = $curfontsize;
11439 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
11440 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
11441 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
11442 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
11443 $this->SetFont($fontname, $fontstyle, $fontsize);
11444 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11445 if (is_numeric($fontsize) AND ($fontsize > 0)
11446 AND is_numeric($curfontsize) AND ($curfontsize > 0)
11447 AND ($fontsize != $curfontsize) AND (!$this->newline)
11448 AND ($key < ($maxel - 1))
11450 if ((!$this->newline) AND ($this->page > $startlinepage)) {
11451 // fix lines splitted over two pages
11452 if (isset($this->footerlen[$startlinepage])) {
11453 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11455 // line to be moved one page forward
11456 $pagebuff = $this->getPageBuffer($startlinepage);
11457 $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
11458 $tstart = substr($pagebuff, 0, $startlinepos);
11459 $tend = substr($this->getPageBuffer($startlinepage), $curpos);
11460 // remove line start from previous page
11461 $this->setPageBuffer($startlinepage, $tstart.''.$tend);
11462 $pagebuff = $this->getPageBuffer($this->page);
11463 $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
11464 $tend = substr($pagebuff, $this->intmrk[$this->page]);
11465 // add line start to current page
11466 $yshift = $minstartliney - $this->y;
11467 $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
11468 $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
11469 // shift the annotations and links
11470 if (isset($this->PageAnnots[$startlinepage])) {
11471 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
11472 if ($pak >= $pask) {
11473 $this->PageAnnots[$this->page][] = $pac;
11474 unset($this->PageAnnots[$startlinepage][$pak]);
11475 $npak = count($this->PageAnnots[$this->page]) - 1;
11476 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
11481 $this->y += (($curfontsize - $fontsize) / $this->k);
11482 $minstartliney = min($this->y, $minstartliney);
11484 $curfontname = $fontname;
11485 $curfontstyle = $fontstyle;
11486 $curfontsize = $fontsize;
11489 if (($plalign == 'J') AND (in_array($dom[$key]['value'], $blocktags))) {
11492 // get current position on page buffer
11493 $curpos = $this->pagelen[$startlinepage];
11494 if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
11495 $this->SetFillColorArray($dom[$key]['bgcolor']);
11498 $wfill = $fill | false;
11500 if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
11501 $this->SetTextColorArray($dom[$key]['fgcolor']);
11503 if (isset($dom[$key]['align'])) {
11504 $lalign = $dom[$key]['align'];
11506 if ($this->empty_string($lalign)) {
11511 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
11513 // we are at the beginning of a new line
11514 if (isset($startlinex)) {
11515 $yshift = $minstartliney - $startliney;
11516 if (($yshift > 0) OR ($this->page > $startlinepage)) {
11519 if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
11520 // the last line must be shifted to be aligned as requested
11521 $linew = abs($this->endlinex - $startlinex);
11522 $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
11523 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
11524 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11525 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
11526 } elseif (isset($opentagpos)) {
11527 $midpos = $opentagpos;
11528 } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
11529 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11530 $midpos = $this->footerpos[$startlinepage];
11535 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
11536 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
11538 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
11541 // calculate shifting amount
11543 if ($this->lMargin != $prevlMargin) {
11544 $tw += ($prevlMargin - $this->lMargin);
11546 if ($this->rMargin != $prevrMargin) {
11547 $tw += ($prevrMargin - $this->rMargin);
11549 $mdiff = abs($tw - $linew);
11551 if ($plalign == 'C') {
11553 $t_x = -($mdiff / 2);
11555 $t_x = ($mdiff / 2);
11557 } elseif (($plalign == 'R') AND (!$this->rtl)) {
11558 // right alignment on LTR document
11560 } elseif (($plalign == 'L') AND ($this->rtl)) {
11561 // left alignment on RTL document
11563 } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
11565 if ($this->rtl OR $this->tmprtl) {
11566 $t_x = $this->lMargin - $this->endlinex;
11571 // escape special characters
11572 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
11573 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
11575 if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
11576 $maxkk = count($lnstring[1]) - 1;
11577 for ($kk=0; $kk <= $maxkk; ++$kk) {
11578 // restore special characters
11579 $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
11580 $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
11581 if ($kk == $maxkk) {
11582 if ($this->rtl OR $this->tmprtl) {
11583 $tvalue = ltrim($lnstring[1][$kk]);
11585 $tvalue = rtrim($lnstring[1][$kk]);
11588 $tvalue = $lnstring[1][$kk];
11590 // count spaces on line
11591 $no += substr_count($lnstring[1][$kk], chr(32));
11592 $ns += substr_count($tvalue, chr(32));
11594 if ($this->rtl OR $this->tmprtl) {
11595 $t_x = $this->lMargin - $this->endlinex - (($no - $ns - 1) * $this->GetStringWidth(chr(32)));
11597 // calculate additional space to add to each space
11598 $spacewidth = (($tw - $linew + (($no - $ns) * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1)) * $this->k;
11599 $spacewidthu = ($tw - $linew + ($no * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1) / $this->FontSize / $this->k;
11605 $prev_epsposbeg = 0;
11607 while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
11608 if ($this->rtl OR $this->tmprtl) {
11609 $spacew = ($spacewidth * ($nsmax - $ns));
11611 $spacew = ($spacewidth * $ns);
11613 $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
11614 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
11615 $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset) + strlen($this->epsmarker.'Q');
11616 if ((($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend))
11617 OR (($epsposbeg === false) AND ($epsposend > 0) AND ($offset < $epsposend))) {
11618 // shift EPS images
11619 $trx = sprintf('1 0 0 1 %.3F 0 cm', $spacew);
11620 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
11621 $pmid_b = substr($pmid, 0, $epsposbeg);
11622 $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
11623 $pmid_e = substr($pmid, $epsposend);
11624 $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
11625 $offset = $epsposend;
11628 $prev_epsposbeg = $epsposbeg;
11630 // shift blocks of code
11631 switch ($strpiece[2][0]) {
11636 // get current X position
11637 preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11638 $currentxpos = $xmatches[1];
11639 if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
11640 if ($strcount == $maxkk) {
11641 if ($this->rtl OR $this->tmprtl) {
11642 $tvalue = $lnstring[1][$strcount];
11644 $tvalue = rtrim($lnstring[1][$strcount]);
11647 $tvalue = $lnstring[1][$strcount];
11649 $ns += substr_count($tvalue, chr(32));
11652 if ($this->rtl OR $this->tmprtl) {
11653 $spacew = ($spacewidth * ($nsmax - $ns));
11656 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11657 create_function('$matches', 'global $spacew;
11658 $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
11659 return "".$newx." ".$matches[2]." x*#!#*x".$matches[3].$matches[4];'), $pmid, 1);
11663 // get current X position
11664 preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11665 $currentxpos = $xmatches[1];
11667 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11668 create_function('$matches', 'global $spacew;
11669 $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
11670 return "".$newx." ".$matches[2]." ".$matches[3]." ".$matches[4]." x*#!#*x".$matches[5].$matches[6];'), $pmid, 1);
11674 // get current X position
11675 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);
11676 $currentxpos = $xmatches[1];
11678 $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',
11679 create_function('$matches', 'global $spacew;
11680 $newx1 = sprintf("%.3F",(floatval($matches[1]) + $spacew));
11681 $newx2 = sprintf("%.3F",(floatval($matches[3]) + $spacew));
11682 $newx3 = sprintf("%.3F",(floatval($matches[5]) + $spacew));
11683 return "".$newx1." ".$matches[2]." ".$newx2." ".$matches[4]." ".$newx3." ".$matches[6]." x*#!#*x".$matches[7].$matches[8];'), $pmid, 1);
11687 // shift the annotations and links
11688 if (isset($this->PageAnnots[$this->page])) {
11689 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
11690 if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
11691 $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
11692 $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
11699 $pmid = str_replace('x*#!#*x', '', $pmid);
11700 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
11701 // multibyte characters
11702 $spacew = $spacewidthu;
11704 // escape special characters
11705 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
11706 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
11707 $pmid = preg_replace_callback("/\[\(([^\)]*)\)\]/x",
11708 create_function('$matches', 'global $spacew;
11709 $matches[1] = str_replace("#!#OP#!#", "(", $matches[1]);
11710 $matches[1] = str_replace("#!#CP#!#", ")", $matches[1]);
11711 return "[(".str_replace(chr(0).chr(32), ") ".(-2830 * $spacew)." (", $matches[1]).")]";'), $pmidtemp);
11712 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
11713 $endlinepos = strlen($pstart."\n".$pmid."\n");
11715 // non-unicode (single-byte characters)
11716 $rs = sprintf("%.3F Tw", $spacewidth);
11717 $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
11718 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
11719 $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
11723 if (($t_x != 0) OR ($yshift < 0)) {
11725 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
11726 $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
11727 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
11728 // shift the annotations and links
11729 if (isset($this->PageAnnots[$this->page])) {
11730 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
11731 if ($pak >= $pask) {
11732 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
11733 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
11737 $this->y -= $yshift;
11741 $this->newline = false;
11742 $pbrk = $this->checkPageBreak($this->lasth);
11743 $this->SetFont($fontname, $fontstyle, $fontsize);
11745 $this->SetFillColorArray($this->bgcolor);
11747 $startlinex = $this->x;
11748 $startliney = $this->y;
11749 $minstartliney = $this->y;
11750 $startlinepage = $this->page;
11751 if (isset($endlinepos) AND (!$pbrk)) {
11752 $startlinepos = $endlinepos;
11753 unset($endlinepos);
11755 if (isset($this->footerlen[$this->page])) {
11756 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11758 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11760 $startlinepos = $this->footerpos[$this->page];
11762 $plalign = $lalign;
11763 if (isset($this->PageAnnots[$this->page])) {
11764 $pask = count($this->PageAnnots[$this->page]);
11769 if (isset($opentagpos)) {
11770 unset($opentagpos);
11772 if ($dom[$key]['tag']) {
11773 if ($dom[$key]['opening']) {
11774 if ($dom[$key]['value'] == 'table') {
11776 $wtmp = $this->x - $this->lMargin;
11778 $wtmp = $this->w - $this->rMargin - $this->x;
11780 $wtmp -= (2 * $this->cMargin);
11781 // calculate cell width
11782 if (isset($dom[$key]['width'])) {
11783 $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
11785 $table_width = $wtmp;
11788 // table content is handled in a special way
11789 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
11790 $trid = $dom[$key]['parent'];
11791 $table_el = $dom[$trid]['parent'];
11792 if (!isset($dom[$table_el]['cols'])) {
11793 $dom[$table_el]['cols'] = $trid['cols'];
11795 $oldmargin = $this->cMargin;
11796 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
11797 $currentcmargin = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
11799 $currentcmargin = 0;
11801 $this->cMargin = $currentcmargin;
11802 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
11803 $cellspacing = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'], 1, 'px');
11808 $cellspacingx = -$cellspacing;
11810 $cellspacingx = $cellspacing;
11812 $colspan = $dom[$key]['attribute']['colspan'];
11813 $wtmp = ($colspan * ($table_width / $dom[$table_el]['cols']));
11814 if (isset($dom[$key]['width'])) {
11815 $cellw = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
11819 if (isset($dom[$key]['height'])) {
11820 // minimum cell height
11821 $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
11825 $cellw -= $cellspacing;
11826 if (isset($dom[$key]['content'])) {
11827 $cell_content = $dom[$key]['content'];
11829 $cell_content = ' ';
11831 $tagtype = $dom[$key]['value'];
11833 while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
11834 // move $key index forward
11837 if (!isset($dom[$trid]['startpage'])) {
11838 $dom[$trid]['startpage'] = $this->page;
11840 $this->setPage($dom[$trid]['startpage']);
11842 if (!isset($dom[$trid]['starty'])) {
11843 $dom[$trid]['starty'] = $this->y;
11845 $this->y = $dom[$trid]['starty'];
11847 if (!isset($dom[$trid]['startx'])) {
11848 $dom[$trid]['startx'] = $this->x;
11850 $this->x += ($cellspacingx / 2);
11851 if (isset($dom[$parentid]['attribute']['rowspan'])) {
11852 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
11856 // skip row-spanned cells started on the previous rows
11857 if (isset($dom[$table_el]['rowspans'])) {
11859 $rskmax = count($dom[$table_el]['rowspans']);
11860 while ($rsk < $rskmax) {
11861 $trwsp = $dom[$table_el]['rowspans'][$rsk];
11862 $rsstartx = $trwsp['startx'];
11863 $rsendx = $trwsp['endx'];
11864 // account for margin changes
11865 if ($trwsp['startpage'] < $this->page) {
11866 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
11867 $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
11870 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
11871 $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
11876 if (($trwsp['rowspan'] > 0)
11877 AND ($rsstartx > ($this->x - $cellspacing - $currentcmargin - $this->feps))
11878 AND ($rsstartx < ($this->x + $cellspacing + $currentcmargin + $this->feps))
11879 AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page))) {
11880 // set the starting X position of the current cell
11881 $this->x = $rsendx + $cellspacingx;
11882 if (($trwsp['rowspan'] == 1)
11883 AND (isset($dom[$trid]['endy']))
11884 AND (isset($dom[$trid]['endpage']))
11885 AND ($trwsp['endpage'] == $dom[$trid]['endpage'])) {
11886 // set ending Y position for row
11887 $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
11888 $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
11896 // add rowspan information to table element
11897 if ($rowspan > 1) {
11898 if (isset($this->footerlen[$this->page])) {
11899 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11901 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11903 $trintmrkpos = $this->footerpos[$this->page];
11904 $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));
11906 $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
11907 if ($rowspan > 1) {
11908 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
11910 // push background colors
11911 if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
11912 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
11914 $prevLastH = $this->lasth;
11915 // ****** write the cell content ******
11916 $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
11917 $this->lasth = $prevLastH;
11918 $this->cMargin = $oldmargin;
11919 $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
11920 // update the end of row position
11921 if ($rowspan <= 1) {
11922 if (isset($dom[$trid]['endy'])) {
11923 if ($this->page == $dom[$trid]['endpage']) {
11924 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
11925 } elseif ($this->page > $dom[$trid]['endpage']) {
11926 $dom[$trid]['endy'] = $this->y;
11929 $dom[$trid]['endy'] = $this->y;
11931 if (isset($dom[$trid]['endpage'])) {
11932 $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
11934 $dom[$trid]['endpage'] = $this->page;
11937 // account for row-spanned cells
11938 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
11939 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
11940 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
11942 if (isset($dom[$table_el]['rowspans'])) {
11943 // update endy and endpage on rowspanned cells
11944 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
11945 if ($trwsp['rowspan'] > 0) {
11946 if (isset($dom[$trid]['endpage'])) {
11947 if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
11948 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
11949 } elseif ($trwsp['endpage'] < $dom[$trid]['endpage']) {
11950 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
11951 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
11953 $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
11959 $this->x += ($cellspacingx / 2);
11961 // opening tag (or self-closing tag)
11962 if (!isset($opentagpos)) {
11963 if (!$this->InFooter) {
11964 if (isset($this->footerlen[$this->page])) {
11965 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11967 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11969 $opentagpos = $this->footerpos[$this->page];
11972 $this->openHTMLTagHandler($dom, $key, $cell);
11976 $this->closeHTMLTagHandler($dom, $key, $cell);
11978 } elseif (strlen($dom[$key]['value']) > 0) {
11980 if (!$this->empty_string($this->lispacer)) {
11981 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
11982 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11983 $minstartliney = $this->y;
11984 $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
11985 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
11986 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11987 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
11988 $this->y += (($pfontsize - $curfontsize) / $this->k);
11989 $minstartliney = min($this->y, $minstartliney);
11993 $this->htmlvspace = 0;
11994 if ((!$this->premode) AND ($this->rtl OR $this->tmprtl)) {
11995 // reverse spaces order
11996 $len1 = strlen($dom[$key]['value']);
11997 $lsp = $len1 - strlen(ltrim($dom[$key]['value']));
11998 $rsp = $len1 - strlen(rtrim($dom[$key]['value']));
12001 $tmpstr .= substr($dom[$key]['value'], -$rsp);
12003 $tmpstr .= trim($dom[$key]['value']);
12005 $tmpstr .= substr($dom[$key]['value'], 0, $lsp);
12007 $dom[$key]['value'] = $tmpstr;
12010 if (!$this->premode) {
12011 if (($this->rtl OR $this->tmprtl)) {
12012 $dom[$key]['value'] = rtrim($dom[$key]['value']);
12014 $dom[$key]['value'] = ltrim($dom[$key]['value']);
12018 $firstblock = true;
12020 $firstblock = false;
12023 if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
12025 $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $this->HREF['color'], $this->HREF['style']);
12027 $ctmpmargin = $this->cMargin;
12028 $this->cMargin = 0;
12029 // ****** write only until the end of the line and get the rest ******
12030 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock);
12031 $this->cMargin = $ctmpmargin;
12033 if (strlen($strrest) > 0) {
12034 // store the remaining string on the previous $key position
12035 $this->newline = true;
12038 $this->x -= $this->cMargin;
12040 $this->x += $this->cMargin;
12043 if ($strrest == $dom[$key]['value']) {
12044 // used to avoid infinite loop
12049 $dom[$key]['value'] = ltrim($strrest);
12058 } // end for each $key
12059 // align the last line
12060 if (isset($startlinex)) {
12061 $yshift = $minstartliney - $startliney;
12062 if (($yshift > 0) OR ($this->page > $startlinepage)) {
12065 if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
12066 // the last line must be shifted to be aligned as requested
12067 $linew = abs($this->endlinex - $startlinex);
12068 $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
12069 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
12070 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
12071 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
12072 } elseif (isset($opentagpos)) {
12073 $midpos = $opentagpos;
12074 } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
12075 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
12076 $midpos = $this->footerpos[$startlinepage];
12081 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
12082 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
12084 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
12087 // calculate shifting amount
12089 if ($this->lMargin != $prevlMargin) {
12090 $tw += ($prevlMargin - $this->lMargin);
12092 if ($this->rMargin != $prevrMargin) {
12093 $tw += ($prevrMargin - $this->rMargin);
12095 $mdiff = abs($tw - $linew);
12096 if ($plalign == 'C') {
12098 $t_x = -($mdiff / 2);
12100 $t_x = ($mdiff / 2);
12102 } elseif (($plalign == 'R') AND (!$this->rtl)) {
12103 // right alignment on LTR document
12105 } elseif (($plalign == 'L') AND ($this->rtl)) {
12106 // left alignment on RTL document
12111 if (($t_x != 0) OR ($yshift < 0)) {
12113 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
12114 $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
12115 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
12116 // shift the annotations and links
12117 if (isset($this->PageAnnots[$this->page])) {
12118 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
12119 if ($pak >= $pask) {
12120 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
12121 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
12125 $this->y -= $yshift;
12129 if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
12130 $this->Ln($this->lasth);
12132 // restore previous values
12133 $this->setGraphicVars($gvars);
12134 if ($this->page > $prevPage) {
12135 $this->lMargin = $this->pagedim[$this->page]['olm'];
12136 $this->rMargin = $this->pagedim[$this->page]['orm'];
12142 * Process opening tags.
12143 * @param array $dom html dom array
12144 * @param int $key current element id
12145 * @param boolean $cell if true add the default cMargin space to each new line (default false).
12146 * @access protected
12148 protected function openHTMLTagHandler(&$dom, $key, $cell=false) {
12150 $parent = $dom[($dom[$key]['parent'])];
12151 $firstorlast = ($key == 1);
12152 // check for text direction attribute
12153 if (isset($tag['attribute']['dir'])) {
12154 $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
12156 $this->tmprtl = false;
12159 switch($tag['value']) {
12163 $dom[$key]['rowspans'] = array();
12164 if (!$this->empty_string($dom[$key]['thead'])) {
12165 // set table header
12166 $this->thead = $dom[$key]['thead'];
12168 if (isset($tag['attribute']['cellpadding'])) {
12169 $cp = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
12170 $this->oldcMargin = $this->cMargin;
12171 $this->cMargin = $cp;
12173 if (isset($tag['attribute']['cellspacing'])) {
12174 $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
12176 $this->checkPageBreak((2 * $cp) + (2 * $cs) + $this->lasth);
12180 // array of columns positions
12181 $dom[$key]['cellpos'] = array();
12185 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12186 $this->htmlvspace = 0;
12187 $wtmp = $this->w - $this->lMargin - $this->rMargin;
12188 if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
12189 $hrWidth = $this->getHTMLUnitToUnits($tag['attribute']['width'], $wtmp, 'px');
12193 $x = $this->GetX();
12194 $y = $this->GetY();
12195 $prevlinewidth = $this->GetLineWidth();
12196 $this->Line($x, $y, $x + $hrWidth, $y);
12197 $this->SetLineWidth($prevlinewidth);
12198 $this->addHTMLVertSpace(1, $cell, '', !isset($dom[($key + 1)]), $tag['value'], false);
12202 if (array_key_exists('href', $tag['attribute'])) {
12203 $this->HREF['url'] = $tag['attribute']['href'];
12205 $this->HREF['color'] = $this->htmlLinkColorArray;
12206 $this->HREF['style'] = $this->htmlLinkFontStyle;
12207 if (array_key_exists('style', $tag['attribute'])) {
12208 // get style attributes
12209 preg_match_all('/([^;:\s]*):([^;]*)/', $tag['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
12211 while (list($id, $name) = each($style_array[1])) {
12212 $name = strtolower($name);
12213 $astyle[$name] = trim($style_array[2][$id]);
12215 if (isset($astyle['color'])) {
12216 $this->HREF['color'] = $this->convertHTMLColorToDec($astyle['color']);
12218 if (isset($astyle['text-decoration'])) {
12219 $this->HREF['style'] = '';
12220 $decors = explode(' ', strtolower($astyle['text-decoration']));
12221 foreach ($decors as $dec) {
12223 if (!$this->empty_string($dec)) {
12224 if ($dec{0} == 'u') {
12225 $this->HREF['style'] .= 'U';
12226 } elseif ($dec{0} == 'l') {
12227 $this->HREF['style'] .= 'D';
12236 if (isset($tag['attribute']['src'])) {
12237 // replace relative path with real server path
12238 if ($tag['attribute']['src'][0] == '/') {
12239 $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
12241 $tag['attribute']['src'] = urldecode($tag['attribute']['src']);
12242 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
12243 if (!isset($tag['attribute']['width'])) {
12244 $tag['attribute']['width'] = 0;
12246 if (!isset($tag['attribute']['height'])) {
12247 $tag['attribute']['height'] = 0;
12249 //if (!isset($tag['attribute']['align'])) {
12250 // the only alignment supported is "bottom"
12251 // further development is required for other modes.
12252 $tag['attribute']['align'] = 'bottom';
12254 switch($tag['attribute']['align']) {
12272 $fileinfo = pathinfo($tag['attribute']['src']);
12273 if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
12274 $type = strtolower($fileinfo['extension']);
12277 $xpos = $this->GetX();
12278 if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == ' ')) {
12280 $xpos += $this->GetStringWidth(' ');
12282 $xpos -= $this->GetStringWidth(' ');
12286 if (isset($this->HREF['url']) AND !$this->empty_string($this->HREF['url'])) {
12287 $imglink = $this->HREF['url'];
12288 if ($imglink{0} == '#') {
12289 // convert url to internal link
12290 $page = intval(substr($imglink, 1));
12291 $imglink = $this->AddLink();
12292 $this->SetLink($imglink, 0, $page);
12296 if (isset($tag['attribute']['border']) AND !empty($tag['attribute']['border'])) {
12297 // currently only support 1 (frame) or a combination of 'LTRB'
12298 $border = $tag['attribute']['border'];
12301 if (isset($tag['attribute']['width'])) {
12302 $iw = $this->getHTMLUnitToUnits($tag['attribute']['width'], 1, 'px', false);
12305 if (isset($tag['attribute']['height'])) {
12306 $ih = $this->getHTMLUnitToUnits($tag['attribute']['height'], 1, 'px', false);
12308 if (($type == 'eps') OR ($type == 'ai')) {
12309 $this->ImageEps($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, $imglink, true, $align, '', $border);
12311 $this->Image($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border);
12319 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
12323 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
12332 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12336 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12341 $this->rMargin += $this->listindent;
12343 $this->lMargin += $this->listindent;
12345 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12350 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12351 $this->htmlvspace = 0;
12353 if ($tag['value'] == 'ol') {
12354 $this->listordered[$this->listnum] = true;
12356 $this->listordered[$this->listnum] = false;
12358 if (isset($tag['attribute']['start'])) {
12359 $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
12361 $this->listcount[$this->listnum] = 0;
12364 $this->rMargin += $this->listindent;
12366 $this->lMargin += $this->listindent;
12368 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12369 $this->htmlvspace = 0;
12373 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12374 if ($this->listordered[$this->listnum]) {
12376 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
12377 $this->lispacer = $parent['attribute']['type'];
12378 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
12379 $this->lispacer = $parent['listtype'];
12380 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
12381 $this->lispacer = $this->lisymbol;
12383 $this->lispacer = '#';
12385 ++$this->listcount[$this->listnum];
12386 if (isset($tag['attribute']['value'])) {
12387 $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
12391 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
12392 $this->lispacer = $parent['attribute']['type'];
12393 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
12394 $this->lispacer = $parent['listtype'];
12395 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
12396 $this->lispacer = $this->lisymbol;
12398 $this->lispacer = '!';
12403 case 'blockquote': {
12405 $this->rMargin += $this->listindent;
12407 $this->lMargin += $this->listindent;
12409 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
12413 $this->Ln('', $cell);
12417 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12421 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
12425 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12426 $this->premode = true;
12430 $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
12434 $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
12443 $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], false);
12447 if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
12448 // Special tag used to call TCPDF methods
12449 if (isset($tag['attribute']['method'])) {
12450 $tcpdf_method = $tag['attribute']['method'];
12451 if (method_exists($this, $tcpdf_method)) {
12452 if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
12453 $params = unserialize(urldecode($tag['attribute']['params']));
12454 call_user_func_array(array($this, $tcpdf_method), $params);
12456 $this->$tcpdf_method();
12458 $this->newline = true;
12470 * Process closing tags.
12471 * @param array $dom html dom array
12472 * @param int $key current element id
12473 * @param boolean $cell if true add the default cMargin space to each new line (default false).
12474 * @access protected
12476 protected function closeHTMLTagHandler(&$dom, $key, $cell=false) {
12478 $parent = $dom[($dom[$key]['parent'])];
12479 $firstorlast = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
12481 switch($tag['value']) {
12483 $table_el = $dom[($dom[$key]['parent'])]['parent'];
12484 if(!isset($parent['endy'])) {
12485 $dom[($dom[$key]['parent'])]['endy'] = $this->y;
12486 $parent['endy'] = $this->y;
12488 if(!isset($parent['endpage'])) {
12489 $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
12490 $parent['endpage'] = $this->page;
12492 // update row-spanned cells
12493 if (isset($dom[$table_el]['rowspans'])) {
12494 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12495 $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
12496 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12497 if ($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) {
12498 $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
12499 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) {
12500 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
12501 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
12505 // report new endy and endpage to the rowspanned cells
12506 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12507 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12508 $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
12509 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
12510 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
12511 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
12514 // update remaining rowspanned cells
12515 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12516 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12517 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
12518 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
12522 $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
12523 $this->y = $dom[($dom[$key]['parent'])]['endy'];
12524 if (isset($dom[$table_el]['attribute']['cellspacing'])) {
12525 $cellspacing = $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
12526 $this->y += $cellspacing;
12528 $this->Ln(0, $cell);
12529 $this->x = $parent['startx'];
12530 // account for booklet mode
12531 if ($this->page > $parent['startpage']) {
12532 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
12533 $this->x += ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
12534 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
12535 $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
12542 $table_el = $parent;
12543 if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
12544 OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
12549 // fix bottom line alignment of last line before page break
12550 foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
12551 // update row-spanned cells
12552 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
12553 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
12554 if ($trwsp['trid'] == $trkey) {
12555 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
12557 if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0)) {
12558 $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
12562 if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
12563 $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
12564 $dom[$prevtrkey]['endy'] = $pgendy;
12565 // update row-spanned cells
12566 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
12567 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
12568 if (($trwsp['trid'] == $trkey) AND ($trwsp['mrowspan'] == 1) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
12569 $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
12570 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
12575 $prevtrkey = $trkey;
12576 $table_el = $dom[($dom[$key]['parent'])];
12579 foreach ($table_el['trids'] as $j => $trkey) {
12580 $parent = $dom[$trkey];
12581 // for each cell on the row
12582 foreach ($parent['cellpos'] as $k => $cellpos) {
12583 if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
12584 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
12585 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
12586 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
12587 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
12588 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
12590 $endy = $parent['endy'];
12591 $startpage = $parent['startpage'];
12592 $endpage = $parent['endpage'];
12594 if ($endpage > $startpage) {
12595 // design borders around HTML cells.
12596 for ($page=$startpage; $page <= $endpage; ++$page) {
12597 $this->setPage($page);
12598 if ($page == $startpage) {
12599 $this->y = $parent['starty']; // put cursor at the beginning of row on the first page
12600 $ch = $this->getPageHeight() - $parent['starty'] - $this->getBreakMargin();
12601 $cborder = $this->getBorderMode($border, $position='start');
12602 } elseif ($page == $endpage) {
12603 $this->y = $this->tMargin; // put cursor at the beginning of last page
12604 $ch = $endy - $this->tMargin;
12605 $cborder = $this->getBorderMode($border, $position='end');
12607 $this->y = $this->tMargin; // put cursor at the beginning of the current page
12608 $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
12609 $cborder = $this->getBorderMode($border, $position='middle');
12611 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
12612 $this->SetFillColorArray($cellpos['bgcolor']);
12617 $cw = abs($cellpos['endx'] - $cellpos['startx']);
12618 $this->x = $cellpos['startx'];
12619 // account for margin changes
12620 if ($page > $startpage) {
12621 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
12622 $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
12623 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['lm'] != $this->pagedim[$startpage]['olm'])) {
12624 $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
12627 // design a cell around the text
12628 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $cborder, 1, '', $fill, '', 0, true);
12629 if ($cborder OR $fill) {
12630 $pagebuff = $this->getPageBuffer($this->page);
12631 $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
12632 $pend = substr($pagebuff, $this->intmrk[$this->page]);
12633 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
12634 $this->intmrk[$this->page] += strlen($ccode."\n");
12638 $this->setPage($startpage);
12639 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
12640 $this->SetFillColorArray($cellpos['bgcolor']);
12645 $this->x = $cellpos['startx'];
12646 $this->y = $parent['starty'];
12647 $cw = abs($cellpos['endx'] - $cellpos['startx']);
12648 $ch = $endy - $parent['starty'];
12649 // design a cell around the text
12650 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $border, 1, '', $fill, '', 0, true);
12651 if ($border OR $fill) {
12652 if (end($this->transfmrk[$this->page]) !== false) {
12653 $pagemarkkey = key($this->transfmrk[$this->page]);
12654 $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
12655 } elseif ($this->InFooter) {
12656 $pagemark = &$this->footerpos[$this->page];
12658 $pagemark = &$this->intmrk[$this->page];
12660 $pagebuff = $this->getPageBuffer($this->page);
12661 $pstart = substr($pagebuff, 0, $pagemark);
12662 $pend = substr($pagebuff, $pagemark);
12663 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
12664 $pagemark += strlen($ccode."\n");
12668 if (isset($table_el['attribute']['cellspacing'])) {
12669 $cellspacing = $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
12670 $this->y += $cellspacing;
12672 $this->Ln(0, $cell);
12673 $this->x = $parent['startx'];
12674 if ($endpage > $startpage) {
12675 if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
12676 $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
12677 } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
12678 $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
12682 if (isset($parent['cellpadding'])) {
12683 $this->cMargin = $this->oldcMargin;
12685 $this->lasth = $this->FontSize * $this->cell_height_ratio;
12686 if (!$this->empty_string($this->theadMargin)) {
12687 // restore top margin
12688 $this->tMargin = $this->theadMargin;
12689 $this->pagedim[$this->page]['tm'] = $this->theadMargin;
12691 // reset table header
12693 $this->theadMargin = '';
12701 $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
12705 $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
12709 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
12712 case 'blockquote': {
12714 $this->rMargin -= $this->listindent;
12716 $this->lMargin -= $this->listindent;
12718 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12722 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12726 $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
12727 $this->premode = false;
12732 if ($this->listnum <= 0) {
12733 $this->listnum = 0;
12734 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12739 $this->lispacer = '';
12740 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12744 $this->lispacer = '';
12746 $this->rMargin -= $this->listindent;
12748 $this->lMargin -= $this->listindent;
12750 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12756 $this->lispacer = '';
12758 $this->rMargin -= $this->listindent;
12760 $this->lMargin -= $this->listindent;
12762 if ($this->listnum <= 0) {
12763 $this->listnum = 0;
12764 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12766 $this->lasth = $this->FontSize * $this->cell_height_ratio;
12770 $this->lispacer = '';
12771 $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12780 $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], true);
12787 $this->tmprtl = false;
12791 * Add vertical spaces if needed.
12792 * @param int $n number of spaces to add
12793 * @param boolean $cell if true add the default cMargin space to each new line (default false).
12794 * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
12795 * @param boolean $firstorlast if true do not print additional empty lines.
12796 * @param string $tag HTML tag to which this space will be applied
12797 * @param boolean $closing true if this space will be applied to a closing tag, false otherwise
12798 * @access protected
12800 protected function addHTMLVertSpace($n, $cell=false, $h='', $firstorlast=false, $tag='', $closing=false) {
12801 if ($firstorlast) {
12802 $this->Ln(0, $cell);
12803 $this->htmlvspace = 0;
12806 if (isset($this->tagvspaces[$tag][intval($closing)]['n'])) {
12807 $n = $this->tagvspaces[$tag][intval($closing)]['n'];
12809 if (isset($this->tagvspaces[$tag][intval($closing)]['h'])) {
12810 $h = $this->tagvspaces[$tag][intval($closing)]['h'];
12812 if (is_string($h)) {
12813 $vsize = $n * $this->lasth;
12817 if ($vsize > $this->htmlvspace) {
12818 $this->Ln(($vsize - $this->htmlvspace), $cell);
12819 $this->htmlvspace = $vsize;
12824 * Set the default bullet to be used as LI bullet symbol
12825 * @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')
12827 * @since 4.0.028 (2008-09-26)
12829 public function setLIsymbol($symbol='!') {
12830 $symbol = strtolower($symbol);
12840 case 'decimal-leading-zero':
12842 case 'lower-roman':
12844 case 'upper-roman':
12846 case 'lower-alpha':
12847 case 'lower-latin':
12849 case 'upper-alpha':
12850 case 'upper-latin':
12851 case 'lower-greek': {
12852 $this->lisymbol = $symbol;
12856 $this->lisymbol = '';
12862 * Set the booklet mode for double-sided pages.
12863 * @param boolean $booklet true set the booklet mode on, fals eotherwise.
12864 * @param float $inner Inner page margin.
12865 * @param float $outer Outer page margin.
12867 * @since 4.2.000 (2008-10-29)
12869 public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
12870 $this->booklet = $booklet;
12872 $this->lMargin = $inner;
12875 $this->rMargin = $outer;
12880 * Swap the left and right margins.
12881 * @param boolean $reverse if true swap left and right margins.
12882 * @access protected
12883 * @since 4.2.000 (2008-10-29)
12885 protected function swapMargins($reverse=true) {
12887 // swap left and right margins
12888 $mtemp = $this->original_lMargin;
12889 $this->original_lMargin = $this->original_rMargin;
12890 $this->original_rMargin = $mtemp;
12891 $deltam = $this->original_lMargin - $this->original_rMargin;
12892 $this->lMargin += $deltam;
12893 $this->rMargin -= $deltam;
12898 * Set the vertical spaces for HTML tags.
12899 * The array must have the following structure (example):
12900 * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
12901 * The first array level contains the tag names,
12902 * the second level contains 0 for opening tags or 1 for closing tags,
12903 * the third level contains the vertical space unit (h) and the number spaces to add (n).
12904 * If the h parameter is not specified, default values are used.
12905 * @param array $tagvs array of tags and relative vertical spaces.
12907 * @since 4.2.001 (2008-10-30)
12909 public function setHtmlVSpace($tagvs) {
12910 $this->tagvspaces = $tagvs;
12914 * Set custom width for list indentation.
12915 * @param float $width width of the indentation. Use negative value to disable it.
12917 * @since 4.2.007 (2008-11-12)
12919 public function setListIndentWidth($width) {
12920 return $this->customlistindent = floatval($width);
12924 * Set the top/bottom cell sides to be open or closed when the cell cross the page.
12925 * @param boolean $isopen if true keeps the top/bottom border open for the cell sides that cross the page.
12927 * @since 4.2.010 (2008-11-14)
12929 public function setOpenCell($isopen) {
12930 $this->opencell = $isopen;
12934 * Set the color and font style for HTML links.
12935 * @param array $color RGB array of colors
12936 * @param string $fontstyle additional font styles to add
12938 * @since 4.4.003 (2008-12-09)
12940 public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
12941 $this->htmlLinkColorArray = $color;
12942 $this->htmlLinkFontStyle = $fontstyle;
12946 * convert html string containing value and unit of measure to user's units or points.
12947 * @param string $htmlval string containing values and unit
12948 * @param string $refsize reference value in points
12949 * @param string $defaultunit default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
12950 * @param boolean $point if true returns points, otherwise returns value in user's units
12951 * @return float value in user's unit or point if $points=true
12953 * @since 4.4.004 (2008-12-10)
12955 public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
12956 $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
12964 if (in_array($defaultunit, $supportedunits)) {
12965 $unit = $defaultunit;
12967 if (is_numeric($htmlval)) {
12968 $value = floatval($htmlval);
12969 } elseif (preg_match('/([0-9\.]+)/', $htmlval, $mnum)) {
12970 $value = floatval($mnum[1]);
12971 if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
12972 if (in_array($munit[1], $supportedunits)) {
12980 $retval = (($value * $refsize) / 100);
12985 $retval = ($value * $refsize);
12989 $retval = $value * ($refsize / 2);
12994 $retval = ($value * $this->dpi) / $k;
12998 $retval = ($value / 2.54 * $this->dpi) / $k;
13002 $retval = ($value / 25.4 * $this->dpi) / $k;
13006 // one pica is 12 points
13007 $retval = ($value * 12) / $k;
13011 $retval = $value / $k;
13015 $retval = $this->pixelsToUnits($value);
13023 * Returns the Roman representation of an integer number
13024 * @param int number to convert
13025 * @return string roman representation of the specified number
13027 * @since 4.4.004 (2008-12-10)
13029 public function intToRoman($number) {
13031 while ($number >= 1000) {
13035 while ($number >= 900) {
13039 while ($number >= 500) {
13043 while ($number >= 400) {
13047 while ($number >= 100) {
13051 while ($number >= 90) {
13055 while ($number >= 50) {
13059 while ($number >= 40) {
13063 while ($number >= 10) {
13067 while ($number >= 9) {
13071 while ($number >= 5) {
13075 while ($number >= 4) {
13079 while ($number >= 1) {
13087 * Output an HTML list bullet or ordered item symbol
13088 * @param int $listdepth list nesting level
13089 * @param string $listtype type of list
13090 * @param float $size current font size
13091 * @access protected
13092 * @since 4.4.004 (2008-12-10)
13094 protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
13097 $color = $this->fgcolor;
13101 $lspace = $this->GetStringWidth(' ');
13102 if ($listtype == '!') {
13103 // set default list type for unordered list
13104 $deftypes = array('disc', 'circle', 'square');
13105 $listtype = $deftypes[($listdepth - 1) % 3];
13106 } elseif ($listtype == '#') {
13107 // set default list type for ordered list
13108 $listtype = 'decimal';
13110 switch ($listtype) {
13121 $lspace += (2 * $r);
13123 $this->x = $this->w - $this->x - $lspace;
13125 $this->x -= $lspace;
13127 $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, $fill, array('color'=>$color), $color, 8);
13134 $this->x = $this->w - $this->x - $lspace;
13136 $this->x -= $lspace;
13138 $this->Rect($this->x, ($this->y + (($this->lasth - $l)/ 2)), $l, $l, 'F', array(), $color);
13143 // $this->listcount[$this->listnum];
13147 $textitem = $this->listcount[$this->listnum];
13150 case 'decimal-leading-zero': {
13151 $textitem = sprintf("%02d", $this->listcount[$this->listnum]);
13155 case 'lower-roman': {
13156 $textitem = strtolower($this->intToRoman($this->listcount[$this->listnum]));
13160 case 'upper-roman': {
13161 $textitem = $this->intToRoman($this->listcount[$this->listnum]);
13165 case 'lower-alpha':
13166 case 'lower-latin': {
13167 $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
13171 case 'upper-alpha':
13172 case 'upper-latin': {
13173 $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
13176 case 'lower-greek': {
13177 $textitem = $this->unichr(945 + $this->listcount[$this->listnum] - 1);
13181 // Types to be implemented (special handling)
13191 case 'cjk-ideographic': {
13200 case 'hiragana-iroha': {
13203 case 'katakana-iroha': {
13208 $textitem = $this->listcount[$this->listnum];
13211 if (!$this->empty_string($textitem)) {
13212 // print ordered item
13214 $textitem = '.'.$textitem;
13216 $textitem = $textitem.'.';
13218 $lspace += $this->GetStringWidth($textitem);
13220 $this->x += $lspace;
13222 $this->x -= $lspace;
13224 $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
13227 $this->lispacer = '';
13231 * Returns current graphic variables as array.
13232 * @return array graphic variables
13233 * @access protected
13234 * @since 4.2.010 (2008-11-14)
13236 protected function getGraphicVars() {
13238 'FontFamily' => $this->FontFamily,
13239 'FontStyle' => $this->FontStyle,
13240 'FontSizePt' => $this->FontSizePt,
13241 'rMargin' => $this->rMargin,
13242 'lMargin' => $this->lMargin,
13243 'cMargin' => $this->cMargin,
13244 'LineWidth' => $this->LineWidth,
13245 'linestyleWidth' => $this->linestyleWidth,
13246 'linestyleCap' => $this->linestyleCap,
13247 'linestyleJoin' => $this->linestyleJoin,
13248 'linestyleDash' => $this->linestyleDash,
13249 'DrawColor' => $this->DrawColor,
13250 'FillColor' => $this->FillColor,
13251 'TextColor' => $this->TextColor,
13252 'ColorFlag' => $this->ColorFlag,
13253 'bgcolor' => $this->bgcolor,
13254 'fgcolor' => $this->fgcolor,
13255 'htmlvspace' => $this->htmlvspace,
13256 'lasth' => $this->lasth
13262 * Set graphic variables.
13263 * @param $gvars array graphic variables
13264 * @access protected
13265 * @since 4.2.010 (2008-11-14)
13267 protected function setGraphicVars($gvars) {
13268 $this->FontFamily = $gvars['FontFamily'];
13269 $this->FontStyle = $gvars['FontStyle'];
13270 $this->FontSizePt = $gvars['FontSizePt'];
13271 $this->rMargin = $gvars['rMargin'];
13272 $this->lMargin = $gvars['lMargin'];
13273 $this->cMargin = $gvars['cMargin'];
13274 $this->LineWidth = $gvars['LineWidth'];
13275 $this->linestyleWidth = $gvars['linestyleWidth'];
13276 $this->linestyleCap = $gvars['linestyleCap'];
13277 $this->linestyleJoin = $gvars['linestyleJoin'];
13278 $this->linestyleDash = $gvars['linestyleDash'];
13279 $this->DrawColor = $gvars['DrawColor'];
13280 $this->FillColor = $gvars['FillColor'];
13281 $this->TextColor = $gvars['TextColor'];
13282 $this->ColorFlag = $gvars['ColorFlag'];
13283 $this->bgcolor = $gvars['bgcolor'];
13284 $this->fgcolor = $gvars['fgcolor'];
13285 $this->htmlvspace = $gvars['htmlvspace'];
13286 //$this->lasth = $gvars['lasth'];
13287 $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
13288 if (!$this->empty_string($this->FontFamily)) {
13289 $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
13294 * Returns a temporary filename for caching object on filesystem.
13295 * @param string $prefix prefix to add to filename
13296 * return string filename.
13297 * @access protected
13298 * @since 4.5.000 (2008-12-31)
13300 protected function getObjFilename($name) {
13301 return tempnam(K_PATH_CACHE, $name.'_');
13305 * Writes data to a temporary file on filesystem.
13306 * @param string $file file name
13307 * @param mixed $data data to write on file
13308 * @param boolean $append if true append data, false replace.
13309 * @access protected
13310 * @since 4.5.000 (2008-12-31)
13312 protected function writeDiskCache($filename, $data, $append=false) {
13318 $f = @fopen($filename, $fmode);
13320 $this->Error('Unable to write cache file: '.$filename);
13325 // update file lenght (needed for transactions)
13326 if (!isset($this->cache_file_lenght['_'.$filename])) {
13327 $this->cache_file_lenght['_'.$filename] = strlen($data);
13329 $this->cache_file_lenght['_'.$filename] += strlen($data);
13334 * Read data from a temporary file on filesystem.
13335 * @param string $file file name
13336 * @return mixed retrieved data
13337 * @access protected
13338 * @since 4.5.000 (2008-12-31)
13340 protected function readDiskCache($filename) {
13341 return file_get_contents($filename);
13345 * Set buffer content (always append data).
13346 * @param string $data data
13347 * @access protected
13348 * @since 4.5.000 (2009-01-02)
13350 protected function setBuffer($data) {
13351 $this->bufferlen += strlen($data);
13352 if ($this->diskcache) {
13353 if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
13354 $this->buffer = $this->getObjFilename('buffer');
13356 $this->writeDiskCache($this->buffer, $data, true);
13358 $this->buffer .= $data;
13363 * Get buffer content.
13364 * @return string buffer content
13365 * @access protected
13366 * @since 4.5.000 (2009-01-02)
13368 protected function getBuffer() {
13369 if ($this->diskcache) {
13370 return $this->readDiskCache($this->buffer);
13372 return $this->buffer;
13377 * Set page buffer content.
13378 * @param int $page page number
13379 * @param string $data page data
13380 * @param boolean $append if true append data, false replace.
13381 * @access protected
13382 * @since 4.5.000 (2008-12-31)
13384 protected function setPageBuffer($page, $data, $append=false) {
13385 if ($this->diskcache) {
13386 if (!isset($this->pages[$page])) {
13387 $this->pages[$page] = $this->getObjFilename('page'.$page);
13389 $this->writeDiskCache($this->pages[$page], $data, $append);
13392 $this->pages[$page] .= $data;
13394 $this->pages[$page] = $data;
13397 if ($append AND isset($this->pagelen[$page])) {
13398 $this->pagelen[$page] += strlen($data);
13400 $this->pagelen[$page] = strlen($data);
13405 * Get page buffer content.
13406 * @param int $page page number
13407 * @return string page buffer content or false in case of error
13408 * @access protected
13409 * @since 4.5.000 (2008-12-31)
13411 protected function getPageBuffer($page) {
13412 if ($this->diskcache) {
13413 return $this->readDiskCache($this->pages[$page]);
13414 } elseif (isset($this->pages[$page])) {
13415 return $this->pages[$page];
13421 * Set image buffer content.
13422 * @param string $image image key
13423 * @param array $data image data
13424 * @access protected
13425 * @since 4.5.000 (2008-12-31)
13427 protected function setImageBuffer($image, $data) {
13428 if ($this->diskcache) {
13429 if (!isset($this->images[$image])) {
13430 $this->images[$image] = $this->getObjFilename('image'.$image);
13432 $this->writeDiskCache($this->images[$image], serialize($data));
13434 $this->images[$image] = $data;
13436 if (!in_array($image, $this->imagekeys)) {
13437 $this->imagekeys[] = $image;
13439 ++$this->numimages;
13443 * Set image buffer content.
13444 * @param string $image image key
13445 * @param string $key image sub-key
13446 * @param array $data image data
13447 * @access protected
13448 * @since 4.5.000 (2008-12-31)
13450 protected function setImageSubBuffer($image, $key, $data) {
13451 if (!isset($this->images[$image])) {
13452 $this->setImageBuffer($image, array());
13454 if ($this->diskcache) {
13455 $tmpimg = $this->getImageBuffer($image);
13456 $tmpimg[$key] = $data;
13457 $this->writeDiskCache($this->images[$image], serialize($tmpimg));
13459 $this->images[$image][$key] = $data;
13464 * Get page buffer content.
13465 * @param string $image image key
13466 * @return string image buffer content or false in case of error
13467 * @access protected
13468 * @since 4.5.000 (2008-12-31)
13470 protected function getImageBuffer($image) {
13471 if ($this->diskcache AND isset($this->images[$image])) {
13472 return unserialize($this->readDiskCache($this->images[$image]));
13473 } elseif (isset($this->images[$image])) {
13474 return $this->images[$image];
13480 * Set font buffer content.
13481 * @param string $font font key
13482 * @param array $data font data
13483 * @access protected
13484 * @since 4.5.000 (2009-01-02)
13486 protected function setFontBuffer($font, $data) {
13487 if ($this->diskcache) {
13488 if (!isset($this->fonts[$font])) {
13489 $this->fonts[$font] = $this->getObjFilename('font');
13491 $this->writeDiskCache($this->fonts[$font], serialize($data));
13493 $this->fonts[$font] = $data;
13495 if (!in_array($font, $this->fontkeys)) {
13496 $this->fontkeys[] = $font;
13501 * Set font buffer content.
13502 * @param string $font font key
13503 * @param string $key font sub-key
13504 * @param array $data font data
13505 * @access protected
13506 * @since 4.5.000 (2009-01-02)
13508 protected function setFontSubBuffer($font, $key, $data) {
13509 if (!isset($this->fonts[$font])) {
13510 $this->setFontBuffer($font, array());
13512 if ($this->diskcache) {
13513 $tmpfont = $this->getFontBuffer($font);
13514 $tmpfont[$key] = $data;
13515 $this->writeDiskCache($this->fonts[$font], serialize($tmpfont));
13517 $this->fonts[$font][$key] = $data;
13522 * Get font buffer content.
13523 * @param string $font font key
13524 * @return string font buffer content or false in case of error
13525 * @access protected
13526 * @since 4.5.000 (2009-01-02)
13528 protected function getFontBuffer($font) {
13529 if ($this->diskcache AND isset($this->fonts[$font])) {
13530 return unserialize($this->readDiskCache($this->fonts[$font]));
13531 } elseif (isset($this->fonts[$font])) {
13532 return $this->fonts[$font];
13538 * Move a page to a previous position.
13539 * @param int $frompage number of the source page
13540 * @param int $topage number of the destination page (must be less than $frompage)
13541 * @return true in case of success, false in case of error.
13543 * @since 4.5.000 (2009-01-02)
13545 public function movePage($frompage, $topage) {
13546 if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
13549 if ($frompage == $this->page) {
13550 // close the page before moving it
13553 // move all page-related states
13554 $tmppage = $this->pages[$frompage];
13555 $tmppagedim = $this->pagedim[$frompage];
13556 $tmppagelen = $this->pagelen[$frompage];
13557 $tmpintmrk = $this->intmrk[$frompage];
13558 if (isset($this->footerpos[$frompage])) {
13559 $tmpfooterpos = $this->footerpos[$frompage];
13561 if (isset($this->footerlen[$frompage])) {
13562 $tmpfooterlen = $this->footerlen[$frompage];
13564 if (isset($this->transfmrk[$frompage])) {
13565 $tmptransfmrk = $this->transfmrk[$frompage];
13567 if (isset($this->PageAnnots[$frompage])) {
13568 $tmpannots = $this->PageAnnots[$frompage];
13570 if (isset($this->newpagegroup[$frompage])) {
13571 $tmpnewpagegroup = $this->newpagegroup[$frompage];
13573 for ($i = $frompage; $i > $topage; --$i) {
13575 // shift pages down
13576 $this->pages[$i] = $this->pages[$j];
13577 $this->pagedim[$i] = $this->pagedim[$j];
13578 $this->pagelen[$i] = $this->pagelen[$j];
13579 $this->intmrk[$i] = $this->intmrk[$j];
13580 if (isset($this->footerpos[$j])) {
13581 $this->footerpos[$i] = $this->footerpos[$j];
13582 } elseif (isset($this->footerpos[$i])) {
13583 unset($this->footerpos[$i]);
13585 if (isset($this->footerlen[$j])) {
13586 $this->footerlen[$i] = $this->footerlen[$j];
13587 } elseif (isset($this->footerlen[$i])) {
13588 unset($this->footerlen[$i]);
13590 if (isset($this->transfmrk[$j])) {
13591 $this->transfmrk[$i] = $this->transfmrk[$j];
13592 } elseif (isset($this->transfmrk[$i])) {
13593 unset($this->transfmrk[$i]);
13595 if (isset($this->PageAnnots[$j])) {
13596 $this->PageAnnots[$i] = $this->PageAnnots[$j];
13597 } elseif (isset($this->PageAnnots[$i])) {
13598 unset($this->PageAnnots[$i]);
13600 if (isset($this->newpagegroup[$j])) {
13601 $this->newpagegroup[$i] = $this->newpagegroup[$j];
13602 } elseif (isset($this->newpagegroup[$i])) {
13603 unset($this->newpagegroup[$i]);
13606 $this->pages[$topage] = $tmppage;
13607 $this->pagedim[$topage] = $tmppagedim;
13608 $this->pagelen[$topage] = $tmppagelen;
13609 $this->intmrk[$topage] = $tmpintmrk;
13610 if (isset($tmpfooterpos)) {
13611 $this->footerpos[$topage] = $tmpfooterpos;
13612 } elseif (isset($this->footerpos[$topage])) {
13613 unset($this->footerpos[$topage]);
13615 if (isset($tmpfooterlen)) {
13616 $this->footerlen[$topage] = $tmpfooterlen;
13617 } elseif (isset($this->footerlen[$topage])) {
13618 unset($this->footerlen[$topage]);
13620 if (isset($tmptransfmrk)) {
13621 $this->transfmrk[$topage] = $tmptransfmrk;
13622 } elseif (isset($this->transfmrk[$topage])) {
13623 unset($this->transfmrk[$topage]);
13625 if (isset($tmpannots)) {
13626 $this->PageAnnots[$topage] = $tmpannots;
13627 } elseif (isset($this->PageAnnots[$topage])) {
13628 unset($this->PageAnnots[$topage]);
13630 if (isset($tmpnewpagegroup)) {
13631 $this->newpagegroup[$topage] = $tmpnewpagegroup;
13632 } elseif (isset($this->newpagegroup[$topage])) {
13633 unset($this->newpagegroup[$topage]);
13636 $tmpoutlines = $this->outlines;
13637 foreach ($tmpoutlines as $key => $outline) {
13638 if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
13639 $this->outlines[$key]['p'] = $outline['p'] + 1;
13640 } elseif ($outline['p'] == $frompage) {
13641 $this->outlines[$key]['p'] = $topage;
13645 $tmplinks = $this->links;
13646 foreach ($tmplinks as $key => $link) {
13647 if (($link[0] >= $topage) AND ($link[0] < $frompage)) {
13648 $this->links[$key][0] = $link[0] + 1;
13649 } elseif ($link[0] == $frompage) {
13650 $this->links[$key][0] = $topage;
13653 // adjust javascript
13654 $tmpjavascript = $this->javascript;
13655 global $jfrompage, $jtopage;
13656 $jfrompage = $frompage;
13657 $jtopage = $topage;
13658 $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
13659 create_function('$matches', 'global $jfrompage, $jtopage;
13660 $pagenum = intval($matches[3]) + 1;
13661 if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
13662 $newpage = ($pagenum + 1);
13663 } elseif ($pagenum == $jfrompage) {
13664 $newpage = $jtopage;
13666 $newpage = $pagenum;
13669 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
13670 // return to last page
13671 $this->lastPage(true);
13676 * Remove the specified page.
13677 * @param int $page page to remove
13678 * @return true in case of success, false in case of error.
13680 * @since 4.6.004 (2009-04-23)
13682 public function deletePage($page) {
13683 if ($page > $this->numpages) {
13686 // delete current page
13687 unset($this->pages[$page]);
13688 unset($this->pagedim[$page]);
13689 unset($this->pagelen[$page]);
13690 unset($this->intmrk[$page]);
13691 if (isset($this->footerpos[$page])) {
13692 unset($this->footerpos[$page]);
13694 if (isset($this->footerlen[$page])) {
13695 unset($this->footerlen[$page]);
13697 if (isset($this->transfmrk[$page])) {
13698 unset($this->transfmrk[$page]);
13700 if (isset($this->PageAnnots[$page])) {
13701 unset($this->PageAnnots[$page]);
13703 if (isset($this->newpagegroup[$page])) {
13704 unset($this->newpagegroup[$page]);
13706 if (isset($this->pageopen[$page])) {
13707 unset($this->pageopen[$page]);
13709 // update remaining pages
13710 for ($i = $page; $i < $this->numpages; ++$i) {
13713 $this->pages[$i] = $this->pages[$j];
13714 $this->pagedim[$i] = $this->pagedim[$j];
13715 $this->pagelen[$i] = $this->pagelen[$j];
13716 $this->intmrk[$i] = $this->intmrk[$j];
13717 if (isset($this->footerpos[$j])) {
13718 $this->footerpos[$i] = $this->footerpos[$j];
13719 } elseif (isset($this->footerpos[$i])) {
13720 unset($this->footerpos[$i]);
13722 if (isset($this->footerlen[$j])) {
13723 $this->footerlen[$i] = $this->footerlen[$j];
13724 } elseif (isset($this->footerlen[$i])) {
13725 unset($this->footerlen[$i]);
13727 if (isset($this->transfmrk[$j])) {
13728 $this->transfmrk[$i] = $this->transfmrk[$j];
13729 } elseif (isset($this->transfmrk[$i])) {
13730 unset($this->transfmrk[$i]);
13732 if (isset($this->PageAnnots[$j])) {
13733 $this->PageAnnots[$i] = $this->PageAnnots[$j];
13734 } elseif (isset($this->PageAnnots[$i])) {
13735 unset($this->PageAnnots[$i]);
13737 if (isset($this->newpagegroup[$j])) {
13738 $this->newpagegroup[$i] = $this->newpagegroup[$j];
13739 } elseif (isset($this->newpagegroup[$i])) {
13740 unset($this->newpagegroup[$i]);
13742 if (isset($this->pageopen[$j])) {
13743 $this->pageopen[$i] = $this->pageopen[$j];
13744 } elseif (isset($this->pageopen[$i])) {
13745 unset($this->pageopen[$i]);
13748 // remove last page
13749 unset($this->pages[$this->numpages]);
13750 unset($this->pagedim[$this->numpages]);
13751 unset($this->pagelen[$this->numpages]);
13752 unset($this->intmrk[$this->numpages]);
13753 if (isset($this->footerpos[$this->numpages])) {
13754 unset($this->footerpos[$this->numpages]);
13756 if (isset($this->footerlen[$this->numpages])) {
13757 unset($this->footerlen[$this->numpages]);
13759 if (isset($this->transfmrk[$this->numpages])) {
13760 unset($this->transfmrk[$this->numpages]);
13762 if (isset($this->PageAnnots[$this->numpages])) {
13763 unset($this->PageAnnots[$this->numpages]);
13765 if (isset($this->newpagegroup[$this->numpages])) {
13766 unset($this->newpagegroup[$this->numpages]);
13768 if (isset($this->pageopen[$this->numpages])) {
13769 unset($this->pageopen[$this->numpages]);
13772 $this->page = $this->numpages;
13774 $tmpoutlines = $this->outlines;
13775 foreach ($tmpoutlines as $key => $outline) {
13776 if ($outline['p'] > $page) {
13777 $this->outlines[$key]['p'] = $outline['p'] - 1;
13778 } elseif ($outline['p'] == $page) {
13779 unset($this->outlines[$key]);
13783 $tmplinks = $this->links;
13784 foreach ($tmplinks as $key => $link) {
13785 if ($link[0] > $page) {
13786 $this->links[$key][0] = $link[0] - 1;
13787 } elseif ($link[0] == $page) {
13788 unset($this->links[$key]);
13791 // adjust javascript
13792 $tmpjavascript = $this->javascript;
13795 $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
13796 create_function('$matches', 'global $jpage;
13797 $pagenum = intval($matches[3]) + 1;
13798 if ($pagenum >= $jpage) {
13799 $newpage = ($pagenum - 1);
13800 } elseif ($pagenum == $jpage) {
13803 $newpage = $pagenum;
13806 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
13807 // return to last page
13808 $this->lastPage(true);
13813 * Output a Table of Content Index (TOC).
13814 * You can override this method to achieve different styles.
13815 * @param int $page page number where this TOC should be inserted (leave empty for current page).
13816 * @param string $numbersfont set the font for page numbers (please use monospaced font for better alignment).
13817 * @param string $filler string used to fill the space between text and page number.
13819 * @author Nicola Asuni
13820 * @since 4.5.000 (2009-01-02)
13822 public function addTOC($page='', $numbersfont='', $filler='.') {
13823 $fontsize = $this->FontSizePt;
13824 $fontfamily = $this->FontFamily;
13825 $fontstyle = $this->FontStyle;
13826 $w = $this->w - $this->lMargin - $this->rMargin;
13827 $spacer = $this->GetStringWidth(' ') * 4;
13828 $page_first = $this->getPage();
13829 $lmargin = $this->lMargin;
13830 $rmargin = $this->rMargin;
13831 $x_start = $this->GetX();
13832 if ($this->empty_string($numbersfont)) {
13833 $numbersfont = $this->default_monospaced_font;
13835 if ($this->empty_string($filler)) {
13838 if ($this->empty_string($page)) {
13843 foreach ($this->outlines as $key => $outline) {
13851 if ($outline['l'] == 0) {
13852 $this->SetFont($fontfamily, $fontstyle.'B', $fontsize);
13854 $this->SetFont($fontfamily, $fontstyle, $fontsize - $outline['l']);
13856 $indent = ($spacer * $outline['l']);
13858 $this->rMargin += $indent;
13859 $this->x -= $indent;
13861 $this->lMargin += $indent;
13862 $this->x += $indent;
13864 $link = $this->AddLink();
13865 $this->SetLink($link, 0, $outline['p']);
13867 $this->Write(0, $outline['t'], $link, 0, $aligntext, false, 0, false, false, 0);
13868 $this->SetFont($numbersfont, $fontstyle, $fontsize);
13869 if ($this->empty_string($page)) {
13870 $pagenum = $outline['p'];
13872 // placemark to be replaced with the correct number
13873 $pagenum = '{#'.($outline['p']).'}';
13874 if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
13875 $pagenum = '{'.$pagenum.'}';
13878 $numwidth = $this->GetStringWidth($pagenum);
13880 $tw = $this->x - $this->lMargin;
13882 $tw = $this->w - $this->rMargin - $this->x;
13884 $fw = $tw - $numwidth - $this->GetStringWidth(' ');
13885 $numfills = floor($fw / $this->GetStringWidth($filler));
13886 if ($numfills > 0) {
13887 $rowfill = str_repeat($filler, $numfills);
13892 $pagenum = $pagenum.$gap.$rowfill.' ';
13894 $pagenum = ' '.$rowfill.$gap.$pagenum;
13896 // write the number
13897 //$this->SetX($x_start);
13898 $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
13899 $this->SetX($x_start);
13900 $this->lMargin = $lmargin;
13901 $this->rMargin = $rmargin;
13903 $page_last = $this->getPage();
13904 $numpages = $page_last - $page_first + 1;
13905 if (!$this->empty_string($page)) {
13906 for ($p = $page_first; $p <= $page_last; ++$p) {
13908 $temppage = $this->getPageBuffer($p);
13909 for ($n = 1; $n <= $this->numpages; ++$n) {
13910 // update page numbers
13913 $alias_a = $this->_escape($k);
13914 $alias_au = $this->_escape('{'.$k.'}');
13915 if ($this->isunicode) {
13916 $alias_b = $this->_escape($this->UTF8ToLatin1($k));
13917 $alias_bu = $this->_escape($this->UTF8ToLatin1($ku));
13918 $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
13919 $alias_cu = $this->_escape($this->utf8StrRev($ku, false, $this->tmprtl));
13922 $np = $n + $numpages;
13926 $ns = $this->formatTOCPageNumber($np);
13928 $sdiff = strlen($k) - strlen($ns) - 1;
13929 $sdiffu = strlen($ku) - strlen($ns) - 1;
13930 $sfill = str_repeat($filler, $sdiff);
13931 $sfillu = str_repeat($filler, $sdiffu);
13933 $ns = $ns.' '.$sfill;
13934 $nu = $nu.' '.$sfillu;
13936 $ns = $sfill.' '.$ns;
13937 $nu = $sfillu.' '.$nu;
13939 $nu = $this->UTF8ToUTF16BE($nu, false);
13940 $temppage = str_replace($alias_au, $nu, $temppage);
13941 if ($this->isunicode) {
13942 $temppage = str_replace($alias_bu, $nu, $temppage);
13943 $temppage = str_replace($alias_cu, $nu, $temppage);
13944 $temppage = str_replace($alias_b, $ns, $temppage);
13945 $temppage = str_replace($alias_c, $ns, $temppage);
13947 $temppage = str_replace($alias_a, $ns, $temppage);
13950 $this->setPageBuffer($p, $temppage);
13953 for ($i = 0; $i < $numpages; ++$i) {
13954 $this->movePage($page_last, $page);
13957 $this->SetFont($fontfamily, $fontstyle, $fontsize);
13961 * Stores a copy of the current TCPDF object used for undo operation.
13963 * @since 4.5.029 (2009-03-19)
13965 public function startTransaction() {
13966 if (isset($this->objcopy)) {
13967 // remove previous copy
13968 $this->commitTransaction();
13970 // clone current object
13971 $this->objcopy = $this->objclone($this);
13975 * Delete the copy of the current TCPDF object used for undo operation.
13977 * @since 4.5.029 (2009-03-19)
13979 public function commitTransaction() {
13980 if (isset($this->objcopy)) {
13981 $this->objcopy->_destroy(true, true);
13982 unset($this->objcopy);
13987 * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
13988 * @return TCPDF object.
13990 * @since 4.5.029 (2009-03-19)
13992 public function rollbackTransaction() {
13993 if (isset($this->objcopy)) {
13994 if (isset($this->objcopy->diskcache) AND $this->objcopy->diskcache) {
13995 // truncate files to previous values
13996 foreach ($this->objcopy->cache_file_lenght as $file => $lenght) {
13997 $file = substr($file, 1);
13998 $handle = fopen($file, 'r+');
13999 ftruncate($handle, $lenght);
14002 $this->_destroy(true, true);
14003 return $this->objcopy;
14009 * Creates a copy of a class object
14010 * @param object $object class object to be cloned
14011 * @return cloned object
14013 * @since 4.5.029 (2009-03-19)
14015 public function objclone($object) {
14016 return @clone($object);
14020 * Determine whether a string is empty.
14021 * @param srting $str string to be checked
14022 * @return boolean true if string is empty
14024 * @since 4.5.044 (2009-04-16)
14026 public function empty_string($str) {
14027 return (is_null($str) OR (is_string($str) AND (strlen($str) == 0)));
14030 } // END OF TCPDF CLASS
14032 //============================================================+
14034 //============================================================+