2 //============================================================+
3 // File name : tcpdf.php
5 // Last Update : 2008-09-19
6 // Author : Nicola Asuni - info@tecnick.com - http://www.tcpdf.org
7 // Version : 4.0.027_PHP4
8 // License : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
9 // ----------------------------------------------------------------------------
10 // Copyright (C) 2002-2008 Nicola Asuni - Tecnick.com S.r.l.
12 // This program is free software: you can redistribute it and/or modify
13 // it under the terms of the GNU Lesser General Public License as published by
14 // the Free Software Foundation, either version 2.1 of the License, or
15 // (at your option) any later version.
17 // This program is distributed in the hope that it will be useful,
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 // GNU Lesser General Public License for more details.
22 // You should have received a copy of the GNU Lesser General Public License
23 // along with this program. If not, see <http://www.gnu.org/licenses/>.
25 // See LICENSE.TXT file for more information.
26 // ----------------------------------------------------------------------------
28 // Description : This is a PHP class for generating PDF documents without
29 // requiring external extensions.
32 // This class was originally derived in 2002 from the Public
33 // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
34 // but now is almost entirely rewritten.
37 // * no external libraries are required for the basic functions;
38 // * supports all ISO page formats;
39 // * supports UTF-8 Unicode and Right-To-Left languages;
40 // * supports document encryption;
41 // * includes methods to publish some XHTML code;
42 // * includes graphic (geometric) and transformation methods;
43 // * includes bookmarks;
44 // * includes Javascript and forms support;
45 // * includes a method to print various barcode formats;
46 // * supports TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;
47 // * supports custom page formats, margins and units of measure;
48 // * includes methods for page header and footer management;
49 // * supports automatic page break;
50 // * supports automatic page numbering and page groups;
51 // * supports automatic line break and text justification;
52 // * supports JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
53 // * supports stroke and clipping mode for text;
54 // * supports clipping masks;
55 // * supports Grayscale, RGB, CMYK, Spot colors and transparency;
56 // * supports links and annotations;
57 // * supports page compression (requires zlib extension);
58 // * supports PDF user's rights.
60 // -----------------------------------------------------------
63 // Olivier Plathey (http://www.fpdf.org) for original FPDF.
64 // Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support.
65 // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm.
66 // Warren Sherliker (wsherliker@gmail.com) for better image handling.
67 // dullus for text Justification.
68 // Bob Vincent (pillarsdotnet@users.sourceforge.net) for <li> value attribute.
69 // Patrick Benny for text stretch suggestion on Cell().
70 // Johannes Güntert for JavaScript support.
71 // Denis Van Nuffelen for Dynamic Form.
72 // Jacek Czekaj for multibyte justification
73 // Anthony Ferrara for the reintroduction of legacy image methods.
74 // Sourceforge user 1707880 (hucste) for line-trough mode.
75 // Larry Stanbery for page groups.
76 // Martin Hall-May for transparency.
77 // Aaron C. Spike for Polycurve method.
78 // Mohamad Ali Golkar, Saleh AlMatrafe, Charles Abbott for Arabic and Persian support.
79 // Moritz Wagner and Andreas Wurmser for graphic functions.
80 // Andrew Whitehead for core fonts support.
81 // Esteban Joël Marín for OpenType font conversion.
82 // Teus Hagen for several suggestions and fixes.
83 // Yukihiro Nakadaira for CID-0 CJK fonts fixes.
84 // Kosmas Papachristos for some CSS improvements.
85 // Anyone that has reported a bug or sent a suggestion.
86 //============================================================+
89 * This is a PHP class for generating PDF documents without requiring external extensions.<br>
90 * 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>
91 * <h3>TCPDF main features are:</h3>
93 * <li>no external libraries are required for the basic functions;</li>
94 * <li>supports all ISO page formats;</li>
95 * <li>supports UTF-8 Unicode and Right-To-Left languages;</li>
96 * <li>supports document encryption;</li>
97 * <li>includes methods to publish some XHTML code;</li>
98 * <li>includes graphic (geometric) and transformation methods;</li>
99 * <li>includes bookmarks;</li>
100 * <li>includes Javascript and forms support;</li>
101 * <li>includes a method to print various barcode formats;</li>
102 * <li>supports TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;</li>
103 * <li>supports custom page formats, margins and units of measure;</li>
104 * <li>includes methods for page header and footer management;</li>
105 * <li>supports automatic page break;</li>
106 * <li>supports automatic page numbering and page groups;</li>
107 * <li>supports automatic line break and text justification;
108 * <li>supports JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;</li>
109 * <li>supports stroke and clipping mode for text;</li>
110 * <li>supports clipping masks;</li>
111 * <li>supports Grayscale, RGB and CMYK colors and transparency;</li>
112 * <li>supports links and annotations;</li>
113 * <li>supports page compression (requires zlib extension);</li>
114 * <li>supports PDF user's rights.</li>
116 * Tools to encode your unicode fonts are on fonts/utils directory.</p>
117 * @package com.tecnick.tcpdf
118 * @abstract Class for generating PDF files on-the-fly without requiring external extensions.
119 * @author Nicola Asuni
120 * @copyright 2004-2008 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
121 * @link http://www.tcpdf.org
122 * @license http://www.gnu.org/copyleft/lesser.html LGPL
123 * @version 4.0.027_PHP4
127 * main configuration file
129 /** -------------------------------FrontAccounting 2.0 ---------------------------
130 * following changes are done for FrontAccounting 2.0 - Joe Hunt 06.08.2008
131 * 1. /config/tcpdf_config.php is not included, commented out
132 * 2. Following 3 defines instead:
133 * if (!defined("K_PATH_FONTS"))
134 * define ("K_PATH_FONTS", '../reporting/fonts/');
135 * define ("K_PATH_CACHE", '../reporting/fonts/');
136 * define("K_CELL_HEIGHT_RATIO", 1.25);
137 * 3. ./unicode_data2.php only included if unicode is set. (in class constructor)
138 * We only use a reduced variant of unicode_data.php (unicode_data.php).af wrap the
140 * if (!defined("K_RE_PATTERN_RTL"))
142 * if (!defined("K_RE_PATTERN_ARABIC"))
143 * 4. Parameter $unicode in constructor renamed to $uni.
144 * 5. Header function renamed to Header1 (due to conflict with FrontReport Header)
145 * 6. Line 6190, SetLineWidth (cast of values to avoid problem in PHP 5.2.6
146 * -------------------------------------------------------------------------------
148 if (!defined("K_PATH_FONTS"))
149 define ("K_PATH_FONTS", '../reporting/fonts/');
150 define ("K_PATH_CACHE", '../reporting/fonts/');
151 define("K_CELL_HEIGHT_RATIO", 1.25);
153 //require_once(dirname(__FILE__).'/config/tcpdf_config.php');
155 // includes some support files
160 // only included if unicode
161 //include_once(dirname(__FILE__)."/unicode_data2.php");
166 require_once(dirname(__FILE__).'/htmlcolors.php');
171 require_once(dirname(__FILE__)."/barcodes.php");
174 * HTML entity decode functions
176 require_once(dirname(__FILE__)."/html_entity_decode_php4.php");
178 if (!class_exists('TCPDF')) {
180 * define default PDF document producer
182 define('PDF_PRODUCER','TCPDF 4.0.027_PHP4 (http://www.tcpdf.org)');
185 * This is a PHP class for generating PDF documents without requiring external extensions.<br>
186 * 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>
188 * @package com.tecnick.tcpdf
189 * @version 4.0.027_PHP4
190 * @author Nicola Asuni - info@tecnick.com
191 * @link http://www.tcpdf.org
192 * @license http://www.gnu.org/copyleft/lesser.html LGPL
196 // protected or Protected properties
199 * @var current page number
205 * @var current object number
211 * @var array of object offsets
217 * @var buffer holding in-memory PDF
223 * @var array containing pages
226 var $pages = array();
229 * @var current document state
235 * @var compression flag
241 * @var current page orientation (P = Portrait, L = Landscape)
247 * @var array that stores page dimensions.<ul><li>$this->pagedim[$this->page]['w'] => page_width_in_points</li><li>$this->pagedim[$this->page]['h'] => 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></ul>
250 var $pagedim = array();
253 * @var scale factor (number of points in user unit)
259 * @var width of page format in points
265 * @var height of page format in points
271 * @var current width of page in points
277 * @var current height of page in points
283 * @var current width of page in user unit
289 * @var current height of page in user unit
313 * @var page break margin
319 * @var cell internal padding
325 * @var cell internal padding (previous value)
331 * @var current horizontal position in user unit for cell positioning
337 * @var current vertical position in user unit for cell positioning
343 * @var height of last cell printed
349 * @var line width in user unit
355 * @var array of standard font names
361 * @var array of used fonts
364 var $fonts = array();
367 * @var array of font files
370 var $FontFiles = array();
373 * @var array of encoding differences
376 var $diffs = array();
379 * @var array of used images
382 var $images = array();
385 * @var array of Annotations in pages
388 var $PageAnnots = array();
391 * @var array of internal links
394 var $links = array();
397 * @var current font family
403 * @var current font style
409 * @var current font ascent (distance between font top and baseline)
411 * @since 2.8.000 (2007-03-29)
416 * @var current font descent (distance between font bottom and baseline)
418 * @since 2.8.000 (2007-03-29)
423 * @var underlining flag
429 * @var current font info
435 * @var current font size in points
441 * @var current font size in user unit
447 * @var commands for drawing color
453 * @var commands for filling color
459 * @var commands for text color
465 * @var indicates whether fill and text colors are different
477 * @var automatic page breaking
483 * @var threshold used to trigger page breaks
486 var $PageBreakTrigger;
489 * @var flag set when processing footer
495 * @var zoom display mode
501 * @var layout display mode
537 * @var alias for total number of pages
543 * @var right-bottom corner X coordinate of inserted image
545 * @author Nicola Asuni
551 * @var right-bottom corner Y coordinate of inserted image
553 * @author Nicola Asuni
559 * @var image scale factor
561 * @author Nicola Asuni
567 * @var boolean set to true when the input text is unicode (require unicode fonts)
569 * @author Nicola Asuni
572 var $isunicode = false;
579 var $PDFVersion = "1.7";
582 // ----------------------
585 * @var Minimum distance between header and top page margin.
591 * @var Minimum distance between footer and bottom page margin.
597 * @var original left margin value
599 * @since 1.53.0.TC013
601 var $original_lMargin;
604 * @var original right margin value
606 * @since 1.53.0.TC013
608 var $original_rMargin;
623 * @var Language templates.
629 * @var Barcode to print on page footer (only if set).
632 var $barcode = false;
635 * @var If true prints header
638 var $print_header = true;
641 * @var If true prints footer.
644 var $print_footer = true;
647 * @var Header image logo.
650 var $header_logo = "";
653 * @var Header image logo width in mm.
656 var $header_logo_width = 30;
659 * @var String to print as title on document header.
662 var $header_title = "";
665 * @var String to print on document header.
668 var $header_string = "";
671 * @var Default number of columns for html table.
674 var $default_table_columns = 4;
677 // variables for html parser
680 * @var HTML PARSER: store current link.
686 * @var store available fonts list.
689 var $fontlist = array();
692 * @var current foreground color
698 * @var HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
701 var $listordered = array();
704 * @var HTML PARSER: array count list items on nested lists.
707 var $listcount = array();
710 * @var HTML PARSER: current list nesting level.
716 * @var HTML PARSER: indent amount for lists.
722 * @var current background color
728 * @var Store temporary font size in points.
731 var $tempfontsize = 10;
734 * @var Bold font style status.
740 * @var Underlined font style status.
746 * @var Italic font style status.
752 * @var Line through font style status.
754 * @since 2.8.000 (2008-03-19)
759 * @var spacer for LI tags.
765 * @var default encoding
767 * @since 1.53.0.TC010
769 var $encoding = "UTF-8";
772 * @var PHP internal encoding
774 * @since 1.53.0.TC016
776 var $internal_encoding;
779 * @var indicates if the document language is Right-To-Left
786 * @var used to force RTL or LTR string inversion
792 // --- Variables used for document encryption:
795 * Indicates whether document is protected
797 * @since 2.0.000 (2008-01-02)
802 * U entry in pdf document
804 * @since 2.0.000 (2008-01-02)
809 * O entry in pdf document
811 * @since 2.0.000 (2008-01-02)
816 * P entry in pdf document
818 * @since 2.0.000 (2008-01-02)
823 * encryption object id
825 * @since 2.0.000 (2008-01-02)
830 * last RC4 key encrypted (cached for optimisation)
832 * @since 2.0.000 (2008-01-02)
837 * last RC4 computed key
839 * @since 2.0.000 (2008-01-02)
846 * Outlines for bookmark
848 * @since 2.1.002 (2008-02-12)
850 var $outlines = array();
853 * Outline root for bookmark
855 * @since 2.1.002 (2008-02-12)
860 // --- javascript and form ---
865 * @since 2.1.002 (2008-02-12)
867 var $javascript = "";
872 * @since 2.1.002 (2008-02-12)
879 * @since 2.8.000 (2008-03-19)
883 // --- Variables used for User's Rights ---
884 // See PDF reference chapter 8.7 Digital Signatures
887 * If true enables user's rights on PDF reader
889 * @since 2.9.000 (2008-03-26)
894 * Names specifying additional document-wide usage rights for the document.
896 * @since 2.9.000 (2008-03-26)
901 * Names specifying additional annotation-related usage rights for the document.
903 * @since 2.9.000 (2008-03-26)
908 * Names specifying additional form-field-related usage rights for the document.
910 * @since 2.9.000 (2008-03-26)
915 * Names specifying additional signature-related usage rights for the document.
917 * @since 2.9.000 (2008-03-26)
922 * Dot Per Inch Document Resolution (do not change)
924 * @since 3.0.000 (2008-03-27)
929 * Indicates whether a new page group was requested
931 * @since 3.0.000 (2008-03-27)
936 * Contains the number of pages of the groups
938 * @since 3.0.000 (2008-03-27)
943 * Contains the alias of the current page group
945 * @since 3.0.000 (2008-03-27)
950 * Restrict the rendering of some elements to screen or printout.
952 * @since 3.0.000 (2008-03-27)
954 var $visibility="all";
959 * @since 3.0.000 (2008-03-27)
966 * @since 3.0.000 (2008-03-27)
971 * Array of transparency objects and parameters.
973 * @since 3.0.000 (2008-03-27)
978 * Set the default JPEG compression quality (1-100)
980 * @since 3.0.000 (2008-03-27)
985 * Default cell height ratio.
987 * @since 3.0.014 (2008-05-23)
989 var $cell_height_ratio = K_CELL_HEIGHT_RATIO;
992 * PDF viewer preferences.
994 * @since 3.1.000 (2008-06-09)
996 var $viewer_preferences;
999 * A name object specifying how the document should be displayed when opened.
1001 * @since 3.1.000 (2008-06-09)
1006 * Array for storing gradient information.
1008 * @since 3.1.000 (2008-06-09)
1010 var $gradients = array();
1013 * Array used to store positions inside the pages buffer.
1014 * keys are the page numbers
1016 * @since 3.2.000 (2008-06-26)
1018 var $intmrk = array();
1021 * Array used to store footer positions of each page.
1023 * @since 3.2.000 (2008-07-01)
1025 var $footerpos = array();
1029 * Array used to store footer lenght of each page.
1031 * @since 4.0.014 (2008-07-29)
1033 var $footerlen = array();
1036 * True if a newline is created.
1038 * @since 3.2.000 (2008-07-01)
1040 var $newline = true;
1043 * End position of the latest inserted line
1045 * @since 3.2.000 (2008-07-01)
1050 * PDF string for last line width
1052 * @since 4.0.006 (2008-07-16)
1054 var $linestyleWidth = "";
1057 * PDF string for last line width
1059 * @since 4.0.006 (2008-07-16)
1061 var $linestyleCap = "0 J";
1064 * PDF string for last line width
1066 * @since 4.0.006 (2008-07-16)
1068 var $linestyleJoin = "0 j";
1071 * PDF string for last line width
1073 * @since 4.0.006 (2008-07-16)
1075 var $linestyleDash = "[] 0 d";
1078 * True if marked-content sequence is open
1080 * @since 4.0.013 (2008-07-28)
1082 var $openMarkedContent = false;
1085 * Count the latest inserted vertical spaces on HTML.
1087 * @since 4.0.021 (2008-08-24)
1089 var $htmlvspace = 0;
1092 * Array of Spot colors
1094 * @since 4.0.024 (2008-09-12)
1096 var $spot_colors = array();
1098 //------------------------------------------------------------
1100 //------------------------------------------------------------
1103 * This is the class constructor.
1104 * It allows to set up the page format, the orientation and
1105 * the measure unit used in all the methods (except for the font sizes).
1107 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
1108 * @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.
1109 * @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>
1110 * @param boolean $unicode TRUE means that the input text is unicode (default = true)
1111 * @param String $encoding charset encoding; default is UTF-8
1113 function TCPDF($orientation='P', $unit='mm', $format='A4', $uni=true, $encoding="UTF-8") {
1114 if ($uni) // Fix for FrontAccounting
1116 global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
1117 include_once(dirname(__FILE__)."/unicode_data2.php");
1119 /* Set internal character encoding to ASCII */
1120 if (function_exists("mb_internal_encoding") AND mb_internal_encoding()) {
1121 $this->internal_encoding = mb_internal_encoding();
1122 mb_internal_encoding("ASCII");
1124 // set language direction
1125 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
1126 $this->tmprtl = false;
1129 //Initialization of properties
1130 $this->isunicode = $uni;
1132 $this->pagedim = array();
1135 $this->pages = array();
1137 $this->fonts = array();
1138 $this->FontFiles = array();
1139 $this->diffs = array();
1140 $this->images = array();
1141 $this->links = array();
1142 $this->gradients = array();
1143 $this->InFooter = false;
1145 $this->FontFamily = 'helvetica';
1146 $this->FontStyle = '';
1147 $this->FontSizePt = 12;
1148 $this->underline = false;
1149 $this->linethrough = false;
1150 $this->DrawColor = '0 G';
1151 $this->FillColor = '0 g';
1152 $this->TextColor = '0 g';
1153 $this->ColorFlag = false;
1155 // encryption values
1156 $this->encrypted = false;
1157 $this->last_rc4_key = '';
1158 $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";
1159 //Standard Unicode fonts
1160 $this->CoreFonts = array(
1161 'courier'=>'Courier',
1162 'courierB'=>'Courier-Bold',
1163 'courierI'=>'Courier-Oblique',
1164 'courierBI'=>'Courier-BoldOblique',
1165 'helvetica'=>'Helvetica',
1166 'helveticaB'=>'Helvetica-Bold',
1167 'helveticaI'=>'Helvetica-Oblique',
1168 'helveticaBI'=>'Helvetica-BoldOblique',
1169 'times'=>'Times-Roman',
1170 'timesB'=>'Times-Bold',
1171 'timesI'=>'Times-Italic',
1172 'timesBI'=>'Times-BoldItalic',
1174 'zapfdingbats'=>'ZapfDingbats'
1177 $this->setPageUnit($unit);
1178 // set page format and orientation
1179 $this->setPageFormat($format, $orientation);
1180 //Page margins (1 cm)
1181 $margin = 28.35 / $this->k;
1182 $this->SetMargins($margin,$margin);
1183 //Interior cell margin (1 mm)
1184 $this->cMargin = $margin / 10;
1185 //Line width (0.2 mm)
1186 $this->LineWidth = 0.57 / $this->k;
1187 $this->linestyleWidth = sprintf('%.2f w', ($this->LineWidth * $this->k));
1188 $this->linestyleCap = "0 J";
1189 $this->linestyleJoin = "0 j";
1190 $this->linestyleDash = "[] 0 d";
1191 //Automatic page break
1192 $this->SetAutoPageBreak(true, 2*$margin);
1193 //Full width display mode
1194 $this->SetDisplayMode('fullwidth');
1196 $this->SetCompression(true);
1197 //Set default PDF version number
1198 $this->PDFVersion = "1.7";
1199 $this->encoding = $encoding;
1201 $this->getFontsList();
1202 $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
1203 $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
1204 $this->extgstates = array();
1207 $this->ur_document = "/FullSave";
1208 $this->ur_annots = "/Create/Delete/Modify/Copy/Import/Export";
1209 $this->ur_form = "/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate";
1210 $this->ur_signature = "/Modify";
1211 // set default JPEG quality
1212 $this->jpeg_quality = 75;
1213 // initialize some settings
1214 $this->utf8Bidi(array(""));
1218 * Default destructor.
1219 * @since 1.53.0.TC016
1221 function TCPDFDestruct() {
1222 // restore internal encoding
1223 if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
1224 mb_internal_encoding($this->internal_encoding);
1229 * Set the units of measure for the document.
1230 * @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.
1231 * @since 3.0.015 (2008-06-06)
1233 function setPageUnit($unit) {
1235 switch (strtolower($unit)) {
1243 $this->k = $this->dpi / 25.4;
1248 $this->k = $this->dpi / 2.54;
1253 $this->k = $this->dpi;
1258 $this->Error('Incorrect unit: '.$unit);
1262 if (isset($this->CurOrientation)) {
1263 $this->setPageOrientation($this->CurOrientation);
1268 * Set the page format
1269 * @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>
1270 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1271 * @since 3.0.015 (2008-06-06)
1273 function setPageFormat($format, $orientation="P") {
1275 if (is_string($format)) {
1276 // Page formats (45 standard ISO paper formats and 4 american common formats).
1277 // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm)
1278 switch (strtoupper($format)){
1279 case '4A0': {$format = array(4767.87,6740.79); break;}
1280 case '2A0': {$format = array(3370.39,4767.87); break;}
1281 case 'A0': {$format = array(2383.94,3370.39); break;}
1282 case 'A1': {$format = array(1683.78,2383.94); break;}
1283 case 'A2': {$format = array(1190.55,1683.78); break;}
1284 case 'A3': {$format = array(841.89,1190.55); break;}
1285 case 'A4': default: {$format = array(595.28,841.89); break;}
1286 case 'A5': {$format = array(419.53,595.28); break;}
1287 case 'A6': {$format = array(297.64,419.53); break;}
1288 case 'A7': {$format = array(209.76,297.64); break;}
1289 case 'A8': {$format = array(147.40,209.76); break;}
1290 case 'A9': {$format = array(104.88,147.40); break;}
1291 case 'A10': {$format = array(73.70,104.88); break;}
1292 case 'B0': {$format = array(2834.65,4008.19); break;}
1293 case 'B1': {$format = array(2004.09,2834.65); break;}
1294 case 'B2': {$format = array(1417.32,2004.09); break;}
1295 case 'B3': {$format = array(1000.63,1417.32); break;}
1296 case 'B4': {$format = array(708.66,1000.63); break;}
1297 case 'B5': {$format = array(498.90,708.66); break;}
1298 case 'B6': {$format = array(354.33,498.90); break;}
1299 case 'B7': {$format = array(249.45,354.33); break;}
1300 case 'B8': {$format = array(175.75,249.45); break;}
1301 case 'B9': {$format = array(124.72,175.75); break;}
1302 case 'B10': {$format = array(87.87,124.72); break;}
1303 case 'C0': {$format = array(2599.37,3676.54); break;}
1304 case 'C1': {$format = array(1836.85,2599.37); break;}
1305 case 'C2': {$format = array(1298.27,1836.85); break;}
1306 case 'C3': {$format = array(918.43,1298.27); break;}
1307 case 'C4': {$format = array(649.13,918.43); break;}
1308 case 'C5': {$format = array(459.21,649.13); break;}
1309 case 'C6': {$format = array(323.15,459.21); break;}
1310 case 'C7': {$format = array(229.61,323.15); break;}
1311 case 'C8': {$format = array(161.57,229.61); break;}
1312 case 'C9': {$format = array(113.39,161.57); break;}
1313 case 'C10': {$format = array(79.37,113.39); break;}
1314 case 'RA0': {$format = array(2437.80,3458.27); break;}
1315 case 'RA1': {$format = array(1729.13,2437.80); break;}
1316 case 'RA2': {$format = array(1218.90,1729.13); break;}
1317 case 'RA3': {$format = array(864.57,1218.90); break;}
1318 case 'RA4': {$format = array(609.45,864.57); break;}
1319 case 'SRA0': {$format = array(2551.18,3628.35); break;}
1320 case 'SRA1': {$format = array(1814.17,2551.18); break;}
1321 case 'SRA2': {$format = array(1275.59,1814.17); break;}
1322 case 'SRA3': {$format = array(907.09,1275.59); break;}
1323 case 'SRA4': {$format = array(637.80,907.09); break;}
1324 case 'LETTER': {$format = array(612.00,792.00); break;}
1325 case 'LEGAL': {$format = array(612.00,1008.00); break;}
1326 case 'EXECUTIVE': {$format = array(521.86,756.00); break;}
1327 case 'FOLIO': {$format = array(612.00,936.00); break;}
1329 $this->fwPt = $format[0];
1330 $this->fhPt = $format[1];
1333 $this->fwPt = $format[0] * $this->k;
1334 $this->fhPt = $format[1] * $this->k;
1336 $this->setPageOrientation($orientation);
1341 * Set page orientation.
1342 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1343 * @param boolean $autopagebreak Boolean indicating if auto-page-break mode should be on or off.
1344 * @param float $bottommargin bottom margin of the page.
1345 * @since 3.0.015 (2008-06-06)
1347 function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
1348 $orientation = strtoupper($orientation);
1349 if (($orientation == 'P') OR ($orientation == 'PORTRAIT')) {
1350 $this->CurOrientation = 'P';
1351 $this->wPt = $this->fwPt;
1352 $this->hPt = $this->fhPt;
1353 } elseif (($orientation == 'L') OR ($orientation == 'LANDSCAPE')) {
1354 $this->CurOrientation = 'L';
1355 $this->wPt = $this->fhPt;
1356 $this->hPt = $this->fwPt;
1359 $this->Error('Incorrect orientation: '.$orientation);
1361 $this->w = $this->wPt / $this->k;
1362 $this->h = $this->hPt / $this->k;
1363 if (empty($autopagebreak)) {
1364 if (isset($this->AutoPageBreak)) {
1365 $autopagebreak = $this->AutoPageBreak;
1367 $autopagebreak = true;
1370 if (empty($bottommargin)) {
1371 if (isset($this->bMargin)) {
1372 $bottommargin = $this->bMargin;
1374 // default value = 2 cm
1375 $bottommargin = 2 * 28.35 / $this->k;
1378 $this->SetAutoPageBreak($autopagebreak, $bottommargin);
1379 // store page dimensions
1380 $this->pagedim[$this->page] = array('w' => $this->wPt, 'h' => $this->hPt, 'tm' => $this->tMargin, 'bm' => $bottommargin, 'lm' => $this->lMargin, 'rm' => $this->rMargin, 'pb' => $autopagebreak, 'or' => $this->CurOrientation);
1384 * Enable or disable Right-To-Left language mode
1385 * @param Boolean $enable if true enable Right-To-Left language mode.
1386 * @since 2.0.000 (2008-01-03)
1388 function setRTL($enable) {
1389 $this->rtl = $enable ? true : false;
1390 $this->tmprtl = false;
1394 * Return the RTL status
1396 * @since 4.0.012 (2008-07-24)
1403 * Force temporary RTL language direction
1404 * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL
1405 * @since 2.1.000 (2008-01-09)
1407 function setTempRTL($mode) {
1412 $this->tmprtl = $mode;
1418 * Set the last cell height.
1419 * @param float $h cell height.
1420 * @author Nicola Asuni
1421 * @since 1.53.0.TC034
1423 function setLastH($h) {
1428 * Get the last cell height.
1429 * @return last cell height
1430 * @since 4.0.017 (2008-08-05)
1432 function getLastH() {
1433 return $this->lasth;
1437 * Set the image scale.
1438 * @param float $scale image scale.
1439 * @author Nicola Asuni
1442 function setImageScale($scale) {
1443 $this->imgscale = $scale;
1447 * Returns the image scale.
1448 * @return float image scale.
1449 * @author Nicola Asuni
1452 function getImageScale() {
1453 return $this->imgscale;
1457 * Returns the page width in units.
1458 * @return int page width.
1459 * @author Nicola Asuni
1462 function getPageWidth() {
1467 * Returns the page height in units.
1468 * @return int page height.
1469 * @author Nicola Asuni
1472 function getPageHeight() {
1477 * Returns the page break margin.
1478 * @return int page break margin.
1479 * @author Nicola Asuni
1482 function getBreakMargin() {
1483 return $this->bMargin;
1487 * Returns the scale factor (number of points in user unit).
1488 * @return int scale factor.
1489 * @author Nicola Asuni
1492 function getScaleFactor() {
1497 * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
1498 * @param float $left Left margin.
1499 * @param float $top Top margin.
1500 * @param float $right Right margin. Default value is the left one.
1502 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
1504 function SetMargins($left, $top, $right=-1) {
1505 //Set left, top and right margins
1506 $this->lMargin = $left;
1507 $this->tMargin = $top;
1511 $this->rMargin = $right;
1515 * 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.
1516 * @param float $margin The margin.
1518 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1520 function SetLeftMargin($margin) {
1522 $this->lMargin=$margin;
1523 if (($this->page > 0) AND ($this->x < $margin)) {
1529 * Defines the top margin. The method can be called before creating the first page.
1530 * @param float $margin The margin.
1532 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1534 function SetTopMargin($margin) {
1536 $this->tMargin=$margin;
1537 if (($this->page > 0) AND ($this->y < $margin)) {
1543 * Defines the right margin. The method can be called before creating the first page.
1544 * @param float $margin The margin.
1546 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1548 function SetRightMargin($margin) {
1549 $this->rMargin=$margin;
1550 if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
1551 $this->x = $this->w - $margin;
1556 * Set the internal Cell padding.
1557 * @param float $pad internal padding.
1558 * @since 2.1.000 (2008-01-09)
1559 * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1561 function SetCellPadding($pad) {
1562 $this->cMargin = $pad;
1566 * 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.
1567 * @param boolean $auto Boolean indicating if mode should be on or off.
1568 * @param float $margin Distance from the bottom of the page.
1570 * @see Cell(), MultiCell(), AcceptPageBreak()
1572 function SetAutoPageBreak($auto, $margin=0) {
1573 //Set auto page break mode and triggering margin
1574 $this->AutoPageBreak = $auto;
1575 $this->bMargin = $margin;
1576 $this->PageBreakTrigger = $this->h - $margin;
1580 * Defines the way the document is to be displayed by the viewer.
1581 * @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>
1582 * @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>
1583 * @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>
1586 function SetDisplayMode($zoom, $layout='SinglePage', $mode="UseNone") {
1587 //Set display mode in viewer
1588 if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
1589 $this->ZoomMode = $zoom;
1591 $this->Error('Incorrect zoom display mode: '.$zoom);
1596 case "SinglePage": {
1597 $this->LayoutMode = "SinglePage";
1602 $this->LayoutMode = "OneColumn";
1606 case "TwoColumnLeft": {
1607 $this->LayoutMode = "TwoColumnLeft";
1610 case "TwoColumnRight": {
1611 $this->LayoutMode = "TwoColumnRight";
1614 case "TwoPageLeft": {
1615 $this->LayoutMode = "TwoPageLeft";
1618 case "TwoPageRight": {
1619 $this->LayoutMode = "TwoPageRight";
1623 $this->LayoutMode = "SinglePage";
1628 $this->PageMode = "UseNone";
1631 case "UseOutlines": {
1632 $this->PageMode = "UseOutlines";
1636 $this->PageMode = "UseThumbs";
1639 case "FullScreen": {
1640 $this->PageMode = "FullScreen";
1644 $this->PageMode = "UseOC";
1648 $this->PageMode = "UseAttachments";
1652 $this->PageMode = "UseNone";
1658 * 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.
1659 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
1660 * @param boolean $compress Boolean indicating if compression must be enabled.
1663 function SetCompression($compress) {
1664 //Set page compression
1665 if (function_exists('gzcompress')) {
1666 $this->compress = $compress;
1668 $this->compress = false;
1673 * Defines the title of the document.
1674 * @param string $title The title.
1676 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
1678 function SetTitle($title) {
1680 $this->title = $title;
1684 * Defines the subject of the document.
1685 * @param string $subject The subject.
1687 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
1689 function SetSubject($subject) {
1690 //Subject of document
1691 $this->subject = $subject;
1695 * Defines the author of the document.
1696 * @param string $author The name of the author.
1698 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
1700 function SetAuthor($author) {
1701 //Author of document
1702 $this->author = $author;
1706 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
1707 * @param string $keywords The list of keywords.
1709 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
1711 function SetKeywords($keywords) {
1712 //Keywords of document
1713 $this->keywords = $keywords;
1717 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
1718 * @param string $creator The name of the creator.
1720 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
1722 function SetCreator($creator) {
1723 //Creator of document
1724 $this->creator = $creator;
1728 * Defines an alias for the total number of pages. It will be substituted as the document is closed.<br />
1729 * @param string $alias The alias. Default value: {nb}.
1731 * @see getAliasNbPages(), PageNo(), Footer()
1733 function AliasNbPages($alias='{nb}') {
1734 //Define an alias for total number of pages
1735 $this->AliasNbPages = $alias;
1739 * Returns the string alias used for the total number of pages.
1740 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
1742 * @since 4.0.018 (2008-08-08)
1743 * @see AliasNbPages(), PageNo(), Footer()
1745 function getAliasNbPages() {
1746 if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
1747 return "{".$this->AliasNbPages."}";
1749 return $this->AliasNbPages;
1753 * 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.
1754 * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
1755 * @param string $msg The error message
1758 function Error($msg) {
1760 display_error('<strong>TCPDF error: </strong>'.$msg);
1765 * This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.
1766 * Note: no page is created by this method
1768 * @see AddPage(), Close()
1776 * Terminates the PDF document. It is not necessary to call this method explicitly because Output() does it automatically. If the document contains no page, AddPage() is called to prevent from getting an invalid document.
1778 * @see Open(), Output()
1781 //Terminate document
1782 if ($this->state == 3) {
1785 if ($this->page == 0) {
1797 * Move pointer at the specified document page and update page dimensions.
1798 * @param int $pnum page number
1799 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
1800 * @since 2.1.000 (2008-01-07)
1801 * @see getPage(), lastpage(), getNumPages()
1803 function setPage($pnum, $resetmargins=false) {
1804 if (($pnum > 0) AND ($pnum <= count($this->pages))) {
1805 $this->page = $pnum;
1806 $this->wPt = $this->pagedim[$this->page]['w'];
1807 $this->hPt = $this->pagedim[$this->page]['h'];
1808 $this->w = $this->wPt / $this->k;
1809 $this->h = $this->hPt / $this->k;
1810 $this->tMargin = $this->pagedim[$this->page]['tm'];
1811 $this->bMargin = $this->pagedim[$this->page]['bm'];
1812 $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
1813 $this->CurOrientation = $this->pagedim[$this->page]['or'];
1814 $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
1815 if ($resetmargins) {
1816 $this->lMargin = $this->pagedim[$this->page]['lm'];
1817 $this->rMargin = $this->pagedim[$this->page]['rm'];
1818 $this->SetY($this->tMargin);
1821 $this->Error('Wrong page number on setPage() function.');
1826 * Reset pointer to the last document page.
1827 * @since 2.0.000 (2008-01-04)
1828 * @see setPage(), getPage(), getNumPages()
1830 function lastPage() {
1831 $this->setPage($this->getNumPages());
1835 * Get current document page number.
1836 * @return int page number
1837 * @since 2.1.000 (2008-01-07)
1838 * @see setPage(), lastpage(), getNumPages()
1840 function getPage() {
1846 * Get the total number of insered pages.
1847 * @return int number of pages
1848 * @since 2.1.000 (2008-01-07)
1849 * @see setPage(), getPage(), lastpage()
1851 function getNumPages() {
1852 return count($this->pages);
1856 * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer. Then the page is added, the current position set to the top-left corner according to the left and top margins, and Header() is called to display the header.
1857 * The font which was set before calling is automatically restored. There is no need to call SetFont() again if you want to continue with the same font. The same is true for colors and line width.
1858 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
1859 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1860 * @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>
1862 * @see TCPDF(), Header(), Footer(), SetMargins()
1864 function AddPage($orientation='', $format='') {
1865 if (!isset($this->original_lMargin)) {
1866 $this->original_lMargin = $this->lMargin;
1868 if (!isset($this->original_rMargin)) {
1869 $this->original_rMargin = $this->rMargin;
1871 if (count($this->pages) > $this->page) {
1872 // this page has been already added
1873 $this->setPage(($this->page + 1));
1874 $this->SetY($this->tMargin);
1878 if ($this->state == 0) {
1881 // save current settings
1882 $font_family = $this->FontFamily;
1883 $font_style = $this->FontStyle.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '');
1884 $font_size = $this->FontSizePt;
1885 $prev_rMargin = $this->rMargin;
1886 $prev_lMargin = $this->lMargin;
1887 $prev_cMargin = $this->cMargin;
1888 $prev_linestyleWidth = $this->linestyleWidth;
1889 $prev_linestyleCap = $this->linestyleCap;
1890 $prev_linestyleJoin = $this->linestyleJoin;
1891 $prev_linestyleDash = $this->linestyleDash;
1892 $prev_DrawColor = $this->DrawColor;
1893 $prev_FillColor = $this->FillColor;
1894 $prev_TextColor = $this->TextColor;
1895 $prev_ColorFlag = $this->ColorFlag;
1896 if ($this->page > 0) {
1903 $this->_beginpage($orientation, $format);
1904 // restore graphic styles
1905 $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1906 if (!empty($font_family)) {
1907 $this->SetFont($font_family, $font_style, $font_size);
1911 // restore graphic styles
1912 $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1913 if (!empty($font_family)) {
1914 $this->SetFont($font_family, $font_style, $font_size);
1917 $this->FontFamily = $font_family;
1918 $this->FontStyle = $font_style;
1919 $this->FontSizePt = $font_size;
1920 $this->rMargin = $prev_rMargin;
1921 $this->lMargin = $prev_lMargin;
1922 $this->cMargin = $prev_cMargin;
1923 $this->linestyleWidth = $prev_linestyleWidth;
1924 $this->linestyleCap = $prev_linestyleCap;
1925 $this->linestyleJoin = $prev_linestyleJoin;
1926 $this->linestyleDash = $prev_linestyleDash;
1927 $this->DrawColor = $prev_DrawColor;
1928 $this->FillColor = $prev_FillColor;
1929 $this->TextColor = $prev_TextColor;
1930 $this->ColorFlag = $prev_ColorFlag;
1932 $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1936 * Set start-writing mark on current page for multicell borders and fills.
1937 * This function must be called after calling Image() function for a background image.
1938 * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
1940 * @since 4.0.016 (2008-07-30)
1942 function setPageMark() {
1943 $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1948 * @param string $ln header image logo
1949 * @param string $lw header image logo width in mm
1950 * @param string $ht string to print as title on document header
1951 * @param string $hs string to print on document header
1953 function setHeaderData($ln="", $lw=0, $ht="", $hs="") {
1954 $this->header_logo = $ln;
1955 $this->header_logo_width = $lw;
1956 $this->header_title = $ht;
1957 $this->header_string = $hs;
1961 * Returns header data:
1962 * <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>
1964 * @since 4.0.012 (2008-07-24)
1966 function getHeaderData() {
1968 $ret['logo'] = $this->header_logo;
1969 $ret['logo_width'] = $this->header_logo_width;
1970 $ret['title'] = $this->header_title;
1971 $ret['string'] = $this->header_string;
1976 * Set header margin.
1977 * (minimum distance between header and top page margin)
1978 * @param int $hm distance in user units
1980 function setHeaderMargin($hm=10) {
1981 $this->header_margin = $hm;
1985 * Returns header margin in user units.
1987 * @since 4.0.012 (2008-07-24)
1989 function getHeaderMargin() {
1990 return $this->header_margin;
1994 * Set footer margin.
1995 * (minimum distance between footer and bottom page margin)
1996 * @param int $fm distance in user units
1998 function setFooterMargin($fm=10) {
1999 $this->footer_margin = $fm;
2003 * Returns footer margin in user units.
2005 * @since 4.0.012 (2008-07-24)
2007 function getFooterMargin() {
2008 return $this->footer_margin;
2011 * Set a flag to print page header.
2012 * @param boolean $val set to true to print the page header (default), false otherwise.
2014 function setPrintHeader($val=true) {
2015 $this->print_header = $val;
2019 * Set a flag to print page footer.
2020 * @param boolean $value set to true to print the page footer (default), false otherwise.
2022 function setPrintFooter($val=true) {
2023 $this->print_footer = $val;
2027 * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
2030 function getImageRBX() {
2031 return $this->img_rb_x;
2035 * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
2038 function getImageRBY() {
2039 return $this->img_rb_y;
2043 * This method is used to render the page header.
2044 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2046 function Header1() {
2047 $ormargins = $this->getOriginalMargins();
2048 $headerfont = $this->getHeaderFont();
2049 $headerdata = $this->getHeaderData();
2050 if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
2051 $this->Image(K_PATH_IMAGES.$headerdata['logo'], $this->GetX(), $this->getHeaderMargin(), $headerdata['logo_width']);
2052 $imgy = $this->getImageRBY();
2054 $imgy = $this->GetY();
2056 $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2);
2057 // set starting margin for text data cell
2058 if ($this->getRTL()) {
2059 $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1);
2061 $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1);
2063 $this->SetTextColor(0, 0, 0);
2065 $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
2066 $this->SetX($header_x);
2067 $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '');
2069 $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
2070 $this->SetX($header_x);
2071 $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, 0, 0, true, 0);
2072 // print an ending header line
2073 $this->SetLineStyle(array("width" => 0.85 / $this->getScaleFactor(), "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2074 $this->SetY(1 + max($imgy, $this->GetY()));
2075 if ($this->getRTL()) {
2076 $this->SetX($ormargins['right']);
2078 $this->SetX($ormargins['left']);
2080 $this->Cell(0, 0, '', 'T', 0, 'C');
2084 * This method is used to render the page footer.
2085 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2088 $cur_y = $this->GetY();
2089 $ormargins = $this->getOriginalMargins();
2090 $this->SetTextColor(0, 0, 0);
2091 //set style for cell border
2092 $line_width = 0.85 / $this->getScaleFactor();
2093 $this->SetLineStyle(array("width" => $line_width, "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2094 //print document barcode
2095 $barcode = $this->getBarcode();
2096 if (!empty($barcode)) {
2098 $barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right'])/3);
2099 $this->write1DBarcode($barcode, "C128B", $this->GetX(), $cur_y + $line_width, $barcode_width, (($this->getFooterMargin() / 3) - $line_width), 0.3, '', '');
2101 $pagenumtxt = $this->l['w_page']." ".$this->PageNo().' / '.$this->getAliasNbPages();
2102 $this->SetY($cur_y);
2104 if ($this->getRTL()) {
2105 $this->SetX($ormargins['right']);
2106 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
2108 $this->SetX($ormargins['left']);
2109 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R');
2114 * This method is used to render the page header.
2116 * @since 4.0.012 (2008-07-24)
2118 function setHeader() {
2119 if ($this->print_header) {
2120 $lasth = $this->lasth;
2122 $this->rMargin = $this->original_rMargin;
2123 $this->lMargin = $this->original_lMargin;
2124 //set current position
2126 $this->SetXY($this->original_rMargin, $this->header_margin);
2128 $this->SetXY($this->original_lMargin, $this->header_margin);
2130 $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
2134 $this->SetXY($this->original_rMargin, $this->tMargin);
2136 $this->SetXY($this->original_lMargin, $this->tMargin);
2139 $this->lasth = $lasth;
2144 * This method is used to render the page footer.
2146 * @since 4.0.012 (2008-07-24)
2148 function setFooter() {
2150 $this->InFooter = true;
2152 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
2153 if ($this->print_footer) {
2154 $lasth = $this->lasth;
2156 $this->rMargin = $this->original_rMargin;
2157 $this->lMargin = $this->original_lMargin;
2158 //set current position
2159 $footer_y = $this->h - $this->footer_margin;
2161 $this->SetXY($this->original_rMargin, $footer_y);
2163 $this->SetXY($this->original_lMargin, $footer_y);
2165 $this->SetFont($this->footer_font[0], $this->footer_font[1] , $this->footer_font[2]);
2169 $this->SetXY($this->original_rMargin, $this->tMargin);
2171 $this->SetXY($this->original_lMargin, $this->tMargin);
2174 $this->lasth = $lasth;
2176 $this->footerlen[$this->page] = strlen($this->pages[$this->page]) - $this->footerpos[$this->page];
2177 $this->InFooter = false;
2181 * Returns the current page number.
2182 * @return int page number
2184 * @see AliasNbPages(), getAliasNbPages()
2191 * Defines a new spot color.
2192 * It can be expressed in RGB components or gray scale.
2193 * The method can be called before the first page is created and the value is retained from page to page.
2194 * @param int $c Cyan color for CMYK. Value between 0 and 255
2195 * @param int $m Magenta color for CMYK. Value between 0 and 255
2196 * @param int $y Yellow color for CMYK. Value between 0 and 255
2197 * @param int $k Key (Black) color for CMYK. Value between 0 and 255
2198 * @since 4.0.024 (2008-09-12)
2199 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2201 function AddSpotColor($name, $c, $m, $y, $k) {
2202 if (!isset($this->spot_colors[$name])) {
2203 $i = 1 + count($this->spot_colors);
2204 $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k);
2209 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
2210 * It can be expressed in RGB components or gray scale.
2211 * The method can be called before the first page is created and the value is retained from page to page.
2212 * @param array $color array of colors
2213 * @since 3.1.000 (2008-06-11)
2214 * @see SetDrawColor()
2216 function SetDrawColorArray($color) {
2217 if (isset($color)) {
2218 $color = array_values($color);
2219 $r = isset($color[0]) ? $color[0] : -1;
2220 $g = isset($color[1]) ? $color[1] : -1;
2221 $b = isset($color[2]) ? $color[2] : -1;
2222 $k = isset($color[3]) ? $color[3] : -1;
2224 $this->SetDrawColor($r, $g, $b, $k);
2230 * 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.
2231 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2232 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2233 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2234 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2236 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
2238 function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2239 // set default values
2240 if (!is_numeric($col1)) {
2243 if (!is_numeric($col2)) {
2246 if (!is_numeric($col3)) {
2249 if (!is_numeric($col4)) {
2252 //Set color for all stroking operations
2253 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2255 $this->DrawColor = sprintf('%.3f G', $col1/255);
2256 } elseif ($col4 == -1) {
2258 $this->DrawColor = sprintf('%.3f %.3f %.3f RG', $col1/255, $col2/255, $col3/255);
2261 $this->DrawColor = sprintf('%.3f %.3f %.3f %.3f K', $col1/100, $col2/100, $col3/100, $col4/100);
2263 if ($this->page > 0) {
2264 $this->_out($this->DrawColor);
2269 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
2270 * @param string $name name of the spot color
2271 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2272 * @since 4.0.024 (2008-09-12)
2273 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2275 function SetDrawSpotColor($name, $tint=100) {
2276 if (!isset($this->spot_colors[$name])) {
2277 $this->Error('Undefined spot color: '.$name);
2279 $this->DrawColor = sprintf('/CS%d CS %.3f SCN', $this->spot_colors[$name]['i'], $tint/100);
2280 if ($this->page > 0) {
2281 $this->_out($this->DrawColor);
2286 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
2287 * It can be expressed in RGB components or gray scale.
2288 * The method can be called before the first page is created and the value is retained from page to page.
2289 * @param array $color array of colors
2290 * @since 3.1.000 (2008-6-11)
2291 * @see SetFillColor()
2293 function SetFillColorArray($color) {
2294 if (isset($color)) {
2295 $color = array_values($color);
2296 $r = isset($color[0]) ? $color[0] : -1;
2297 $g = isset($color[1]) ? $color[1] : -1;
2298 $b = isset($color[2]) ? $color[2] : -1;
2299 $k = isset($color[3]) ? $color[3] : -1;
2301 $this->SetFillColor($r, $g, $b, $k);
2307 * 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.
2308 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2309 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2310 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2311 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2313 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
2315 function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2316 // set default values
2317 if (!is_numeric($col1)) {
2320 if (!is_numeric($col2)) {
2323 if (!is_numeric($col3)) {
2326 if (!is_numeric($col4)) {
2329 //Set color for all filling operations
2330 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2332 $this->FillColor = sprintf('%.3f g', $col1/255);
2333 $this->bgcolor = array('G' => $col1);
2334 } elseif ($col4 == -1) {
2336 $this->FillColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2337 $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2340 $this->FillColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2341 $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2343 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2344 if ($this->page > 0) {
2345 $this->_out($this->FillColor);
2350 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
2351 * @param string $name name of the spot color
2352 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2353 * @since 4.0.024 (2008-09-12)
2354 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
2356 function SetFillSpotColor($name, $tint=100) {
2357 if (!isset($this->spot_colors[$name])) {
2358 $this->Error('Undefined spot color: '.$name);
2360 $this->FillColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2361 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2362 if ($this->page > 0) {
2363 $this->_out($this->FillColor);
2368 * Defines the color used for text. It can be expressed in RGB components or gray scale.
2369 * The method can be called before the first page is created and the value is retained from page to page.
2370 * @param array $color array of colors
2371 * @since 3.1.000 (2008-6-11)
2372 * @see SetFillColor()
2374 function SetTextColorArray($color) {
2375 if (isset($color)) {
2376 $color = array_values($color);
2377 $r = isset($color[0]) ? $color[0] : -1;
2378 $g = isset($color[1]) ? $color[1] : -1;
2379 $b = isset($color[2]) ? $color[2] : -1;
2380 $k = isset($color[3]) ? $color[3] : -1;
2382 $this->SetTextColor($r, $g, $b, $k);
2388 * 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.
2389 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2390 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2391 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2392 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2394 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
2396 function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2397 // set default values
2398 if (!is_numeric($col1)) {
2401 if (!is_numeric($col2)) {
2404 if (!is_numeric($col3)) {
2407 if (!is_numeric($col4)) {
2410 //Set color for text
2411 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2413 $this->TextColor = sprintf('%.3f g', $col1/255);
2414 $this->fgcolor = array('G' => $col1);
2415 } elseif ($col4 == -1) {
2417 $this->TextColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2418 $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2421 $this->TextColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2422 $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2424 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2428 * Defines the spot color used for text.
2429 * @param string $name name of the spot color
2430 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2431 * @since 4.0.024 (2008-09-12)
2432 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
2434 function SetTextSpotColor($name, $tint=100) {
2435 if (!isset($this->spot_colors[$name])) {
2436 $this->Error('Undefined spot color: '.$name);
2438 $this->TextColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2439 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2440 if ($this->page > 0) {
2441 $this->_out($this->TextColor);
2446 * Returns the length of a string in user unit. A font must be selected.<br>
2447 * @param string $s The string whose length is to be computed
2448 * @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.
2449 * @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.
2450 * @param float $fontsize Font size in points. The default value is the current size.
2451 * @return int string length
2452 * @author Nicola Asuni
2455 function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0) {
2456 return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $this->tmprtl), $fontname, $fontstyle, $fontsize);
2460 * Returns the string length of an array of chars in user unit. A font must be selected.<br>
2461 * @param string $arr The array of chars whose total length is to be computed
2462 * @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.
2463 * @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.
2464 * @param float $fontsize Font size in points. The default value is the current size.
2465 * @return int string length
2466 * @author Nicola Asuni
2467 * @since 2.4.000 (2008-03-06)
2469 function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0) {
2470 // store current values
2471 if (!empty($fontname)) {
2472 $prev_FontFamily = $this->FontFamily;
2473 $prev_FontStyle = $this->FontStyle;
2474 $prev_FontSizePt = $this->FontSizePt;
2475 $this->SetFont($fontname, $fontstyle, $fontsize);
2478 foreach($sa as $char) {
2479 $w += $this->GetCharWidth($char);
2481 // restore previous values
2482 if (!empty($fontname)) {
2483 $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt);
2489 * Returns the length of the char in user unit for the current font.<br>
2490 * @param int $char The char code whose length is to be returned
2491 * @return int char width
2492 * @author Nicola Asuni
2493 * @since 2.4.000 (2008-03-06)
2495 function GetCharWidth($char) {
2496 $cw = &$this->CurrentFont['cw'];
2497 if (isset($cw[$char])) {
2500 } elseif (isset($cw[ord($char)])) {
2501 $w = $cw[ord($char)];
2502 } elseif (isset($cw[chr($char)])) {
2503 $w = $cw[chr($char)];
2505 } elseif (isset($this->CurrentFont['dw'])) {
2506 $w = $this->CurrentFont['dw'];
2507 } elseif (isset($this->CurrentFont['desc']['MissingWidth'])) {
2508 $w = $this->CurrentFont['desc']['MissingWidth']; // set default size
2510 $w = 500; // default width
2512 return ($w * $this->FontSize / 1000);
2516 * Returns the numbero of characters in a string.
2517 * @param string $s The input string.
2518 * @return int number of characters
2519 * @since 2.0.0001 (2008-01-07)
2521 function GetNumChars($s) {
2522 if ($this->isunicode) {
2523 return count($this->UTF8StringToArray($s));
2529 * Fill the list of available fonts ($this->fontlist).
2531 * @since 4.0.013 (2008-07-28)
2533 function getFontsList() {
2534 $fontsdir = opendir($this->_getfontpath());
2535 while (($file = readdir($fontsdir)) !== false) {
2536 if (substr($file, -4) == ".php") {
2537 array_push($this->fontlist, strtolower(basename($file, ".php")));
2540 closedir($fontsdir);
2544 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
2545 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
2546 * 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.
2547 * Changed to support UTF-8 Unicode [Nicola Asuni, 2005-01-02].
2548 * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
2549 * @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>
2550 * @param string $file The font definition file. By default, the name is built from the family and style, in lower case with no space.
2551 * @return array containing the font data, or false in case of error.
2555 function AddFont($family, $style='', $file='') {
2556 if (empty($family)) {
2557 if (!empty($this->FontFamily)) {
2558 $family = $this->FontFamily;
2560 $this->Error('Empty font family');
2563 $family = strtolower($family);
2564 if ((!$this->isunicode) AND ($family == 'arial')) {
2565 $family = 'helvetica';
2567 if (($family == "symbol") OR ($family == "zapfdingbats")) {
2570 $style = strtoupper($style);
2572 if (strpos($style,'U') !== false) {
2573 $this->underline = true;
2574 $style = str_replace('U', '', $style);
2576 $this->underline = false;
2578 //line through (deleted)
2579 if (strpos($style,'D') !== false) {
2580 $this->linethrough = true;
2581 $style = str_replace('D', '', $style);
2583 $this->linethrough = false;
2585 if ($style == 'IB') {
2588 $fontkey = $family.$style;
2589 $fontdata = array("fontkey" => $fontkey, "family" => $family, "style" => $style);
2590 // check if the font has been already added
2591 if (isset($this->fonts[$fontkey])) {
2595 $file = str_replace(' ', '', $family).strtolower($style).'.php';
2597 if (!file_exists($this->_getfontpath().$file)) {
2598 // try to load the basic file without styles
2599 $file = str_replace(' ', '', $family).'.php';
2607 @include($this->_getfontpath().$file);
2608 if ((!isset($type)) OR (!isset($cw))) {
2609 $this->Error("Could not include font definition file: ".$file);
2611 $i = count($this->fonts) + 1;
2612 // register CID font (all styles at once)
2613 if ($type == 'cidfont0') {
2614 $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
2615 foreach ($styles as $skey => $qual) {
2616 $sname = $name.$qual;
2617 $sfontkey = $family.$skey;
2618 $this->fonts[$sfontkey] = array('i' => $i, 'type' => $type, 'name' => $sname, 'desc' => $desc, 'cidinfo' => $cidinfo, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc);
2619 $i = count($this->fonts) + 1;
2622 } elseif ($type == 'core') {
2623 $def_width = $cw[ord('?')];
2624 $this->fonts[$fontkey] = array('i' => $i, 'type' => 'core', 'name' => $this->CoreFonts[$fontkey], 'up' => -100, 'ut' => 50, 'cw' => $cw, 'dw' => $def_width);
2625 } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
2626 if (!isset($file)) {
2632 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'file' => $file, 'enc' => $enc, 'desc' => $desc);
2633 } elseif ($type == 'TrueTypeUnicode') {
2634 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'enc' => $enc, 'file' => $file, 'ctg' => $ctg);
2636 $this->Error('Unknow font type');
2638 if (isset($diff) AND (!empty($diff))) {
2639 //Search existing encodings
2641 $nb = count($this->diffs);
2642 for($i=1; $i <= $nb; $i++) {
2643 if ($this->diffs[$i] == $diff) {
2650 $this->diffs[$d] = $diff;
2652 $this->fonts[$fontkey]['diff'] = $d;
2654 if (!empty($file)) {
2655 if ((strcasecmp($type,"TrueType") == 0) OR (strcasecmp($type,"TrueTypeUnicode") == 0)) {
2656 $this->FontFiles[$file] = array('length1' => $originalsize);
2657 } elseif ($type != 'core') {
2658 $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2);
2665 * Sets the font used to print character strings.
2666 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
2667 * The method can be called before the first page is created and the font is retained from page to page.
2668 * If you just wish to change the current font size, it is simpler to call SetFontSize().
2669 * 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 />
2670 * @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.
2671 * @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.
2672 * @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
2674 * @see AddFont(), SetFontSize()
2676 function SetFont($family, $style='', $size=0) {
2677 //Select a font; size given in points
2679 $size = $this->FontSizePt;
2681 // try to add font (if not already added)
2682 $fontdata = $this->AddFont($family, $style);
2683 $this->FontFamily = $fontdata['family'];
2684 $this->FontStyle = $fontdata['style'];
2685 $this->CurrentFont = &$this->fonts[$fontdata['fontkey']];
2686 $this->SetFontSize($size);
2690 * Defines the size of the current font.
2691 * @param float $size The size (in points)
2695 function SetFontSize($size) {
2696 //Set font size in points
2697 $this->FontSizePt = $size;
2698 $this->FontSize = $size / $this->k;
2699 if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
2700 $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000;
2702 $this->FontAscent = 0.8 * $this->FontSize;
2704 if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] > 0)) {
2705 $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000;
2707 $this->FontDescent = 0.2 * $this->FontSize;
2709 if (($this->page > 0) AND (isset($this->CurrentFont['i']))) {
2710 $this->_out(sprintf('BT /F%d %.2f Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
2715 * 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 />
2716 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
2718 * @see Cell(), Write(), Image(), Link(), SetLink()
2720 function AddLink() {
2721 //Create a new internal link
2722 $n = count($this->links) + 1;
2723 $this->links[$n] = array(0, 0);
2728 * Defines the page and position a link points to.
2729 * @param int $link The link identifier returned by AddLink()
2730 * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
2731 * @param int $page Number of target page; -1 indicates the current page. This is the default value
2735 function SetLink($link, $y=0, $page=-1) {
2740 $page = $this->page;
2742 $this->links[$link] = array($page, $y);
2746 * Puts a link on a rectangular area of the page.
2747 * 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.
2748 * @param float $x Abscissa of the upper-left corner of the rectangle
2749 * @param float $y Ordinate of the upper-left corner of the rectangle
2750 * @param float $w Width of the rectangle
2751 * @param float $h Height of the rectangle
2752 * @param mixed $link URL or identifier returned by AddLink()
2754 * @see AddLink(), Annotation(), Cell(), Write(), Image()
2756 function Link($x, $y, $w, $h, $link) {
2757 $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'));
2761 * Puts a text annotation on a rectangular area of the page.
2762 * !!!! THIS FUNCTION IS NOT YET FULLY IMPLEMENTED !!!!
2763 * @param float $x Abscissa of the upper-left corner of the rectangle
2764 * @param float $y Ordinate of the upper-left corner of the rectangle
2765 * @param float $w Width of the rectangle
2766 * @param float $h Height of the rectangle
2767 * @param string $text annotation text
2768 * @param array $opt array of options (see section 8.4 of PDF reference 1.7).
2769 * @since 4.0.018 (2008-08-06)
2771 function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text')) {
2772 $this->PageAnnots[$this->page][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt);
2776 * Prints a character string. The origin is on the left of the first charcter, on the baseline. This method allows to place a string precisely on the page, but it is usually easier to use Cell(), MultiCell() or Write() which are the standard methods to print text.
2777 * @param float $x Abscissa of the origin
2778 * @param float $y Ordinate of the origin
2779 * @param string $txt String to print
2780 * @param int $stroke outline size in points (0 = disable)
2781 * @param boolean $clip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
2783 * @see SetFont(), SetTextColor(), Cell(), MultiCell(), Write()
2785 function Text($x, $y, $txt, $stroke=0, $clip=false) {
2788 // bidirectional algorithm (some chars may be changed affecting the line length)
2789 $s = $this->utf8Bidi($this->UTF8StringToArray($txt), $this->tmprtl);
2790 $l = $this->GetArrStringWidth($s);
2791 $xr = $this->w - $x - $this->GetArrStringWidth($s);
2796 if (($stroke > 0) AND (!$clip)) {
2797 $opt .= "1 Tr ".intval($stroke)." w ";
2798 } elseif (($stroke > 0) AND $clip) {
2799 $opt .= "5 Tr ".intval($stroke)." w ";
2803 $s = sprintf('BT %.2f %.2f Td %s(%s) Tj ET 0 Tr', $xr * $this->k, ($this->h-$y) * $this->k, $opt, $this->_escapetext($txt));
2804 if ($this->underline AND ($txt!='')) {
2805 $s .= ' '.$this->_dounderline($xr, $y, $txt);
2807 if ($this->linethrough AND ($txt!='')) {
2808 $s .= ' '.$this->_dolinethrough($xr, $y, $txt);
2810 if ($this->ColorFlag AND (!$clip)) {
2811 $s='q '.$this->TextColor.' '.$s.' Q';
2817 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
2818 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
2819 * This method is called automatically and should not be called directly by the application.
2822 * @see SetAutoPageBreak()
2824 function AcceptPageBreak() {
2825 return $this->AutoPageBreak;
2829 * Add page if needed.
2830 * @param float $h Cell height. Default value: 0.
2831 * @since 3.2.000 (2008-07-01)
2834 function checkPageBreak($h) {
2835 if ((($this->y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
2837 //Automatic page break
2844 $this->AddPage($this->CurOrientation);
2847 $rs .= sprintf('%.3f Tw', $ws * $k);
2850 $this->y = $this->tMargin;
2856 * 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 />
2857 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2858 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2859 * @param float $h Cell height. Default value: 0.
2860 * @param string $txt String to print. Default value: empty string.
2861 * @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>
2862 * @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>
2863 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
2864 * @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>
2865 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2866 * @param mixed $link URL or identifier returned by AddLink().
2867 * @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>
2869 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
2871 function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2872 //$min_cell_height = $this->FontAscent + $this->FontDescent;
2873 $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2874 if ($h < $min_cell_height) {
2875 $h = $min_cell_height;
2877 $this->checkPageBreak($h);
2878 $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch));
2882 * 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 />
2883 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2884 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2885 * @param float $h Cell height. Default value: 0.
2886 * @param string $txt String to print. Default value: empty string.
2887 * @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>
2888 * @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.
2889 * @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>
2890 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2891 * @param mixed $link URL or identifier returned by AddLink().
2892 * @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>
2896 function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2897 $rs = ""; //string to be returned
2898 $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2899 if ($h < $min_cell_height) {
2900 $h = $min_cell_height;
2903 if (empty($w) OR ($w <= 0)) {
2905 $w = $this->x - $this->lMargin;
2907 $w = $this->w - $this->rMargin - $this->x;
2911 if (($fill == 1) OR ($border == 1)) {
2913 $op = ($border == 1) ? 'B' : 'f';
2918 $xk = (($this->x - $w) * $k);
2920 $xk = ($this->x * $k);
2922 $s .= sprintf('%.2f %.2f %.2f %.2f re %s ', $xk, (($this->h - $this->y) * $k), ($w * $k), (-$h * $k), $op);
2925 if (is_string($border)) {
2928 if (strpos($border,'L') !== false) {
2930 $xk = ($x - $w) * $k;
2934 $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h)) * $k));
2936 if (strpos($border,'T') !== false) {
2938 $xk = ($x - $w) * $k;
2942 $xwk = ($x + $w) * $k;
2944 $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xwk, (($this->h - $y) * $k));
2946 if (strpos($border,'R') !== false) {
2950 $xk = ($x + $w) * $k;
2952 $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h))* $k));
2954 if (strpos($border,'B') !== false) {
2956 $xk = ($x - $w) * $k;
2960 $xwk = ($x + $w) * $k;
2962 $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - ($y + $h)) * $k), $xwk, (($this->h - ($y + $h)) * $k));
2967 $width = $this->GetStringWidth($txt);
2968 // ratio between cell lenght and text lenght
2969 $ratio = ($w - (2 * $this->cMargin)) / $width;
2971 // stretch text if required
2972 if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) {
2975 //Calculate character spacing in points
2976 $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1);
2977 //Set character spacing
2978 $rs .= sprintf('BT %.2f Tc ET ', $char_space);
2981 //Calculate horizontal scaling
2982 $horiz_scale = $ratio * 100.0;
2983 //Set horizontal scaling
2984 $rs .= sprintf('BT %.2f Tz ET ', $horiz_scale);
2987 $width = $w - (2 * $this->cMargin);
2991 if ($align == 'L') {
2993 $dx = $w - $width - $this->cMargin;
2995 $dx = $this->cMargin;
2997 } elseif ($align == 'R') {
2999 $dx = $this->cMargin;
3001 $dx = $w - $width - $this->cMargin;
3003 } elseif ($align == 'C') {
3004 $dx = ($w - $width) / 2;
3005 } elseif ($align == 'J') {
3007 $dx = $w - $width - $this->cMargin;
3009 $dx = $this->cMargin;
3012 $dx = $this->cMargin;
3014 if ($this->ColorFlag) {
3015 $s .= 'q '.$this->TextColor.' ';
3017 $txt2 = $this->_escapetext($txt);
3019 $xdk = ($this->x - $dx - $width) * $k;
3021 $xdk = ($this->x + $dx) * $k;
3024 if ($align == 'J') {
3025 // count number of spaces
3026 $ns = substr_count($txt, ' ');
3027 //if ($this->isunicode) {
3028 if (($this->CurrentFont['type'] == "TrueTypeUnicode") OR ($this->CurrentFont['type'] == "cidfont0")) {
3029 // get string width without spaces
3030 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
3031 // calculate average space width
3032 $spacewidth = ($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1) / $this->FontSize / $this->k;
3033 // set word position to be used with TJ operator
3034 $txt2 = str_replace(chr(0).' ', ') '.(-2830 * $spacewidth).' (', $txt2);
3037 $width = $this->GetStringWidth($txt);
3038 $spacewidth = (($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1)) * $this->k;
3039 $rs .= sprintf('BT %.3f Tw ET ', $spacewidth);
3042 // calculate approximate position of the font base line
3043 //$basefonty = $this->y + (($h + $this->FontAscent - $this->FontDescent)/2);
3044 $basefonty = $this->y + ($h/2) + ($this->FontSize/3);
3046 $s .= sprintf('BT %.2f %.2f Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
3048 $xdx = $this->x - $dx - $width;
3050 $xdx = $this->x + $dx;
3052 if ($this->underline) {
3053 $s .= ' '.$this->_dounderline($xdx, $basefonty, $txt);
3055 if ($this->linethrough) {
3056 $s .= ' '.$this->_dolinethrough($xdx, $basefonty, $txt);
3058 if ($this->ColorFlag) {
3062 $this->Link($xdx, $this->y + (($h - $this->FontSize)/2), $width, $this->FontSize, $link);
3069 // reset text stretching
3071 //Reset character horizontal spacing
3072 $rs .= ' BT 0 Tc ET';
3073 } elseif ($stretch > 0) {
3074 //Reset character horizontal scaling
3075 $rs .= ' BT 100 Tz ET';
3078 // reset word spacing
3079 if ((!$this->isunicode) AND ($align == 'J')) {
3080 $rs .= ' BT 0 Tw ET';
3084 //Go to the beginning of the next line
3088 $this->x = $this->w - $this->rMargin;
3090 $this->x = $this->lMargin;
3094 // go left or right by case
3101 $gstyles = $this->linestyleWidth." ".$this->linestyleCap." ".$this->linestyleJoin." ".$this->linestyleDash." ".$this->DrawColor." ".$this->FillColor."\n";
3107 * This method allows printing text with line breaks.
3108 * 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 />
3109 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
3110 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
3111 * @param float $h Cell minimum height. The cell extends automatically if needed.
3112 * @param string $txt String to print
3113 * @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>
3114 * @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>
3115 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3116 * @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>
3117 * @param int $x x position in user units
3118 * @param int $y y position in user units
3119 * @param boolean $reseth if true reset the last cell height (default true).
3120 * @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>
3121 * @param boolean $ishtml se to true if $txt is HTML content (default = false).
3122 * @return int Return the number of cells or 1 for html mode.
3124 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
3126 function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false) {
3127 if ((empty($this->lasth))OR ($reseth)) {
3129 $this->lasth = $this->FontSize * $this->cell_height_ratio;
3136 // check for page break
3137 $this->checkPageBreak($h);
3139 // get current page number
3140 $startpage = $this->page;
3146 if (empty($w) OR ($w <= 0)) {
3148 $w = $this->x - $this->lMargin;
3150 $w = $this->w - $this->rMargin - $this->x;
3153 // store original margin values
3154 $lMargin = $this->lMargin;
3155 $rMargin = $this->rMargin;
3157 $this->SetRightMargin($this->w - $this->x);
3158 $this->SetLeftMargin($this->x - $w);
3160 $this->SetLeftMargin($this->x);
3161 $this->SetRightMargin($this->w - $this->x - $w);
3163 // calculate remaining vertical space on first page ($startpage)
3164 $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin();
3165 // Adjust internal padding
3166 if ($this->cMargin < ($this->LineWidth / 2)) {
3167 $this->cMargin = ($this->LineWidth / 2);
3169 // Add top space if needed
3170 if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3171 $this->y += $this->LineWidth / 2;
3174 $this->y += $this->cMargin;
3177 $this->writeHTML($txt, true, 0, $reseth, true, $align);
3181 $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false);
3183 // add bottom padding
3184 $this->y += $this->cMargin;
3185 // Add bottom space if needed
3186 if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3187 $this->y += $this->LineWidth / 2;
3189 // Get end-of-text Y position
3190 $currentY = $this->GetY();
3191 // get latest page number
3192 $endpage = $this->page;
3193 // check if a new page has been created
3194 if ($endpage > $startpage) {
3195 // design borders around HTML cells.
3196 for ($page=$startpage; $page <= $endpage; $page++) {
3197 $this->setPage($page);
3198 if ($page == $startpage) {
3199 $this->SetY($this->getPageHeight() - $restspace - $this->getBreakMargin());
3201 } elseif ($page == $endpage) {
3202 $this->SetY($this->tMargin); // put cursor at the beginning of text
3203 $h = $currentY - $this->tMargin;
3205 $this->SetY($this->tMargin); // put cursor at the beginning of text
3206 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
3209 $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3210 if ($border OR $fill) {
3211 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3212 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3213 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3214 $this->intmrk[$this->page] += strlen($ccode."\n");
3218 $h = max($h, ($currentY - $y));
3219 // put cursor at the beginning of text
3222 $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3223 if ($border OR $fill) {
3224 // design a cell around the text
3225 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3226 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3227 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3228 $this->intmrk[$this->page] += strlen($ccode."\n");
3231 // Get end-of-cell Y position
3232 $currentY = $this->GetY();
3233 // restore original margin values
3234 $this->SetLeftMargin($lMargin);
3235 $this->SetRightMargin($rMargin);
3237 //Go to the beginning of the next line
3238 $this->SetY($currentY);
3240 $this->SetX($x + $w);
3243 // go left or right by case
3244 $this->setPage($startpage);
3246 $this->SetX($x + $w);
3252 * This method prints text from the current position.<br />
3253 * @param float $h Line height
3254 * @param string $txt String to print
3255 * @param mixed $link URL or identifier returned by AddLink()
3256 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
3257 * @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>
3258 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
3259 * @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>
3260 * @param boolean $firstline if true prints only the first line and return the remaining string.
3261 * @return mixed Return the number of cells or the remaining string if $firstline = true.
3264 function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false) {
3265 // remove carriage returns
3266 $s = str_replace("\r", '', $txt);
3267 // check if string contains arabic text
3268 if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
3273 // get array of chars
3274 $chars = $this->UTF8StringToArray($s);
3275 // get the number of characters
3276 $nb = count($chars);
3277 // handle single space character
3278 if (($nb == 1) AND preg_match("/[\s]/u", $s)) {
3280 $this->x -= $this->GetStringWidth($s);
3282 $this->x += $this->GetStringWidth($s);
3286 // store current position
3289 // calculate remaining line width ($w)
3291 $w = $this->x - $this->lMargin;
3293 $w = $this->w - $this->rMargin - $this->x;
3296 $wmax = $w - (2 * $this->cMargin);
3297 $i = 0; // character position
3298 $j = 0; // current starting position
3299 $sep = -1; // position of the last blank space
3300 $l = 0; // current string lenght
3301 $nl = 0; //number of lines
3303 // for each character
3305 //Get the current character
3307 if ($c == 10) { // 10 = "\n" = new line
3308 //Explicit line break
3309 if ($align == "J") {
3320 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3322 $this->endlinex = $startx - $linew;
3324 $this->endlinex = $startx + $linew;
3327 $tmpcmargin = $this->cMargin;
3330 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $talign, $fill, $link, $stretch);
3332 $this->cMargin = $tmpcmargin;
3333 return ($this->UTF8ArrSubString($chars, $i));
3339 $w = $this->getRemainingWidth();
3340 $wmax = $w - (2 * $this->cMargin);
3342 if (preg_match("/[\s]/u", $this->unichr($c))) {
3343 // update last blank space position
3346 // update string length
3347 if (($this->isunicode) AND ($arabic)) {
3348 // with bidirectional algorithm some chars may be changed affecting the line length
3349 // *** very slow ***
3350 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), $this->tmprtl));
3352 $l += $this->GetCharWidth($c);
3355 // we have reached the end of column
3357 // check if the line was already started
3358 if (($this->rtl AND ($this->x < ($this->w - $this->rMargin)))
3359 OR ((!$this->rtl) AND ($this->x > $this->lMargin))) {
3360 // print a void cell and go to next line
3361 $this->Cell($w, $h, "", 0, 1);
3364 return ($this->UTF8ArrSubString($chars, $j));
3367 // truncate the word because do not fit on column
3370 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3372 $this->endlinex = $startx - $linew;
3374 $this->endlinex = $startx + $linew;
3377 $tmpcmargin = $this->cMargin;
3380 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $align, $fill, $link, $stretch);
3382 $this->cMargin = $tmpcmargin;
3383 return ($this->UTF8ArrSubString($chars, $i));
3392 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $sep), $this->tmprtl));
3394 $this->endlinex = $startx - $linew;
3396 $this->endlinex = $startx + $linew;
3399 $tmpcmargin = $this->cMargin;
3402 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $sep), 0, 1, $align, $fill, $link, $stretch);
3404 $this->cMargin = $tmpcmargin;
3405 return ($this->UTF8ArrSubString($chars, $sep));
3411 $w = $this->getRemainingWidth();
3412 $wmax = $w - (2 * $this->cMargin);
3422 } // end while i < nb
3423 // print last substring (if any)
3454 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $nb), $this->tmprtl));
3456 $this->endlinex = $startx - $linew;
3458 $this->endlinex = $startx + $linew;
3461 $tmpcmargin = $this->cMargin;
3464 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $nb), 0, $ln, $align, $fill, $link, $stretch);
3466 $this->cMargin = $tmpcmargin;
3467 return ($this->UTF8ArrSubString($chars, $nb));
3478 * Returns the remaining width between the current position and margins.
3479 * @return int Return the remaining width
3482 function getRemainingWidth() {
3484 return ($this->x - $this->lMargin);
3486 return ($this->w - $this->rMargin - $this->x);
3491 * Extract a slice of the $strarr array and return it as string.
3492 * @param string $strarr The input array of characters.
3493 * @param int $start the starting element of $strarr.
3494 * @param int $end first element that will not be returned.
3495 * @return Return part of a string
3497 function UTF8ArrSubString($strarr, $start='', $end='') {
3498 if (strlen($start) == 0) {
3501 if (strlen($end) == 0) {
3502 $end = count($strarr);
3505 for ($i=$start; $i < $end; $i++) {
3506 $string .= $this->unichr($strarr[$i]);
3512 * Returns the unicode caracter specified by UTF-8 code
3513 * @param int $c UTF-8 code
3514 * @return Returns the specified character.
3515 * @author Miguel Perez, Nicola Asuni
3516 * @since 2.3.000 (2008-03-05)
3518 function unichr($c) {
3519 if (!$this->isunicode) {
3521 } elseif ($c <= 0x7F) {
3524 } elseif ($c <= 0x7FF) {
3526 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
3527 } elseif ($c <= 0xFFFF) {
3529 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3530 } elseif ($c <= 0x10FFFF) {
3532 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3539 * Puts an image in the page.
3540 * The upper-left corner must be given.
3541 * The dimensions can be specified in different ways:<ul>
3542 * <li>explicit width and height (expressed in user unit)</li>
3543 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
3544 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
3545 * 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;
3546 * The format can be specified explicitly or inferred from the file extension.<br />
3547 * It is possible to put a link on the image.<br />
3548 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
3549 * @param string $file Name of the file containing the image.
3550 * @param float $x Abscissa of the upper-left corner.
3551 * @param float $y Ordinate of the upper-left corner.
3552 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
3553 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
3554 * @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.
3555 * @param mixed $link URL or identifier returned by AddLink().
3556 * @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>
3557 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
3558 * @param int $dpi dot-per-inch resolution used on resize
3559 * @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>
3563 function Image($file, $x, $y, $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
3565 list($pixw, $pixh) = getimagesize($file);
3566 // calculate image width and height on document
3567 if (($w <= 0) AND ($h <= 0)) {
3568 // convert image size to document unit
3569 $w = $pixw / ($this->imgscale * $this->k);
3570 $h = $pixh / ($this->imgscale * $this->k);
3571 } elseif ($w <= 0) {
3572 $w = $h * $pixw / $pixh;
3573 } elseif ($h <= 0) {
3574 $h = $w * $pixh / $pixw;
3576 // calculate new minimum dimensions in pixels
3577 $neww = round($w * $this->k * $dpi / $this->dpi);
3578 $newh = round($h * $this->k * $dpi / $this->dpi);
3579 // check if resize is necessary (resize is used only to reduce the image)
3580 if (($neww * $newh) >= ($pixw * $pixh)) {
3583 // check if image has been already added on document
3584 if (!isset($this->images[$file])) {
3585 //First use of image, get info
3587 $fileinfo = pathinfo($file);
3588 if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
3589 $type = $fileinfo['extension'];
3591 $this->Error('Image file has no extension and no type was specified: '.$file);
3594 $type = strtolower($type);
3595 if ($type == "jpg") {
3598 $mqr = get_magic_quotes_runtime();
3599 set_magic_quotes_runtime(0);
3600 // Specific image handlers
3601 $mtd = '_parse'.$type;
3602 // GD image handler function
3603 $gdfunction = "imagecreatefrom".$type;
3605 if ((method_exists($this,$mtd)) AND (!($resize AND function_exists($gdfunction)))) {
3606 $info = $this->$mtd($file);
3609 if (function_exists($gdfunction)) {
3610 $img = $gdfunction($file);
3612 $imgr = imagecreatetruecolor($neww, $newh);
3613 imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
3614 $info = $this->_toJPEG($imgr);
3616 $info = $this->_toJPEG($img);
3622 if ($info === false) {
3623 //If false, we cannot process image
3626 set_magic_quotes_runtime($mqr);
3627 $info['i'] = count($this->images) + 1;
3628 // add image to document
3629 $this->images[$file] = $info;
3631 $info = $this->images[$file];
3633 // Check whether we need a new page first as this does not fit
3634 if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
3635 // Automatic page break
3636 $this->AddPage($this->CurOrientation);
3637 // Reset coordinates to top fo next page
3638 //$x = $this->GetX();
3639 $y = $this->GetY() + $this->cMargin;
3641 // 2007-10-19 Warren Sherliker: End Edit
3642 // set bottomcoordinates
3643 $this->img_rb_y = $y + $h;
3646 if ($palign == 'L') {
3647 $ximg = $this->lMargin;
3648 // set right side coordinate
3649 $this->img_rb_x = $ximg + $w;
3650 } elseif ($palign == 'C') {
3651 $ximg = ($this->w - $x - $w) / 2;
3652 // set right side coordinate
3653 $this->img_rb_x = $ximg + $w;
3655 $ximg = $this->w - $x - $w;
3656 // set left side coordinate
3657 $this->img_rb_x = $ximg;
3660 if ($palign == 'R') {
3661 $ximg = $this->w - $this->rMargin - $w;
3662 // set left side coordinate
3663 $this->img_rb_x = $ximg;
3664 } elseif ($palign == 'C') {
3665 $ximg = ($this->w - $x - $w) / 2;
3666 // set right side coordinate
3667 $this->img_rb_x = $ximg + $w;
3670 // set right side coordinate
3671 $this->img_rb_x = $ximg + $w;
3674 $xkimg = $ximg * $this->k;
3675 $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']));
3677 $this->Link($ximg, $y, $w, $h, $link);
3679 // set pointer to align the successive text/objects
3683 $this->x = $this->img_rb_x;
3687 $this->y = $y + round($h/2);
3688 $this->x = $this->img_rb_x;
3692 $this->y = $this->img_rb_y;
3693 $this->x = $this->img_rb_x;
3697 $this->SetY($this->img_rb_y);
3704 $this->endlinex = $this->img_rb_x;
3708 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
3709 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
3710 * @param string $file Image file name.
3711 * @param image $image Image object.
3712 * return image JPEG image object.
3715 function _toJPEG($image) {
3716 $tempname = tempnam(K_PATH_CACHE,'jpg');
3717 imagejpeg($image, $tempname, $this->jpeg_quality);
3718 imagedestroy($image);
3719 $retvars = $this->_parsejpeg($tempname);
3720 // tidy up by removing temporary image
3726 * Extract info from a JPEG file without using the GD library.
3727 * @param string $file image file to parse
3728 * @return array structure containing the image data
3731 function _parsejpeg($file) {
3732 $a = getimagesize($file);
3734 $this->Error('Missing or incorrect image file: '.$file);
3737 $this->Error('Not a JPEG file: '.$file);
3739 if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
3740 $colspace = 'DeviceRGB';
3741 } elseif ($a['channels'] == 4) {
3742 $colspace = 'DeviceCMYK';
3744 $colspace = 'DeviceGray';
3746 $bpc = isset($a['bits']) ? $a['bits'] : 8;
3747 $data = file_get_contents($file);
3748 return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
3752 * Extract info from a PNG file without using the GD library.
3753 * @param string $file image file to parse
3754 * @return array structure containing the image data
3757 function _parsepng($file) {
3758 $f = fopen($file,'rb');
3760 $this->Error('Can\'t open image file: '.$file);
3763 if (fread($f,8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3764 $this->Error('Not a PNG file: '.$file);
3768 if (fread($f,4) != 'IHDR') {
3769 $this->Error('Incorrect PNG file: '.$file);
3771 $w = $this->_freadint($f);
3772 $h = $this->_freadint($f);
3773 $bpc = ord(fread($f,1));
3775 //$this->Error('16-bit depth not supported: '.$file);
3778 $ct = ord(fread($f,1));
3780 $colspace = 'DeviceGray';
3781 } elseif ($ct == 2) {
3782 $colspace = 'DeviceRGB';
3783 } elseif ($ct == 3) {
3784 $colspace = 'Indexed';
3786 //$this->Error('Alpha channel not supported: '.$file);
3789 if (ord(fread($f,1)) != 0) {
3790 //$this->Error('Unknown compression method: '.$file);
3793 if (ord(fread($f,1)) != 0) {
3794 //$this->Error('Unknown filter method: '.$file);
3797 if (ord(fread($f,1)) != 0) {
3798 //$this->Error('Interlacing not supported: '.$file);
3802 $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
3803 //Scan chunks looking for palette, transparency and image data
3808 $n = $this->_freadint($f);
3809 $type = fread($f,4);
3810 if ($type == 'PLTE') {
3812 $pal = fread($f,$n);
3814 } elseif ($type == 'tRNS') {
3815 //Read transparency info
3818 $trns = array(ord(substr($t,1,1)));
3821 $trns = array(ord(substr($t,1,1)), ord(substr($t,3,1)), ord(substr($t,5,1)));
3823 $pos = strpos($t,chr(0));
3824 if ($pos !== false) {
3825 $trns = array($pos);
3829 } elseif ($type == 'IDAT') {
3830 //Read image data block
3831 $data .= fread($f,$n);
3833 } elseif ($type == 'IEND') {
3840 if (($colspace == 'Indexed') AND (empty($pal))) {
3841 //$this->Error('Missing palette in '.$file);
3845 return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
3849 * Performs a line break.
3850 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
3851 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
3852 * @param boolean $cell if true add a cMargin to the x coordinate
3856 function Ln($h='', $cell=false) {
3857 //Line feed; default value is last cell height
3859 $cellmargin = $this->cMargin;
3864 $this->x = $this->w - $this->rMargin - $cellmargin;
3866 $this->x = $this->lMargin + $cellmargin;
3868 if (is_string($h)) {
3869 $this->y += $this->lasth;
3873 $this->newline = true;
3877 * Returns the relative X value of current position.
3878 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
3881 * @see SetX(), GetY(), SetY()
3886 return ($this->w - $this->x);
3893 * Returns the absolute X value of current position.
3896 * @see SetX(), GetY(), SetY()
3898 function GetAbsX() {
3903 * Returns the ordinate of the current position.
3906 * @see SetY(), GetX(), SetX()
3914 * Defines the abscissa of the current position.
3915 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
3916 * @param float $x The value of the abscissa.
3918 * @see GetX(), GetY(), SetY(), SetXY()
3924 $this->x = $this->w - $x;
3932 $this->x = $this->w + $x;
3938 * Moves the current abscissa back to the left margin and sets the ordinate.
3939 * If the passed value is negative, it is relative to the bottom of the page.
3940 * @param float $y The value of the ordinate.
3942 * @see GetX(), GetY(), SetY(), SetXY()
3945 //Set y position and reset x
3947 $this->x = $this->w - $this->rMargin;
3949 $this->x = $this->lMargin;
3954 $this->y = $this->h + $y;
3959 * Defines the abscissa and ordinate of the current position.
3960 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
3961 * @param float $x The value of the abscissa
3962 * @param float $y The value of the ordinate
3964 * @see SetX(), SetY()
3966 function SetXY($x, $y) {
3967 //Set x and y positions
3973 * Send the document to a given destination: string, local file or browser.
3974 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
3975 * The method first calls Close() if necessary to terminate the document.
3976 * @param string $name The name of the file when saved.
3977 * @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>
3981 function Output($name='doc.pdf', $dest='I') {
3982 //Output PDF to some destination
3983 //Finish document if necessary
3984 if ($this->state < 3) {
3987 //Normalize parameters
3988 if (is_bool($dest)) {
3989 $dest = $dest ? 'D' : 'F';
3991 $dest = strtoupper($dest);
3993 $name = str_replace("+", "%20", urlencode($name));
3994 $name = preg_replace('/[\r\n]+\s*/', '' , $name);
3998 //Send to standard output
3999 if (ob_get_contents()) {
4000 $this->Error('Some data has already been output, can\'t send PDF file');
4002 if (php_sapi_name() != 'cli') {
4003 //We send to a browser
4004 header('Content-Type: application/pdf');
4005 if (headers_sent()) {
4006 $this->Error('Some data has already been output to browser, can\'t send PDF file');
4008 header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4009 header("Pragma: public");
4010 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4011 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
4012 header('Content-Length: '.strlen($this->buffer));
4013 header('Content-Disposition: inline; filename="'.basename($name).'";');
4020 if (ob_get_contents()) {
4021 $this->Error('Some data has already been output, can\'t send PDF file');
4023 header('Content-Description: File Transfer');
4024 if (headers_sent()) {
4025 $this->Error('Some data has already been output to browser, can\'t send PDF file');
4027 header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4028 header("Pragma: public");
4029 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4030 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
4031 // force download dialog
4032 header("Content-Type: application/force-download");
4033 header("Content-Type: application/octet-stream", false);
4034 header("Content-Type: application/download", false);
4035 // use the Content-Disposition header to supply a recommended filename
4036 header('Content-Disposition: attachment; filename="'.basename($name).'";');
4037 header("Content-Transfer-Encoding: binary");
4038 header("Content-Length: ".strlen($this->buffer));
4043 //Save to local file
4044 $f = fopen($name, 'wb');
4046 $this->Error('Unable to create output file: '.$name);
4048 fwrite($f, $this->buffer,strlen($this->buffer));
4053 //Return as a string
4054 return $this->buffer;
4057 $this->Error('Incorrect output destination: '.$dest);
4064 * Check for locale-related bug
4067 function _dochecks() {
4068 //Check for locale-related bug
4070 $this->Error('Don\'t alter the locale before including class file');
4072 //Check for decimal separator
4073 if (sprintf('%.1f', 1.0) != '1.0') {
4074 setlocale(LC_NUMERIC, 'C');
4083 function _getfontpath() {
4084 if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
4085 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
4087 return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
4094 function _putpages() {
4095 $nb = count($this->pages);
4096 if (!empty($this->pagegroups)) {
4097 // do page number replacement
4098 foreach ($this->pagegroups as $k => $v) {
4099 $vu = $this->UTF8ToUTF16BE($v, false);
4100 $alias_a = $this->_escape($k);
4101 $alias_au = $this->_escape("{".$k."}");
4102 if ($this->isunicode) {
4103 $alias_b = $this->_escape($this->UTF8ToLatin1($k));
4104 $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$k."}"));
4105 $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
4106 $alias_cu = $this->_escape($this->utf8StrRev("{".$k."}", false, $this->tmprtl));
4108 for ($n = 1; $n <= $nb; $n++) {
4109 $this->pages[$n] = str_replace($alias_au, $vu, $this->pages[$n]);
4110 if ($this->isunicode) {
4111 $this->pages[$n] = str_replace($alias_bu, $vu, $this->pages[$n]);
4112 $this->pages[$n] = str_replace($alias_cu, $vu, $this->pages[$n]);
4113 $this->pages[$n] = str_replace($alias_b, $v, $this->pages[$n]);
4114 $this->pages[$n] = str_replace($alias_c, $v, $this->pages[$n]);
4116 $this->pages[$n] = str_replace($alias_a, $v, $this->pages[$n]);
4120 if (!empty($this->AliasNbPages)) {
4121 $nbu = $this->UTF8ToUTF16BE($nb, false); // replacement for unicode font
4122 $alias_a = $this->_escape($this->AliasNbPages);
4123 $alias_au = $this->_escape("{".$this->AliasNbPages."}");
4124 if ($this->isunicode) {
4125 $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
4126 $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$this->AliasNbPages."}"));
4127 $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
4128 $alias_cu = $this->_escape($this->utf8StrRev("{".$this->AliasNbPages."}", false, $this->tmprtl));
4130 //Replace number of pages
4131 for($n = 1; $n <= $nb; $n++) {
4132 $this->pages[$n] = str_replace($alias_au, $nbu, $this->pages[$n]);
4133 if ($this->isunicode) {
4134 $this->pages[$n] = str_replace($alias_bu, $nbu, $this->pages[$n]);
4135 $this->pages[$n] = str_replace($alias_cu, $nbu, $this->pages[$n]);
4136 $this->pages[$n] = str_replace($alias_b, $nb, $this->pages[$n]);
4137 $this->pages[$n] = str_replace($alias_c, $nb, $this->pages[$n]);
4139 $this->pages[$n] = str_replace($alias_a, $nb, $this->pages[$n]);
4142 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4143 for($n=1; $n <= $nb; $n++) {
4146 $this->_out('<</Type /Page');
4147 $this->_out('/Parent 1 0 R');
4148 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
4149 $this->_out('/Resources 2 0 R');
4150 $this->_putannots($n);
4151 $this->_out('/Contents '.($this->n + 1).' 0 R>>');
4152 $this->_out('endobj');
4154 $p = ($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n];
4156 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
4157 $this->_putstream($p);
4158 $this->_out('endobj');
4161 $this->offsets[1] = strlen($this->buffer);
4162 $this->_out('1 0 obj');
4163 $this->_out('<</Type /Pages');
4165 for($i=0; $i < $nb; $i++) {
4166 $kids .= (3+2*$i).' 0 R ';
4168 $this->_out($kids.']');
4169 $this->_out('/Count '.$nb);
4170 //$this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
4172 $this->_out('endobj');
4176 * Output Page Annotations.
4177 * See section 8.4 of PDF reference.
4178 * @param int $n page number
4180 * @author Nicola Asuni
4181 * @since 4.0.018 (2008-08-06)
4183 function _putannots($n) {
4184 if (isset($this->PageAnnots[$n])) {
4185 $annots = '/Annots [';
4186 foreach ($this->PageAnnots[$n] as $key => $pl) {
4187 $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
4188 $a = $pl['x'] * $this->k;
4189 $b = $this->hPt - $pl['y'] * $this->k;
4190 $c = $pl['w'] * $this->k;
4191 $d = $pl['h'] * $this->k;
4192 $rect = sprintf('%.2f %.2f %.2f %.2f', $a, $b, $a+$c, $b-$d);
4193 $annots .= '<</Type /Annot';
4194 $annots .= ' /Subtype /'.$pl['opt']['subtype'];
4195 $annots .= ' /Rect ['.$rect.']';
4196 $annots .= ' /Contents '.$this->_textstring($pl['txt']);
4197 //$annots .= ' /P ';
4198 $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
4199 $annots .= ' /M '.$this->_datestring('D:'.date('YmdHis'));
4200 if (isset($pl['opt']['f'])) {
4202 if (is_array($pl['opt']['f'])) {
4203 foreach ($pl['opt']['f'] as $f) {
4204 switch (strtolower($f)) {
4237 case 'togglenoview': {
4241 case 'lockedcontents': {
4251 $annots .= ' /F '.intval($val);
4253 //$annots .= ' /AP ';
4254 //$annots .= ' /AS ';
4255 $annots .= ' /Border [';
4256 if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
4257 $annots .= intval($pl['opt']['border'][0]).' ';
4258 $annots .= intval($pl['opt']['border'][1]).' ';
4259 $annots .= intval($pl['opt']['border'][2]);
4260 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
4262 foreach ($pl['opt']['border'][3] as $dash) {
4263 $annots .= intval($dash).' ';
4271 if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
4272 $annots .= ' /BS <<Type /Border';
4273 if (isset($pl['opt']['bs']['w'])) {
4274 $annots .= ' /W '.sprintf("%.4f", floatval($pl['opt']['bs']['w']));
4276 $bstyles = array('S', 'D', 'B', 'I', 'U');
4277 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $markups)) {
4278 $annots .= ' /S /'.$pl['opt']['bs']['s'];
4280 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
4282 foreach ($pl['opt']['bs']['d'] as $cord) {
4283 $cord = floatval($cord);
4284 $annots .= sprintf(" %.4f", $cord);
4290 if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
4291 $annots .= ' /BE <<';
4292 $bstyles = array('S', 'C');
4293 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
4294 $annots .= ' /S /'.$pl['opt']['bs']['s'];
4296 $annots .= ' /S /S';
4298 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
4299 $annots .= ' /I '.sprintf(" %.4f", $pl['opt']['be']['i']);
4304 if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
4305 foreach ($pl['opt']['c'] as $col) {
4306 $col = intval($col);
4307 $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
4308 $annots .= sprintf(" %.4f", $color);
4312 //$annots .= ' /StructParent ';
4313 //$annots .= ' /OC ';
4314 $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
4315 if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
4316 // this is a markup type
4317 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
4318 $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
4320 //$annots .= ' /Popup ';
4321 if (isset($pl['opt']['ca'])) {
4322 $annots .= ' /CA '.sprintf("%.4f", floatval($pl['opt']['ca']));
4324 if (isset($pl['opt']['rc'])) {
4325 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4327 $annots .= ' /CreationDate '.$this->_datestring('D:'.date('YmdHis'));
4328 //$annots .= ' /IRT ';
4329 if (isset($pl['opt']['subj'])) {
4330 $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
4332 //$annots .= ' /RT ';
4333 //$annots .= ' /IT ';
4334 //$annots .= ' /ExData ';
4336 switch (strtolower($pl['opt']['subtype'])) {
4338 if (isset($pl['opt']['open'])) {
4339 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
4341 $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
4342 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
4343 $annots .= ' /Name /'.$pl['opt']['name'];
4345 $annots .= ' /Name /Note';
4347 $statemodels = array('Marked', 'Review');
4348 if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
4349 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4351 $pl['opt']['statemodel'] = 'Marked';
4352 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4354 if ($pl['opt']['statemodel'] == 'Marked') {
4355 $states = array('Accepted', 'Unmarked');
4357 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
4359 if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
4360 $annots .= ' /State /'.$pl['opt']['state'];
4362 if ($pl['opt']['statemodel'] == 'Marked') {
4363 $annots .= ' /State /Unmarked';
4365 $annots .= ' /State /None';
4371 $annots .= ' /A <</S /URI /URI '.$this->_uristring($pl['txt']).'>>';
4372 $hmodes = array('N', 'I', 'O', 'P');
4373 if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
4374 $annots .= ' /H /'.$pl['opt']['h'];
4376 $annots .= ' /H /I';
4378 //$annots .= ' /Dest ';
4379 //$annots .= ' /PA ';
4380 //$annots .= ' /Quadpoints ';
4384 $annots .= ' /DA '.$this->_textstring($pl['txt']);
4385 if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
4386 $annots .= ' /Q '.intval($pl['opt']['q']);
4388 if (isset($pl['opt']['rc'])) {
4389 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4391 if (isset($pl['opt']['ds'])) {
4392 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
4394 if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
4395 $annots .= ' /CL [';
4396 foreach ($pl['opt']['cl'] as $cl) {
4397 $annots .= sprintf("%.4f ", $cl * $this->k);
4401 $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
4402 if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
4403 $annots .= ' /IT '.$pl['opt']['it'];
4405 if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
4406 $l = $pl['opt']['rd'][0] * $this->k;
4407 $r = $pl['opt']['rd'][1] * $this->k;
4408 $t = $pl['opt']['rd'][2] * $this->k;
4409 $b = $pl['opt']['rd'][3] * $this->k;
4410 $annots .= ' /RD ['.sprintf('%.2f %.2f %.2f %.2f', $l, $r, $t, $b).']';
4412 //$annots .= ' /LE ';
4415 // ... to be completed ...
4455 case 'fileattachment': {
4470 case 'printermark': {
4489 $this->_out($annots.']');
4498 function _putfonts() {
4500 foreach($this->diffs as $diff) {
4503 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
4504 $this->_out('endobj');
4506 $mqr = get_magic_quotes_runtime();
4507 set_magic_quotes_runtime(0);
4508 foreach($this->FontFiles as $file => $info) {
4509 //Font file embedding
4511 $this->FontFiles[$file]['n'] = $this->n;
4512 $font = file_get_contents($this->_getfontpath().strtolower($file));
4513 $compressed = (substr($file,-2)=='.z');
4514 if ((!$compressed) AND (isset($info['length2']))) {
4515 $header = (ord($font{0}) == 128);
4517 //Strip first binary header
4518 $font = substr($font,6);
4520 if ($header AND (ord($font{$info['length1']}) == 128)) {
4521 //Strip second binary header
4522 $font = substr($font, 0, $info['length1']).substr($font, $info['length1']+6);
4525 $this->_out('<</Length '.strlen($font));
4527 $this->_out('/Filter /FlateDecode');
4529 $this->_out('/Length1 '.$info['length1']);
4530 if (isset($info['length2'])) {
4531 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
4534 $this->_putstream($font);
4535 $this->_out('endobj');
4537 set_magic_quotes_runtime($mqr);
4538 foreach($this->fonts as $k => $font) {
4540 $this->fonts[$k]['n'] = $this->n + 1;
4541 $type = $font['type'];
4542 $name = $font['name'];
4543 if ($type == 'core') {
4546 $this->_out('<</Type /Font');
4547 $this->_out('/BaseFont /'.$name);
4548 $this->_out('/Subtype /Type1');
4549 if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
4550 $this->_out('/Encoding /WinAnsiEncoding');
4553 $this->_out('endobj');
4554 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
4555 //Additional Type1 or TrueType font
4557 $this->_out('<</Type /Font');
4558 $this->_out('/BaseFont /'.$name);
4559 $this->_out('/Subtype /'.$type);
4560 $this->_out('/FirstChar 32 /LastChar 255');
4561 $this->_out('/Widths '.($this->n + 1).' 0 R');
4562 $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
4564 if (isset($font['diff'])) {
4565 $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
4567 $this->_out('/Encoding /WinAnsiEncoding');
4571 $this->_out('endobj');
4576 for($i=32; $i <= 255; $i++) {
4577 //$s .= $cw[chr($i)].' ';
4580 $this->_out($s.']');
4581 $this->_out('endobj');
4584 $s = '<</Type /FontDescriptor /FontName /'.$name;
4585 foreach($font['desc'] as $k => $v) {
4586 $s .= ' /'.$k.' '.$v;
4588 $file = $font['file'];
4590 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
4592 $this->_out($s.'>>');
4593 $this->_out('endobj');
4595 //Allow for additional types
4596 $mtd = '_put'.strtolower($type);
4597 if (!method_exists($this, $mtd)) {
4598 $this->Error('Unsupported font type: '.$type);
4606 * Output CID-0 fonts.
4607 * @param array $font font data
4609 * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
4610 * @since 3.2.000 (2008-06-23)
4612 function _putcidfont0($font) {
4613 if (isset($font['cidinfo']['uni2cid'])) {
4614 // convert unicode to cid.
4615 $uni2cid = $font['cidinfo']['uni2cid'];
4617 foreach ($font['cw'] as $uni => $width) {
4618 if (isset($uni2cid[$uni])) {
4619 $cw[($uni2cid[$uni] + 31)] = $width;
4620 } elseif ($uni <= 255) {
4622 } // else unknown character
4625 $font = array_merge($font, array('cw'=>$cw));
4627 $longname = $name = $font['name'];
4628 $enc = $font['enc'];
4630 $longname .= "-$enc";
4633 $this->_out('<</Type /Font');
4634 $this->_out('/BaseFont /'.$longname);
4635 $this->_out('/Subtype /Type0');
4637 $this->_out('/Encoding /'.$enc);
4639 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
4641 $this->_out('endobj');
4643 $this->_out('<</Type /Font');
4644 $this->_out('/BaseFont /'.$name);
4645 $this->_out('/Subtype /CIDFontType0');
4646 $cidinfo = '/Registry ('.$font['cidinfo']['Registry'].') ';
4647 $cidinfo .= '/Ordering ('.$font['cidinfo']['Ordering'].') ';
4648 $cidinfo .= '/Supplement '.$font['cidinfo']['Supplement'];
4649 $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
4650 $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
4651 $codes = array_keys($font['cw']);
4652 $first = current($codes);
4653 $last = end($codes);
4654 $this->_out('/DW '.$font['dw']);
4658 for($i = $first; $i <= $last; $i++) {
4659 if (isset($font['cw'][$i]) AND (!$currange)) {
4660 $currange = $i - 31;
4661 } elseif (!isset($font['cw'][$i])) {
4665 $ranges[$currange][] = $font['cw'][$i];
4668 foreach($ranges as $k => $ws) {
4669 $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
4674 $this->_out('endobj');
4676 $s = '<</Type /FontDescriptor /FontName /'.$name;
4677 foreach($font['desc'] as $k => $v) {
4678 $s .= ' /'.$k.' '.$v;
4680 $this->_out($s.'>>');
4681 $this->_out('endobj');
4688 function _putimages() {
4689 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4690 reset($this->images);
4691 while (list($file, $info) = each($this->images)) {
4693 $this->images[$file]['n'] = $this->n;
4694 $this->_out('<</Type /XObject');
4695 $this->_out('/Subtype /Image');
4696 $this->_out('/Width '.$info['w']);
4697 $this->_out('/Height '.$info['h']);
4698 if (isset($info["masked"])) {
4699 $this->_out('/SMask '.($this->n-1).' 0 R');
4701 if ($info['cs'] == 'Indexed') {
4702 $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal']) / 3 - 1).' '.($this->n + 1).' 0 R]');
4704 $this->_out('/ColorSpace /'.$info['cs']);
4705 if ($info['cs'] == 'DeviceCMYK') {
4706 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
4709 $this->_out('/BitsPerComponent '.$info['bpc']);
4710 if (isset($info['f'])) {
4711 $this->_out('/Filter /'.$info['f']);
4713 if (isset($info['parms'])) {
4714 $this->_out($info['parms']);
4716 if (isset($info['trns']) and is_array($info['trns'])) {
4718 for($i=0; $i < count($info['trns']); $i++) {
4719 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
4721 $this->_out('/Mask ['.$trns.']');
4723 $this->_out('/Length '.strlen($info['data']).'>>');
4724 $this->_putstream($info['data']);
4725 unset($this->images[$file]['data']);
4726 $this->_out('endobj');
4728 if ($info['cs'] == 'Indexed') {
4730 $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
4731 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
4732 $this->_putstream($pal);
4733 $this->_out('endobj');
4739 * Output Spot Colors Resources.
4741 * @since 4.0.024 (2008-09-12)
4743 function _putspotcolors() {
4744 foreach ($this->spot_colors as $name => $color) {
4746 $this->spot_colors[$name]['n'] = $this->n;
4747 $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
4748 $this->_out('/DeviceCMYK <<');
4749 $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
4750 $this->_out(sprintf('/C1 [%.4f %.4f %.4f %.4f] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
4751 $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
4752 $this->_out('endobj');
4757 * Output object dictionary for images.
4760 function _putxobjectdict() {
4761 foreach($this->images as $image) {
4762 $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
4767 * Output Resources Dictionary.
4770 function _putresourcedict(){
4771 $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
4772 $this->_out('/Font <<');
4773 foreach($this->fonts as $font) {
4774 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
4777 $this->_out('/XObject <<');
4778 $this->_putxobjectdict();
4781 $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
4783 $this->_out('/ExtGState <<');
4784 foreach($this->extgstates as $k => $extgstate) {
4785 $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
4789 if (isset($this->gradients) AND (count($this->gradients) > 0)) {
4790 $this->_out('/Shading <<');
4791 foreach($this->gradients as $id => $grad) {
4792 $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
4797 if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
4798 $this->_out('/ColorSpace <<');
4799 foreach ($this->spot_colors as $color) {
4800 $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
4810 function _putresources() {
4811 $this->_putextgstates();
4814 $this->_putimages();
4815 $this->_putspotcolors();
4816 $this->_putshaders();
4817 //Resource dictionary
4818 $this->offsets[2] = strlen($this->buffer);
4819 $this->_out('2 0 obj');
4821 $this->_putresourcedict();
4823 $this->_out('endobj');
4824 $this->_putjavascript();
4825 $this->_putbookmarks();
4827 if ($this->encrypted) {
4829 $this->enc_obj_id = $this->n;
4831 $this->_putencryption();
4833 $this->_out('endobj');
4838 * Adds some Metadata information
4839 * (see Chapter 10.2 of PDF Reference)
4842 function _putinfo() {
4843 if (!empty($this->title)) {
4844 $this->_out('/Title '.$this->_textstring($this->title));
4846 if (!empty($this->author)) {
4847 $this->_out('/Author '.$this->_textstring($this->author));
4849 if (!empty($this->subject)) {
4850 $this->_out('/Subject '.$this->_textstring($this->subject));
4852 if (!empty($this->keywords)) {
4853 $this->_out('/Keywords '.$this->_textstring($this->keywords));
4855 if (!empty($this->creator)) {
4856 $this->_out('/Creator '.$this->_textstring($this->creator));
4858 if (defined('PDF_PRODUCER')) {
4859 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
4861 $this->_out('/CreationDate '.$this->_datestring('D:'.date('YmdHis')));
4862 $this->_out('/ModDate '.$this->_datestring('D:'.date('YmdHis')));
4866 * Format a date string for meta information
4867 * @param string $s date string to escape.
4868 * @return string escaped string.
4871 function _datestring($s) {
4872 if ($this->encrypted) {
4873 $s = $this->_RC4($this->_objectkey($this->n), $s);
4875 return '('. $this->_escape($s).')';
4882 function _putcatalog() {
4883 $this->_out('/Type /Catalog');
4884 $this->_out('/Pages 1 0 R');
4886 if ($this->ZoomMode == 'fullpage') {
4887 $this->_out('/OpenAction [3 0 R /Fit]');
4888 } elseif ($this->ZoomMode == 'fullwidth') {
4889 $this->_out('/OpenAction [3 0 R /FitH null]');
4890 } elseif ($this->ZoomMode == 'real') {
4891 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
4892 } elseif (!is_string($this->ZoomMode)) {
4893 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
4895 if (isset($this->LayoutMode) AND (!empty($this->LayoutMode))) {
4896 $this->_out('/PageLayout /'.$this->LayoutMode.'');
4898 if (isset($this->PageMode) AND (!empty($this->PageMode))) {
4899 $this->_out('/PageMode /'.$this->PageMode);
4901 if (isset($this->l['a_meta_language'])) {
4902 $this->_out('/Lang /'.$this->l['a_meta_language']);
4904 if (!empty($this->javascript)) {
4905 $this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
4907 if (count($this->outlines) > 0) {
4908 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
4909 $this->_out('/PageMode /UseOutlines');
4911 $this->_putviewerpreferences();
4912 $p = $this->n_ocg_print.' 0 R';
4913 $v = $this->n_ocg_view.' 0 R';
4914 $as = "<</Event /Print /OCGs [".$p." ".$v."] /Category [/Print]>> <</Event /View /OCGs [".$p." ".$v."] /Category [/View]>>";
4915 $this->_out("/OCProperties <</OCGs [".$p." ".$v."] /D <</ON [".$p."] /OFF [".$v."] /AS [".$as."]>>>>");
4916 $this->_putuserrights();
4920 * Output viewer preferences.
4921 * @author Nicola asuni
4922 * @since 3.1.000 (2008-06-09)
4925 function _putviewerpreferences() {
4926 $this->_out('/ViewerPreferences<<');
4928 $this->_out('/Direction /R2L');
4930 $this->_out('/Direction /L2R');
4932 if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
4933 $this->_out('/HideToolbar true');
4935 if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
4936 $this->_out('/HideMenubar true');
4938 if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
4939 $this->_out('/HideWindowUI true');
4941 if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
4942 $this->_out('/FitWindow true');
4944 if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
4945 $this->_out('/CenterWindow true');
4947 if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
4948 $this->_out('/DisplayDocTitle true');
4950 if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
4951 $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
4953 if (isset($this->viewer_preferences['ViewArea'])) {
4954 $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
4956 if (isset($this->viewer_preferences['ViewClip'])) {
4957 $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
4959 if (isset($this->viewer_preferences['PrintArea'])) {
4960 $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
4962 if (isset($this->viewer_preferences['PrintClip'])) {
4963 $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
4965 if (isset($this->viewer_preferences['PrintScaling'])) {
4966 $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
4968 if (isset($this->viewer_preferences['Duplex']) AND (!empty($this->viewer_preferences['Duplex']))) {
4969 $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
4971 if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
4972 if ($this->viewer_preferences['PickTrayByPDFSize']) {
4973 $this->_out('/PickTrayByPDFSize true');
4975 $this->_out('/PickTrayByPDFSize false');
4978 if (isset($this->viewer_preferences['PrintPageRange'])) {
4979 $PrintPageRangeNum = "";
4980 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
4981 $PrintPageRangeNum .= " ".($v-1)."";
4983 $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
4985 if (isset($this->viewer_preferences['NumCopies'])) {
4986 $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
4995 function _puttrailer() {
4996 $this->_out('/Size '.($this->n + 1));
4997 $this->_out('/Root '.$this->n.' 0 R');
4998 $this->_out('/Info '.($this->n - 1).' 0 R');
4999 if ($this->encrypted) {
5000 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
5001 $this->_out('/ID [()()]');
5006 * Output PDF header.
5009 function _putheader() {
5010 $this->buffer = '%PDF-'.$this->PDFVersion."\n".$this->buffer;
5011 // $this->_out('%PDF-'.$this->PDFVersion);
5015 * Output end of document (EOF).
5018 function _enddoc() {
5019 $this->_putheader();
5021 $this->_putresources();
5027 $this->_out('endobj');
5031 $this->_putcatalog();
5033 $this->_out('endobj');
5035 $o = strlen($this->buffer);
5036 $this->_out('xref');
5037 $this->_out('0 '.($this->n + 1));
5038 $this->_out('0000000000 65535 f ');
5039 for($i=1; $i <= $this->n; $i++) {
5040 $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i]));
5043 $this->_out('trailer');
5045 $this->_puttrailer();
5047 $this->_out('startxref');
5049 $this->_out('%%EOF');
5054 * Initialize a new page.
5055 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
5056 * @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>
5059 function _beginpage($orientation='', $format='') {
5061 $this->pages[$this->page] = ""; // this mark should be removed before output
5063 if (empty($orientation)) {
5064 if (isset($this->CurOrientation)) {
5065 $orientation = $this->CurOrientation;
5070 if (!empty($format)) {
5071 $this->setPageFormat($format, $orientation);
5073 $this->setPageOrientation($orientation);
5076 $this->x = $this->w - $this->rMargin;
5078 $this->x = $this->lMargin;
5080 $this->y = $this->tMargin;
5081 if ($this->newpagegroup){
5082 // start a new group
5083 $n = sizeof($this->pagegroups) + 1;
5084 $alias = "{nb".$n."}";
5085 $this->pagegroups[$alias] = 1;
5086 $this->currpagegroup = $alias;
5087 $this->newpagegroup = false;
5088 } elseif ($this->currpagegroup) {
5089 $this->pagegroups[$this->currpagegroup]++;
5097 function _endpage() {
5098 $this->setVisibility("all");
5103 * Begin a new object.
5106 function _newobj() {
5108 $this->offsets[$this->n] = strlen($this->buffer);
5109 $this->_out($this->n.' 0 obj');
5114 * @param int $x X coordinate
5115 * @param int $y Y coordinate
5116 * @param string $txt text to underline
5119 function _dounderline($x, $y, $txt) {
5120 $up = $this->CurrentFont['up'];
5121 $ut = $this->CurrentFont['ut'];
5122 $w = $this->GetStringWidth($txt);
5123 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);
5127 * Line through text.
5128 * @param int $x X coordinate
5129 * @param int $y Y coordinate
5130 * @param string $txt text to underline
5133 function _dolinethrough($x, $y, $txt) {
5134 $up = $this->CurrentFont['up'];
5135 $ut = $this->CurrentFont['ut'];
5136 $w = $this->GetStringWidth($txt);
5137 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);
5141 * Read a 4-byte integer from file.
5142 * @param string $f file name.
5143 * @return 4-byte integer
5146 function _freadint($f) {
5147 $a = unpack('Ni', fread($f,4));
5152 * Format a text string for meta information
5153 * @param string $s string to escape.
5154 * @return string escaped string.
5157 function _textstring($s) {
5158 if ($this->isunicode) {
5159 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5160 $s = $this->UTF8ToLatin1($s);
5162 //Convert string to UTF-16BE
5163 $s = $this->UTF8ToUTF16BE($s, true);
5166 if ($this->encrypted) {
5167 $s = $this->_RC4($this->_objectkey($this->n), $s);
5169 return '('. $this->_escape($s).')';
5173 * Format an URI string
5174 * @param string $s string to escape.
5175 * @return string escaped string.
5178 function _uristring($s) {
5179 if ($this->encrypted) {
5180 $s = $this->_RC4($this->_objectkey($this->n), $s);
5182 return '('.$this->_escape($s).')';
5186 * Format a text string
5187 * @param string $s string to escape.
5188 * @return string escaped string.
5191 function _escapetext($s) {
5192 if ($this->isunicode) {
5193 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5194 $s = $this->UTF8ToLatin1($s);
5196 //Convert string to UTF-16BE and reverse RTL language
5197 $s = $this->utf8StrRev($s, false, $this->tmprtl);
5200 return $this->_escape($s);
5204 * Add "\" before "\", "(" and ")"
5205 * @param string $s string to escape.
5206 * @return string escaped string.
5209 function _escape($s) {
5210 // the chr(13) substitution fixes the Bugs item #1421290.
5211 return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
5216 * @param string $s string to output.
5219 function _putstream($s) {
5220 if ($this->encrypted) {
5221 $s = $this->_RC4($this->_objectkey($this->n), $s);
5223 $this->_out('stream');
5225 $this->_out('endstream');
5229 * Output a string to the document.
5230 * @param string $s string to output.
5234 if ($this->state == 2) {
5235 if (isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
5236 // puts data before page footer
5237 $page = substr($this->pages[$this->page], 0, -$this->footerlen[$this->page]);
5238 $footer = substr($this->pages[$this->page], -$this->footerlen[$this->page]);
5239 $this->pages[$this->page] = $page." ".$s."\n".$footer;
5241 $this->pages[$this->page] .= $s."\n";
5244 $this->buffer .= $s."\n";
5249 * Adds unicode fonts.<br>
5250 * Based on PDF Reference 1.3 (section 5)
5252 * @author Nicola Asuni
5253 * @since 1.52.0.TC005 (2005-01-05)
5255 function _puttruetypeunicode($font) {
5257 // A composite font composed of other fonts, organized hierarchically
5259 $this->_out('<</Type /Font');
5260 $this->_out('/Subtype /Type0');
5261 $this->_out('/BaseFont /'.$font['name'].'');
5262 $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.
5263 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
5264 $this->_out('/ToUnicode '.($this->n + 2).' 0 R');
5266 $this->_out('endobj');
5268 // A CIDFont whose glyph descriptions are based on TrueType font technology
5270 $this->_out('<</Type /Font');
5271 $this->_out('/Subtype /CIDFontType2');
5272 $this->_out('/BaseFont /'.$font['name'].'');
5273 $this->_out('/CIDSystemInfo '.($this->n + 2).' 0 R');
5274 $this->_out('/FontDescriptor '.($this->n + 3).' 0 R');
5275 if (isset($font['desc']['MissingWidth'])){
5276 $this->_out('/DW '.$font['desc']['MissingWidth'].''); // The default width for glyphs in the CIDFont MissingWidth
5279 foreach ($font['cw'] as $cid => $width) {
5280 $w .= ''.$cid.' ['.$width.'] '; // define a specific width for each individual CID
5282 $this->_out('/W ['.$w.']'); // A description of the widths for the glyphs in the CIDFont
5283 $this->_out('/CIDToGIDMap '.($this->n + 4).' 0 R');
5285 $this->_out('endobj');
5287 // is a stream object that contains the definition of the CMap
5288 // (PDF Reference 1.3 chap. 5.9)
5290 $this->_out('<</Length 345>>');
5291 $this->_out('stream');
5292 $this->_out('/CIDInit /ProcSet findresource begin');
5293 $this->_out('12 dict begin');
5294 $this->_out('begincmap');
5295 $this->_out('/CIDSystemInfo');
5296 $this->_out('<</Registry (Adobe)');
5297 $this->_out('/Ordering (UCS)');
5298 $this->_out('/Supplement 0');
5299 $this->_out('>> def');
5300 $this->_out('/CMapName /Adobe-Identity-UCS def');
5301 $this->_out('/CMapType 2 def');
5302 $this->_out('1 begincodespacerange');
5303 $this->_out('<0000> <FFFF>');
5304 $this->_out('endcodespacerange');
5305 $this->_out('1 beginbfrange');
5306 $this->_out('<0000> <FFFF> <0000>');
5307 $this->_out('endbfrange');
5308 $this->_out('endcmap');
5309 $this->_out('CMapName currentdict /CMap defineresource pop');
5312 $this->_out('endstream');
5313 $this->_out('endobj');
5314 // CIDSystemInfo dictionary
5315 // A dictionary containing entries that define the character collection of the CIDFont.
5317 $this->_out('<</Registry (Adobe)'); // A string identifying an issuer of character collections
5318 $this->_out('/Ordering (UCS)'); // A string that uniquely names a character collection issued by a specific registry
5319 $this->_out('/Supplement 0'); // The supplement number of the character collection.
5321 $this->_out('endobj');
5323 // A font descriptor describing the CIDFont default metrics other than its glyph widths
5325 $this->_out('<</Type /FontDescriptor');
5326 $this->_out('/FontName /'.$font['name']);
5327 foreach ($font['desc'] as $key => $value) {
5328 $this->_out('/'.$key.' '.$value);
5330 if ($font['file']) {
5331 // A stream containing a TrueType font program
5332 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
5335 $this->_out('endobj');
5336 // Embed CIDToGIDMap
5337 // A specification of the mapping from CIDs to glyph indices
5339 $ctgfile = $this->_getfontpath().strtolower($font['ctg']);
5340 if (!file_exists($ctgfile)) {
5341 $this->Error('Font file not found: '.$ctgfile);
5343 $size = filesize($ctgfile);
5344 $this->_out('<</Length '.$size.'');
5345 if (substr($ctgfile, -2) == '.z') { // check file extension
5346 /* Decompresses data encoded using the public-domain
5347 zlib/deflate compression method, reproducing the
5348 original text or binary data */
5349 $this->_out('/Filter /FlateDecode');
5352 $this->_putstream(file_get_contents($ctgfile));
5353 $this->_out('endobj');
5357 * Converts UTF-8 strings to codepoints array.<br>
5358 * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
5359 * Based on: http://www.faqs.org/rfcs/rfc3629.html
5361 * Char. number range | UTF-8 octet sequence
5362 * (hexadecimal) | (binary)
5363 * --------------------+-----------------------------------------------
5364 * 0000 0000-0000 007F | 0xxxxxxx
5365 * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
5366 * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
5367 * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
5368 * ---------------------------------------------------------------------
5371 * ---------------------------------------------------------------------
5372 * UTF8-octets = *( UTF8-char )
5373 * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
5375 * UTF8-2 = %xC2-DF UTF8-tail
5377 * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
5378 * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
5379 * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
5380 * %xF4 %x80-8F 2( UTF8-tail )
5381 * UTF8-tail = %x80-BF
5382 * ---------------------------------------------------------------------
5384 * @param string $str string to process.
5385 * @return array containing codepoints (UTF-8 characters values)
5387 * @author Nicola Asuni
5388 * @since 1.53.0.TC005 (2005-01-05)
5390 function UTF8StringToArray($str) {
5391 if (!$this->isunicode) {
5392 // split string into array of equivalent codes
5394 $strlen = strlen($str);
5395 for($i=0; $i < $strlen; $i++) {
5396 $strarr[] = ord($str{$i});
5400 $unicode = array(); // array containing unicode values
5401 $bytes = array(); // array containing single character byte sequences
5402 $numbytes = 1; // number of octetc needed to represent the UTF-8 character
5403 $str .= ""; // force $str to be a string
5404 $length = strlen($str);
5405 for($i = 0; $i < $length; $i++) {
5406 $char = ord($str{$i}); // get one string character at time
5407 if (count($bytes) == 0) { // get starting octect
5408 if ($char <= 0x7F) {
5409 $unicode[] = $char; // use the character "as is" because is ASCII
5411 } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
5412 $bytes[] = ($char - 0xC0) << 0x06;
5414 } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
5415 $bytes[] = ($char - 0xE0) << 0x0C;
5417 } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
5418 $bytes[] = ($char - 0xF0) << 0x12;
5421 // use replacement character for other invalid sequences
5422 $unicode[] = 0xFFFD;
5426 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
5427 $bytes[] = $char - 0x80;
5428 if (count($bytes) == $numbytes) {
5429 // compose UTF-8 bytes to a single unicode value
5431 for($j = 1; $j < $numbytes; $j++) {
5432 $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
5434 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
5435 /* The definition of UTF-8 prohibits encoding character numbers between
5436 U+D800 and U+DFFF, which are reserved for use with the UTF-16
5437 encoding form (as surrogate pairs) and do not directly represent
5439 $unicode[] = 0xFFFD; // use replacement character
5441 $unicode[] = $char; // add char to array
5443 // reset data for next char
5448 // use replacement character for other invalid sequences
5449 $unicode[] = 0xFFFD;
5458 * Converts UTF-8 strings to UTF16-BE.<br>
5459 * @param string $str string to process.
5460 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5463 * @author Nicola Asuni
5464 * @since 1.53.0.TC005 (2005-01-05)
5465 * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
5467 function UTF8ToUTF16BE($str, $setbom=true) {
5468 if (!$this->isunicode) {
5469 return $str; // string is not in unicode
5471 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5472 return $this->arrUTF8ToUTF16BE($unicode, $setbom);
5476 * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
5477 * @param string $str string to process.
5479 * @author Andrew Whitehead, Nicola Asuni
5481 * @since 3.2.000 (2008-06-23)
5483 function UTF8ToLatin1($str) {
5484 if (!$this->isunicode) {
5485 return $str; // string is not in unicode
5487 $outstr = ""; // string to be returned
5488 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5489 foreach ($unicode as $char) {
5490 if ($char == 0xFFFD) {
5492 } elseif ($char == 0x2022) {
5494 $outstr .= chr(183);
5495 } elseif ($char < 256) {
5496 $outstr .= chr($char);
5505 * Converts array of UTF-8 characters to UTF16-BE string.<br>
5506 * Based on: http://www.faqs.org/rfcs/rfc2781.html
5510 * Encoding of a single character from an ISO 10646 character value to
5511 * UTF-16 proceeds as follows. Let U be the character number, no greater
5514 * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
5517 * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
5518 * U' must be less than or equal to 0xFFFFF. That is, U' can be
5519 * represented in 20 bits.
5521 * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
5522 * 0xDC00, respectively. These integers each have 10 bits free to
5523 * encode the character value, for a total of 20 bits.
5525 * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
5526 * bits of W1 and the 10 low-order bits of U' to the 10 low-order
5527 * bits of W2. Terminate.
5529 * Graphically, steps 2 through 4 look like:
5530 * U' = yyyyyyyyyyxxxxxxxxxx
5531 * W1 = 110110yyyyyyyyyy
5532 * W2 = 110111xxxxxxxxxx
5534 * @param array $unicode array containing UTF-8 unicode values
5535 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5538 * @author Nicola Asuni
5539 * @since 2.1.000 (2008-01-08)
5540 * @see UTF8ToUTF16BE()
5542 function arrUTF8ToUTF16BE($unicode, $setbom=true) {
5543 $outstr = ""; // string to be returned
5545 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
5547 foreach($unicode as $char) {
5548 if ($char == 0xFFFD) {
5549 $outstr .= "\xFF\xFD"; // replacement character
5550 } elseif ($char < 0x10000) {
5551 $outstr .= chr($char >> 0x08);
5552 $outstr .= chr($char & 0xFF);
5555 $w1 = 0xD800 | ($char >> 0x10);
5556 $w2 = 0xDC00 | ($char & 0x3FF);
5557 $outstr .= chr($w1 >> 0x08);
5558 $outstr .= chr($w1 & 0xFF);
5559 $outstr .= chr($w2 >> 0x08);
5560 $outstr .= chr($w2 & 0xFF);
5565 // ====================================================
5569 * @param array $font font
5572 function setHeaderFont($font) {
5573 $this->header_font = $font;
5579 * @since 4.0.012 (2008-07-24)
5581 function getHeaderFont() {
5582 return $this->header_font;
5587 * @param array $font font
5590 function setFooterFont($font) {
5591 $this->footer_font = $font;
5597 * @since 4.0.012 (2008-07-24)
5599 function getFooterFont() {
5600 return $this->footer_font;
5604 * Set language array.
5605 * @param array $language
5608 function setLanguageArray($language) {
5609 $this->l = $language;
5610 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
5614 * Returns the PDF data.
5616 function getPDFData() {
5617 if ($this->state < 3) {
5620 return $this->buffer;
5625 * @param string $tag tag name in lowercase. Supported tags are:<ul>
5626 * <li>b : bold text</li>
5627 * <li>i : italic</li>
5628 * <li>u : underlined</li>
5629 * <li>d : line-through</li></ul>
5630 * @param boolean $enable
5633 function setStyle($tag, $enable) {
5634 $this->$tag += ($enable ? 1 : -1);
5636 foreach(array('b', 'i', 'u', 'd') as $s) {
5637 if ($this->$s > 0) {
5641 $this->SetFont('', $style);
5645 * Output anchor link.
5646 * @param string $url link URL
5647 * @param string $name link name
5648 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
5649 * @param boolean $firstline if true prints only the first line and return the remaining string.
5650 * @return the number of cells used or the remaining text if $firstline = true;
5653 function addHtmlLink($url, $name, $fill=0, $firstline=false) {
5654 $prevcolor = $this->fgcolor;
5655 $this->SetTextColor(0, 0, 255);
5656 $this->setStyle('u', true);
5657 $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
5658 $this->setStyle('u', false);
5659 $this->SetTextColorArray($prevcolor);
5664 * 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).
5665 * @param string $color html color
5669 function convertHTMLColorToDec($color="#000000") {
5671 $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
5672 // set default color to be returned in case of error
5673 $returncolor = array ('R' => 0, 'G' => 0, 'B' => 0);
5674 if (empty($color)) {
5675 return $returncolor;
5677 if (substr(strtolower($color), 0, 3) == 'rgb') {
5678 $codes = substr($color, 4);
5679 $codes = str_replace(')', '', $codes);
5680 $returncolor = explode(',', $codes, 3);
5681 return $returncolor;
5683 if (substr($color, 0, 1) != "#") {
5684 // decode color name
5685 if (isset($webcolor[strtolower($color)])) {
5686 $color_code = $webcolor[strtolower($color)];
5688 return $returncolor;
5691 $color_code = substr($color, 1);
5693 switch (strlen($color_code)) {
5695 // three-digit hexadecimal representation
5696 $r = substr($color_code, 0, 1);
5697 $g = substr($color_code, 1, 1);
5698 $b = substr($color_code, 2, 1);
5699 $returncolor['R'] = hexdec($r.$r);
5700 $returncolor['G'] = hexdec($g.$g);
5701 $returncolor['B'] = hexdec($b.$b);
5705 // six-digit hexadecimal representation
5706 $returncolor['R'] = hexdec(substr($color_code, 0, 2));
5707 $returncolor['G'] = hexdec(substr($color_code, 2, 2));
5708 $returncolor['B'] = hexdec(substr($color_code, 4, 2));
5712 return $returncolor;
5716 * Converts pixels to Units.
5717 * @param int $px pixels
5718 * @return float millimeters
5721 function pixelsToUnits($px){
5722 return $px / $this->k;
5726 * Reverse function for htmlentities.
5727 * Convert entities in UTF-8.
5728 * @param $text_to_convert Text to convert.
5729 * @return string converted
5731 function unhtmlentities($text_to_convert) {
5732 if (!$this->isunicode) {
5733 return html_entity_decode($text_to_convert, ENT_QUOTES);
5735 return html_entity_decode_php4($text_to_convert);
5738 // ENCRYPTION METHODS ----------------------------------
5739 // SINCE 2.0.000 (2008-01-02)
5741 * Compute encryption key depending on object number where the encrypted data is stored
5742 * @param int $n object number
5743 * @since 2.0.000 (2008-01-02)
5745 function _objectkey($n) {
5746 return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);
5750 * Put encryption on PDF document.
5751 * @since 2.0.000 (2008-01-02)
5753 function _putencryption() {
5754 $this->_out('/Filter /Standard');
5755 $this->_out('/V 1');
5756 $this->_out('/R 2');
5757 $this->_out('/O ('.$this->_escape($this->Ovalue).')');
5758 $this->_out('/U ('.$this->_escape($this->Uvalue).')');
5759 $this->_out('/P '.$this->Pvalue);
5763 * Returns the input text exrypted using RC4 algorithm and the specified key.
5764 * RC4 is the standard encryption algorithm used in PDF format
5765 * @param string $key encryption key
5766 * @param String $text input text to be encrypted
5767 * @return String encrypted text
5768 * @since 2.0.000 (2008-01-02)
5769 * @author Klemen Vodopivec
5771 function _RC4($key, $text) {
5772 if ($this->last_rc4_key != $key) {
5773 $k = str_repeat($key, 256/strlen($key)+1);
5774 $rc4 = range(0,255);
5776 for ($i=0; $i < 256; $i++) {
5778 $j = ($j + $t + ord($k{$i})) % 256;
5779 $rc4[$i] = $rc4[$j];
5782 $this->last_rc4_key = $key;
5783 $this->last_rc4_key_c = $rc4;
5785 $rc4 = $this->last_rc4_key_c;
5787 $len = strlen($text);
5791 for ($i=0; $i < $len; $i++) {
5792 $a = ($a + 1) % 256;
5794 $b = ($b + $t) % 256;
5795 $rc4[$a] = $rc4[$b];
5797 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
5798 $out .= chr(ord($text{$i}) ^ $k);
5804 * Encrypts a string using MD5 and returns it's value as a binary string.
5805 * @param string $str input string
5806 * @return String MD5 encrypted binary string
5807 * @since 2.0.000 (2008-01-02)
5808 * @author Klemen Vodopivec
5810 function _md5_16($str) {
5811 return pack('H*',md5($str));
5815 * Compute O value (used for RC4 encryption)
5816 * @param String $user_pass user password
5817 * @param String $owner_pass user password
5818 * @return String O value
5819 * @since 2.0.000 (2008-01-02)
5820 * @author Klemen Vodopivec
5822 function _Ovalue($user_pass, $owner_pass) {
5823 $tmp = $this->_md5_16($owner_pass);
5824 $owner_RC4_key = substr($tmp,0,5);
5825 return $this->_RC4($owner_RC4_key, $user_pass);
5829 * Compute U value (used for RC4 encryption)
5830 * @return String U value
5831 * @since 2.0.000 (2008-01-02)
5832 * @author Klemen Vodopivec
5834 function _Uvalue() {
5835 return $this->_RC4($this->encryption_key, $this->padding);
5839 * Compute encryption key
5840 * @param String $user_pass user password
5841 * @param String $owner_pass user password
5842 * @param String $protection protection type
5843 * @since 2.0.000 (2008-01-02)
5844 * @author Klemen Vodopivec
5846 function _generateencryptionkey($user_pass, $owner_pass, $protection) {
5848 $user_pass = substr($user_pass.$this->padding,0,32);
5849 $owner_pass = substr($owner_pass.$this->padding,0,32);
5851 $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
5852 // Compute encyption key
5853 $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
5854 $this->encryption_key = substr($tmp,0,5);
5856 $this->Uvalue = $this->_Uvalue();
5858 $this->Pvalue = -(($protection^255)+1);
5862 * Set document protection
5863 * The permission array is composed of values taken from the following ones:
5864 * - copy: copy text and images to the clipboard
5865 * - print: print the document
5866 * - modify: modify it (except for annotations and forms)
5867 * - annot-forms: add annotations and forms
5868 * Remark: the protection against modification is for people who have the full Acrobat product.
5869 * 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.
5870 * 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.
5871 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
5872 * @param String $user_pass user password. Empty by default.
5873 * @param String $owner_pass owner password. If not specified, a random value is used.
5874 * @since 2.0.000 (2008-01-02)
5875 * @author Klemen Vodopivec
5877 function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
5878 $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
5880 foreach($permissions as $permission) {
5881 if (!isset($options[$permission])) {
5882 $this->Error('Incorrect permission: '.$permission);
5884 $protection += $options[$permission];
5886 if ($owner_pass === null) {
5887 $owner_pass = uniqid(rand());
5889 $this->encrypted = true;
5890 $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
5893 // END OF ENCRYPTION FUNCTIONS -------------------------
5895 // START TRANSFORMATIONS SECTION -----------------------
5896 // authors: Moritz Wagner, Andreas Wurmser, Nicola Asuni
5899 * Starts a 2D tranformation saving current graphic state.
5900 * This function must be called before scaling, mirroring, translation, rotation and skewing.
5901 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5902 * @since 2.1.000 (2008-01-07)
5903 * @see StartTransform(), StopTransform()
5905 function StartTransform() {
5910 * Stops a 2D tranformation restoring previous graphic state.
5911 * This function must be called after scaling, mirroring, translation, rotation and skewing.
5912 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5913 * @since 2.1.000 (2008-01-07)
5914 * @see StartTransform(), StopTransform()
5916 function StopTransform() {
5920 * Horizontal Scaling.
5921 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5922 * @param int $x abscissa of the scaling center. Default is current x position
5923 * @param int $y ordinate of the scaling center. Default is current y position
5924 * @since 2.1.000 (2008-01-07)
5925 * @see StartTransform(), StopTransform()
5927 function ScaleX($s_x, $x='', $y=''){
5928 $this->Scale($s_x, 100, $x, $y);
5933 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5934 * @param int $x abscissa of the scaling center. Default is current x position
5935 * @param int $y ordinate of the scaling center. Default is current y position
5936 * @since 2.1.000 (2008-01-07)
5937 * @see StartTransform(), StopTransform()
5939 function ScaleY($s_y, $x='', $y=''){
5940 $this->Scale(100, $s_y, $x, $y);
5944 * Vertical and horizontal proportional Scaling.
5945 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
5946 * @param int $x abscissa of the scaling center. Default is current x position
5947 * @param int $y ordinate of the scaling center. Default is current y position
5948 * @since 2.1.000 (2008-01-07)
5949 * @see StartTransform(), StopTransform()
5951 function ScaleXY($s, $x='', $y=''){
5952 $this->Scale($s, $s, $x, $y);
5956 * Vertical and horizontal non-proportional Scaling.
5957 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5958 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5959 * @param int $x abscissa of the scaling center. Default is current x position
5960 * @param int $y ordinate of the scaling center. Default is current y position
5961 * @since 2.1.000 (2008-01-07)
5962 * @see StartTransform(), StopTransform()
5964 function Scale($s_x, $s_y, $x='', $y=''){
5974 if (($s_x == 0) OR ($s_y == 0)) {
5975 $this->Error('Please do not use values equal to zero for scaling');
5977 $y = ($this->h - $y) * $this->k;
5979 //calculate elements of transformation matrix
5986 $tm[4] = $x * (1 - $s_x);
5987 $tm[5] = $y * (1 - $s_y);
5988 //scale the coordinate system
5989 $this->Transform($tm);
5993 * Horizontal Mirroring.
5994 * @param int $x abscissa of the point. Default is current x position
5995 * @since 2.1.000 (2008-01-07)
5996 * @see StartTransform(), StopTransform()
5998 function MirrorH($x=''){
5999 $this->Scale(-100, 100, $x);
6003 * Verical Mirroring.
6004 * @param int $y ordinate of the point. Default is current y position
6005 * @since 2.1.000 (2008-01-07)
6006 * @see StartTransform(), StopTransform()
6008 function MirrorV($y=''){
6009 $this->Scale(100, -100, '', $y);
6013 * Point reflection mirroring.
6014 * @param int $x abscissa of the point. Default is current x position
6015 * @param int $y ordinate of the point. Default is current y position
6016 * @since 2.1.000 (2008-01-07)
6017 * @see StartTransform(), StopTransform()
6019 function MirrorP($x='',$y=''){
6020 $this->Scale(-100, -100, $x, $y);
6024 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
6025 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
6026 * @param int $x abscissa of the point. Default is current x position
6027 * @param int $y ordinate of the point. Default is current y position
6028 * @since 2.1.000 (2008-01-07)
6029 * @see StartTransform(), StopTransform()
6031 function MirrorL($angle=0, $x='',$y=''){
6032 $this->Scale(-100, 100, $x, $y);
6033 $this->Rotate(-2*($angle-90), $x, $y);
6037 * Translate graphic object horizontally.
6038 * @param int $t_x movement to the right (or left for RTL)
6039 * @since 2.1.000 (2008-01-07)
6040 * @see StartTransform(), StopTransform()
6042 function TranslateX($t_x){
6043 $this->Translate($t_x, 0);
6047 * Translate graphic object vertically.
6048 * @param int $t_y movement to the bottom
6049 * @since 2.1.000 (2008-01-07)
6050 * @see StartTransform(), StopTransform()
6052 function TranslateY($t_y){
6053 $this->Translate(0, $t_y);
6057 * Translate graphic object horizontally and vertically.
6058 * @param int $t_x movement to the right
6059 * @param int $t_y movement to the bottom
6060 * @since 2.1.000 (2008-01-07)
6061 * @see StartTransform(), StopTransform()
6063 function Translate($t_x, $t_y){
6067 //calculate elements of transformation matrix
6072 $tm[4] = $t_x * $this->k;
6073 $tm[5] = -$t_y * $this->k;
6074 //translate the coordinate system
6075 $this->Transform($tm);
6080 * @param float $angle angle in degrees for counter-clockwise rotation
6081 * @param int $x abscissa of the rotation center. Default is current x position
6082 * @param int $y ordinate of the rotation center. Default is current y position
6083 * @since 2.1.000 (2008-01-07)
6084 * @see StartTransform(), StopTransform()
6086 function Rotate($angle, $x='', $y=''){
6097 $y = ($this->h - $y) * $this->k;
6099 //calculate elements of transformation matrix
6100 $tm[0] = cos(deg2rad($angle));
6101 $tm[1] = sin(deg2rad($angle));
6104 $tm[4] = $x + $tm[1] * $y - $tm[0] * $x;
6105 $tm[5] = $y - $tm[0] * $y - $tm[1] * $x;
6106 //rotate the coordinate system around ($x,$y)
6107 $this->Transform($tm);
6111 * Skew horizontally.
6112 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6113 * @param int $x abscissa of the skewing center. default is current x position
6114 * @param int $y ordinate of the skewing center. default is current y position
6115 * @since 2.1.000 (2008-01-07)
6116 * @see StartTransform(), StopTransform()
6118 function SkewX($angle_x, $x='', $y=''){
6119 $this->Skew($angle_x, 0, $x, $y);
6124 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6125 * @param int $x abscissa of the skewing center. default is current x position
6126 * @param int $y ordinate of the skewing center. default is current y position
6127 * @since 2.1.000 (2008-01-07)
6128 * @see StartTransform(), StopTransform()
6130 function SkewY($angle_y, $x='', $y=''){
6131 $this->Skew(0, $angle_y, $x, $y);
6136 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6137 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6138 * @param int $x abscissa of the skewing center. default is current x position
6139 * @param int $y ordinate of the skewing center. default is current y position
6140 * @since 2.1.000 (2008-01-07)
6141 * @see StartTransform(), StopTransform()
6143 function Skew($angle_x, $angle_y, $x='', $y=''){
6152 $angle_x = -$angle_x;
6154 if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
6155 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
6158 $y = ($this->h - $y) * $this->k;
6159 //calculate elements of transformation matrix
6161 $tm[1] = tan(deg2rad($angle_y));
6162 $tm[2] = tan(deg2rad($angle_x));
6164 $tm[4] = -$tm[2] * $y;
6165 $tm[5] = -$tm[1] * $x;
6166 //skew the coordinate system
6167 $this->Transform($tm);
6171 * Apply graphic transformations.
6172 * @since 2.1.000 (2008-01-07)
6173 * @see StartTransform(), StopTransform()
6175 function Transform($tm){
6176 $this->_out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
6179 // END TRANSFORMATIONS SECTION -------------------------
6182 // START GRAPHIC FUNCTIONS SECTION ---------------------
6183 // The following section is based on the code provided by David Hernandez Sanz
6186 * 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.
6187 * @param float $width The width.
6189 * @see Line(), Rect(), Cell(), MultiCell()
6191 function SetLineWidth($width) {
6193 $this->LineWidth = $width;
6194 //$this->linestyleWidth = sprintf('%.2f w', ($width * $this->k));
6195 // FrontAccounting fix
6196 // My PHP 5.2.6 environment gave an "Unsupported operand types"
6197 // error for the multiplication on the next line some of the
6198 // time when this method is called - I debugged and sometimes
6199 // the $width parameter is some sort of weird array. I don't
6200 // understand what's going on, but casting it to a (float) seems
6201 // to "fix" the problem. -Jason Maas, 2009/09/25
6202 $this->linestyleWidth = sprintf('%.2f w', ((float) $width * (float) $this->k));
6203 $this->_out($this->linestyleWidth);
6207 * Returns the current the line width.
6208 * @return int Line width
6209 * @since 2.1.000 (2008-01-07)
6210 * @see Line(), SetLineWidth()
6212 function GetLineWidth() {
6213 return $this->LineWidth;
6218 * @param array $style Line style. Array with keys among the following:
6220 * <li>width (float): Width of the line in user units.</li>
6221 * <li>cap (string): Type of cap to put on the line. Possible values are:
6222 * butt, round, square. The difference between "square" and "butt" is that
6223 * "square" projects a flat end past the end of the line.</li>
6224 * <li>join (string): Type of join. Possible values are: miter, round,
6226 * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
6227 * series of length values, which are the lengths of the on and off dashes.
6228 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
6229 * 1 off, 2 on, 1 off, ...</li>
6230 * <li>phase (integer): Modifier on the dash pattern which is used to shift
6231 * the point at which the pattern starts.</li>
6232 * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
6235 * @since 2.1.000 (2008-01-08)
6237 function SetLineStyle($style) {
6239 if (isset($width)) {
6240 $width_prev = $this->LineWidth;
6241 $this->SetLineWidth($width);
6242 $this->LineWidth = $width_prev;
6245 $ca = array("butt" => 0, "round"=> 1, "square" => 2);
6246 if (isset($ca[$cap])) {
6247 $this->linestyleCap = $ca[$cap]." J";
6248 $this->_out($this->linestyleCap);
6252 $ja = array("miter" => 0, "round" => 1, "bevel" => 2);
6253 if (isset($ja[$join])) {
6254 $this->linestyleJoin = $ja[$join]." j";
6255 $this->_out($this->linestyleJoin);
6261 if (ereg("^.+,", $dash)) {
6262 $tab = explode(",", $dash);
6264 $tab = array($dash);
6267 foreach ($tab as $i => $v) {
6269 $dash_string .= " ";
6271 $dash_string .= sprintf("%.2f", $v);
6274 if (!isset($phase) OR !$dash) {
6277 $this->linestyleDash = sprintf("[%s] %.2f d", $dash_string, $phase);
6278 $this->_out($this->linestyleDash);
6280 if (isset($color)) {
6281 $this->SetDrawColorArray($color);
6287 * @param float $x Abscissa of point.
6288 * @param float $y Ordinate of point.
6290 * @since 2.1.000 (2008-01-08)
6292 function _outPoint($x, $y) {
6296 $this->_out(sprintf("%.2f %.2f m", $x * $this->k, ($this->h - $y) * $this->k));
6300 * Draws a line from last draw point.
6301 * @param float $x Abscissa of end point.
6302 * @param float $y Ordinate of end point.
6304 * @since 2.1.000 (2008-01-08)
6306 function _outLine($x, $y) {
6310 $this->_out(sprintf("%.2f %.2f l", $x * $this->k, ($this->h - $y) * $this->k));
6314 * Draws a rectangle.
6315 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6316 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6317 * @param float $w Width.
6318 * @param float $h Height.
6319 * @param string $op options
6321 * @since 2.1.000 (2008-01-08)
6323 function _outRect($x, $y, $w, $h, $op) {
6325 $x = $this->w - $x - $w;
6327 $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
6331 * Draws a Bezier curve from last draw point.
6332 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
6333 * @param float $x1 Abscissa of control point 1.
6334 * @param float $y1 Ordinate of control point 1.
6335 * @param float $x2 Abscissa of control point 2.
6336 * @param float $y2 Ordinate of control point 2.
6337 * @param float $x3 Abscissa of end point.
6338 * @param float $y3 Ordinate of end point.
6340 * @since 2.1.000 (2008-01-08)
6342 function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
6344 $x1 = $this->w - $x1;
6345 $x2 = $this->w - $x2;
6346 $x3 = $this->w - $x3;
6348 $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));
6352 * Draws a line between two points.
6353 * @param float $x1 Abscissa of first point.
6354 * @param float $y1 Ordinate of first point.
6355 * @param float $x2 Abscissa of second point.
6356 * @param float $y2 Ordinate of second point.
6357 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6360 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
6362 function Line($x1, $y1, $x2, $y2, $style=array()) {
6364 $this->SetLineStyle($style);
6366 $this->_outPoint($x1, $y1);
6367 $this->_outLine($x2, $y2);
6372 * Draws a rectangle.
6373 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6374 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6375 * @param float $w Width.
6376 * @param float $h Height.
6377 * @param string $style Style of rendering. Possible values are:
6379 * <li>D or empty string: Draw (default).</li>
6381 * <li>DF or FD: Draw and fill.</li>
6382 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6383 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6385 * @param array $border_style Border style of rectangle. Array with keys among the following:
6387 * <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
6388 * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
6390 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
6391 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6392 * @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).
6395 * @see SetLineStyle()
6397 function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
6398 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6399 $this->SetFillColorArray($fill_color);
6404 $border_style = array();
6405 $this->_outRect($x, $y, $w, $h, $op);
6410 if ((!$border_style) OR (isset($border_style["all"]))) {
6412 if (isset($border_style["all"])) {
6413 $this->SetLineStyle($border_style["all"]);
6414 $border_style = array();
6419 $this->_outRect($x, $y, $w, $h, $op);
6432 if ((!$border_style) OR (isset($border_style["all"]))) {
6433 if (isset($border_style["all"]) AND $border_style["all"]) {
6434 $this->SetLineStyle($border_style["all"]);
6435 $border_style = array();
6437 $this->_outRect($x, $y, $w, $h, $op);
6442 if ($border_style) {
6443 $border_style2 = array();
6444 foreach ($border_style as $line => $value) {
6445 $lenght = strlen($line);
6446 for ($i = 0; $i < $lenght; $i++) {
6447 $border_style2[$line[$i]] = $value;
6450 $border_style = $border_style2;
6451 if (isset($border_style["L"]) AND $border_style["L"]) {
6452 $this->Line($x, $y, $x, $y + $h, $border_style["L"]);
6454 if (isset($border_style["T"]) AND $border_style["T"]) {
6455 $this->Line($x, $y, $x + $w, $y, $border_style["T"]);
6457 if (isset($border_style["R"]) AND $border_style["R"]) {
6458 $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style["R"]);
6460 if (isset($border_style["B"]) AND $border_style["B"]) {
6461 $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style["B"]);
6468 * Draws a Bezier curve.
6469 * The Bezier curve is a tangent to the line between the control points at
6470 * either end of the curve.
6471 * @param float $x0 Abscissa of start point.
6472 * @param float $y0 Ordinate of start point.
6473 * @param float $x1 Abscissa of control point 1.
6474 * @param float $y1 Ordinate of control point 1.
6475 * @param float $x2 Abscissa of control point 2.
6476 * @param float $y2 Ordinate of control point 2.
6477 * @param float $x3 Abscissa of end point.
6478 * @param float $y3 Ordinate of end point.
6479 * @param string $style Style of rendering. Possible values are:
6481 * <li>D or empty string: Draw (default).</li>
6483 * <li>DF or FD: Draw and fill.</li>
6484 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6485 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6487 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6488 * @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).
6490 * @see SetLineStyle()
6491 * @since 2.1.000 (2008-01-08)
6493 function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style="", $line_style=array(), $fill_color=array()) {
6494 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6495 $this->SetFillColorArray($fill_color);
6500 $line_style = array();
6522 $this->SetLineStyle($line_style);
6524 $this->_outPoint($x0, $y0);
6525 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6530 * Draws a poly-Bezier curve.
6531 * Each Bezier curve segment is a tangent to the line between the control points at
6532 * either end of the curve.
6533 * @param float $x0 Abscissa of start point.
6534 * @param float $y0 Ordinate of start point.
6535 * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
6536 * @param string $style Style of rendering. Possible values are:
6538 * <li>D or empty string: Draw (default).</li>
6540 * <li>DF or FD: Draw and fill.</li>
6541 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6542 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6544 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6545 * @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).
6547 * @see SetLineStyle()
6548 * @since 3.0008 (2008-05-12)
6550 function Polycurve($x0, $y0, $segments, $style="", $line_style=array(), $fill_color=array()) {
6551 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6552 $this->SetFillColorArray($fill_color);
6557 $line_style = array();
6579 $this->SetLineStyle($line_style);
6581 $this->_outPoint($x0, $y0);
6582 foreach ($segments as $segment) {
6583 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
6584 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6591 * An ellipse is formed from n Bezier curves.
6592 * @param float $x0 Abscissa of center point.
6593 * @param float $y0 Ordinate of center point.
6594 * @param float $rx Horizontal radius.
6595 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
6596 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6597 * @param float $astart: Angle start of draw line. Default value: 0.
6598 * @param float $afinish: Angle finish of draw line. Default value: 360.
6599 * @param string $style Style of rendering. Possible values are:
6601 * <li>D or empty string: Draw (default).</li>
6603 * <li>DF or FD: Draw and fill.</li>
6604 * <li>C: Draw close.</li>
6605 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6606 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6608 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6609 * @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).
6610 * @param integer $nc Number of curves used in ellipse. Default value: 8.
6612 * @since 2.1.000 (2008-01-08)
6614 function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6616 $this->StartTransform();
6617 $this->Rotate($angle, $x0, $y0);
6618 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6619 $this->StopTransform();
6623 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6624 $this->SetFillColorArray($fill_color);
6629 $line_style = array();
6638 $op = "s"; // Small "s" signifies closing the path as well
6655 $this->SetLineStyle($line_style);
6665 $astart = deg2rad((float) $astart);
6666 $afinish = deg2rad((float) $afinish);
6667 $total_angle = $afinish - $astart;
6668 $dt = $total_angle / $nc;
6671 $y0 = ($this->h - $y0) * $this->k;
6673 $a0 = $x0 + ($rx * cos($t1));
6674 $b0 = $y0 + ($ry * sin($t1));
6675 $c0 = -$rx * sin($t1);
6676 $d0 = $ry * cos($t1);
6677 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
6678 for ($i = 1; $i <= $nc; $i++) {
6679 // Draw this bit of the total curve
6680 $t1 = ($i * $dt) + $astart;
6681 $a1 = $x0 + ($rx * cos($t1));
6682 $b1 = $y0 + ($ry * sin($t1));
6683 $c1 = -$rx * sin($t1);
6684 $d1 = $ry * cos($t1);
6685 $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));
6697 * A circle is formed from n Bezier curves.
6698 * @param float $x0 Abscissa of center point.
6699 * @param float $y0 Ordinate of center point.
6700 * @param float $r Radius.
6701 * @param float $astart: Angle start of draw line. Default value: 0.
6702 * @param float $afinish: Angle finish of draw line. Default value: 360.
6703 * @param string $style Style of rendering. Possible values are:
6705 * <li>D or empty string: Draw (default).</li>
6707 * <li>DF or FD: Draw and fill.</li>
6708 * <li>C: Draw close.</li>
6709 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6710 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6712 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6713 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6714 * @param integer $nc Number of curves used in circle. Default value: 8.
6716 * @since 2.1.000 (2008-01-08)
6718 function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6719 $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6724 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
6725 * @param string $style Style of rendering. Possible values are:
6727 * <li>D or empty string: Draw (default).</li>
6729 * <li>DF or FD: Draw and fill.</li>
6730 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6731 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6733 * @param array $line_style Line style of polygon. Array with keys among the following:
6735 * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
6736 * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
6738 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
6739 * @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).
6741 * @since 2.1.000 (2008-01-08)
6743 function Polygon($p, $style="", $line_style=array(), $fill_color=array()) {
6744 $np = count($p) / 2;
6745 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6746 $this->SetFillColorArray($fill_color);
6750 $line_style = array();
6774 if (isset($line_style["all"])) {
6775 $this->SetLineStyle($line_style["all"]);
6776 } else { // 0 .. (np - 1), op = {B, S}
6780 $this->_outPoint($p[0], $p[1]);
6781 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6782 $this->_outLine($p[$i], $p[$i + 1]);
6784 $this->_outLine($p[0], $p[1]);
6787 $p[($np * 2)] = $p[0];
6788 $p[(($np * 2) + 1)] = $p[1];
6789 for ($i = 0; $i < $np; $i++) {
6790 if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
6791 $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
6797 $this->_outPoint($p[0], $p[1]);
6798 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6799 $this->_outLine($p[$i], $p[$i + 1]);
6801 $this->_outLine($p[0], $p[1]);
6807 * Draws a regular polygon.
6808 * @param float $x0 Abscissa of center point.
6809 * @param float $y0 Ordinate of center point.
6810 * @param float $r: Radius of inscribed circle.
6811 * @param integer $ns Number of sides.
6812 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
6813 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
6814 * @param string $style Style of rendering. Possible values are:
6816 * <li>D or empty string: Draw (default).</li>
6818 * <li>DF or FD: Draw and fill.</li>
6819 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6820 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6822 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6824 * <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
6825 * <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6827 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6828 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6829 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6831 * <li>D or empty string: Draw (default).</li>
6833 * <li>DF or FD: Draw and fill.</li>
6834 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6835 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6837 * @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).
6838 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6840 * @since 2.1.000 (2008-01-08)
6842 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()) {
6847 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6850 for ($i = 0; $i < $ns; $i++) {
6851 $a = $angle + ($i * 360 / $ns);
6852 $a_rad = deg2rad((float) $a);
6853 $p[] = $x0 + ($r * sin($a_rad));
6854 $p[] = $y0 + ($r * cos($a_rad));
6856 $this->Polygon($p, $style, $line_style, $fill_color);
6860 * Draws a star polygon
6861 * @param float $x0 Abscissa of center point.
6862 * @param float $y0 Ordinate of center point.
6863 * @param float $r Radius of inscribed circle.
6864 * @param integer $nv Number of vertices.
6865 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
6866 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6867 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
6868 * @param string $style Style of rendering. Possible values are:
6870 * <li>D or empty string: Draw (default).</li>
6872 * <li>DF or FD: Draw and fill.</li>
6873 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6874 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6876 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6878 * <li>all: Line style of all sides. Array like for
6879 * {@link SetLineStyle SetLineStyle}.</li>
6880 * <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6882 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6883 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6884 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6886 * <li>D or empty string: Draw (default).</li>
6888 * <li>DF or FD: Draw and fill.</li>
6889 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6890 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6892 * @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).
6893 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6895 * @since 2.1.000 (2008-01-08)
6897 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()) {
6902 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6906 for ($i = 0; $i < $nv; $i++) {
6907 $a = $angle + ($i * 360 / $nv);
6908 $a_rad = deg2rad((float) $a);
6909 $p2[] = $x0 + ($r * sin($a_rad));
6910 $p2[] = $y0 + ($r * cos($a_rad));
6917 $p[] = $p2[($i * 2) + 1];
6918 $visited[$i] = true;
6921 } while (!$visited[$i]);
6922 $this->Polygon($p, $style, $line_style, $fill_color);
6926 * Draws a rounded rectangle.
6927 * @param float $x Abscissa of upper-left corner.
6928 * @param float $y Ordinate of upper-left corner.
6929 * @param float $w Width.
6930 * @param float $h Height.
6931 * @param float $r Radius of the rounded corners.
6932 * @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").
6933 * @param string $style Style of rendering. Possible values are:
6935 * <li>D or empty string: Draw (default).</li>
6937 * <li>DF or FD: Draw and fill.</li>
6938 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6939 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6941 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6942 * @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).
6944 * @since 2.1.000 (2008-01-08)
6946 function RoundedRect($x, $y, $w, $h, $r, $round_corner="1111", $style="", $border_style=array(), $fill_color=array()) {
6947 if ("0000" == $round_corner) { // Not rounded
6948 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
6950 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6951 $this->SetFillColorArray($fill_color);
6955 $border_style = array();
6977 if ($border_style) {
6978 $this->SetLineStyle($border_style);
6980 $MyArc = 4 / 3 * (sqrt(2) - 1);
6981 $this->_outPoint($x + $r, $y);
6984 $this->_outLine($xc, $y);
6985 if ($round_corner[0]) {
6986 $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
6988 $this->_outLine($x + $w, $y);
6992 $this->_outLine($x + $w, $yc);
6993 if ($round_corner[1]) {
6994 $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
6996 $this->_outLine($x + $w, $y + $h);
7000 $this->_outLine($xc, $y + $h);
7001 if ($round_corner[2]) {
7002 $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
7004 $this->_outLine($x, $y + $h);
7008 $this->_outLine($x, $yc);
7009 if ($round_corner[3]) {
7010 $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
7012 $this->_outLine($x, $y);
7013 $this->_outLine($x + $r, $y);
7019 // END GRAPHIC FUNCTIONS SECTION -----------------------
7021 // BIDIRECTIONAL TEXT SECTION --------------------------
7023 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7024 * @param string $str string to manipulate.
7025 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7027 * @author Nicola Asuni
7028 * @since 2.1.000 (2008-01-08)
7030 function utf8StrRev($str, $setbom=false, $forcertl=false) {
7031 return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $forcertl), $setbom);
7035 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7036 * @param array $ta array of characters composing the string.
7037 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7039 * @author Nicola Asuni
7040 * @since 2.4.000 (2008-03-06)
7042 function utf8Bidi($ta, $forcertl=false) {
7043 global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
7044 // paragraph embedding level
7048 // create string from array
7049 $str = $this->UTF8ArrSubString($ta);
7050 // check if string contains arabic text
7051 if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
7056 // check if string contains RTL text
7057 if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
7061 // get number of chars
7062 $numchars = count($ta);
7064 if ($forcertl == 'R') {
7066 } elseif ($forcertl == 'L') {
7069 // P2. In each paragraph, find the first character of type L, AL, or R.
7070 // 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.
7071 for ($i=0; $i < $numchars; $i++) {
7072 $type = $unicode[$ta[$i]];
7076 } elseif (($type == 'AL') OR ($type == 'R')) {
7083 // Current Embedding Level
7085 // directional override status
7087 $remember = array();
7088 // start-of-level-run
7089 $sor = $pel % 2 ? 'R' : 'L';
7092 //$levels = array(array('level' => $cel, 'sor' => $sor, 'eor' => '', 'chars' => array()));
7093 //$current_level = &$levels[count( $levels )-1];
7095 // Array of characters data
7096 $chardata = Array();
7098 // 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.
7099 // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
7100 for ($i=0; $i < $numchars; $i++) {
7101 if ($ta[$i] == K_RLE) {
7102 // X2. With each RLE, compute the least greater odd embedding level.
7103 // 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.
7104 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7105 $next_level = $cel + ($cel % 2) + 1;
7106 if ($next_level < 62) {
7107 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
7111 $eor = $cel % 2 ? 'R' : 'L';
7113 } elseif ($ta[$i] == K_LRE) {
7114 // X3. With each LRE, compute the least greater even embedding level.
7115 // 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.
7116 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7117 $next_level = $cel + 2 - ($cel % 2);
7118 if ( $next_level < 62 ) {
7119 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
7123 $eor = $cel % 2 ? 'R' : 'L';
7125 } elseif ($ta[$i] == K_RLO) {
7126 // X4. With each RLO, compute the least greater odd embedding level.
7127 // 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.
7128 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7129 $next_level = $cel + ($cel % 2) + 1;
7130 if ($next_level < 62) {
7131 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
7135 $eor = $cel % 2 ? 'R' : 'L';
7137 } elseif ($ta[$i] == K_LRO) {
7138 // X5. With each LRO, compute the least greater even embedding level.
7139 // 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.
7140 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7141 $next_level = $cel + 2 - ($cel % 2);
7142 if ( $next_level < 62 ) {
7143 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
7147 $eor = $cel % 2 ? 'R' : 'L';
7149 } elseif ($ta[$i] == K_PDF) {
7150 // 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.
7151 if (count($remember)) {
7152 $last = count($remember ) - 1;
7153 if (($remember[$last]['num'] == K_RLE) OR
7154 ($remember[$last]['num'] == K_LRE) OR
7155 ($remember[$last]['num'] == K_RLO) OR
7156 ($remember[$last]['num'] == K_LRO)) {
7157 $match = array_pop($remember);
7158 $cel = $match['cel'];
7159 $dos = $match['dos'];
7161 $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
7164 } elseif (($ta[$i] != K_RLE) AND
7165 ($ta[$i] != K_LRE) AND
7166 ($ta[$i] != K_RLO) AND
7167 ($ta[$i] != K_LRO) AND
7168 ($ta[$i] != K_PDF)) {
7169 // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
7170 // a. Set the level of the current character to the current embedding level.
7171 // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
7175 $chardir = $unicode[$ta[$i]];
7177 // stores string characters and other information
7178 $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
7180 } // end for each char
7182 // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
7183 // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
7184 // 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.
7186 // 3.3.3 Resolving Weak Types
7187 // 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.
7188 // Nonspacing marks are now resolved based on the previous characters.
7189 $numchars = count($chardata);
7191 // 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.
7192 $prevlevel = -1; // track level changes
7193 $levcount = 0; // counts consecutive chars at the same level
7194 for ($i=0; $i < $numchars; $i++) {
7195 if ($chardata[$i]['type'] == 'NSM') {
7197 $chardata[$i]['type'] = $chardata[$i]['sor'];
7199 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
7202 if ($chardata[$i]['level'] != $prevlevel) {
7207 $prevlevel = $chardata[$i]['level'];
7210 // 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.
7213 for ($i=0; $i < $numchars; $i++) {
7214 if ($chardata[$i]['char'] == 'EN') {
7215 for ($j=$levcount; $j >= 0; $j--) {
7216 if ($chardata[$j]['type'] == 'AL') {
7217 $chardata[$i]['type'] = 'AN';
7218 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
7223 if ($chardata[$i]['level'] != $prevlevel) {
7228 $prevlevel = $chardata[$i]['level'];
7231 // W3. Change all ALs to R.
7232 for ($i=0; $i < $numchars; $i++) {
7233 if ($chardata[$i]['type'] == 'AL') {
7234 $chardata[$i]['type'] = 'R';
7238 // 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.
7241 for ($i=0; $i < $numchars; $i++) {
7242 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7243 if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7244 $chardata[$i]['type'] = 'EN';
7245 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7246 $chardata[$i]['type'] = 'EN';
7247 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
7248 $chardata[$i]['type'] = 'AN';
7251 if ($chardata[$i]['level'] != $prevlevel) {
7256 $prevlevel = $chardata[$i]['level'];
7259 // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
7262 for ($i=0; $i < $numchars; $i++) {
7263 if ($chardata[$i]['type'] == 'ET') {
7264 if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
7265 $chardata[$i]['type'] = 'EN';
7268 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
7269 if ($chardata[$j]['type'] == 'EN') {
7270 $chardata[$i]['type'] = 'EN';
7272 } elseif ($chardata[$j]['type'] != 'ET') {
7279 if ($chardata[$i]['level'] != $prevlevel) {
7284 $prevlevel = $chardata[$i]['level'];
7287 // W6. Otherwise, separators and terminators change to Other Neutral.
7290 for ($i=0; $i < $numchars; $i++) {
7291 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
7292 $chardata[$i]['type'] = 'ON';
7294 if ($chardata[$i]['level'] != $prevlevel) {
7299 $prevlevel = $chardata[$i]['level'];
7302 //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.
7305 for ($i=0; $i < $numchars; $i++) {
7306 if ($chardata[$i]['char'] == 'EN') {
7307 for ($j=$levcount; $j >= 0; $j--) {
7308 if ($chardata[$j]['type'] == 'L') {
7309 $chardata[$i]['type'] = 'L';
7310 } elseif ($chardata[$j]['type'] == 'R') {
7315 if ($chardata[$i]['level'] != $prevlevel) {
7320 $prevlevel = $chardata[$i]['level'];
7323 // 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.
7326 for ($i=0; $i < $numchars; $i++) {
7327 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7328 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7329 $chardata[$i]['type'] = 'L';
7330 } elseif (($chardata[$i]['type'] == 'N') AND
7331 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7332 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7333 $chardata[$i]['type'] = 'R';
7334 } elseif ($chardata[$i]['type'] == 'N') {
7335 // N2. Any remaining neutrals take the embedding direction
7336 $chardata[$i]['type'] = $chardata[$i]['sor'];
7338 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7340 if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7341 $chardata[$i]['type'] = 'L';
7342 } elseif (($chardata[$i]['type'] == 'N') AND
7343 (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
7344 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7345 $chardata[$i]['type'] = 'R';
7346 } elseif ($chardata[$i]['type'] == 'N') {
7347 // N2. Any remaining neutrals take the embedding direction
7348 $chardata[$i]['type'] = $chardata[$i]['sor'];
7350 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
7352 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
7353 $chardata[$i]['type'] = 'L';
7354 } elseif (($chardata[$i]['type'] == 'N') AND
7355 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7356 (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
7357 $chardata[$i]['type'] = 'R';
7358 } elseif ($chardata[$i]['type'] == 'N') {
7359 // N2. Any remaining neutrals take the embedding direction
7360 $chardata[$i]['type'] = $chardata[$i]['sor'];
7362 } elseif ($chardata[$i]['type'] == 'N') {
7363 // N2. Any remaining neutrals take the embedding direction
7364 $chardata[$i]['type'] = $chardata[$i]['sor'];
7366 if ($chardata[$i]['level'] != $prevlevel) {
7371 $prevlevel = $chardata[$i]['level'];
7374 // 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.
7375 // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
7376 for ($i=0; $i < $numchars; $i++) {
7377 $odd = $chardata[$i]['level'] % 2;
7379 if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7380 $chardata[$i]['level'] += 1;
7383 if ($chardata[$i]['type'] == 'R') {
7384 $chardata[$i]['level'] += 1;
7385 } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7386 $chardata[$i]['level'] += 2;
7389 $maxlevel = max($chardata[$i]['level'],$maxlevel);
7392 // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
7393 // 1. Segment separators,
7394 // 2. Paragraph separators,
7395 // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
7396 // 4. Any sequence of white space characters at the end of the line.
7397 for ($i=0; $i < $numchars; $i++) {
7398 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
7399 $chardata[$i]['level'] = $pel;
7400 } elseif ($chardata[$i]['type'] == 'WS') {
7402 while ($j < $numchars) {
7403 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
7404 (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
7405 $chardata[$i]['level'] = $pel;
7407 } elseif ($chardata[$j]['type'] != 'WS') {
7416 // 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.
7418 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
7419 $alfletter = array(1570,1571,1573,1575);
7420 $chardata2 = $chardata;
7424 for ($i=0; $i < $numchars; $i++) {
7425 if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
7426 $charAL[$x] = $chardata[$i];
7427 $charAL[$x]['i'] = $i;
7428 $chardata[$i]['x'] = $x;
7433 for ($i=0; $i < $numchars; $i++) {
7434 $thischar = $chardata[$i];
7436 $prevchar = $chardata[($i-1)];
7440 if (($i+1) < $numchars) {
7441 $nextchar = $chardata[($i+1)];
7445 if ($unicode[$thischar['char']] == 'AL') {
7446 $x = $thischar['x'];
7448 $prevchar = $charAL[($x-1)];
7452 if (($x+1) < $numAL) {
7453 $nextchar = $charAL[($x+1)];
7458 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
7459 $arabicarr = $laa_array;
7462 $prevchar = $charAL[($x-2)];
7467 $arabicarr = $unicode_arlet;
7470 if (($prevchar !== false) AND ($nextchar !== false) AND
7471 (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7472 (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7473 ($prevchar['type'] == $thischar['type']) AND
7474 ($nextchar['type'] == $thischar['type']) AND
7475 ($nextchar['char'] != 1567)) {
7476 if (in_array($prevchar['char'], $endedletter)) {
7477 if (isset($arabicarr[$thischar['char']][2])) {
7479 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7482 if (isset($arabicarr[$thischar['char']][3])) {
7484 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
7487 } elseif (($nextchar !== false) AND
7488 (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7489 ($nextchar['type'] == $thischar['type']) AND
7490 ($nextchar['char'] != 1567)) {
7491 if (isset($arabicarr[$chardata[$i]['char']][2])) {
7493 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7495 } elseif ((($prevchar !== false) AND
7496 (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7497 ($prevchar['type'] == $thischar['type'])) OR
7498 (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
7500 if (($i > 1) AND ($thischar['char'] == 1607) AND
7501 ($chardata[$i-1]['char'] == 1604) AND
7502 ($chardata[$i-2]['char'] == 1604)) {
7504 // mark characters to delete with false
7505 $chardata2[$i-2]['char'] = false;
7506 $chardata2[$i-1]['char'] = false;
7507 $chardata2[$i]['char'] = 65010;
7509 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
7510 if (isset($arabicarr[$thischar['char']][0])) {
7512 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7515 if (isset($arabicarr[$thischar['char']][1])) {
7517 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
7521 } elseif (isset($arabicarr[$thischar['char']][0])) {
7523 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7527 // mark characters to delete with false
7528 $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
7530 } // end if AL (Arabic Letter)
7531 } // end for each char
7533 * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
7534 * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
7536 $cw = &$this->CurrentFont['cw'];
7537 for ($i=0; $i < ($numchars-1); $i++) {
7538 if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
7539 // check if the subtitution font is defined on current font
7540 if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
7541 $chardata2[$i]['char'] = false;
7542 $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
7546 // remove marked characters
7547 foreach($chardata2 as $key => $value) {
7548 if ($value['char'] === false) {
7549 unset($chardata2[$key]);
7552 $chardata = array_values($chardata2);
7553 $numchars = count($chardata);
7560 // 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.
7561 for ($j=$maxlevel; $j > 0; $j--) {
7562 $ordarray = Array();
7565 for ($i=0; $i < $numchars; $i++) {
7566 if ($chardata[$i]['level'] >= $j) {
7568 if (isset($unicode_mirror[$chardata[$i]['char']])) {
7569 // 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.
7570 $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
7572 $revarr[] = $chardata[$i];
7575 $revarr = array_reverse($revarr);
7576 $ordarray = array_merge($ordarray, $revarr);
7580 $ordarray[] = $chardata[$i];
7584 $revarr = array_reverse($revarr);
7585 $ordarray = array_merge($ordarray, $revarr);
7587 $chardata = $ordarray;
7590 $ordarray = array();
7591 for ($i=0; $i < $numchars; $i++) {
7592 $ordarray[] = $chardata[$i]['char'];
7598 // END OF BIDIRECTIONAL TEXT SECTION -------------------
7602 * @param string $txt bookmark description.
7603 * @param int $level bookmark level (minimum value is 0).
7604 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
7606 * @author Olivier Plathey, Nicola Asuni
7607 * @since 2.1.002 (2008-02-12)
7609 function Bookmark($txt, $level=0, $y=-1) {
7613 if (isset($this->outlines[0])) {
7614 $lastoutline = end($this->outlines);
7615 $maxlevel = $lastoutline['l'] + 1;
7619 if ($level > $maxlevel) {
7625 $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $this->PageNo());
7629 * Create a bookmark PDF string.
7631 * @author Olivier Plathey, Nicola Asuni
7632 * @since 2.1.002 (2008-02-12)
7634 function _putbookmarks() {
7635 $nb = count($this->outlines);
7641 foreach($this->outlines as $i => $o) {
7643 $parent = $lru[($o['l'] - 1)];
7644 //Set parent and last pointers
7645 $this->outlines[$i]['parent'] = $parent;
7646 $this->outlines[$parent]['last'] = $i;
7647 if ($o['l'] > $level) {
7648 //Level increasing: set first pointer
7649 $this->outlines[$parent]['first'] = $i;
7652 $this->outlines[$i]['parent'] = $nb;
7654 if (($o['l'] <= $level) AND ($i > 0)) {
7655 //Set prev and next pointers
7656 $prev = $lru[$o['l']];
7657 $this->outlines[$prev]['next'] = $i;
7658 $this->outlines[$i]['prev'] = $prev;
7665 foreach($this->outlines as $i => $o) {
7667 $this->_out('<</Title '.$this->_textstring($o['t']));
7668 $this->_out('/Parent '.($n+$o['parent']).' 0 R');
7669 if (isset($o['prev']))
7670 $this->_out('/Prev '.($n+$o['prev']).' 0 R');
7671 if (isset($o['next']))
7672 $this->_out('/Next '.($n+$o['next']).' 0 R');
7673 if (isset($o['first']))
7674 $this->_out('/First '.($n+$o['first']).' 0 R');
7675 if (isset($o['last']))
7676 $this->_out('/Last '.($n+$o['last']).' 0 R');
7677 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]', 1+2*$o['p'], ($this->h-$o['y'])*$this->k));
7678 $this->_out('/Count 0>>');
7679 $this->_out('endobj');
7683 $this->OutlineRoot=$this->n;
7684 $this->_out('<</Type /Outlines /First '.$n.' 0 R');
7685 $this->_out('/Last '.($n+$lru[0]).' 0 R>>');
7686 $this->_out('endobj');
7690 // --- JAVASCRIPT - FORMS ------------------------------
7695 * @author Johannes Güntert, Nicola Asuni
7696 * @since 2.1.002 (2008-02-12)
7698 function IncludeJS($script) {
7699 $this->javascript .= $script;
7703 * Create a javascript PDF string.
7705 * @author Johannes Güntert, Nicola Asuni
7706 * @since 2.1.002 (2008-02-12)
7708 function _putjavascript() {
7709 if (empty($this->javascript)) {
7712 // the following two lines are uded to avoid form fields duplication after saving
7713 $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2f,%.2f,%.2f,%.2f]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
7714 $js2 = "getField('tcpdfdocsaved').value = 'saved';";
7716 $this->n_js = $this->n;
7718 $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
7720 $this->_out('endobj');
7723 $this->_out('/S /JavaScript');
7724 $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
7726 $this->_out('endobj');
7730 * Convert color to javascript color.
7731 * @param string $color color name or #RRGGBB
7733 * @author Denis Van Nuffelen, Nicola Asuni
7734 * @since 2.1.002 (2008-02-12)
7736 function _JScolor($color) {
7737 static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
7738 if (substr($color,0,1) == '#') {
7739 return sprintf("['RGB',%.3f,%.3f,%.3f]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
7741 if (!in_array($color,$aColors)) {
7742 $this->Error('Invalid color: '.$color);
7744 return 'color.'.$color;
7748 * Adds a javascript form field.
7749 * @param string $type field type
7750 * @param string $name field name
7751 * @param int $x horizontal position
7752 * @param int $y vertical position
7753 * @param int $w width
7754 * @param int $h height
7755 * @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>
7757 * @author Denis Van Nuffelen, Nicola Asuni
7758 * @since 2.1.002 (2008-02-12)
7760 function _addfield($type, $name, $x, $y, $w, $h, $prop) {
7761 // the followind avoid fields duplication after saving the document
7762 $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
7764 $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";
7765 $this->javascript .= "f".$name.".textSize=".$this->FontSizePt.";\n";
7766 while (list($key, $val) = each($prop)) {
7767 if (strcmp(substr($key,-5),"Color") == 0) {
7768 $val = $this->_JScolor($val);
7770 $val = "'".$val."'";
7772 $this->javascript .= "f".$name.".".$key."=".$val.";\n";
7775 $this->javascript .= "}";
7779 * Creates a text field
7780 * @param string $name field name
7781 * @param int $w width
7782 * @param int $h height
7783 * @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>
7785 * @author Denis Van Nuffelen, Nicola Asuni
7786 * @since 2.1.002 (2008-02-12)
7788 function TextField($name, $w, $h, $prop=array()) {
7789 $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
7793 * Creates a RadioButton field
7794 * @param string $name field name
7795 * @param int $w width
7796 * @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>
7798 * @author Nicola Asuni
7799 * @since 2.2.003 (2008-03-03)
7801 function RadioButton($name, $w, $prop=array()) {
7802 if (!isset($prop['strokeColor'])) {
7803 $prop['strokeColor']='black';
7805 $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
7809 * Creates a List-box field
7810 * @param string $name field name
7811 * @param int $w width
7812 * @param int $h height
7813 * @param array $values array containing the list of values.
7814 * @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>
7816 * @author Nicola Asuni
7817 * @since 2.2.003 (2008-03-03)
7819 function ListBox($name, $w, $h, $values, $prop=array()) {
7820 if (!isset($prop['strokeColor'])) {
7821 $prop['strokeColor'] = 'ltGray';
7823 $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
7825 foreach($values as $value) {
7826 $s .= "'".addslashes($value)."',";
7828 $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7832 * Creates a Combo-box field
7833 * @param string $name field name
7834 * @param int $w width
7835 * @param int $h height
7836 * @param array $values array containing the list of values.
7837 * @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>
7839 * @author Denis Van Nuffelen, Nicola Asuni
7840 * @since 2.1.002 (2008-02-12)
7842 function ComboBox($name, $w, $h, $values, $prop=array()) {
7843 $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
7845 foreach($values as $value) {
7846 $s .= "'".addslashes($value)."',";
7848 $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7852 * Creates a CheckBox field
7853 * @param string $name field name
7854 * @param int $w width
7855 * @param boolean $checked define the initial state (default = false).
7856 * @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>
7858 * @author Denis Van Nuffelen, Nicola Asuni
7859 * @since 2.1.002 (2008-02-12)
7861 function CheckBox($name, $w, $checked=false, $prop=array()) {
7862 $prop['value'] = ($checked ? 'Yes' : 'Off');
7863 if (!isset($prop['strokeColor'])) {
7864 $prop['strokeColor'] = 'black';
7866 $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
7870 * Creates a button field
7871 * @param string $name field name
7872 * @param int $w width
7873 * @param int $h height
7874 * @param string $caption caption.
7875 * @param string $action action triggered by the button (JavaScript code).
7876 * @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>
7878 * @author Denis Van Nuffelen, Nicola Asuni
7879 * @since 2.1.002 (2008-02-12)
7881 function Button($name, $w, $h, $caption, $action, $prop=array()) {
7882 if (!isset($prop['strokeColor'])) {
7883 $prop['strokeColor'] = 'black';
7885 if (!isset($prop['borderStyle'])) {
7886 $prop['borderStyle'] = 'beveled';
7888 $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
7889 $this->javascript .= "f".$name.".buttonSetCaption('".addslashes($caption)."');\n";
7890 $this->javascript .= "f".$name.".setAction('MouseUp','".addslashes($action)."');\n";
7891 $this->javascript .= "f".$name.".highlight='push';\n";
7892 $this->javascript .= "f".$name.".print=false;\n";
7895 // END JAVASCRIPT - FORMS ------------------------------
7898 * Enable Write permissions for PDF Reader.
7900 * @author Nicola Asuni
7901 * @since 2.9.000 (2008-03-26)
7903 function _putuserrights() {
7907 $this->_out('/Perms');
7909 $this->_out('/UR3');
7911 //$this->_out('/SubFilter/adbe.pkcs7.detached/Filter/Adobe.PPKLite/Contents');
7912 //$this->_out('<0>');
7913 //$this->_out('/ByteRange[0 3]');
7914 $this->_out('/M '.$this->_datestring('D:'.date('YmdHis')));
7915 $this->_out('/Name(TCPDF)');
7916 $this->_out('/Reference[');
7918 $this->_out('/TransformParams');
7920 $this->_out('/Type/TransformParams');
7921 $this->_out('/V/2.2');
7922 if (!empty($this->ur_document)) {
7923 $this->_out('/Document['.$this->ur_document.']');
7925 if (!empty($this->ur_annots)) {
7926 $this->_out('/Annots['.$this->ur_annots.']');
7928 if (!empty($this->ur_form)) {
7929 $this->_out('/Form['.$this->ur_form.']');
7931 if (!empty($this->ur_signature)) {
7932 $this->_out('/Signature['.$this->ur_signature.']');
7935 $this->_out('/TransformMethod/UR3');
7936 $this->_out('/Type/SigRef');
7939 $this->_out('/Type/Sig');
7945 * Set User's Rights for PDF Reader
7946 * Check the PDF Reference 8.7.1 Transform Methods,
7947 * Table 8.105 Entries in the UR transform parameters dictionary
7948 * @param boolean $enable if true enable user's rights on PDF reader
7949 * @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.
7950 * @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.
7951 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
7952 * @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.
7954 * @author Nicola Asuni
7955 * @since 2.9.000 (2008-03-26)
7957 function setUserRights(
7959 $document="/FullSave",
7960 $annots="/Create/Delete/Modify/Copy/Import/Export",
7961 $form="/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate",
7962 $signature="/Modify") {
7963 $this->ur = $enable;
7964 $this->ur_document = $document;
7965 $this->ur_annots = $annots;
7966 $this->ur_form = $form;
7967 $this->ur_signature = $signature;
7971 * Create a new page group.
7972 * NOTE: call this function before calling AddPage()
7974 * @since 3.0.000 (2008-03-27)
7976 function startPageGroup() {
7977 $this->newpagegroup = true;
7981 * Return the current page in the group.
7982 * @return current page in the group
7984 * @since 3.0.000 (2008-03-27)
7986 function getGroupPageNo() {
7987 return $this->pagegroups[$this->currpagegroup];
7991 * Return the alias of the current page group
7992 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
7993 * (will be replaced by the total number of pages in this group).
7994 * @return alias of the current page group
7996 * @since 3.0.000 (2008-03-27)
7998 function getPageGroupAlias() {
7999 if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
8000 return "{".$this->currpagegroup."}";
8002 return $this->currpagegroup;
8006 * Put visibility settings.
8008 * @since 3.0.000 (2008-03-27)
8010 function _putocg() {
8012 $this->n_ocg_print = $this->n;
8013 $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
8014 $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
8015 $this->_out('endobj');
8017 $this->n_ocg_view=$this->n;
8018 $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
8019 $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
8020 $this->_out('endobj');
8024 * Set the visibility of the successive elements.
8025 * This can be useful, for instance, to put a background
8026 * image or color that will show on screen but won't print.
8027 * @param string $v visibility mode. Legal values are: all, print, screen.
8029 * @since 3.0.000 (2008-03-27)
8031 function setVisibility($v) {
8032 if ($this->openMarkedContent) {
8033 // close existing open marked-content
8035 $this->openMarkedContent = false;
8039 $this->_out('/OC /OC1 BDC');
8040 $this->openMarkedContent = true;
8044 $this->_out('/OC /OC2 BDC');
8045 $this->openMarkedContent = true;
8053 $this->Error('Incorrect visibility: '.$v);
8057 $this->visibility = $v;
8061 * Add transparency parameters to the current extgstate
8062 * @param array $params parameters
8063 * @return the number of extgstates
8065 * @since 3.0.000 (2008-03-27)
8067 function addExtGState($parms) {
8068 $n = count($this->extgstates) + 1;
8069 $this->extgstates[$n]['parms'] = $parms;
8075 * @param array $gs extgstate
8077 * @since 3.0.000 (2008-03-27)
8079 function setExtGState($gs) {
8080 $this->_out(sprintf('/GS%d gs', $gs));
8084 * Put extgstates for object transparency
8085 * @param array $gs extgstate
8087 * @since 3.0.000 (2008-03-27)
8089 function _putextgstates() {
8090 $ne = count($this->extgstates);
8091 for ($i = 1; $i <= $ne; $i++) {
8093 $this->extgstates[$i]['n'] = $this->n;
8094 $this->_out('<</Type /ExtGState');
8095 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
8096 $this->_out('/'.$k.' '.$v);
8099 $this->_out('endobj');
8104 * Set alpha for stroking (CA) and non-stroking (ca) operations.
8105 * @param float $alpha real value from 0 (transparent) to 1 (opaque)
8106 * @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
8108 * @since 3.0.000 (2008-03-27)
8110 function setAlpha($alpha, $bm='Normal') {
8111 $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
8112 $this->setExtGState($gs);
8116 * Set the default JPEG compression quality (1-100)
8117 * @param int $quality JPEG quality, integer between 1 and 100
8119 * @since 3.0.000 (2008-03-27)
8121 function setJPEGQuality($quality) {
8122 if (($quality < 1) OR ($quality > 100)) {
8125 $this->jpeg_quality = intval($quality);
8129 * Set the default number of columns in a row for HTML tables.
8130 * @param int $cols number of columns
8132 * @since 3.0.014 (2008-06-04)
8134 function setDefaultTableColumns($cols=4) {
8135 $this->default_table_columns = intval($cols);
8139 * Set the height of cell repect font height.
8140 * @param int $h cell proportion respect font height (typical value = 1.25).
8142 * @since 3.0.014 (2008-06-04)
8144 function setCellHeightRatio($h) {
8145 $this->cell_height_ratio = $h;
8149 * return the height of cell repect font height.
8151 * @since 4.0.012 (2008-07-24)
8153 function getCellHeightRatio() {
8154 return $this->cell_height_ratio;
8158 * Set the PDF version (check PDF reference for valid values).
8159 * Default value is 1.t
8161 * @since 3.1.000 (2008-06-09)
8163 function setPDFVersion($version="1.7") {
8164 $this->PDFVersion = $version;
8168 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
8169 * (see Section 8.1 of PDF reference, "Viewer Preferences").
8171 * <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>
8172 * <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>
8173 * <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>
8174 * <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>
8175 * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
8176 * <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>
8177 * <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>
8178 * <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>
8179 * <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>
8180 * <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>
8181 * <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>
8182 * <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>
8183 * <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>
8184 * <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>
8185 * <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>
8186 * <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>
8188 * @param array $preferences array of options.
8189 * @author Nicola Asuni
8191 * @since 3.1.000 (2008-06-09)
8193 function setViewerPreferences($preferences) {
8194 $this->viewer_preferences = $preferences;
8198 * Paints a linear colour gradient.
8199 * @param float $x abscissa of the top left corner of the rectangle.
8200 * @param float $y ordinate of the top left corner of the rectangle.
8201 * @param float $w width of the rectangle.
8202 * @param float $h height of the rectangle.
8203 * @param array $col1 first color (RGB components).
8204 * @param array $col2 second color (RGB components).
8205 * @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).
8206 * @author Andreas Würmser, Nicola Asuni
8207 * @since 3.1.000 (2008-06-09)
8210 function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
8211 $this->Clip($x, $y, $w, $h);
8212 $this->Gradient(2, $col1, $col2, $coords);
8216 * Paints a radial colour gradient.
8217 * @param float $x abscissa of the top left corner of the rectangle.
8218 * @param float $y ordinate of the top left corner of the rectangle.
8219 * @param float $w width of the rectangle.
8220 * @param float $h height of the rectangle.
8221 * @param array $col1 first color (RGB components).
8222 * @param array $col2 second color (RGB components).
8223 * @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.
8224 * @author Andreas Würmser, Nicola Asuni
8225 * @since 3.1.000 (2008-06-09)
8228 function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
8229 $this->Clip($x, $y, $w, $h);
8230 $this->Gradient(3, $col1, $col2, $coords);
8234 * Paints a coons patch mesh.
8235 * @param float $x abscissa of the top left corner of the rectangle.
8236 * @param float $y ordinate of the top left corner of the rectangle.
8237 * @param float $w width of the rectangle.
8238 * @param float $h height of the rectangle.
8239 * @param array $col1 first color (lower left corner) (RGB components).
8240 * @param array $col2 second color (lower right corner) (RGB components).
8241 * @param array $col3 third color (upper right corner) (RGB components).
8242 * @param array $col4 fourth color (upper left corner) (RGB components).
8243 * @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>
8244 * @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
8245 * @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
8246 * @author Andreas Würmser, Nicola Asuni
8247 * @since 3.1.000 (2008-06-09)
8250 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) {
8251 $this->Clip($x, $y, $w, $h);
8252 $n = count($this->gradients) + 1;
8253 $this->gradients[$n]['type'] = 6; //coons patch mesh
8254 //check the coords array if it is the simple array or the multi patch array
8255 if (!isset($coords[0]['f'])){
8256 //simple array -> convert to multi patch array
8257 if (!isset($col1[1])) {
8258 $col1[1] = $col1[2] = $col1[0];
8260 if (!isset($col2[1])) {
8261 $col2[1] = $col2[2] = $col2[0];
8263 if (!isset($col3[1])) {
8264 $col3[1] = $col3[2] = $col3[0];
8266 if (!isset($col4[1])) {
8267 $col4[1] = $col4[2] = $col4[0];
8269 $patch_array[0]['f'] = 0;
8270 $patch_array[0]['points'] = $coords;
8271 $patch_array[0]['colors'][0]['r'] = $col1[0];
8272 $patch_array[0]['colors'][0]['g'] = $col1[1];
8273 $patch_array[0]['colors'][0]['b'] = $col1[2];
8274 $patch_array[0]['colors'][1]['r'] = $col2[0];
8275 $patch_array[0]['colors'][1]['g'] = $col2[1];
8276 $patch_array[0]['colors'][1]['b'] = $col2[2];
8277 $patch_array[0]['colors'][2]['r'] = $col3[0];
8278 $patch_array[0]['colors'][2]['g'] = $col3[1];
8279 $patch_array[0]['colors'][2]['b'] = $col3[2];
8280 $patch_array[0]['colors'][3]['r'] = $col4[0];
8281 $patch_array[0]['colors'][3]['g'] = $col4[1];
8282 $patch_array[0]['colors'][3]['b'] = $col4[2];
8285 $patch_array = $coords;
8287 $bpcd = 65535; //16 BitsPerCoordinate
8288 //build the data stream
8289 $this->gradients[$n]['stream'] = "";
8290 for($i=0; $i < count($patch_array); $i++) {
8291 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
8292 for($j=0; $j < count($patch_array[$i]['points']); $j++) {
8293 //each point as 16 bit
8294 $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j]-$coords_min)/($coords_max-$coords_min))*$bpcd;
8295 if ($patch_array[$i]['points'][$j] < 0) {
8296 $patch_array[$i]['points'][$j] = 0;
8298 if ($patch_array[$i]['points'][$j] > $bpcd) {
8299 $patch_array[$i]['points'][$j] = $bpcd;
8301 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]/256));
8302 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]%256));
8304 for($j=0; $j < count($patch_array[$i]['colors']); $j++) {
8305 //each color component as 8 bit
8306 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
8307 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
8308 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
8311 //paint the gradient
8312 $this->_out('/Sh'.$n.' sh');
8313 //restore previous Graphic State
8318 * Set a rectangular clipping area.
8319 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
8320 * @param float $y ordinate of the top left corner of the rectangle.
8321 * @param float $w width of the rectangle.
8322 * @param float $h height of the rectangle.
8323 * @author Andreas Würmser, Nicola Asuni
8324 * @since 3.1.000 (2008-06-09)
8327 function Clip($x, $y, $w, $h){
8329 $x = $this->w - $x - $w;
8331 //save current Graphic State
8334 $s .= sprintf(' %.2f %.2f %.2f %.2f re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
8335 //set up transformation matrix for gradient
8336 $s .= sprintf(' %.3f 0 0 %.3f %.3f %.3f cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
8342 * @param int $type type of gradient.
8343 * @param array $col1 first color (RGB components).
8344 * @param array $col2 second color (RGB components).
8345 * @param array $coords array of coordinates.
8346 * @author Andreas Würmser, Nicola Asuni
8347 * @since 3.1.000 (2008-06-09)
8350 function Gradient($type, $col1, $col2, $coords){
8351 $n = count($this->gradients) + 1;
8352 $this->gradients[$n]['type'] = $type;
8353 if (!isset($col1[1])) {
8354 $col1[1]=$col1[2]=$col1[0];
8356 $this->gradients[$n]['col1'] = sprintf('%.3f %.3f %.3f', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
8357 if (!isset($col2[1])) {
8358 $col2[1] = $col2[2] = $col2[0];
8360 $this->gradients[$n]['col2'] = sprintf('%.3f %.3f %.3f', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
8361 $this->gradients[$n]['coords'] = $coords;
8362 //paint the gradient
8363 $this->_out('/Sh'.$n.' sh');
8364 //restore previous Graphic State
8370 * @author Andreas Würmser, Nicola Asuni
8371 * @since 3.1.000 (2008-06-09)
8374 function _putshaders() {
8375 foreach($this->gradients as $id => $grad) {
8376 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
8379 $this->_out('/FunctionType 2');
8380 $this->_out('/Domain [0.0 1.0]');
8381 $this->_out('/C0 ['.$grad['col1'].']');
8382 $this->_out('/C1 ['.$grad['col2'].']');
8383 $this->_out('/N 1');
8385 $this->_out('endobj');
8390 $this->_out('/ShadingType '.$grad['type']);
8391 $this->_out('/ColorSpace /DeviceRGB');
8392 if ($grad['type'] == 2) {
8393 $this->_out(sprintf('/Coords [%.3f %.3f %.3f %.3f]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
8394 $this->_out('/Function '.$f1.' 0 R');
8395 $this->_out('/Extend [true true] ');
8397 } elseif ($grad['type'] == 3) {
8398 //x0, y0, r0, x1, y1, r1
8399 //at this this time radius of inner circle is 0
8400 $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]));
8401 $this->_out('/Function '.$f1.' 0 R');
8402 $this->_out('/Extend [true true] ');
8404 } elseif ($grad['type'] == 6) {
8405 $this->_out('/BitsPerCoordinate 16');
8406 $this->_out('/BitsPerComponent 8');
8407 $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
8408 $this->_out('/BitsPerFlag 8');
8409 $this->_out('/Length '.strlen($grad['stream']));
8411 $this->_putstream($grad['stream']);
8413 $this->_out('endobj');
8414 $this->gradients[$id]['id'] = $this->n;
8420 * @author Maxime Delorme, Nicola Asuni
8421 * @since 3.1.000 (2008-06-09)
8424 function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
8426 $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));
8430 * Draw the sector of a circle.
8431 * It can be used for instance to render pie charts.
8432 * @param float $xc abscissa of the center.
8433 * @param float $yc ordinate of the center.
8434 * @param float $r radius.
8435 * @param float $a start angle (in degrees).
8436 * @param float $b end angle (in degrees).
8437 * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
8438 * @param float $cw: indicates whether to go clockwise (default: true).
8439 * @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.
8440 * @author Maxime Delorme, Nicola Asuni
8441 * @since 3.1.000 (2008-06-09)
8444 function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
8446 $xc = $this->w - $xc - $w;
8456 $a = ($a % 360) + 360;
8457 $b = ($b % 360) + 360;
8461 $b = $b / 360 * 2 * M_PI;
8462 $a = $a / 360 * 2 * M_PI;
8471 } elseif ($style=='FD' or $style=='DF') {
8477 $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
8479 //first put the center
8480 $this->_out(sprintf('%.2f %.2f m', ($xc)*$k, ($hp-$yc)*$k));
8481 //put the first point
8482 $this->_out(sprintf('%.2f %.2f l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
8484 if ($d < (M_PI/2)) {
8485 $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));
8488 $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
8489 $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));
8492 $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));
8495 $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) );
8498 $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));
8505 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
8506 * Only vector drawing is supported, not text or bitmap.
8507 * 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).
8508 * @param string $file Name of the file containing the image.
8509 * @param float $x Abscissa of the upper-left corner.
8510 * @param float $y Ordinate of the upper-left corner.
8511 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
8512 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
8513 * @param mixed $link URL or identifier returned by AddLink().
8514 * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
8515 * @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>
8516 * @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>
8517 * @author Valentin Schmidt, Nicola Asuni
8518 * @since 3.1.000 (2008-06-09)
8521 function ImageEps($file, $x, $y, $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='') {
8522 $data = file_get_contents($file);
8523 if ($data === false) {
8524 $this->Error('EPS file not found: '.$file);
8527 // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
8528 preg_match ('/%%Creator:([^\r\n]+)/', $data, $regs); # find Creator
8529 if (count($regs) > 1) {
8530 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
8531 if (strpos($version_str, 'Adobe Illustrator') !== false) {
8532 $versexp = explode(' ', $version_str);
8533 $version = (float)array_pop($versexp);
8534 if ($version >= 9) {
8535 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
8539 // strip binary bytes in front of PS-header
8540 $start = strpos($data, '%!PS-Adobe');
8542 $data = substr($data, $start);
8544 // find BoundingBox params
8545 preg_match ("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
8546 if (count($regs) > 1) {
8547 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
8549 $this->Error('No BoundingBox found in EPS file: '.$file);
8551 $start = strpos($data, '%%EndSetup');
8552 if ($start === false) {
8553 $start = strpos($data, '%%EndProlog');
8555 if ($start === false) {
8556 $start = strpos($data, '%%BoundingBox');
8558 $data = substr($data, $start);
8559 $end = strpos($data, '%%PageTrailer');
8561 $end = strpos($data, 'showpage');
8564 $data = substr($data, 0, $end);
8568 $scale_x = $w/(($x2-$x1)/$k);
8570 $scale_y = $h/(($y2-$y1)/$k);
8572 $scale_y = $scale_x;
8573 $h = ($y2-$y1)/$k * $scale_y;
8577 $scale_y = $h/(($y2-$y1)/$k);
8578 $scale_x = $scale_y;
8579 $w = ($x2-$x1)/$k * $scale_x;
8581 $w = ($x2 - $x1) / $k;
8582 $h = ($y2 - $y1) / $k;
8585 // Check whether we need a new page first as this does not fit
8586 if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
8587 // Automatic page break
8588 $this->AddPage($this->CurOrientation);
8589 // Reset coordinates to top fo next page
8590 //$x = $this->GetX();
8591 $y = $this->GetY() + $this->cMargin;
8593 // set bottomcoordinates
8594 $this->img_rb_y = $y + $h;
8597 if ($palign == 'L') {
8598 $ximg = $this->lMargin;
8599 // set right side coordinate
8600 $this->img_rb_x = $ximg + $w;
8601 } elseif ($palign == 'C') {
8602 $ximg = ($this->w - $x - $w) / 2;
8603 // set right side coordinate
8604 $this->img_rb_x = $ximg + $w;
8606 $ximg = $this->w - $x - $w;
8607 // set left side coordinate
8608 $this->img_rb_x = $ximg;
8611 if ($palign == 'R') {
8612 $ximg = $this->w - $this->rMargin - $w;
8613 // set left side coordinate
8614 $this->img_rb_x = $ximg;
8615 } elseif ($palign == 'C') {
8616 $ximg = ($this->w - $x - $w) / 2;
8617 // set right side coordinate
8618 $this->img_rb_x = $ximg + $w;
8621 // set right side coordinate
8622 $this->img_rb_x = $ximg + $w;
8625 if ($useBoundingBox){
8626 $dx = $ximg * $k - $x1;
8627 $dy = $y * $k - $y1;
8632 // save the current graphic state
8635 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy+($this->hPt - 2*$y*$k - ($y2-$y1))));
8637 if (isset($scale_x)) {
8638 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1*(1-$scale_x), $y2*(1-$scale_y)));
8640 // handle pc/unix/mac line endings
8641 $lines = split("\r\n|[\r\n]", $data);
8643 $cnt = count($lines);
8644 for ($i=0; $i < $cnt; $i++) {
8646 if (($line == '') OR ($line{0} == '%')) {
8649 $len = strlen($line);
8650 $chunks = explode(' ', $line);
8651 $cmd = array_pop($chunks);
8653 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
8654 $b = array_pop($chunks);
8655 $g = array_pop($chunks);
8656 $r = array_pop($chunks);
8657 $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!
8682 case 'x': {// custom fill color
8683 list($c,$m,$y,$k) = $chunks;
8684 $this->_out("$c $m $y $k k");
8687 case 'X': { // custom stroke color
8688 list($c,$m,$y,$k) = $chunks;
8689 $this->_out("$c $m $y $k K");
8697 $line{$len-1} = strtolower($cmd);
8703 $this->_out($cmd . '*');
8710 $max = min($i+5, $cnt);
8711 for ($j=$i+1; $j < $max; $j++)
8712 $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
8731 // restore previous graphic state
8734 $this->Link($ximg, $y, $w, $h, $link);
8736 // set pointer to align the successive text/objects
8740 $this->x = $this->img_rb_x;
8744 $this->y = $y + round($h/2);
8745 $this->x = $this->img_rb_x;
8749 $this->y = $this->img_rb_y;
8750 $this->x = $this->img_rb_x;
8754 $this->SetY($this->img_rb_y);
8761 $this->endlinex = $this->img_rb_x;
8765 * Set document barcode.
8766 * @param string $bc barcode
8768 function setBarcode($bc="") {
8769 $this->barcode = $bc;
8773 * Get current barcode.
8775 * @since 4.0.012 (2008-07-24)
8777 function getBarcode() {
8778 return $this->barcode;
8783 * @param string $code code to print
8784 * @param string $type type of barcode.
8785 * @param int $x x position in user units
8786 * @param int $y y position in user units
8787 * @param int $w width in user units
8788 * @param int $h height position in user units
8789 * @param float $xres width of the smallest bar in user units
8790 * @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>
8791 * @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>
8792 * @author Nicola Asuni
8793 * @since 3.1.000 (2008-06-09)
8796 function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
8800 $barcodeobj = new TCPDFbarcode($code, $type);
8801 $arrcode = $barcodeobj->getBarcodeArray();
8802 if ($arrcode === false) {
8803 $this->Error('Error in barcode string');
8805 // set default values
8806 if (!isset($style["position"])) {
8808 $style["position"] = "R";
8810 $style["position"] = "L";
8813 if (!isset($style["padding"])) {
8814 $style["padding"] = 0;
8816 if (!isset($style["fgcolor"])) {
8817 $style["fgcolor"] = array(0,0,0); // default black
8819 if (!isset($style["bgcolor"])) {
8820 $style["bgcolor"] = false; // default transparent
8822 if (!isset($style["border"])) {
8823 $style["border"] = false;
8825 if (!isset($style["text"])) {
8826 $style["text"] = false;
8829 if ($style["text"] AND isset($style["font"])) {
8830 $prevFontFamily = $this->FontFamily;
8831 $prevFontStyle = $this->FontStyle;
8832 $prevFontSizePt = $this->FontSizePt;
8833 if (isset($style["fontsize"])) {
8834 $fontsize = $style["fontsize"];
8838 $this->SetFont($style["font"], '', $fontsize);
8840 if (!isset($style["stretchtext"])) {
8841 $style["stretchtext"] = 4;
8843 // set foreground color
8844 $prevDrawColor = $this->DrawColor;
8845 $prevTextColor = $this->TextColor;
8846 $this->SetDrawColorArray($style["fgcolor"]);
8847 $this->SetTextColorArray($style["fgcolor"]);
8848 if (empty($w) OR ($w <= 0)) {
8850 $w = $this->x - $this->lMargin;
8852 $w = $this->w - $this->rMargin - $this->x;
8867 $fbw = ($arrcode["maxw"] * $xres) + (2 * $style["padding"]);
8868 $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style["padding"]);
8870 $h = 10 + $extraspace;
8872 if ((($y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
8873 //Automatic page break
8878 $this->_out('0 Tw');
8880 $this->AddPage($this->CurOrientation);
8883 $this->_out(sprintf('%.3f Tw',$ws * $k));
8888 // maximum bar heigth
8889 $barh = $h - $extraspace;
8890 switch ($style["position"]) {
8899 case "C": { // center
8900 $xdiff = (($w - $fbw) / 2);
8902 $xpos = $x - $w + $xdiff;
8904 $xpos = $x + $xdiff;
8908 case "R": { // right
8912 $xpos = $x + $w - $fbw;
8916 case "S": { // stretch
8918 $xres = ($w - (2 * $style["padding"])) / $arrcode["maxw"];
8928 $xpos = $xpos_rect + $style["padding"];
8930 // barcode is always printed in LTR direction
8931 $tempRTL = $this->rtl;
8933 // print background color
8934 if ($style["bgcolor"]) {
8935 $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style["bgcolor"]);
8936 } elseif ($style["border"]) {
8937 $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
8940 if ($arrcode !== false) {
8941 foreach ($arrcode["bcode"] as $k => $v) {
8942 $bw = ($v["w"] * $xres);
8944 // braw a vertical bar
8945 $ypos = $y + $style["padding"] + ($v["p"] * $barh / $arrcode["maxh"]);
8946 $this->Rect($xpos, $ypos, $bw, ($v["h"] * $barh / $arrcode["maxh"]), 'DF', array("L"=>0,"T"=>0,"R"=>0,"B"=>0), $style["fgcolor"]);
8952 if ($style["text"]) {
8954 $this->x = $xpos_text;
8955 $this->y = $y + $style["padding"] + $barh;
8956 $this->Cell(($arrcode["maxw"] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style["stretchtext"]);
8958 // restore original direction
8959 $this->rtl = $tempRTL;
8960 // restore previous font
8961 if ($style["text"] AND isset($style["font"])) {
8962 $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
8965 $this->DrawColor = $prevDrawColor;
8966 $this->TextColor = $prevTextColor;
8967 // set bottomcoordinates
8968 $this->img_rb_y = $y + $h;
8970 // set left side coordinate
8971 $this->img_rb_x = ($this->w - $x - $w);
8973 // set right side coordinate
8974 $this->img_rb_x = $x + $w;
8976 // set pointer to align the successive text/objects
8980 $this->x = $this->img_rb_x;
8984 $this->y = $y + round($h/2);
8985 $this->x = $this->img_rb_x;
8989 $this->y = $this->img_rb_y;
8990 $this->x = $this->img_rb_x;
8994 $this->SetY($this->img_rb_y);
9004 * This function is DEPRECATED, please use the new write1DBarcode() function.
9005 * @param int $x x position in user units
9006 * @param int $y y position in user units
9007 * @param int $w width in user units
9008 * @param int $h height position in user units
9009 * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
9010 * @param string $style barcode style
9011 * @param string $font font for text
9012 * @param int $xres x resolution
9013 * @param string $code code to print
9014 * @deprecated deprecated since version 3.1.000 (2008-06-10)
9015 * @see write1DBarcode()
9017 function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
9018 // convert old settings for the new write1DBarcode() function.
9024 "fgcolor" => array(0,0,0),
9032 $newstyle["border"] = true;
9035 $newstyle["bgcolor"] = false;
9038 $newstyle["position"] = "C";
9039 } elseif ($style & 8) {
9040 $newstyle["position"] = "L";
9041 } elseif ($style & 16) {
9042 $newstyle["position"] = "R";
9045 $newstyle["text"] = true;
9048 $newstyle["stretchtext"] = 4;
9050 $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
9054 * Returns an array containing current margins:
9056 <li>$ret['left'] = left margin</li>
9057 <li>$ret['right'] = right margin</li>
9058 <li>$ret['top'] = top margin</li>
9059 <li>$ret['bottom'] = bottom margin</li>
9060 <li>$ret['header'] = header margin</li>
9061 <li>$ret['footer'] = footer margin</li>
9062 <li>$ret['cell'] = cell margin</li>
9064 * @return array containing all margins measures
9065 * @since 3.2.000 (2008-06-23)
9067 function getMargins() {
9069 'left' => $this->lMargin,
9070 'right' => $this->rMargin,
9071 'top' => $this->tMargin,
9072 'bottom' => $this->bMargin,
9073 'header' => $this->header_margin,
9074 'footer' => $this->footer_margin,
9075 'cell' => $this->cMargin,
9081 * Returns an array containing original margins:
9083 <li>$ret['left'] = left margin</li>
9084 <li>$ret['right'] = right margin</li>
9086 * @return array containing all margins measures
9087 * @since 4.0.012 (2008-07-24)
9089 function getOriginalMargins() {
9091 'left' => $this->original_lMargin,
9092 'right' => $this->original_rMargin
9098 * Returns the current font size.
9099 * @return current font size
9100 * @since 3.2.000 (2008-06-23)
9102 function getFontSize() {
9103 return $this->FontSize;
9107 * Returns the current font size in points unit.
9108 * @return current font size in points unit
9109 * @since 3.2.000 (2008-06-23)
9111 function getFontSizePt() {
9112 return $this->FontSizePt;
9116 * Prints a cell (rectangular area) with optional borders, background color and html text string.
9117 * 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 />
9118 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
9119 * @param float $w Cell width. If 0, the cell extends up to the right margin.
9120 * @param float $h Cell minimum height. The cell extends automatically if needed.
9121 * @param float $x upper-left corner X coordinate
9122 * @param float $y upper-left corner Y coordinate
9123 * @param string $html html text to print. Default value: empty string.
9124 * @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>
9125 * @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>
9126 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
9127 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
9128 * @param boolean $reseth if true reset the last cell height (default true).
9129 * @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>
9131 * @see Multicell(), writeHTML()
9133 function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='') {
9134 return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true);
9138 * Returns the HTML DOM array.
9139 * <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>
9140 * @param string $html html code
9142 * @since 3.2.000 (2008-06-20)
9144 function getHtmlDomArray($html) {
9145 // remove all unsupported tags (the line below lists all supported tags)
9146 $html = strip_tags($html, "<a><b><blockquote><br><br/><dd><del><div><dl><dt><em><font><h1><h2><h3><h4><h5><h6><hr><i><img><li><ol><p><small><span><strong><sub><sup><table><td><th><tr><u><ul>");
9147 //replace carriage returns, newlines and tabs
9148 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ", "\\" => "\\\\");
9149 $html = strtr($html, $repTable);
9150 // remove extra spaces from tables
9151 $html = preg_replace('/[\s]*<\/table>[\s]*/', '</table>', $html);
9152 $html = preg_replace('/[\s]*<\/tr>[\s]*/', '</tr>', $html);
9153 $html = preg_replace('/[\s]*<tr/', '<tr', $html);
9154 $html = preg_replace('/[\s]*<\/th>[\s]*/', '</th>', $html);
9155 $html = preg_replace('/[\s]*<th/', '<th', $html);
9156 $html = preg_replace('/[\s]*<\/td>[\s]*/', '</td>', $html);
9157 $html = preg_replace('/[\s]*<td/', '<td', $html);
9158 $html = preg_replace('/<\/th>/', '<span></span></th>', $html);
9159 $html = preg_replace('/<\/td>/', '<span></span></td>', $html);
9160 // pattern for generic tag
9161 $tagpattern = '/(<[^>]+>)/Uu';
9162 // explodes the string
9163 $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
9167 // create an array of elements
9169 $dom[$key] = array();
9170 // set first void element
9171 $dom[$key]['tag'] = false;
9172 $dom[$key]['value'] = "";
9173 $dom[$key]['parent'] = 0;
9174 $dom[$key]['fontname'] = $this->FontFamily;
9175 $dom[$key]['fontstyle'] = $this->FontStyle;
9176 $dom[$key]['fontsize'] = $this->FontSizePt;
9177 $dom[$key]['bgcolor'] = false;
9178 $dom[$key]['fgcolor'] = $this->fgcolor;
9179 $dom[$key]['align'] = '';
9182 array_push($level, 0); // root
9183 while ($key <= $maxel) {
9185 $dom[$key] = array();
9187 $element = $a[($key-1)];
9188 if (preg_match($tagpattern, $element)) {
9190 $dom[$key]['tag'] = true;
9191 $element = substr($element, 1, -1);
9193 preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
9194 $dom[$key]['value'] = strtolower($tag[1]);
9195 if ($element{0} == '/') {
9197 $dom[$key]['opening'] = false;
9198 $dom[$key]['parent'] = end($level);
9200 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
9201 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
9202 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
9203 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
9204 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
9205 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
9206 // set the number of columns in table tag
9207 if (($dom[$key]['value'] == "tr") AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
9208 $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
9210 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9211 $dom[($dom[$key]['parent'])]['content'] = "";
9212 for ($i = ($dom[$key]['parent'] + 1); $i < $key; $i++) {
9213 $dom[($dom[$key]['parent'])]['content'] .= $a[($i-1)];
9219 $dom[$key]['opening'] = true;
9220 $dom[$key]['parent'] = end($level);
9221 if (substr($element, -1, 1) != '/') {
9222 // not self-closing tag
9223 array_push($level, $key);
9224 $dom[$key]['self'] = false;
9226 $dom[$key]['self'] = true;
9228 // copy some values from parent
9230 $dom[$key]['fontname'] = $dom[($dom[$key]['parent'])]['fontname'];
9231 $dom[$key]['fontstyle'] = $dom[($dom[$key]['parent'])]['fontstyle'];
9232 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'];
9233 $dom[$key]['bgcolor'] = $dom[($dom[$key]['parent'])]['bgcolor'];
9234 $dom[$key]['fgcolor'] = $dom[($dom[$key]['parent'])]['fgcolor'];
9235 $dom[$key]['align'] = $dom[($dom[$key]['parent'])]['align'];
9238 preg_match_all('/([^=\s]*)=["\']?([^"\']*)["\']?/', $element, $attr_array, PREG_PATTERN_ORDER);
9239 $dom[$key]['attribute'] = array(); // reset attribute array
9240 while (list($id, $name) = each($attr_array[1])) {
9241 $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
9243 // split style attributes
9244 if (isset($dom[$key]['attribute']['style'])) {
9245 // get style attributes
9246 preg_match_all('/([^:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
9247 $dom[$key]['style'] = array(); // reset style attribute array
9248 while (list($id, $name) = each($style_array[1])) {
9249 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
9251 // --- get some style attributes ---
9252 if (isset($dom[$key]['style']['font-family'])) {
9254 if (isset($dom[$key]['style']['font-family'])) {
9255 $fontslist = split(",", strtolower($dom[$key]['style']['font-family']));
9256 foreach($fontslist as $font) {
9257 $font = trim(strtolower($font));
9258 if (in_array($font, $this->fontlist)){
9259 $dom[$key]['fontname'] = $font;
9266 if (isset($dom[$key]['style']['font-size'])) {
9267 $fsize = trim($dom[$key]['style']['font-size']);
9270 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
9274 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
9278 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
9282 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
9286 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
9290 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
9294 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
9298 $dom[$key]['fontsize'] = intval($fsize);
9303 $dom[$key]['fontstyle'] = "";
9304 if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == "b")) {
9305 $dom[$key]['fontstyle'] .= "B";
9307 if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == "i")) {
9308 $dom[$key]['fontstyle'] .= "I";
9311 if (isset($dom[$key]['style']['color']) AND (!empty($dom[$key]['style']['color']))) {
9312 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
9315 if (isset($dom[$key]['style']['background-color']) AND (!empty($dom[$key]['style']['background-color']))) {
9316 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
9319 if (isset($dom[$key]['style']['text-decoration'])) {
9320 $decors = explode(" ", strtolower($dom[$key]['style']['text-decoration']));
9321 foreach ($decors as $dec) {
9323 if ($dec{0} == "u") {
9324 $dom[$key]['fontstyle'] .= "U";
9325 } elseif ($dec{0} == "l") {
9326 $dom[$key]['fontstyle'] .= "D";
9330 // check for width attribute
9331 if (isset($dom[$key]['style']['width'])) {
9332 $dom[$key]['width'] = intval($dom[$key]['style']['width']);
9334 // check for height attribute
9335 if (isset($dom[$key]['style']['height'])) {
9336 $dom[$key]['height'] = intval($dom[$key]['style']['height']);
9338 // check for text alignment
9339 if (isset($dom[$key]['style']['text-align'])) {
9340 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
9343 // check for font tag
9344 if ($dom[$key]['value'] == "font") {
9346 if (isset($dom[$key]['attribute']['face'])) {
9347 $fontslist = split(",", strtolower($dom[$key]['attribute']['face']));
9348 foreach($fontslist as $font) {
9349 $font = trim(strtolower($font));
9350 if (in_array($font, $this->fontlist)){
9351 $dom[$key]['fontname'] = $font;
9357 if (isset($dom[$key]['attribute']['size'])) {
9359 if ($dom[$key]['attribute']['size']{0} == "+") {
9360 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
9361 } elseif ($dom[$key]['attribute']['size']{0} == "-") {
9362 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
9364 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9367 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9371 if (($dom[$key]['value'] == "ul") OR ($dom[$key]['value'] == "ol") OR ($dom[$key]['value'] == "dl")) {
9372 // force natural alignment for lists
9374 $dom[$key]['align'] = "R";
9376 $dom[$key]['align'] = "L";
9379 if (($dom[$key]['value'] == "small") OR ($dom[$key]['value'] == "sup") OR ($dom[$key]['value'] == "sub")) {
9380 $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
9382 if (($dom[$key]['value'] == "strong") OR ($dom[$key]['value'] == "b")) {
9383 $dom[$key]['fontstyle'] .= "B";
9385 if (($dom[$key]['value'] == "em") OR ($dom[$key]['value'] == "i")) {
9386 $dom[$key]['fontstyle'] .= "I";
9388 if (($dom[$key]['value']{0} == "h") AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
9389 $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
9390 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
9391 $dom[$key]['fontstyle'] .= "B";
9393 if (($dom[$key]['value'] == "table")) {
9394 $dom[$key]['rows'] = 0; // number of rows
9395 $dom[$key]['trids'] = array(); // IDs of TR elements
9397 if (($dom[$key]['value'] == "tr")) {
9398 $dom[$key]['cols'] = 0;
9399 // store the number of rows on table element
9400 $dom[($dom[$key]['parent'])]['rows']++;
9401 // store the TR elements IDs on table element
9402 array_push($dom[($dom[$key]['parent'])]['trids'], $key);
9404 if (($dom[$key]['value'] == "th") OR ($dom[$key]['value'] == "td")) {
9405 if (isset($dom[$key]['attribute']['colspan'])) {
9406 $colspan = intval($dom[$key]['attribute']['colspan']);
9410 $dom[$key]['attribute']['colspan'] = $colspan;
9411 $dom[($dom[$key]['parent'])]['cols'] += $colspan;
9413 // set foreground color attribute
9414 if (isset($dom[$key]['attribute']['color']) AND (!empty($dom[$key]['attribute']['color']))) {
9415 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
9417 // set background color attribute
9418 if (isset($dom[$key]['attribute']['bgcolor']) AND (!empty($dom[$key]['attribute']['bgcolor']))) {
9419 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
9421 // check for width attribute
9422 if (isset($dom[$key]['attribute']['width'])) {
9423 $dom[$key]['width'] = intval($dom[$key]['attribute']['width']);
9425 // check for height attribute
9426 if (isset($dom[$key]['attribute']['height'])) {
9427 $dom[$key]['height'] = intval($dom[$key]['attribute']['height']);
9429 // check for text alignment
9430 if (isset($dom[$key]['attribute']['align']) AND (!empty($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
9431 $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
9433 } // end opening tag
9436 $dom[$key]['tag'] = false;
9437 $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
9438 $dom[$key]['parent'] = end($level);
9439 // calculate text width
9440 //$dom[$key]['width'] = $this->GetStringWidth($dom[$key]['value'], $dom[($dom[$key]['parent'])]['fontname'], $dom[($dom[$key]['parent'])]['fontstyle'], $dom[($dom[$key]['parent'])]['fontsize']);
9448 * Allows to preserve some HTML formatting (limited support).<br />
9449 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
9450 * 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, small, span, strong, sub, sup, table, td, th, tr, u, ul,
9451 * @param string $html text to display
9452 * @param boolean $ln if true add a new line after text (default = true)
9453 * @param int $fill Indicates if the background must be painted (true) or transparent (false).
9454 * @param boolean $reseth if true reset the last cell height (default false).
9455 * @param boolean $cell if true add the default cMargin space to each Write (default false).
9456 * @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>
9458 function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
9459 // store current values
9460 $prevlMargin = $this->lMargin;
9461 $prevrMargin = $this->rMargin;
9462 $prevcMargin = $this->cMargin;
9463 $prevFontFamily = $this->FontFamily;
9464 $prevFontStyle = $this->FontStyle;
9465 $prevFontSizePt = $this->FontSizePt;
9466 $curfontname = $prevFontFamily;
9467 $curfontstyle = $prevFontStyle;
9468 $curfontsize = $prevFontSizePt;
9469 $prevbgcolor = $this->bgcolor;
9470 $prevfgcolor = $this->fgcolor;
9471 $this->newline = true;
9472 $minstartliney = $this->y;
9474 $startlinepage = $this->page;
9476 if (isset($this->footerlen[$this->page])) {
9477 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9479 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9481 $startlinepos = $this->footerpos[$this->page];
9485 $w = $this->x - $this->lMargin;
9487 $w = $this->w - $this->rMargin - $this->x;
9489 $w -= (2 * $this->cMargin);
9492 $this->x -= $this->cMargin;
9494 $this->x += $this->cMargin;
9497 $this->listindent = $this->GetStringWidth("0000");
9499 if ((empty($this->lasth))OR ($reseth)) {
9501 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9503 $dom = $this->getHtmlDomArray($html);
9504 $maxel = count($dom);
9506 while ($key < $maxel) {
9507 if ($dom[$key]['tag'] OR ($key == 0)) {
9508 if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
9509 $dom[$key]['align'] = ($this->rtl)?'R':'L';
9511 // vertically align image in line
9512 if ((!$this->newline) AND ($dom[$key]['value'] == 'img')
9513 AND (isset($dom[$key]['attribute']['height']))
9514 AND ($dom[$key]['attribute']['height'] > 0)
9516 $this->y += (($curfontsize / $this->k) - $this->pixelsToUnits($dom[$key]['attribute']['height']));
9517 $minstartliney = min($this->y, $minstartliney);
9518 } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
9519 // account for different font size
9520 $pfontname = $curfontname;
9521 $pfontstyle = $curfontstyle;
9522 $pfontsize = $curfontsize;
9523 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
9524 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
9525 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
9526 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
9527 $this->SetFont($fontname, $fontstyle, $fontsize);
9528 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9529 if (is_numeric($fontsize) AND ($fontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($fontsize != $curfontsize) AND (!$this->newline)) {
9530 $this->y += (($curfontsize - $fontsize) / $this->k);
9531 $minstartliney = min($this->y, $minstartliney);
9533 $curfontname = $fontname;
9534 $curfontstyle = $fontstyle;
9535 $curfontsize = $fontsize;
9538 if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
9539 $this->SetFillColorArray($dom[$key]['bgcolor']);
9542 $wfill = $fill | false;
9544 if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
9545 $this->SetTextColorArray($dom[$key]['fgcolor']);
9547 if (isset($dom[$key]['align'])) {
9548 $lalign = $dom[$key]['align'];
9550 if (empty($lalign)) {
9555 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
9557 // we are at the beginning of a new line
9558 if (isset($startlinex)) {
9559 $yshift = $minstartliney - $startliney;
9563 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9564 // the last line must be shifted to be aligned as requested
9565 $linew = abs($this->endlinex - $startlinex);
9566 $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9567 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9568 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9569 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9570 } elseif (isset($opentagpos)) {
9571 $midpos = $opentagpos;
9572 } elseif (isset($this->footerlen[$startlinepage])) {
9573 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9574 $midpos = $this->footerpos[$startlinepage];
9579 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9580 $pend = substr($this->pages[$startlinepage], $midpos);
9582 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9585 // calculate shifting amount
9586 $mdiff = abs($w - $linew);
9587 if ($plalign == "C") {
9589 $t_x = -($mdiff / 2);
9591 $t_x = ($mdiff / 2);
9593 } elseif (($plalign == "R") AND (!$this->rtl)) {
9594 // right alignment on LTR document
9596 } elseif (($plalign == "L") AND ($this->rtl)) {
9597 // left alignment on RTL document
9602 if (($t_x != 0) OR ($yshift < 0)) {
9604 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9605 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9606 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9607 // shift the annotations and links
9608 if (isset($this->PageAnnots[$this->page])) {
9609 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9610 if ($pac['y'] >= $minstartliney) {
9611 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9612 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9616 $this->y -= $yshift;
9620 $this->checkPageBreak($this->lasth);
9621 $this->SetFont($fontname, $fontstyle, $fontsize);
9623 $this->SetFillColorArray($this->bgcolor);
9625 $startlinex = $this->x;
9626 $startliney = $this->y;
9627 $minstartliney = $this->y;
9628 $startlinepage = $this->page;
9629 if (isset($endlinepos)) {
9630 $startlinepos = $endlinepos;
9633 if (isset($this->footerlen[$this->page])) {
9634 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9636 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9638 $startlinepos = $this->footerpos[$this->page];
9641 $this->newline = false;
9643 if (isset($opentagpos)) {
9646 if ($dom[$key]['tag']) {
9647 if ($dom[$key]['opening']) {
9648 // table content is handled in a special way
9649 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9650 $trid = $dom[$key]['parent'];
9651 $table_el = $dom[$trid]['parent'];
9652 if (!isset($dom[$table_el]['cols'])) {
9653 $dom[$table_el]['cols'] = $trid['cols'];
9655 // calculate cell width
9656 if (isset($dom[($dom[$key]['parent'])]['width'])) {
9657 $table_width = $this->pixelsToUnits($dom[($dom[$key]['parent'])]['width']);
9661 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
9662 $currentcmargin = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding']);
9664 $currentcmargin = 0;
9666 $this->cMargin = $currentcmargin;
9667 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
9668 $cellspacing = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing']);
9673 $cellspacingx = -$cellspacing;
9675 $cellspacingx = $cellspacing;
9677 $colspan = $dom[$key]['attribute']['colspan'];
9678 if (isset($dom[$key]['width'])) {
9679 $cellw = $this->pixelsToUnits($dom[$key]['width']);
9681 $cellw = ($colspan * ($table_width / $dom[$table_el]['cols']));
9683 $cellw -= $cellspacing;
9684 if (isset($dom[$key]['content'])) {
9685 $cell_content = $dom[$key]['content'];
9687 $cell_content = " ";
9689 $tagtype = $dom[$key]['value'];
9691 while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
9692 // move $key index forward
9695 if (!isset($dom[$trid]['startpage'])) {
9696 $dom[$trid]['startpage'] = $this->page;
9698 $this->setPage($dom[$trid]['startpage']);
9700 if (!isset($dom[$trid]['starty'])) {
9701 $dom[$trid]['starty'] = $this->y;
9703 $this->y = $dom[$trid]['starty'];
9705 if (!isset($dom[$trid]['startx'])) {
9706 $dom[$trid]['startx'] = $this->x;
9708 $this->x += ($cellspacingx / 2);
9709 if (isset($dom[$parentid]['attribute']['rowspan'])) {
9710 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
9714 // skip row-spanned cells started on the previous rows
9715 if (isset($dom[$table_el]['rowspans'])) {
9716 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9717 if (($trwsp['startx'] == $this->x) AND (($trwsp['starty'] < $this->y) OR ($trwsp['startpage'] < $this->page)) AND ($trwsp['rowspan'] > 0)) {
9718 $this->x = $trwsp['endx'] + $cellspacingx;
9722 // add rowspan information to table element
9724 if (isset($this->footerlen[$this->page])) {
9725 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9727 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9729 $trintmrkpos = $this->footerpos[$this->page];
9730 $trsid = array_push($dom[$table_el]['rowspans'], array('rowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startx' => $this->x, 'starty' => $this->y, 'intmrkpos' => $trintmrkpos));
9732 $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
9734 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
9736 // push background colors
9737 if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
9738 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
9741 // write the cell content
9742 $this->MultiCell($cellw, 0, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
9744 $this->cMargin = $currentcmargin;
9745 $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
9747 // update the end of row position
9748 if ($rowspan <= 1) {
9749 if (isset($dom[$trid]['endy'])) {
9750 if ($this->page == $dom[$trid]['endpage']) {
9751 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
9752 } elseif ($this->page > $dom[$trid]['endpage']) {
9753 $dom[$trid]['endy'] = $this->y;
9756 $dom[$trid]['endy'] = $this->y;
9758 if (isset($dom[$trid]['endpage'])) {
9759 $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
9761 $dom[$trid]['endpage'] = $this->page;
9764 // account for row-spanned cells
9765 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
9766 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
9767 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
9769 if (isset($dom[$table_el]['rowspans'])) {
9770 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9771 if ($trwsp['rowspan'] > 0) {
9772 if (isset($dom[$trid]['endpage'])) {
9773 if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
9774 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
9775 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[$trid]['endpage']) {
9776 $dom[$table_el]['rowspans'][$k]['endy'] = $trwsp['endy'];
9778 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
9779 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
9785 $this->x += ($cellspacingx / 2);
9787 // opening tag (or self-closing tag)
9788 if (!isset($opentagpos)) {
9789 if (isset($this->footerlen[$this->page])) {
9790 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9792 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9794 $opentagpos = $this->footerpos[$this->page];
9796 $this->openHTMLTagHandler($dom, $key, $cell);
9800 $this->closeHTMLTagHandler($dom, $key, $cell);
9802 } elseif (strlen($dom[$key]['value']) > 0) {
9804 if (!empty($this->lispacer)) {
9805 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
9806 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9807 $minstartliney = $this->y;
9809 $lspace = $this->GetStringWidth($this->lispacer." ");
9811 $this->x += $lspace;
9813 $this->x -= $lspace;
9815 $this->Write($this->lasth, $this->lispacer, '', false, '', false, 0, false);
9817 $this->lispacer = "";
9818 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
9819 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9820 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
9821 $this->y += (($pfontsize - $curfontsize) / $this->k);
9822 $minstartliney = min($this->y, $minstartliney);
9826 $this->htmlvspace = 0;
9828 if ($this->rtl OR $this->tmprtl) {
9829 $dom[$key]['value'] = rtrim($dom[$key]['value']);
9831 $dom[$key]['value'] = ltrim($dom[$key]['value']);
9837 $strrest = $this->addHtmlLink($this->HREF, $dom[$key]['value'], $wfill, true);
9839 $ctmpmargin = $this->cMargin;
9841 // write only until the end of the line and get the rest
9842 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, "", false, 0, true);
9843 $this->cMargin = $ctmpmargin;
9845 if (strlen($strrest) > 0) {
9846 // store the remaining string on the previous $key position
9847 $this->newline = true;
9850 $this->x -= $this->cMargin;
9852 $this->x += $this->cMargin;
9855 $dom[$key]['value'] = ltrim($strrest);
9860 } // end for each $key
9861 // align the last line
9862 if (isset($startlinex)) {
9863 $yshift = $minstartliney - $startliney;
9867 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9868 // the last line must be shifted to be aligned as requested
9869 $linew = abs($this->endlinex - $startlinex);
9870 $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9871 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9872 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9873 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9874 } elseif (isset($opentagpos)) {
9875 $midpos = $opentagpos;
9876 } elseif (isset($this->footerlen[$startlinepage])) {
9877 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9878 $midpos = $this->footerpos[$startlinepage];
9883 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9884 $pend = substr($this->pages[$startlinepage], $midpos);
9886 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9889 // calculate shifting amount
9890 $mdiff = abs($w - $linew);
9891 if ($plalign == "C") {
9893 $t_x = -($mdiff / 2);
9895 $t_x = ($mdiff / 2);
9897 } elseif (($plalign == "R") AND (!$this->rtl)) {
9898 // right alignment on LTR document
9900 } elseif (($plalign == "L") AND ($this->rtl)) {
9901 // left alignment on RTL document
9906 if (($t_x != 0) OR ($yshift < 0)) {
9908 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9909 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9910 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9911 // shift the annotations and links
9912 if (isset($this->PageAnnots[$this->page])) {
9913 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9914 if ($pac['y'] >= $minstartliney) {
9915 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9916 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9920 $this->y -= $yshift;
9924 if ($ln AND (!($cell AND ($dom[$key-1]['value'] == "table")))) {
9925 $this->Ln($this->lasth);
9927 // restore previous values
9928 $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
9929 $this->SetFillColorArray($prevbgcolor);
9930 $this->SetTextColorArray($prevfgcolor);
9931 $this->lMargin = $prevlMargin;
9932 $this->rMargin = $prevrMargin;
9933 $this->cMargin = $prevcMargin;
9938 * Process opening tags.
9939 * @param array $dom html dom array
9940 * @param int $key current element id
9941 * @param boolean $cell if true add the default cMargin space to each new line (default false).
9944 function openHTMLTagHandler(&$dom, $key, $cell=false) {
9946 $parent = $dom[($dom[$key]['parent'])];
9947 // check for text direction attribute
9948 if (isset($tag['attribute']['dir'])) {
9949 $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
9951 $this->tmprtl = false;
9954 switch($tag['value']) {
9956 $dom[$key]['rowspans'] = array();
9957 if (isset($tag['attribute']['cellpadding'])) {
9958 $this->oldcMargin = $this->cMargin;
9959 $this->cMargin = $this->pixelsToUnits($tag['attribute']['cellpadding']);
9964 // array of columns positions
9965 $dom[$key]['cellpos'] = array();
9973 $this->addHTMLVertSpace(1, $cell);
9974 $this->htmlvspace = 0;
9975 if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
9976 $hrWidth = $this->pixelsToUnits($tag['attribute']['width']);
9978 $hrWidth = $this->w - $this->lMargin - $this->rMargin;
9982 $prevlinewidth = $this->GetLineWidth();
9983 $this->Line($x, $y, $x + $hrWidth, $y);
9984 $this->SetLineWidth($prevlinewidth);
9985 $this->addHTMLVertSpace(1, $cell);
9989 $this->setStyle('b', true);
9993 $this->setStyle('i', true);
9997 $this->setStyle('u', true);
10001 $this->setStyle('d', true);
10005 if (array_key_exists('href', $tag['attribute'])) {
10006 $this->HREF = $tag['attribute']['href'];
10011 if (isset($tag['attribute']['src'])) {
10012 // replace relative path with real server path
10013 if ($tag['attribute']['src'][0] == '/') {
10014 $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
10016 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
10017 if (!isset($tag['attribute']['width'])) {
10018 $tag['attribute']['width'] = 0;
10020 if (!isset($tag['attribute']['height'])) {
10021 $tag['attribute']['height'] = 0;
10023 //if (!isset($tag['attribute']['align'])) {
10024 // the only alignment supported is "bottom"
10025 // further development is required for other modes.
10026 $tag['attribute']['align'] = 'bottom';
10028 switch($tag['attribute']['align']) {
10046 $fileinfo = pathinfo($tag['attribute']['src']);
10047 if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
10048 $type = strtolower($fileinfo['extension']);
10051 if (($type == "eps") OR ($type == "ai")) {
10052 $this->ImageEps($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', true, $align);
10054 $this->Image($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', '', $align);
10062 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
10066 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
10078 $this->addHTMLVertSpace(1, $cell);
10083 $this->rMargin += $this->listindent;
10085 $this->lMargin += $this->listindent;
10087 $this->addHTMLVertSpace(1, $cell);
10093 if ($tag['value'] == "ol") {
10094 $this->listordered[$this->listnum] = true;
10096 $this->listordered[$this->listnum] = false;
10098 $this->listcount[$this->listnum] = 0;
10100 $this->rMargin += $this->listindent;
10102 $this->lMargin += $this->listindent;
10107 $this->Ln('', $cell);
10108 if ($tag['value'] == 'li') {
10109 if ($this->listordered[$this->listnum]) {
10110 if (isset($tag['attribute']['value'])) {
10111 $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
10113 $this->listcount[$this->listnum]++;
10115 $this->lispacer = ".".($this->listcount[$this->listnum]);
10117 $this->lispacer = ($this->listcount[$this->listnum]).".";
10120 //unordered list symbol
10121 $this->lispacer = "-";
10124 $this->lispacer = "";
10128 case 'blockquote': {
10130 $this->rMargin += $this->listindent;
10132 $this->lMargin += $this->listindent;
10134 $this->addHTMLVertSpace(2, $cell);
10138 $this->Ln('', $cell);
10142 $this->addHTMLVertSpace(2, $cell);
10146 $this->addHTMLVertSpace(2, $cell);
10150 $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
10154 $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
10163 $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k);
10173 * Process closing tags.
10174 * @param array $dom html dom array
10175 * @param int $key current element id
10176 * @param boolean $cell if true add the default cMargin space to each new line (default false).
10177 * @access protected
10179 function closeHTMLTagHandler(&$dom, $key, $cell=false) {
10181 $parent = $dom[($dom[$key]['parent'])];
10183 switch($tag['value']) {
10189 $table_el = $dom[($dom[$key]['parent'])]['parent'];
10190 // update row-spanned cells
10191 if (isset($dom[$table_el]['rowspans'])) {
10192 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
10193 $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
10194 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
10195 if ($dom[$table_el]['rowspans'][$k]['endpage'] == $dom[($dom[$key]['parent'])]['endpage']) {
10196 $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
10197 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[($dom[$key]['parent'])]['endpage']) {
10198 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
10199 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
10204 $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
10205 $this->y = $dom[($dom[$key]['parent'])]['endy'];
10206 if (isset($dom[$table_el]['attribute']['cellspacing'])) {
10207 $cellspacing = $this->pixelsToUnits($dom[$table_el]['attribute']['cellspacing']);
10208 $this->y += $cellspacing;
10210 $this->Ln(0, $cell);
10211 $this->x = $dom[($dom[$key]['parent'])]['startx'];
10216 $table_el = $parent;
10217 if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
10218 OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
10224 foreach ($table_el['trids'] as $j => $trkey) {
10225 $parent = $dom[$trkey];
10226 $restspace = $this->getPageHeight() - $this->y - $this->getBreakMargin();
10227 // for each cell on the row
10228 foreach ($parent['cellpos'] as $k => $cellpos) {
10229 if (isset($cellpos['rowspanid'])) {
10230 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
10231 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
10232 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
10233 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
10234 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
10236 $endy = $parent['endy'];
10237 $startpage = $parent['startpage'];
10238 $endpage = $parent['endpage'];
10240 $this->setPage($startpage);
10241 $this->y = $parent['starty'];
10242 if ($endpage > $startpage) {
10243 // design borders around HTML cells.
10244 for ($page=$startpage; $page <= $endpage; $page++) {
10245 $this->setPage($page);
10246 if ($page == $startpage) {
10247 $this->y = $this->getPageHeight() - $restspace - $this->getBreakMargin();
10249 } elseif ($page == $endpage) {
10250 $this->y = $this->tMargin; // put cursor at the beginning of text
10251 $ch = $endy - $this->tMargin;
10253 $this->y = $this->tMargin; // put cursor at the beginning of text
10254 $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
10257 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10258 $this->SetFillColorArray($cellpos['bgcolor']);
10263 $cw = abs($cellpos['endx'] - $cellpos['startx']);
10264 $this->x = $cellpos['startx'];
10265 // design a cell around the text
10266 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10267 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10268 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10269 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10270 $this->intmrk[$this->page] += strlen($ccode."\n");
10273 $ch = $endy - $parent['starty'];
10274 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10275 $this->SetFillColorArray($cellpos['bgcolor']);
10280 $cw = abs($cellpos['endx'] - $cellpos['startx']);
10281 $this->x = $cellpos['startx'];
10282 $this->y = $parent['starty'];
10283 // design a cell around the text
10284 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10285 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10286 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10287 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10288 $this->intmrk[$this->page] += strlen($ccode."\n");
10291 if (isset($table_el['attribute']['cellspacing'])) {
10292 $cellspacing = $this->pixelsToUnits($table_el['attribute']['cellspacing']);
10293 $this->y += $cellspacing;
10295 $this->Ln(0, $cell);
10296 $this->x = $parent['startx'];
10298 if (isset($parent['cellpadding'])) {
10299 $this->cMargin = $this->oldcMargin;
10302 $this->lasth = $this->FontSize * $this->cell_height_ratio;
10306 $this->setStyle('b', false);
10310 $this->setStyle('i', false);
10314 $this->setStyle('u', false);
10318 $this->setStyle('d', false);
10326 $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
10330 $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
10334 $this->addHTMLVertSpace(1, $cell);
10337 case 'blockquote': {
10339 $this->rMargin -= $this->listindent;
10341 $this->lMargin -= $this->listindent;
10343 $this->addHTMLVertSpace(2, $cell);
10347 $this->addHTMLVertSpace(2, $cell);
10352 if ($this->listnum <= 0) {
10353 $this->listnum = 0;
10354 $this->addHTMLVertSpace(2, $cell);
10359 $this->lispacer = "";
10363 $this->lispacer = "";
10365 $this->rMargin -= $this->listindent;
10367 $this->lMargin -= $this->listindent;
10374 $this->lispacer = "";
10376 $this->rMargin -= $this->listindent;
10378 $this->lMargin -= $this->listindent;
10380 if ($this->listnum <= 0) {
10381 $this->listnum = 0;
10382 $this->addHTMLVertSpace(2, $cell);
10384 $this->lasth = $this->FontSize * $this->cell_height_ratio;
10388 $this->lispacer = "";
10397 $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k);
10404 $this->tmprtl = false;
10408 * Add vertical spaces if needed.
10409 * @param int $n number of spaces to add
10410 * @param boolean $cell if true add the default cMargin space to each new line (default false).
10411 * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
10412 * @access protected
10414 function addHTMLVertSpace($n, $cell=false, $h='') {
10415 if (is_string($h)) {
10416 $vsize = $n * $this->lasth;
10420 if ($vsize > $this->htmlvspace) {
10421 $this->Ln(($vsize - $this->htmlvspace), $cell);
10422 $this->htmlvspace = $vsize;
10426 } // END OF TCPDF CLASS
10428 //============================================================+
10430 //============================================================+