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 * 4. Header function renamed to Header1 (due to conflict with FrontReport Header)
145 * -------------------------------------------------------------------------------
147 if (!defined("K_PATH_FONTS"))
148 define ("K_PATH_FONTS", '../reporting/fonts/');
149 define ("K_PATH_CACHE", '../reporting/fonts/');
150 define("K_CELL_HEIGHT_RATIO", 1.25);
152 //require_once(dirname(__FILE__).'/config/tcpdf_config.php');
154 // includes some support files
159 // only included if unicode
160 //include_once(dirname(__FILE__)."/unicode_data2.php");
165 require_once(dirname(__FILE__).'/htmlcolors.php');
170 require_once(dirname(__FILE__)."/barcodes.php");
173 * HTML entity decode functions
175 require_once(dirname(__FILE__)."/html_entity_decode_php4.php");
177 if (!class_exists('TCPDF')) {
179 * define default PDF document producer
181 define('PDF_PRODUCER','TCPDF 4.0.027_PHP4 (http://www.tcpdf.org)');
184 * This is a PHP class for generating PDF documents without requiring external extensions.<br>
185 * 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>
187 * @package com.tecnick.tcpdf
188 * @version 4.0.027_PHP4
189 * @author Nicola Asuni - info@tecnick.com
190 * @link http://www.tcpdf.org
191 * @license http://www.gnu.org/copyleft/lesser.html LGPL
195 // protected or Protected properties
198 * @var current page number
204 * @var current object number
210 * @var array of object offsets
216 * @var buffer holding in-memory PDF
222 * @var array containing pages
225 var $pages = array();
228 * @var current document state
234 * @var compression flag
240 * @var current page orientation (P = Portrait, L = Landscape)
246 * @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>
249 var $pagedim = array();
252 * @var scale factor (number of points in user unit)
258 * @var width of page format in points
264 * @var height of page format in points
270 * @var current width of page in points
276 * @var current height of page in points
282 * @var current width of page in user unit
288 * @var current height of page in user unit
312 * @var page break margin
318 * @var cell internal padding
324 * @var cell internal padding (previous value)
330 * @var current horizontal position in user unit for cell positioning
336 * @var current vertical position in user unit for cell positioning
342 * @var height of last cell printed
348 * @var line width in user unit
354 * @var array of standard font names
360 * @var array of used fonts
363 var $fonts = array();
366 * @var array of font files
369 var $FontFiles = array();
372 * @var array of encoding differences
375 var $diffs = array();
378 * @var array of used images
381 var $images = array();
384 * @var array of Annotations in pages
387 var $PageAnnots = array();
390 * @var array of internal links
393 var $links = array();
396 * @var current font family
402 * @var current font style
408 * @var current font ascent (distance between font top and baseline)
410 * @since 2.8.000 (2007-03-29)
415 * @var current font descent (distance between font bottom and baseline)
417 * @since 2.8.000 (2007-03-29)
422 * @var underlining flag
428 * @var current font info
434 * @var current font size in points
440 * @var current font size in user unit
446 * @var commands for drawing color
452 * @var commands for filling color
458 * @var commands for text color
464 * @var indicates whether fill and text colors are different
476 * @var automatic page breaking
482 * @var threshold used to trigger page breaks
485 var $PageBreakTrigger;
488 * @var flag set when processing footer
494 * @var zoom display mode
500 * @var layout display mode
536 * @var alias for total number of pages
542 * @var right-bottom corner X coordinate of inserted image
544 * @author Nicola Asuni
550 * @var right-bottom corner Y coordinate of inserted image
552 * @author Nicola Asuni
558 * @var image scale factor
560 * @author Nicola Asuni
566 * @var boolean set to true when the input text is unicode (require unicode fonts)
568 * @author Nicola Asuni
571 var $isunicode = false;
578 var $PDFVersion = "1.7";
581 // ----------------------
584 * @var Minimum distance between header and top page margin.
590 * @var Minimum distance between footer and bottom page margin.
596 * @var original left margin value
598 * @since 1.53.0.TC013
600 var $original_lMargin;
603 * @var original right margin value
605 * @since 1.53.0.TC013
607 var $original_rMargin;
622 * @var Language templates.
628 * @var Barcode to print on page footer (only if set).
631 var $barcode = false;
634 * @var If true prints header
637 var $print_header = true;
640 * @var If true prints footer.
643 var $print_footer = true;
646 * @var Header image logo.
649 var $header_logo = "";
652 * @var Header image logo width in mm.
655 var $header_logo_width = 30;
658 * @var String to print as title on document header.
661 var $header_title = "";
664 * @var String to print on document header.
667 var $header_string = "";
670 * @var Default number of columns for html table.
673 var $default_table_columns = 4;
676 // variables for html parser
679 * @var HTML PARSER: store current link.
685 * @var store available fonts list.
688 var $fontlist = array();
691 * @var current foreground color
697 * @var HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
700 var $listordered = array();
703 * @var HTML PARSER: array count list items on nested lists.
706 var $listcount = array();
709 * @var HTML PARSER: current list nesting level.
715 * @var HTML PARSER: indent amount for lists.
721 * @var current background color
727 * @var Store temporary font size in points.
730 var $tempfontsize = 10;
733 * @var Bold font style status.
739 * @var Underlined font style status.
745 * @var Italic font style status.
751 * @var Line through font style status.
753 * @since 2.8.000 (2008-03-19)
758 * @var spacer for LI tags.
764 * @var default encoding
766 * @since 1.53.0.TC010
768 var $encoding = "UTF-8";
771 * @var PHP internal encoding
773 * @since 1.53.0.TC016
775 var $internal_encoding;
778 * @var indicates if the document language is Right-To-Left
785 * @var used to force RTL or LTR string inversion
791 // --- Variables used for document encryption:
794 * Indicates whether document is protected
796 * @since 2.0.000 (2008-01-02)
801 * U entry in pdf document
803 * @since 2.0.000 (2008-01-02)
808 * O entry in pdf document
810 * @since 2.0.000 (2008-01-02)
815 * P entry in pdf document
817 * @since 2.0.000 (2008-01-02)
822 * encryption object id
824 * @since 2.0.000 (2008-01-02)
829 * last RC4 key encrypted (cached for optimisation)
831 * @since 2.0.000 (2008-01-02)
836 * last RC4 computed key
838 * @since 2.0.000 (2008-01-02)
845 * Outlines for bookmark
847 * @since 2.1.002 (2008-02-12)
849 var $outlines = array();
852 * Outline root for bookmark
854 * @since 2.1.002 (2008-02-12)
859 // --- javascript and form ---
864 * @since 2.1.002 (2008-02-12)
866 var $javascript = "";
871 * @since 2.1.002 (2008-02-12)
878 * @since 2.8.000 (2008-03-19)
882 // --- Variables used for User's Rights ---
883 // See PDF reference chapter 8.7 Digital Signatures
886 * If true enables user's rights on PDF reader
888 * @since 2.9.000 (2008-03-26)
893 * Names specifying additional document-wide usage rights for the document.
895 * @since 2.9.000 (2008-03-26)
900 * Names specifying additional annotation-related usage rights for the document.
902 * @since 2.9.000 (2008-03-26)
907 * Names specifying additional form-field-related usage rights for the document.
909 * @since 2.9.000 (2008-03-26)
914 * Names specifying additional signature-related usage rights for the document.
916 * @since 2.9.000 (2008-03-26)
921 * Dot Per Inch Document Resolution (do not change)
923 * @since 3.0.000 (2008-03-27)
928 * Indicates whether a new page group was requested
930 * @since 3.0.000 (2008-03-27)
935 * Contains the number of pages of the groups
937 * @since 3.0.000 (2008-03-27)
942 * Contains the alias of the current page group
944 * @since 3.0.000 (2008-03-27)
949 * Restrict the rendering of some elements to screen or printout.
951 * @since 3.0.000 (2008-03-27)
953 var $visibility="all";
958 * @since 3.0.000 (2008-03-27)
965 * @since 3.0.000 (2008-03-27)
970 * Array of transparency objects and parameters.
972 * @since 3.0.000 (2008-03-27)
977 * Set the default JPEG compression quality (1-100)
979 * @since 3.0.000 (2008-03-27)
984 * Default cell height ratio.
986 * @since 3.0.014 (2008-05-23)
988 var $cell_height_ratio = K_CELL_HEIGHT_RATIO;
991 * PDF viewer preferences.
993 * @since 3.1.000 (2008-06-09)
995 var $viewer_preferences;
998 * A name object specifying how the document should be displayed when opened.
1000 * @since 3.1.000 (2008-06-09)
1005 * Array for storing gradient information.
1007 * @since 3.1.000 (2008-06-09)
1009 var $gradients = array();
1012 * Array used to store positions inside the pages buffer.
1013 * keys are the page numbers
1015 * @since 3.2.000 (2008-06-26)
1017 var $intmrk = array();
1020 * Array used to store footer positions of each page.
1022 * @since 3.2.000 (2008-07-01)
1024 var $footerpos = array();
1028 * Array used to store footer lenght of each page.
1030 * @since 4.0.014 (2008-07-29)
1032 var $footerlen = array();
1035 * True if a newline is created.
1037 * @since 3.2.000 (2008-07-01)
1039 var $newline = true;
1042 * End position of the latest inserted line
1044 * @since 3.2.000 (2008-07-01)
1049 * PDF string for last line width
1051 * @since 4.0.006 (2008-07-16)
1053 var $linestyleWidth = "";
1056 * PDF string for last line width
1058 * @since 4.0.006 (2008-07-16)
1060 var $linestyleCap = "0 J";
1063 * PDF string for last line width
1065 * @since 4.0.006 (2008-07-16)
1067 var $linestyleJoin = "0 j";
1070 * PDF string for last line width
1072 * @since 4.0.006 (2008-07-16)
1074 var $linestyleDash = "[] 0 d";
1077 * True if marked-content sequence is open
1079 * @since 4.0.013 (2008-07-28)
1081 var $openMarkedContent = false;
1084 * Count the latest inserted vertical spaces on HTML.
1086 * @since 4.0.021 (2008-08-24)
1088 var $htmlvspace = 0;
1091 * Array of Spot colors
1093 * @since 4.0.024 (2008-09-12)
1095 var $spot_colors = array();
1097 //------------------------------------------------------------
1099 //------------------------------------------------------------
1102 * This is the class constructor.
1103 * It allows to set up the page format, the orientation and
1104 * the measure unit used in all the methods (except for the font sizes).
1106 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
1107 * @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.
1108 * @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>
1109 * @param boolean $unicode TRUE means that the input text is unicode (default = true)
1110 * @param String $encoding charset encoding; default is UTF-8
1112 function TCPDF($orientation='P', $unit='mm', $format='A4', $uni=true, $encoding="UTF-8") {
1113 if ($uni) // Fix for FrontAccounting
1115 global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
1116 include_once(dirname(__FILE__)."/unicode_data2.php");
1118 /* Set internal character encoding to ASCII */
1119 if (function_exists("mb_internal_encoding") AND mb_internal_encoding()) {
1120 $this->internal_encoding = mb_internal_encoding();
1121 mb_internal_encoding("ASCII");
1123 // set language direction
1124 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
1125 $this->tmprtl = false;
1128 //Initialization of properties
1129 $this->isunicode = $uni;
1131 $this->pagedim = array();
1134 $this->pages = array();
1136 $this->fonts = array();
1137 $this->FontFiles = array();
1138 $this->diffs = array();
1139 $this->images = array();
1140 $this->links = array();
1141 $this->gradients = array();
1142 $this->InFooter = false;
1144 $this->FontFamily = 'helvetica';
1145 $this->FontStyle = '';
1146 $this->FontSizePt = 12;
1147 $this->underline = false;
1148 $this->linethrough = false;
1149 $this->DrawColor = '0 G';
1150 $this->FillColor = '0 g';
1151 $this->TextColor = '0 g';
1152 $this->ColorFlag = false;
1154 // encryption values
1155 $this->encrypted = false;
1156 $this->last_rc4_key = '';
1157 $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";
1158 //Standard Unicode fonts
1159 $this->CoreFonts = array(
1160 'courier'=>'Courier',
1161 'courierB'=>'Courier-Bold',
1162 'courierI'=>'Courier-Oblique',
1163 'courierBI'=>'Courier-BoldOblique',
1164 'helvetica'=>'Helvetica',
1165 'helveticaB'=>'Helvetica-Bold',
1166 'helveticaI'=>'Helvetica-Oblique',
1167 'helveticaBI'=>'Helvetica-BoldOblique',
1168 'times'=>'Times-Roman',
1169 'timesB'=>'Times-Bold',
1170 'timesI'=>'Times-Italic',
1171 'timesBI'=>'Times-BoldItalic',
1173 'zapfdingbats'=>'ZapfDingbats'
1176 $this->setPageUnit($unit);
1177 // set page format and orientation
1178 $this->setPageFormat($format, $orientation);
1179 //Page margins (1 cm)
1180 $margin = 28.35 / $this->k;
1181 $this->SetMargins($margin,$margin);
1182 //Interior cell margin (1 mm)
1183 $this->cMargin = $margin / 10;
1184 //Line width (0.2 mm)
1185 $this->LineWidth = 0.57 / $this->k;
1186 $this->linestyleWidth = sprintf('%.2f w', ($this->LineWidth * $this->k));
1187 $this->linestyleCap = "0 J";
1188 $this->linestyleJoin = "0 j";
1189 $this->linestyleDash = "[] 0 d";
1190 //Automatic page break
1191 $this->SetAutoPageBreak(true, 2*$margin);
1192 //Full width display mode
1193 $this->SetDisplayMode('fullwidth');
1195 $this->SetCompression(true);
1196 //Set default PDF version number
1197 $this->PDFVersion = "1.7";
1198 $this->encoding = $encoding;
1200 $this->getFontsList();
1201 $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
1202 $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
1203 $this->extgstates = array();
1206 $this->ur_document = "/FullSave";
1207 $this->ur_annots = "/Create/Delete/Modify/Copy/Import/Export";
1208 $this->ur_form = "/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate";
1209 $this->ur_signature = "/Modify";
1210 // set default JPEG quality
1211 $this->jpeg_quality = 75;
1212 // initialize some settings
1213 $this->utf8Bidi(array(""));
1217 * Default destructor.
1218 * @since 1.53.0.TC016
1220 function TCPDFDestruct() {
1221 // restore internal encoding
1222 if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
1223 mb_internal_encoding($this->internal_encoding);
1228 * Set the units of measure for the document.
1229 * @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.
1230 * @since 3.0.015 (2008-06-06)
1232 function setPageUnit($unit) {
1234 switch (strtolower($unit)) {
1242 $this->k = $this->dpi / 25.4;
1247 $this->k = $this->dpi / 2.54;
1252 $this->k = $this->dpi;
1257 $this->Error('Incorrect unit: '.$unit);
1261 if (isset($this->CurOrientation)) {
1262 $this->setPageOrientation($this->CurOrientation);
1267 * Set the page format
1268 * @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>
1269 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1270 * @since 3.0.015 (2008-06-06)
1272 function setPageFormat($format, $orientation="P") {
1274 if (is_string($format)) {
1275 // Page formats (45 standard ISO paper formats and 4 american common formats).
1276 // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm)
1277 switch (strtoupper($format)){
1278 case '4A0': {$format = array(4767.87,6740.79); break;}
1279 case '2A0': {$format = array(3370.39,4767.87); break;}
1280 case 'A0': {$format = array(2383.94,3370.39); break;}
1281 case 'A1': {$format = array(1683.78,2383.94); break;}
1282 case 'A2': {$format = array(1190.55,1683.78); break;}
1283 case 'A3': {$format = array(841.89,1190.55); break;}
1284 case 'A4': default: {$format = array(595.28,841.89); break;}
1285 case 'A5': {$format = array(419.53,595.28); break;}
1286 case 'A6': {$format = array(297.64,419.53); break;}
1287 case 'A7': {$format = array(209.76,297.64); break;}
1288 case 'A8': {$format = array(147.40,209.76); break;}
1289 case 'A9': {$format = array(104.88,147.40); break;}
1290 case 'A10': {$format = array(73.70,104.88); break;}
1291 case 'B0': {$format = array(2834.65,4008.19); break;}
1292 case 'B1': {$format = array(2004.09,2834.65); break;}
1293 case 'B2': {$format = array(1417.32,2004.09); break;}
1294 case 'B3': {$format = array(1000.63,1417.32); break;}
1295 case 'B4': {$format = array(708.66,1000.63); break;}
1296 case 'B5': {$format = array(498.90,708.66); break;}
1297 case 'B6': {$format = array(354.33,498.90); break;}
1298 case 'B7': {$format = array(249.45,354.33); break;}
1299 case 'B8': {$format = array(175.75,249.45); break;}
1300 case 'B9': {$format = array(124.72,175.75); break;}
1301 case 'B10': {$format = array(87.87,124.72); break;}
1302 case 'C0': {$format = array(2599.37,3676.54); break;}
1303 case 'C1': {$format = array(1836.85,2599.37); break;}
1304 case 'C2': {$format = array(1298.27,1836.85); break;}
1305 case 'C3': {$format = array(918.43,1298.27); break;}
1306 case 'C4': {$format = array(649.13,918.43); break;}
1307 case 'C5': {$format = array(459.21,649.13); break;}
1308 case 'C6': {$format = array(323.15,459.21); break;}
1309 case 'C7': {$format = array(229.61,323.15); break;}
1310 case 'C8': {$format = array(161.57,229.61); break;}
1311 case 'C9': {$format = array(113.39,161.57); break;}
1312 case 'C10': {$format = array(79.37,113.39); break;}
1313 case 'RA0': {$format = array(2437.80,3458.27); break;}
1314 case 'RA1': {$format = array(1729.13,2437.80); break;}
1315 case 'RA2': {$format = array(1218.90,1729.13); break;}
1316 case 'RA3': {$format = array(864.57,1218.90); break;}
1317 case 'RA4': {$format = array(609.45,864.57); break;}
1318 case 'SRA0': {$format = array(2551.18,3628.35); break;}
1319 case 'SRA1': {$format = array(1814.17,2551.18); break;}
1320 case 'SRA2': {$format = array(1275.59,1814.17); break;}
1321 case 'SRA3': {$format = array(907.09,1275.59); break;}
1322 case 'SRA4': {$format = array(637.80,907.09); break;}
1323 case 'LETTER': {$format = array(612.00,792.00); break;}
1324 case 'LEGAL': {$format = array(612.00,1008.00); break;}
1325 case 'EXECUTIVE': {$format = array(521.86,756.00); break;}
1326 case 'FOLIO': {$format = array(612.00,936.00); break;}
1328 $this->fwPt = $format[0];
1329 $this->fhPt = $format[1];
1332 $this->fwPt = $format[0] * $this->k;
1333 $this->fhPt = $format[1] * $this->k;
1335 $this->setPageOrientation($orientation);
1340 * Set page orientation.
1341 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1342 * @param boolean $autopagebreak Boolean indicating if auto-page-break mode should be on or off.
1343 * @param float $bottommargin bottom margin of the page.
1344 * @since 3.0.015 (2008-06-06)
1346 function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
1347 $orientation = strtoupper($orientation);
1348 if (($orientation == 'P') OR ($orientation == 'PORTRAIT')) {
1349 $this->CurOrientation = 'P';
1350 $this->wPt = $this->fwPt;
1351 $this->hPt = $this->fhPt;
1352 } elseif (($orientation == 'L') OR ($orientation == 'LANDSCAPE')) {
1353 $this->CurOrientation = 'L';
1354 $this->wPt = $this->fhPt;
1355 $this->hPt = $this->fwPt;
1358 $this->Error('Incorrect orientation: '.$orientation);
1360 $this->w = $this->wPt / $this->k;
1361 $this->h = $this->hPt / $this->k;
1362 if (empty($autopagebreak)) {
1363 if (isset($this->AutoPageBreak)) {
1364 $autopagebreak = $this->AutoPageBreak;
1366 $autopagebreak = true;
1369 if (empty($bottommargin)) {
1370 if (isset($this->bMargin)) {
1371 $bottommargin = $this->bMargin;
1373 // default value = 2 cm
1374 $bottommargin = 2 * 28.35 / $this->k;
1377 $this->SetAutoPageBreak($autopagebreak, $bottommargin);
1378 // store page dimensions
1379 $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);
1383 * Enable or disable Right-To-Left language mode
1384 * @param Boolean $enable if true enable Right-To-Left language mode.
1385 * @since 2.0.000 (2008-01-03)
1387 function setRTL($enable) {
1388 $this->rtl = $enable ? true : false;
1389 $this->tmprtl = false;
1393 * Return the RTL status
1395 * @since 4.0.012 (2008-07-24)
1402 * Force temporary RTL language direction
1403 * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL
1404 * @since 2.1.000 (2008-01-09)
1406 function setTempRTL($mode) {
1411 $this->tmprtl = $mode;
1417 * Set the last cell height.
1418 * @param float $h cell height.
1419 * @author Nicola Asuni
1420 * @since 1.53.0.TC034
1422 function setLastH($h) {
1427 * Get the last cell height.
1428 * @return last cell height
1429 * @since 4.0.017 (2008-08-05)
1431 function getLastH() {
1432 return $this->lasth;
1436 * Set the image scale.
1437 * @param float $scale image scale.
1438 * @author Nicola Asuni
1441 function setImageScale($scale) {
1442 $this->imgscale = $scale;
1446 * Returns the image scale.
1447 * @return float image scale.
1448 * @author Nicola Asuni
1451 function getImageScale() {
1452 return $this->imgscale;
1456 * Returns the page width in units.
1457 * @return int page width.
1458 * @author Nicola Asuni
1461 function getPageWidth() {
1466 * Returns the page height in units.
1467 * @return int page height.
1468 * @author Nicola Asuni
1471 function getPageHeight() {
1476 * Returns the page break margin.
1477 * @return int page break margin.
1478 * @author Nicola Asuni
1481 function getBreakMargin() {
1482 return $this->bMargin;
1486 * Returns the scale factor (number of points in user unit).
1487 * @return int scale factor.
1488 * @author Nicola Asuni
1491 function getScaleFactor() {
1496 * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
1497 * @param float $left Left margin.
1498 * @param float $top Top margin.
1499 * @param float $right Right margin. Default value is the left one.
1501 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
1503 function SetMargins($left, $top, $right=-1) {
1504 //Set left, top and right margins
1505 $this->lMargin = $left;
1506 $this->tMargin = $top;
1510 $this->rMargin = $right;
1514 * 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.
1515 * @param float $margin The margin.
1517 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1519 function SetLeftMargin($margin) {
1521 $this->lMargin=$margin;
1522 if (($this->page > 0) AND ($this->x < $margin)) {
1528 * Defines the top margin. The method can be called before creating the first page.
1529 * @param float $margin The margin.
1531 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1533 function SetTopMargin($margin) {
1535 $this->tMargin=$margin;
1536 if (($this->page > 0) AND ($this->y < $margin)) {
1542 * Defines the right margin. The method can be called before creating the first page.
1543 * @param float $margin The margin.
1545 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1547 function SetRightMargin($margin) {
1548 $this->rMargin=$margin;
1549 if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
1550 $this->x = $this->w - $margin;
1555 * Set the internal Cell padding.
1556 * @param float $pad internal padding.
1557 * @since 2.1.000 (2008-01-09)
1558 * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1560 function SetCellPadding($pad) {
1561 $this->cMargin = $pad;
1565 * 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.
1566 * @param boolean $auto Boolean indicating if mode should be on or off.
1567 * @param float $margin Distance from the bottom of the page.
1569 * @see Cell(), MultiCell(), AcceptPageBreak()
1571 function SetAutoPageBreak($auto, $margin=0) {
1572 //Set auto page break mode and triggering margin
1573 $this->AutoPageBreak = $auto;
1574 $this->bMargin = $margin;
1575 $this->PageBreakTrigger = $this->h - $margin;
1579 * Defines the way the document is to be displayed by the viewer.
1580 * @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>
1581 * @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>
1582 * @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>
1585 function SetDisplayMode($zoom, $layout='SinglePage', $mode="UseNone") {
1586 //Set display mode in viewer
1587 if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
1588 $this->ZoomMode = $zoom;
1590 $this->Error('Incorrect zoom display mode: '.$zoom);
1595 case "SinglePage": {
1596 $this->LayoutMode = "SinglePage";
1601 $this->LayoutMode = "OneColumn";
1605 case "TwoColumnLeft": {
1606 $this->LayoutMode = "TwoColumnLeft";
1609 case "TwoColumnRight": {
1610 $this->LayoutMode = "TwoColumnRight";
1613 case "TwoPageLeft": {
1614 $this->LayoutMode = "TwoPageLeft";
1617 case "TwoPageRight": {
1618 $this->LayoutMode = "TwoPageRight";
1622 $this->LayoutMode = "SinglePage";
1627 $this->PageMode = "UseNone";
1630 case "UseOutlines": {
1631 $this->PageMode = "UseOutlines";
1635 $this->PageMode = "UseThumbs";
1638 case "FullScreen": {
1639 $this->PageMode = "FullScreen";
1643 $this->PageMode = "UseOC";
1647 $this->PageMode = "UseAttachments";
1651 $this->PageMode = "UseNone";
1657 * 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.
1658 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
1659 * @param boolean $compress Boolean indicating if compression must be enabled.
1662 function SetCompression($compress) {
1663 //Set page compression
1664 if (function_exists('gzcompress')) {
1665 $this->compress = $compress;
1667 $this->compress = false;
1672 * Defines the title of the document.
1673 * @param string $title The title.
1675 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
1677 function SetTitle($title) {
1679 $this->title = $title;
1683 * Defines the subject of the document.
1684 * @param string $subject The subject.
1686 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
1688 function SetSubject($subject) {
1689 //Subject of document
1690 $this->subject = $subject;
1694 * Defines the author of the document.
1695 * @param string $author The name of the author.
1697 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
1699 function SetAuthor($author) {
1700 //Author of document
1701 $this->author = $author;
1705 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
1706 * @param string $keywords The list of keywords.
1708 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
1710 function SetKeywords($keywords) {
1711 //Keywords of document
1712 $this->keywords = $keywords;
1716 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
1717 * @param string $creator The name of the creator.
1719 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
1721 function SetCreator($creator) {
1722 //Creator of document
1723 $this->creator = $creator;
1727 * Defines an alias for the total number of pages. It will be substituted as the document is closed.<br />
1728 * @param string $alias The alias. Default value: {nb}.
1730 * @see getAliasNbPages(), PageNo(), Footer()
1732 function AliasNbPages($alias='{nb}') {
1733 //Define an alias for total number of pages
1734 $this->AliasNbPages = $alias;
1738 * Returns the string alias used for the total number of pages.
1739 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
1741 * @since 4.0.018 (2008-08-08)
1742 * @see AliasNbPages(), PageNo(), Footer()
1744 function getAliasNbPages() {
1745 if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
1746 return "{".$this->AliasNbPages."}";
1748 return $this->AliasNbPages;
1752 * 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.
1753 * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
1754 * @param string $msg The error message
1757 function Error($msg) {
1759 die('<strong>TCPDF error: </strong>'.$msg);
1763 * This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.
1764 * Note: no page is created by this method
1766 * @see AddPage(), Close()
1774 * 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.
1776 * @see Open(), Output()
1779 //Terminate document
1780 if ($this->state == 3) {
1783 if ($this->page == 0) {
1795 * Move pointer at the specified document page and update page dimensions.
1796 * @param int $pnum page number
1797 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
1798 * @since 2.1.000 (2008-01-07)
1799 * @see getPage(), lastpage(), getNumPages()
1801 function setPage($pnum, $resetmargins=false) {
1802 if (($pnum > 0) AND ($pnum <= count($this->pages))) {
1803 $this->page = $pnum;
1804 $this->wPt = $this->pagedim[$this->page]['w'];
1805 $this->hPt = $this->pagedim[$this->page]['h'];
1806 $this->w = $this->wPt / $this->k;
1807 $this->h = $this->hPt / $this->k;
1808 $this->tMargin = $this->pagedim[$this->page]['tm'];
1809 $this->bMargin = $this->pagedim[$this->page]['bm'];
1810 $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
1811 $this->CurOrientation = $this->pagedim[$this->page]['or'];
1812 $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
1813 if ($resetmargins) {
1814 $this->lMargin = $this->pagedim[$this->page]['lm'];
1815 $this->rMargin = $this->pagedim[$this->page]['rm'];
1816 $this->SetY($this->tMargin);
1819 $this->Error('Wrong page number on setPage() function.');
1824 * Reset pointer to the last document page.
1825 * @since 2.0.000 (2008-01-04)
1826 * @see setPage(), getPage(), getNumPages()
1828 function lastPage() {
1829 $this->setPage($this->getNumPages());
1833 * Get current document page number.
1834 * @return int page number
1835 * @since 2.1.000 (2008-01-07)
1836 * @see setPage(), lastpage(), getNumPages()
1838 function getPage() {
1844 * Get the total number of insered pages.
1845 * @return int number of pages
1846 * @since 2.1.000 (2008-01-07)
1847 * @see setPage(), getPage(), lastpage()
1849 function getNumPages() {
1850 return count($this->pages);
1854 * 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.
1855 * 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.
1856 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
1857 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1858 * @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>
1860 * @see TCPDF(), Header(), Footer(), SetMargins()
1862 function AddPage($orientation='', $format='') {
1863 if (!isset($this->original_lMargin)) {
1864 $this->original_lMargin = $this->lMargin;
1866 if (!isset($this->original_rMargin)) {
1867 $this->original_rMargin = $this->rMargin;
1869 if (count($this->pages) > $this->page) {
1870 // this page has been already added
1871 $this->setPage(($this->page + 1));
1872 $this->SetY($this->tMargin);
1876 if ($this->state == 0) {
1879 // save current settings
1880 $font_family = $this->FontFamily;
1881 $font_style = $this->FontStyle.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '');
1882 $font_size = $this->FontSizePt;
1883 $prev_rMargin = $this->rMargin;
1884 $prev_lMargin = $this->lMargin;
1885 $prev_cMargin = $this->cMargin;
1886 $prev_linestyleWidth = $this->linestyleWidth;
1887 $prev_linestyleCap = $this->linestyleCap;
1888 $prev_linestyleJoin = $this->linestyleJoin;
1889 $prev_linestyleDash = $this->linestyleDash;
1890 $prev_DrawColor = $this->DrawColor;
1891 $prev_FillColor = $this->FillColor;
1892 $prev_TextColor = $this->TextColor;
1893 $prev_ColorFlag = $this->ColorFlag;
1894 if ($this->page > 0) {
1901 $this->_beginpage($orientation, $format);
1902 // restore graphic styles
1903 $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1904 if (!empty($font_family)) {
1905 $this->SetFont($font_family, $font_style, $font_size);
1909 // restore graphic styles
1910 $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1911 if (!empty($font_family)) {
1912 $this->SetFont($font_family, $font_style, $font_size);
1915 $this->FontFamily = $font_family;
1916 $this->FontStyle = $font_style;
1917 $this->FontSizePt = $font_size;
1918 $this->rMargin = $prev_rMargin;
1919 $this->lMargin = $prev_lMargin;
1920 $this->cMargin = $prev_cMargin;
1921 $this->linestyleWidth = $prev_linestyleWidth;
1922 $this->linestyleCap = $prev_linestyleCap;
1923 $this->linestyleJoin = $prev_linestyleJoin;
1924 $this->linestyleDash = $prev_linestyleDash;
1925 $this->DrawColor = $prev_DrawColor;
1926 $this->FillColor = $prev_FillColor;
1927 $this->TextColor = $prev_TextColor;
1928 $this->ColorFlag = $prev_ColorFlag;
1930 $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1934 * Set start-writing mark on current page for multicell borders and fills.
1935 * This function must be called after calling Image() function for a background image.
1936 * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
1938 * @since 4.0.016 (2008-07-30)
1940 function setPageMark() {
1941 $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1946 * @param string $ln header image logo
1947 * @param string $lw header image logo width in mm
1948 * @param string $ht string to print as title on document header
1949 * @param string $hs string to print on document header
1951 function setHeaderData($ln="", $lw=0, $ht="", $hs="") {
1952 $this->header_logo = $ln;
1953 $this->header_logo_width = $lw;
1954 $this->header_title = $ht;
1955 $this->header_string = $hs;
1959 * Returns header data:
1960 * <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>
1962 * @since 4.0.012 (2008-07-24)
1964 function getHeaderData() {
1966 $ret['logo'] = $this->header_logo;
1967 $ret['logo_width'] = $this->header_logo_width;
1968 $ret['title'] = $this->header_title;
1969 $ret['string'] = $this->header_string;
1974 * Set header margin.
1975 * (minimum distance between header and top page margin)
1976 * @param int $hm distance in user units
1978 function setHeaderMargin($hm=10) {
1979 $this->header_margin = $hm;
1983 * Returns header margin in user units.
1985 * @since 4.0.012 (2008-07-24)
1987 function getHeaderMargin() {
1988 return $this->header_margin;
1992 * Set footer margin.
1993 * (minimum distance between footer and bottom page margin)
1994 * @param int $fm distance in user units
1996 function setFooterMargin($fm=10) {
1997 $this->footer_margin = $fm;
2001 * Returns footer margin in user units.
2003 * @since 4.0.012 (2008-07-24)
2005 function getFooterMargin() {
2006 return $this->footer_margin;
2009 * Set a flag to print page header.
2010 * @param boolean $val set to true to print the page header (default), false otherwise.
2012 function setPrintHeader($val=true) {
2013 $this->print_header = $val;
2017 * Set a flag to print page footer.
2018 * @param boolean $value set to true to print the page footer (default), false otherwise.
2020 function setPrintFooter($val=true) {
2021 $this->print_footer = $val;
2025 * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
2028 function getImageRBX() {
2029 return $this->img_rb_x;
2033 * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
2036 function getImageRBY() {
2037 return $this->img_rb_y;
2041 * This method is used to render the page header.
2042 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2044 function Header1() {
2045 $ormargins = $this->getOriginalMargins();
2046 $headerfont = $this->getHeaderFont();
2047 $headerdata = $this->getHeaderData();
2048 if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
2049 $this->Image(K_PATH_IMAGES.$headerdata['logo'], $this->GetX(), $this->getHeaderMargin(), $headerdata['logo_width']);
2050 $imgy = $this->getImageRBY();
2052 $imgy = $this->GetY();
2054 $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2);
2055 // set starting margin for text data cell
2056 if ($this->getRTL()) {
2057 $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1);
2059 $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1);
2061 $this->SetTextColor(0, 0, 0);
2063 $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
2064 $this->SetX($header_x);
2065 $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '');
2067 $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
2068 $this->SetX($header_x);
2069 $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, 0, 0, true, 0);
2070 // print an ending header line
2071 $this->SetLineStyle(array("width" => 0.85 / $this->getScaleFactor(), "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2072 $this->SetY(1 + max($imgy, $this->GetY()));
2073 if ($this->getRTL()) {
2074 $this->SetX($ormargins['right']);
2076 $this->SetX($ormargins['left']);
2078 $this->Cell(0, 0, '', 'T', 0, 'C');
2082 * This method is used to render the page footer.
2083 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2086 $cur_y = $this->GetY();
2087 $ormargins = $this->getOriginalMargins();
2088 $this->SetTextColor(0, 0, 0);
2089 //set style for cell border
2090 $line_width = 0.85 / $this->getScaleFactor();
2091 $this->SetLineStyle(array("width" => $line_width, "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2092 //print document barcode
2093 $barcode = $this->getBarcode();
2094 if (!empty($barcode)) {
2096 $barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right'])/3);
2097 $this->write1DBarcode($barcode, "C128B", $this->GetX(), $cur_y + $line_width, $barcode_width, (($this->getFooterMargin() / 3) - $line_width), 0.3, '', '');
2099 $pagenumtxt = $this->l['w_page']." ".$this->PageNo().' / '.$this->getAliasNbPages();
2100 $this->SetY($cur_y);
2102 if ($this->getRTL()) {
2103 $this->SetX($ormargins['right']);
2104 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
2106 $this->SetX($ormargins['left']);
2107 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R');
2112 * This method is used to render the page header.
2114 * @since 4.0.012 (2008-07-24)
2116 function setHeader() {
2117 if ($this->print_header) {
2118 $lasth = $this->lasth;
2120 $this->rMargin = $this->original_rMargin;
2121 $this->lMargin = $this->original_lMargin;
2122 //set current position
2124 $this->SetXY($this->original_rMargin, $this->header_margin);
2126 $this->SetXY($this->original_lMargin, $this->header_margin);
2128 $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
2132 $this->SetXY($this->original_rMargin, $this->tMargin);
2134 $this->SetXY($this->original_lMargin, $this->tMargin);
2137 $this->lasth = $lasth;
2142 * This method is used to render the page footer.
2144 * @since 4.0.012 (2008-07-24)
2146 function setFooter() {
2148 $this->InFooter = true;
2150 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
2151 if ($this->print_footer) {
2152 $lasth = $this->lasth;
2154 $this->rMargin = $this->original_rMargin;
2155 $this->lMargin = $this->original_lMargin;
2156 //set current position
2157 $footer_y = $this->h - $this->footer_margin;
2159 $this->SetXY($this->original_rMargin, $footer_y);
2161 $this->SetXY($this->original_lMargin, $footer_y);
2163 $this->SetFont($this->footer_font[0], $this->footer_font[1] , $this->footer_font[2]);
2167 $this->SetXY($this->original_rMargin, $this->tMargin);
2169 $this->SetXY($this->original_lMargin, $this->tMargin);
2172 $this->lasth = $lasth;
2174 $this->footerlen[$this->page] = strlen($this->pages[$this->page]) - $this->footerpos[$this->page];
2175 $this->InFooter = false;
2179 * Returns the current page number.
2180 * @return int page number
2182 * @see AliasNbPages(), getAliasNbPages()
2189 * Defines a new spot color.
2190 * It can be expressed in RGB components or gray scale.
2191 * The method can be called before the first page is created and the value is retained from page to page.
2192 * @param int $c Cyan color for CMYK. Value between 0 and 255
2193 * @param int $m Magenta color for CMYK. Value between 0 and 255
2194 * @param int $y Yellow color for CMYK. Value between 0 and 255
2195 * @param int $k Key (Black) color for CMYK. Value between 0 and 255
2196 * @since 4.0.024 (2008-09-12)
2197 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2199 function AddSpotColor($name, $c, $m, $y, $k) {
2200 if (!isset($this->spot_colors[$name])) {
2201 $i = 1 + count($this->spot_colors);
2202 $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k);
2207 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
2208 * It can be expressed in RGB components or gray scale.
2209 * The method can be called before the first page is created and the value is retained from page to page.
2210 * @param array $color array of colors
2211 * @since 3.1.000 (2008-06-11)
2212 * @see SetDrawColor()
2214 function SetDrawColorArray($color) {
2215 if (isset($color)) {
2216 $color = array_values($color);
2217 $r = isset($color[0]) ? $color[0] : -1;
2218 $g = isset($color[1]) ? $color[1] : -1;
2219 $b = isset($color[2]) ? $color[2] : -1;
2220 $k = isset($color[3]) ? $color[3] : -1;
2222 $this->SetDrawColor($r, $g, $b, $k);
2228 * 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.
2229 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2230 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2231 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2232 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2234 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
2236 function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2237 // set default values
2238 if (!is_numeric($col1)) {
2241 if (!is_numeric($col2)) {
2244 if (!is_numeric($col3)) {
2247 if (!is_numeric($col4)) {
2250 //Set color for all stroking operations
2251 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2253 $this->DrawColor = sprintf('%.3f G', $col1/255);
2254 } elseif ($col4 == -1) {
2256 $this->DrawColor = sprintf('%.3f %.3f %.3f RG', $col1/255, $col2/255, $col3/255);
2259 $this->DrawColor = sprintf('%.3f %.3f %.3f %.3f K', $col1/100, $col2/100, $col3/100, $col4/100);
2261 if ($this->page > 0) {
2262 $this->_out($this->DrawColor);
2267 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
2268 * @param string $name name of the spot color
2269 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2270 * @since 4.0.024 (2008-09-12)
2271 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2273 function SetDrawSpotColor($name, $tint=100) {
2274 if (!isset($this->spot_colors[$name])) {
2275 $this->Error('Undefined spot color: '.$name);
2277 $this->DrawColor = sprintf('/CS%d CS %.3f SCN', $this->spot_colors[$name]['i'], $tint/100);
2278 if ($this->page > 0) {
2279 $this->_out($this->DrawColor);
2284 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
2285 * It can be expressed in RGB components or gray scale.
2286 * The method can be called before the first page is created and the value is retained from page to page.
2287 * @param array $color array of colors
2288 * @since 3.1.000 (2008-6-11)
2289 * @see SetFillColor()
2291 function SetFillColorArray($color) {
2292 if (isset($color)) {
2293 $color = array_values($color);
2294 $r = isset($color[0]) ? $color[0] : -1;
2295 $g = isset($color[1]) ? $color[1] : -1;
2296 $b = isset($color[2]) ? $color[2] : -1;
2297 $k = isset($color[3]) ? $color[3] : -1;
2299 $this->SetFillColor($r, $g, $b, $k);
2305 * 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.
2306 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2307 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2308 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2309 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2311 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
2313 function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2314 // set default values
2315 if (!is_numeric($col1)) {
2318 if (!is_numeric($col2)) {
2321 if (!is_numeric($col3)) {
2324 if (!is_numeric($col4)) {
2327 //Set color for all filling operations
2328 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2330 $this->FillColor = sprintf('%.3f g', $col1/255);
2331 $this->bgcolor = array('G' => $col1);
2332 } elseif ($col4 == -1) {
2334 $this->FillColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2335 $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2338 $this->FillColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2339 $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2341 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2342 if ($this->page > 0) {
2343 $this->_out($this->FillColor);
2348 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
2349 * @param string $name name of the spot color
2350 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2351 * @since 4.0.024 (2008-09-12)
2352 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
2354 function SetFillSpotColor($name, $tint=100) {
2355 if (!isset($this->spot_colors[$name])) {
2356 $this->Error('Undefined spot color: '.$name);
2358 $this->FillColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2359 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2360 if ($this->page > 0) {
2361 $this->_out($this->FillColor);
2366 * Defines the color used for text. It can be expressed in RGB components or gray scale.
2367 * The method can be called before the first page is created and the value is retained from page to page.
2368 * @param array $color array of colors
2369 * @since 3.1.000 (2008-6-11)
2370 * @see SetFillColor()
2372 function SetTextColorArray($color) {
2373 if (isset($color)) {
2374 $color = array_values($color);
2375 $r = isset($color[0]) ? $color[0] : -1;
2376 $g = isset($color[1]) ? $color[1] : -1;
2377 $b = isset($color[2]) ? $color[2] : -1;
2378 $k = isset($color[3]) ? $color[3] : -1;
2380 $this->SetTextColor($r, $g, $b, $k);
2386 * 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.
2387 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2388 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2389 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2390 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2392 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
2394 function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2395 // set default values
2396 if (!is_numeric($col1)) {
2399 if (!is_numeric($col2)) {
2402 if (!is_numeric($col3)) {
2405 if (!is_numeric($col4)) {
2408 //Set color for text
2409 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2411 $this->TextColor = sprintf('%.3f g', $col1/255);
2412 $this->fgcolor = array('G' => $col1);
2413 } elseif ($col4 == -1) {
2415 $this->TextColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2416 $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2419 $this->TextColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2420 $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2422 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2426 * Defines the spot color used for text.
2427 * @param string $name name of the spot color
2428 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2429 * @since 4.0.024 (2008-09-12)
2430 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
2432 function SetTextSpotColor($name, $tint=100) {
2433 if (!isset($this->spot_colors[$name])) {
2434 $this->Error('Undefined spot color: '.$name);
2436 $this->TextColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2437 $this->ColorFlag = ($this->FillColor != $this->TextColor);
2438 if ($this->page > 0) {
2439 $this->_out($this->TextColor);
2444 * Returns the length of a string in user unit. A font must be selected.<br>
2445 * @param string $s The string whose length is to be computed
2446 * @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.
2447 * @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.
2448 * @param float $fontsize Font size in points. The default value is the current size.
2449 * @return int string length
2450 * @author Nicola Asuni
2453 function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0) {
2454 return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $this->tmprtl), $fontname, $fontstyle, $fontsize);
2458 * Returns the string length of an array of chars in user unit. A font must be selected.<br>
2459 * @param string $arr The array of chars whose total length is to be computed
2460 * @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.
2461 * @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.
2462 * @param float $fontsize Font size in points. The default value is the current size.
2463 * @return int string length
2464 * @author Nicola Asuni
2465 * @since 2.4.000 (2008-03-06)
2467 function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0) {
2468 // store current values
2469 if (!empty($fontname)) {
2470 $prev_FontFamily = $this->FontFamily;
2471 $prev_FontStyle = $this->FontStyle;
2472 $prev_FontSizePt = $this->FontSizePt;
2473 $this->SetFont($fontname, $fontstyle, $fontsize);
2476 foreach($sa as $char) {
2477 $w += $this->GetCharWidth($char);
2479 // restore previous values
2480 if (!empty($fontname)) {
2481 $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt);
2487 * Returns the length of the char in user unit for the current font.<br>
2488 * @param int $char The char code whose length is to be returned
2489 * @return int char width
2490 * @author Nicola Asuni
2491 * @since 2.4.000 (2008-03-06)
2493 function GetCharWidth($char) {
2494 $cw = &$this->CurrentFont['cw'];
2495 if (isset($cw[$char])) {
2498 } elseif (isset($cw[ord($char)])) {
2499 $w = $cw[ord($char)];
2500 } elseif (isset($cw[chr($char)])) {
2501 $w = $cw[chr($char)];
2503 } elseif (isset($this->CurrentFont['dw'])) {
2504 $w = $this->CurrentFont['dw'];
2505 } elseif (isset($this->CurrentFont['desc']['MissingWidth'])) {
2506 $w = $this->CurrentFont['desc']['MissingWidth']; // set default size
2508 $w = 500; // default width
2510 return ($w * $this->FontSize / 1000);
2514 * Returns the numbero of characters in a string.
2515 * @param string $s The input string.
2516 * @return int number of characters
2517 * @since 2.0.0001 (2008-01-07)
2519 function GetNumChars($s) {
2520 if ($this->isunicode) {
2521 return count($this->UTF8StringToArray($s));
2527 * Fill the list of available fonts ($this->fontlist).
2529 * @since 4.0.013 (2008-07-28)
2531 function getFontsList() {
2532 $fontsdir = opendir($this->_getfontpath());
2533 while (($file = readdir($fontsdir)) !== false) {
2534 if (substr($file, -4) == ".php") {
2535 array_push($this->fontlist, strtolower(basename($file, ".php")));
2538 closedir($fontsdir);
2542 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
2543 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
2544 * 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.
2545 * Changed to support UTF-8 Unicode [Nicola Asuni, 2005-01-02].
2546 * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
2547 * @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>
2548 * @param string $file The font definition file. By default, the name is built from the family and style, in lower case with no space.
2549 * @return array containing the font data, or false in case of error.
2553 function AddFont($family, $style='', $file='') {
2554 if (empty($family)) {
2555 if (!empty($this->FontFamily)) {
2556 $family = $this->FontFamily;
2558 $this->Error('Empty font family');
2561 $family = strtolower($family);
2562 if ((!$this->isunicode) AND ($family == 'arial')) {
2563 $family = 'helvetica';
2565 if (($family == "symbol") OR ($family == "zapfdingbats")) {
2568 $style = strtoupper($style);
2570 if (strpos($style,'U') !== false) {
2571 $this->underline = true;
2572 $style = str_replace('U', '', $style);
2574 $this->underline = false;
2576 //line through (deleted)
2577 if (strpos($style,'D') !== false) {
2578 $this->linethrough = true;
2579 $style = str_replace('D', '', $style);
2581 $this->linethrough = false;
2583 if ($style == 'IB') {
2586 $fontkey = $family.$style;
2587 $fontdata = array("fontkey" => $fontkey, "family" => $family, "style" => $style);
2588 // check if the font has been already added
2589 if (isset($this->fonts[$fontkey])) {
2593 $file = str_replace(' ', '', $family).strtolower($style).'.php';
2595 if (!file_exists($this->_getfontpath().$file)) {
2596 // try to load the basic file without styles
2597 $file = str_replace(' ', '', $family).'.php';
2605 include($this->_getfontpath().$file);
2606 if ((!isset($type)) OR (!isset($cw))) {
2607 $this->Error('Could not include font definition file');
2609 $i = count($this->fonts) + 1;
2610 // register CID font (all styles at once)
2611 if ($type == 'cidfont0') {
2612 $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
2613 foreach ($styles as $skey => $qual) {
2614 $sname = $name.$qual;
2615 $sfontkey = $family.$skey;
2616 $this->fonts[$sfontkey] = array('i' => $i, 'type' => $type, 'name' => $sname, 'desc' => $desc, 'cidinfo' => $cidinfo, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc);
2617 $i = count($this->fonts) + 1;
2620 } elseif ($type == 'core') {
2621 $def_width = $cw[ord('?')];
2622 $this->fonts[$fontkey] = array('i' => $i, 'type' => 'core', 'name' => $this->CoreFonts[$fontkey], 'up' => -100, 'ut' => 50, 'cw' => $cw, 'dw' => $def_width);
2623 } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
2624 if (!isset($file)) {
2630 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'file' => $file, 'enc' => $enc, 'desc' => $desc);
2631 } elseif ($type == 'TrueTypeUnicode') {
2632 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'enc' => $enc, 'file' => $file, 'ctg' => $ctg);
2634 $this->Error('Unknow font type');
2636 if (isset($diff) AND (!empty($diff))) {
2637 //Search existing encodings
2639 $nb = count($this->diffs);
2640 for($i=1; $i <= $nb; $i++) {
2641 if ($this->diffs[$i] == $diff) {
2648 $this->diffs[$d] = $diff;
2650 $this->fonts[$fontkey]['diff'] = $d;
2652 if (!empty($file)) {
2653 if ((strcasecmp($type,"TrueType") == 0) OR (strcasecmp($type,"TrueTypeUnicode") == 0)) {
2654 $this->FontFiles[$file] = array('length1' => $originalsize);
2655 } elseif ($type != 'core') {
2656 $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2);
2663 * Sets the font used to print character strings.
2664 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
2665 * The method can be called before the first page is created and the font is retained from page to page.
2666 * If you just wish to change the current font size, it is simpler to call SetFontSize().
2667 * 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 />
2668 * @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.
2669 * @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.
2670 * @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
2672 * @see AddFont(), SetFontSize()
2674 function SetFont($family, $style='', $size=0) {
2675 //Select a font; size given in points
2677 $size = $this->FontSizePt;
2679 // try to add font (if not already added)
2680 $fontdata = $this->AddFont($family, $style);
2681 $this->FontFamily = $fontdata['family'];
2682 $this->FontStyle = $fontdata['style'];
2683 $this->CurrentFont = &$this->fonts[$fontdata['fontkey']];
2684 $this->SetFontSize($size);
2688 * Defines the size of the current font.
2689 * @param float $size The size (in points)
2693 function SetFontSize($size) {
2694 //Set font size in points
2695 $this->FontSizePt = $size;
2696 $this->FontSize = $size / $this->k;
2697 if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
2698 $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000;
2700 $this->FontAscent = 0.8 * $this->FontSize;
2702 if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] > 0)) {
2703 $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000;
2705 $this->FontDescent = 0.2 * $this->FontSize;
2707 if (($this->page > 0) AND (isset($this->CurrentFont['i']))) {
2708 $this->_out(sprintf('BT /F%d %.2f Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
2713 * 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 />
2714 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
2716 * @see Cell(), Write(), Image(), Link(), SetLink()
2718 function AddLink() {
2719 //Create a new internal link
2720 $n = count($this->links) + 1;
2721 $this->links[$n] = array(0, 0);
2726 * Defines the page and position a link points to.
2727 * @param int $link The link identifier returned by AddLink()
2728 * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
2729 * @param int $page Number of target page; -1 indicates the current page. This is the default value
2733 function SetLink($link, $y=0, $page=-1) {
2738 $page = $this->page;
2740 $this->links[$link] = array($page, $y);
2744 * Puts a link on a rectangular area of the page.
2745 * 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.
2746 * @param float $x Abscissa of the upper-left corner of the rectangle
2747 * @param float $y Ordinate of the upper-left corner of the rectangle
2748 * @param float $w Width of the rectangle
2749 * @param float $h Height of the rectangle
2750 * @param mixed $link URL or identifier returned by AddLink()
2752 * @see AddLink(), Annotation(), Cell(), Write(), Image()
2754 function Link($x, $y, $w, $h, $link) {
2755 $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'));
2759 * Puts a text annotation on a rectangular area of the page.
2760 * !!!! THIS FUNCTION IS NOT YET FULLY IMPLEMENTED !!!!
2761 * @param float $x Abscissa of the upper-left corner of the rectangle
2762 * @param float $y Ordinate of the upper-left corner of the rectangle
2763 * @param float $w Width of the rectangle
2764 * @param float $h Height of the rectangle
2765 * @param string $text annotation text
2766 * @param array $opt array of options (see section 8.4 of PDF reference 1.7).
2767 * @since 4.0.018 (2008-08-06)
2769 function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text')) {
2770 $this->PageAnnots[$this->page][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt);
2774 * 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.
2775 * @param float $x Abscissa of the origin
2776 * @param float $y Ordinate of the origin
2777 * @param string $txt String to print
2778 * @param int $stroke outline size in points (0 = disable)
2779 * @param boolean $clip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
2781 * @see SetFont(), SetTextColor(), Cell(), MultiCell(), Write()
2783 function Text($x, $y, $txt, $stroke=0, $clip=false) {
2786 // bidirectional algorithm (some chars may be changed affecting the line length)
2787 $s = $this->utf8Bidi($this->UTF8StringToArray($txt), $this->tmprtl);
2788 $l = $this->GetArrStringWidth($s);
2789 $xr = $this->w - $x - $this->GetArrStringWidth($s);
2794 if (($stroke > 0) AND (!$clip)) {
2795 $opt .= "1 Tr ".intval($stroke)." w ";
2796 } elseif (($stroke > 0) AND $clip) {
2797 $opt .= "5 Tr ".intval($stroke)." w ";
2801 $s = sprintf('BT %.2f %.2f Td %s(%s) Tj ET 0 Tr', $xr * $this->k, ($this->h-$y) * $this->k, $opt, $this->_escapetext($txt));
2802 if ($this->underline AND ($txt!='')) {
2803 $s .= ' '.$this->_dounderline($xr, $y, $txt);
2805 if ($this->linethrough AND ($txt!='')) {
2806 $s .= ' '.$this->_dolinethrough($xr, $y, $txt);
2808 if ($this->ColorFlag AND (!$clip)) {
2809 $s='q '.$this->TextColor.' '.$s.' Q';
2815 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
2816 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
2817 * This method is called automatically and should not be called directly by the application.
2820 * @see SetAutoPageBreak()
2822 function AcceptPageBreak() {
2823 return $this->AutoPageBreak;
2827 * Add page if needed.
2828 * @param float $h Cell height. Default value: 0.
2829 * @since 3.2.000 (2008-07-01)
2832 function checkPageBreak($h) {
2833 if ((($this->y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
2835 //Automatic page break
2842 $this->AddPage($this->CurOrientation);
2845 $rs .= sprintf('%.3f Tw', $ws * $k);
2848 $this->y = $this->tMargin;
2854 * 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 />
2855 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2856 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2857 * @param float $h Cell height. Default value: 0.
2858 * @param string $txt String to print. Default value: empty string.
2859 * @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>
2860 * @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>
2861 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
2862 * @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>
2863 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2864 * @param mixed $link URL or identifier returned by AddLink().
2865 * @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>
2867 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
2869 function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2870 //$min_cell_height = $this->FontAscent + $this->FontDescent;
2871 $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2872 if ($h < $min_cell_height) {
2873 $h = $min_cell_height;
2875 $this->checkPageBreak($h);
2876 $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch));
2880 * 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 />
2881 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2882 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2883 * @param float $h Cell height. Default value: 0.
2884 * @param string $txt String to print. Default value: empty string.
2885 * @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>
2886 * @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.
2887 * @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>
2888 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2889 * @param mixed $link URL or identifier returned by AddLink().
2890 * @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>
2894 function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2895 $rs = ""; //string to be returned
2896 $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2897 if ($h < $min_cell_height) {
2898 $h = $min_cell_height;
2901 if (empty($w) OR ($w <= 0)) {
2903 $w = $this->x - $this->lMargin;
2905 $w = $this->w - $this->rMargin - $this->x;
2909 if (($fill == 1) OR ($border == 1)) {
2911 $op = ($border == 1) ? 'B' : 'f';
2916 $xk = (($this->x - $w) * $k);
2918 $xk = ($this->x * $k);
2920 $s .= sprintf('%.2f %.2f %.2f %.2f re %s ', $xk, (($this->h - $this->y) * $k), ($w * $k), (-$h * $k), $op);
2923 if (is_string($border)) {
2926 if (strpos($border,'L') !== false) {
2928 $xk = ($x - $w) * $k;
2932 $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h)) * $k));
2934 if (strpos($border,'T') !== false) {
2936 $xk = ($x - $w) * $k;
2940 $xwk = ($x + $w) * $k;
2942 $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xwk, (($this->h - $y) * $k));
2944 if (strpos($border,'R') !== false) {
2948 $xk = ($x + $w) * $k;
2950 $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h))* $k));
2952 if (strpos($border,'B') !== false) {
2954 $xk = ($x - $w) * $k;
2958 $xwk = ($x + $w) * $k;
2960 $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - ($y + $h)) * $k), $xwk, (($this->h - ($y + $h)) * $k));
2965 $width = $this->GetStringWidth($txt);
2966 // ratio between cell lenght and text lenght
2967 $ratio = ($w - (2 * $this->cMargin)) / $width;
2969 // stretch text if required
2970 if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) {
2973 //Calculate character spacing in points
2974 $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1);
2975 //Set character spacing
2976 $rs .= sprintf('BT %.2f Tc ET ', $char_space);
2979 //Calculate horizontal scaling
2980 $horiz_scale = $ratio * 100.0;
2981 //Set horizontal scaling
2982 $rs .= sprintf('BT %.2f Tz ET ', $horiz_scale);
2985 $width = $w - (2 * $this->cMargin);
2989 if ($align == 'L') {
2991 $dx = $w - $width - $this->cMargin;
2993 $dx = $this->cMargin;
2995 } elseif ($align == 'R') {
2997 $dx = $this->cMargin;
2999 $dx = $w - $width - $this->cMargin;
3001 } elseif ($align == 'C') {
3002 $dx = ($w - $width) / 2;
3003 } elseif ($align == 'J') {
3005 $dx = $w - $width - $this->cMargin;
3007 $dx = $this->cMargin;
3010 $dx = $this->cMargin;
3012 if ($this->ColorFlag) {
3013 $s .= 'q '.$this->TextColor.' ';
3015 $txt2 = $this->_escapetext($txt);
3017 $xdk = ($this->x - $dx - $width) * $k;
3019 $xdk = ($this->x + $dx) * $k;
3022 if ($align == 'J') {
3023 // count number of spaces
3024 $ns = substr_count($txt, ' ');
3025 //if ($this->isunicode) {
3026 if (($this->CurrentFont['type'] == "TrueTypeUnicode") OR ($this->CurrentFont['type'] == "cidfont0")) {
3027 // get string width without spaces
3028 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
3029 // calculate average space width
3030 $spacewidth = ($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1) / $this->FontSize / $this->k;
3031 // set word position to be used with TJ operator
3032 $txt2 = str_replace(chr(0).' ', ') '.(-2830 * $spacewidth).' (', $txt2);
3035 $width = $this->GetStringWidth($txt);
3036 $spacewidth = (($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1)) * $this->k;
3037 $rs .= sprintf('BT %.3f Tw ET ', $spacewidth);
3040 // calculate approximate position of the font base line
3041 //$basefonty = $this->y + (($h + $this->FontAscent - $this->FontDescent)/2);
3042 $basefonty = $this->y + ($h/2) + ($this->FontSize/3);
3044 $s .= sprintf('BT %.2f %.2f Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
3046 $xdx = $this->x - $dx - $width;
3048 $xdx = $this->x + $dx;
3050 if ($this->underline) {
3051 $s .= ' '.$this->_dounderline($xdx, $basefonty, $txt);
3053 if ($this->linethrough) {
3054 $s .= ' '.$this->_dolinethrough($xdx, $basefonty, $txt);
3056 if ($this->ColorFlag) {
3060 $this->Link($xdx, $this->y + (($h - $this->FontSize)/2), $width, $this->FontSize, $link);
3067 // reset text stretching
3069 //Reset character horizontal spacing
3070 $rs .= ' BT 0 Tc ET';
3071 } elseif ($stretch > 0) {
3072 //Reset character horizontal scaling
3073 $rs .= ' BT 100 Tz ET';
3076 // reset word spacing
3077 if ((!$this->isunicode) AND ($align == 'J')) {
3078 $rs .= ' BT 0 Tw ET';
3082 //Go to the beginning of the next line
3086 $this->x = $this->w - $this->rMargin;
3088 $this->x = $this->lMargin;
3092 // go left or right by case
3099 $gstyles = $this->linestyleWidth." ".$this->linestyleCap." ".$this->linestyleJoin." ".$this->linestyleDash." ".$this->DrawColor." ".$this->FillColor."\n";
3105 * This method allows printing text with line breaks.
3106 * 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 />
3107 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
3108 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
3109 * @param float $h Cell minimum height. The cell extends automatically if needed.
3110 * @param string $txt String to print
3111 * @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>
3112 * @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>
3113 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3114 * @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>
3115 * @param int $x x position in user units
3116 * @param int $y y position in user units
3117 * @param boolean $reseth if true reset the last cell height (default true).
3118 * @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>
3119 * @param boolean $ishtml se to true if $txt is HTML content (default = false).
3120 * @return int Return the number of cells or 1 for html mode.
3122 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
3124 function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false) {
3125 if ((empty($this->lasth))OR ($reseth)) {
3127 $this->lasth = $this->FontSize * $this->cell_height_ratio;
3134 // check for page break
3135 $this->checkPageBreak($h);
3137 // get current page number
3138 $startpage = $this->page;
3144 if (empty($w) OR ($w <= 0)) {
3146 $w = $this->x - $this->lMargin;
3148 $w = $this->w - $this->rMargin - $this->x;
3151 // store original margin values
3152 $lMargin = $this->lMargin;
3153 $rMargin = $this->rMargin;
3155 $this->SetRightMargin($this->w - $this->x);
3156 $this->SetLeftMargin($this->x - $w);
3158 $this->SetLeftMargin($this->x);
3159 $this->SetRightMargin($this->w - $this->x - $w);
3161 // calculate remaining vertical space on first page ($startpage)
3162 $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin();
3163 // Adjust internal padding
3164 if ($this->cMargin < ($this->LineWidth / 2)) {
3165 $this->cMargin = ($this->LineWidth / 2);
3167 // Add top space if needed
3168 if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3169 $this->y += $this->LineWidth / 2;
3172 $this->y += $this->cMargin;
3175 $this->writeHTML($txt, true, 0, $reseth, true, $align);
3179 $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false);
3181 // add bottom padding
3182 $this->y += $this->cMargin;
3183 // Add bottom space if needed
3184 if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3185 $this->y += $this->LineWidth / 2;
3187 // Get end-of-text Y position
3188 $currentY = $this->GetY();
3189 // get latest page number
3190 $endpage = $this->page;
3191 // check if a new page has been created
3192 if ($endpage > $startpage) {
3193 // design borders around HTML cells.
3194 for ($page=$startpage; $page <= $endpage; $page++) {
3195 $this->setPage($page);
3196 if ($page == $startpage) {
3197 $this->SetY($this->getPageHeight() - $restspace - $this->getBreakMargin());
3199 } elseif ($page == $endpage) {
3200 $this->SetY($this->tMargin); // put cursor at the beginning of text
3201 $h = $currentY - $this->tMargin;
3203 $this->SetY($this->tMargin); // put cursor at the beginning of text
3204 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
3207 $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3208 if ($border OR $fill) {
3209 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3210 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3211 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3212 $this->intmrk[$this->page] += strlen($ccode."\n");
3216 $h = max($h, ($currentY - $y));
3217 // put cursor at the beginning of text
3220 $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3221 if ($border OR $fill) {
3222 // design a cell around the text
3223 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3224 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3225 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3226 $this->intmrk[$this->page] += strlen($ccode."\n");
3229 // Get end-of-cell Y position
3230 $currentY = $this->GetY();
3231 // restore original margin values
3232 $this->SetLeftMargin($lMargin);
3233 $this->SetRightMargin($rMargin);
3235 //Go to the beginning of the next line
3236 $this->SetY($currentY);
3238 $this->SetX($x + $w);
3241 // go left or right by case
3242 $this->setPage($startpage);
3244 $this->SetX($x + $w);
3250 * This method prints text from the current position.<br />
3251 * @param float $h Line height
3252 * @param string $txt String to print
3253 * @param mixed $link URL or identifier returned by AddLink()
3254 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
3255 * @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>
3256 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
3257 * @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>
3258 * @param boolean $firstline if true prints only the first line and return the remaining string.
3259 * @return mixed Return the number of cells or the remaining string if $firstline = true.
3262 function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false) {
3263 // remove carriage returns
3264 $s = str_replace("\r", '', $txt);
3265 // check if string contains arabic text
3266 if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
3271 // get array of chars
3272 $chars = $this->UTF8StringToArray($s);
3273 // get the number of characters
3274 $nb = count($chars);
3275 // handle single space character
3276 if (($nb == 1) AND preg_match("/[\s]/u", $s)) {
3278 $this->x -= $this->GetStringWidth($s);
3280 $this->x += $this->GetStringWidth($s);
3284 // store current position
3287 // calculate remaining line width ($w)
3289 $w = $this->x - $this->lMargin;
3291 $w = $this->w - $this->rMargin - $this->x;
3294 $wmax = $w - (2 * $this->cMargin);
3295 $i = 0; // character position
3296 $j = 0; // current starting position
3297 $sep = -1; // position of the last blank space
3298 $l = 0; // current string lenght
3299 $nl = 0; //number of lines
3301 // for each character
3303 //Get the current character
3305 if ($c == 10) { // 10 = "\n" = new line
3306 //Explicit line break
3307 if ($align == "J") {
3318 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3320 $this->endlinex = $startx - $linew;
3322 $this->endlinex = $startx + $linew;
3325 $tmpcmargin = $this->cMargin;
3328 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $talign, $fill, $link, $stretch);
3330 $this->cMargin = $tmpcmargin;
3331 return ($this->UTF8ArrSubString($chars, $i));
3337 $w = $this->getRemainingWidth();
3338 $wmax = $w - (2 * $this->cMargin);
3340 if (preg_match("/[\s]/u", $this->unichr($c))) {
3341 // update last blank space position
3344 // update string length
3345 if (($this->isunicode) AND ($arabic)) {
3346 // with bidirectional algorithm some chars may be changed affecting the line length
3347 // *** very slow ***
3348 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), $this->tmprtl));
3350 $l += $this->GetCharWidth($c);
3353 // we have reached the end of column
3355 // check if the line was already started
3356 if (($this->rtl AND ($this->x < ($this->w - $this->rMargin)))
3357 OR ((!$this->rtl) AND ($this->x > $this->lMargin))) {
3358 // print a void cell and go to next line
3359 $this->Cell($w, $h, "", 0, 1);
3362 return ($this->UTF8ArrSubString($chars, $j));
3365 // truncate the word because do not fit on column
3368 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3370 $this->endlinex = $startx - $linew;
3372 $this->endlinex = $startx + $linew;
3375 $tmpcmargin = $this->cMargin;
3378 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $align, $fill, $link, $stretch);
3380 $this->cMargin = $tmpcmargin;
3381 return ($this->UTF8ArrSubString($chars, $i));
3390 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $sep), $this->tmprtl));
3392 $this->endlinex = $startx - $linew;
3394 $this->endlinex = $startx + $linew;
3397 $tmpcmargin = $this->cMargin;
3400 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $sep), 0, 1, $align, $fill, $link, $stretch);
3402 $this->cMargin = $tmpcmargin;
3403 return ($this->UTF8ArrSubString($chars, $sep));
3409 $w = $this->getRemainingWidth();
3410 $wmax = $w - (2 * $this->cMargin);
3420 } // end while i < nb
3421 // print last substring (if any)
3452 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $nb), $this->tmprtl));
3454 $this->endlinex = $startx - $linew;
3456 $this->endlinex = $startx + $linew;
3459 $tmpcmargin = $this->cMargin;
3462 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $nb), 0, $ln, $align, $fill, $link, $stretch);
3464 $this->cMargin = $tmpcmargin;
3465 return ($this->UTF8ArrSubString($chars, $nb));
3476 * Returns the remaining width between the current position and margins.
3477 * @return int Return the remaining width
3480 function getRemainingWidth() {
3482 return ($this->x - $this->lMargin);
3484 return ($this->w - $this->rMargin - $this->x);
3489 * Extract a slice of the $strarr array and return it as string.
3490 * @param string $strarr The input array of characters.
3491 * @param int $start the starting element of $strarr.
3492 * @param int $end first element that will not be returned.
3493 * @return Return part of a string
3495 function UTF8ArrSubString($strarr, $start='', $end='') {
3496 if (strlen($start) == 0) {
3499 if (strlen($end) == 0) {
3500 $end = count($strarr);
3503 for ($i=$start; $i < $end; $i++) {
3504 $string .= $this->unichr($strarr[$i]);
3510 * Returns the unicode caracter specified by UTF-8 code
3511 * @param int $c UTF-8 code
3512 * @return Returns the specified character.
3513 * @author Miguel Perez, Nicola Asuni
3514 * @since 2.3.000 (2008-03-05)
3516 function unichr($c) {
3517 if (!$this->isunicode) {
3519 } elseif ($c <= 0x7F) {
3522 } elseif ($c <= 0x7FF) {
3524 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
3525 } elseif ($c <= 0xFFFF) {
3527 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3528 } elseif ($c <= 0x10FFFF) {
3530 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3537 * Puts an image in the page.
3538 * The upper-left corner must be given.
3539 * The dimensions can be specified in different ways:<ul>
3540 * <li>explicit width and height (expressed in user unit)</li>
3541 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
3542 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
3543 * 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;
3544 * The format can be specified explicitly or inferred from the file extension.<br />
3545 * It is possible to put a link on the image.<br />
3546 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
3547 * @param string $file Name of the file containing the image.
3548 * @param float $x Abscissa of the upper-left corner.
3549 * @param float $y Ordinate of the upper-left corner.
3550 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
3551 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
3552 * @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.
3553 * @param mixed $link URL or identifier returned by AddLink().
3554 * @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>
3555 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
3556 * @param int $dpi dot-per-inch resolution used on resize
3557 * @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>
3561 function Image($file, $x, $y, $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
3563 list($pixw, $pixh) = getimagesize($file);
3564 // calculate image width and height on document
3565 if (($w <= 0) AND ($h <= 0)) {
3566 // convert image size to document unit
3567 $w = $pixw / ($this->imgscale * $this->k);
3568 $h = $pixh / ($this->imgscale * $this->k);
3569 } elseif ($w <= 0) {
3570 $w = $h * $pixw / $pixh;
3571 } elseif ($h <= 0) {
3572 $h = $w * $pixh / $pixw;
3574 // calculate new minimum dimensions in pixels
3575 $neww = round($w * $this->k * $dpi / $this->dpi);
3576 $newh = round($h * $this->k * $dpi / $this->dpi);
3577 // check if resize is necessary (resize is used only to reduce the image)
3578 if (($neww * $newh) >= ($pixw * $pixh)) {
3581 // check if image has been already added on document
3582 if (!isset($this->images[$file])) {
3583 //First use of image, get info
3585 $fileinfo = pathinfo($file);
3586 if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
3587 $type = $fileinfo['extension'];
3589 $this->Error('Image file has no extension and no type was specified: '.$file);
3592 $type = strtolower($type);
3593 if ($type == "jpg") {
3596 $mqr = get_magic_quotes_runtime();
3597 set_magic_quotes_runtime(0);
3598 // Specific image handlers
3599 $mtd = '_parse'.$type;
3600 // GD image handler function
3601 $gdfunction = "imagecreatefrom".$type;
3603 if ((method_exists($this,$mtd)) AND (!($resize AND function_exists($gdfunction)))) {
3604 $info = $this->$mtd($file);
3607 if (function_exists($gdfunction)) {
3608 $img = $gdfunction($file);
3610 $imgr = imagecreatetruecolor($neww, $newh);
3611 imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
3612 $info = $this->_toJPEG($imgr);
3614 $info = $this->_toJPEG($img);
3620 if ($info === false) {
3621 //If false, we cannot process image
3624 set_magic_quotes_runtime($mqr);
3625 $info['i'] = count($this->images) + 1;
3626 // add image to document
3627 $this->images[$file] = $info;
3629 $info = $this->images[$file];
3631 // Check whether we need a new page first as this does not fit
3632 if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
3633 // Automatic page break
3634 $this->AddPage($this->CurOrientation);
3635 // Reset coordinates to top fo next page
3636 //$x = $this->GetX();
3637 $y = $this->GetY() + $this->cMargin;
3639 // 2007-10-19 Warren Sherliker: End Edit
3640 // set bottomcoordinates
3641 $this->img_rb_y = $y + $h;
3644 if ($palign == 'L') {
3645 $ximg = $this->lMargin;
3646 // set right side coordinate
3647 $this->img_rb_x = $ximg + $w;
3648 } elseif ($palign == 'C') {
3649 $ximg = ($this->w - $x - $w) / 2;
3650 // set right side coordinate
3651 $this->img_rb_x = $ximg + $w;
3653 $ximg = $this->w - $x - $w;
3654 // set left side coordinate
3655 $this->img_rb_x = $ximg;
3658 if ($palign == 'R') {
3659 $ximg = $this->w - $this->rMargin - $w;
3660 // set left side coordinate
3661 $this->img_rb_x = $ximg;
3662 } elseif ($palign == 'C') {
3663 $ximg = ($this->w - $x - $w) / 2;
3664 // set right side coordinate
3665 $this->img_rb_x = $ximg + $w;
3668 // set right side coordinate
3669 $this->img_rb_x = $ximg + $w;
3672 $xkimg = $ximg * $this->k;
3673 $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']));
3675 $this->Link($ximg, $y, $w, $h, $link);
3677 // set pointer to align the successive text/objects
3681 $this->x = $this->img_rb_x;
3685 $this->y = $y + round($h/2);
3686 $this->x = $this->img_rb_x;
3690 $this->y = $this->img_rb_y;
3691 $this->x = $this->img_rb_x;
3695 $this->SetY($this->img_rb_y);
3702 $this->endlinex = $this->img_rb_x;
3706 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
3707 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
3708 * @param string $file Image file name.
3709 * @param image $image Image object.
3710 * return image JPEG image object.
3713 function _toJPEG($image) {
3714 $tempname = tempnam(K_PATH_CACHE,'jpg');
3715 imagejpeg($image, $tempname, $this->jpeg_quality);
3716 imagedestroy($image);
3717 $retvars = $this->_parsejpeg($tempname);
3718 // tidy up by removing temporary image
3724 * Extract info from a JPEG file without using the GD library.
3725 * @param string $file image file to parse
3726 * @return array structure containing the image data
3729 function _parsejpeg($file) {
3730 $a = getimagesize($file);
3732 $this->Error('Missing or incorrect image file: '.$file);
3735 $this->Error('Not a JPEG file: '.$file);
3737 if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
3738 $colspace = 'DeviceRGB';
3739 } elseif ($a['channels'] == 4) {
3740 $colspace = 'DeviceCMYK';
3742 $colspace = 'DeviceGray';
3744 $bpc = isset($a['bits']) ? $a['bits'] : 8;
3745 $data = file_get_contents($file);
3746 return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
3750 * Extract info from a PNG file without using the GD library.
3751 * @param string $file image file to parse
3752 * @return array structure containing the image data
3755 function _parsepng($file) {
3756 $f = fopen($file,'rb');
3758 $this->Error('Can\'t open image file: '.$file);
3761 if (fread($f,8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3762 $this->Error('Not a PNG file: '.$file);
3766 if (fread($f,4) != 'IHDR') {
3767 $this->Error('Incorrect PNG file: '.$file);
3769 $w = $this->_freadint($f);
3770 $h = $this->_freadint($f);
3771 $bpc = ord(fread($f,1));
3773 //$this->Error('16-bit depth not supported: '.$file);
3776 $ct = ord(fread($f,1));
3778 $colspace = 'DeviceGray';
3779 } elseif ($ct == 2) {
3780 $colspace = 'DeviceRGB';
3781 } elseif ($ct == 3) {
3782 $colspace = 'Indexed';
3784 //$this->Error('Alpha channel not supported: '.$file);
3787 if (ord(fread($f,1)) != 0) {
3788 //$this->Error('Unknown compression method: '.$file);
3791 if (ord(fread($f,1)) != 0) {
3792 //$this->Error('Unknown filter method: '.$file);
3795 if (ord(fread($f,1)) != 0) {
3796 //$this->Error('Interlacing not supported: '.$file);
3800 $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
3801 //Scan chunks looking for palette, transparency and image data
3806 $n = $this->_freadint($f);
3807 $type = fread($f,4);
3808 if ($type == 'PLTE') {
3810 $pal = fread($f,$n);
3812 } elseif ($type == 'tRNS') {
3813 //Read transparency info
3816 $trns = array(ord(substr($t,1,1)));
3819 $trns = array(ord(substr($t,1,1)), ord(substr($t,3,1)), ord(substr($t,5,1)));
3821 $pos = strpos($t,chr(0));
3822 if ($pos !== false) {
3823 $trns = array($pos);
3827 } elseif ($type == 'IDAT') {
3828 //Read image data block
3829 $data .= fread($f,$n);
3831 } elseif ($type == 'IEND') {
3838 if (($colspace == 'Indexed') AND (empty($pal))) {
3839 //$this->Error('Missing palette in '.$file);
3843 return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
3847 * Performs a line break.
3848 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
3849 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
3850 * @param boolean $cell if true add a cMargin to the x coordinate
3854 function Ln($h='', $cell=false) {
3855 //Line feed; default value is last cell height
3857 $cellmargin = $this->cMargin;
3862 $this->x = $this->w - $this->rMargin - $cellmargin;
3864 $this->x = $this->lMargin + $cellmargin;
3866 if (is_string($h)) {
3867 $this->y += $this->lasth;
3871 $this->newline = true;
3875 * Returns the relative X value of current position.
3876 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
3879 * @see SetX(), GetY(), SetY()
3884 return ($this->w - $this->x);
3891 * Returns the absolute X value of current position.
3894 * @see SetX(), GetY(), SetY()
3896 function GetAbsX() {
3901 * Returns the ordinate of the current position.
3904 * @see SetY(), GetX(), SetX()
3912 * Defines the abscissa of the current position.
3913 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
3914 * @param float $x The value of the abscissa.
3916 * @see GetX(), GetY(), SetY(), SetXY()
3922 $this->x = $this->w - $x;
3930 $this->x = $this->w + $x;
3936 * Moves the current abscissa back to the left margin and sets the ordinate.
3937 * If the passed value is negative, it is relative to the bottom of the page.
3938 * @param float $y The value of the ordinate.
3940 * @see GetX(), GetY(), SetY(), SetXY()
3943 //Set y position and reset x
3945 $this->x = $this->w - $this->rMargin;
3947 $this->x = $this->lMargin;
3952 $this->y = $this->h + $y;
3957 * Defines the abscissa and ordinate of the current position.
3958 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
3959 * @param float $x The value of the abscissa
3960 * @param float $y The value of the ordinate
3962 * @see SetX(), SetY()
3964 function SetXY($x, $y) {
3965 //Set x and y positions
3971 * Send the document to a given destination: string, local file or browser.
3972 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
3973 * The method first calls Close() if necessary to terminate the document.
3974 * @param string $name The name of the file when saved.
3975 * @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>
3979 function Output($name='doc.pdf', $dest='I') {
3980 //Output PDF to some destination
3981 //Finish document if necessary
3982 if ($this->state < 3) {
3985 //Normalize parameters
3986 if (is_bool($dest)) {
3987 $dest = $dest ? 'D' : 'F';
3989 $dest = strtoupper($dest);
3991 $name = str_replace("+", "%20", urlencode($name));
3992 $name = preg_replace('/[\r\n]+\s*/', '' , $name);
3996 //Send to standard output
3997 if (ob_get_contents()) {
3998 $this->Error('Some data has already been output, can\'t send PDF file');
4000 if (php_sapi_name() != 'cli') {
4001 //We send to a browser
4002 header('Content-Type: application/pdf');
4003 if (headers_sent()) {
4004 $this->Error('Some data has already been output to browser, can\'t send PDF file');
4006 header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4007 header("Pragma: public");
4008 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4009 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
4010 header('Content-Length: '.strlen($this->buffer));
4011 header('Content-Disposition: inline; filename="'.basename($name).'";');
4018 if (ob_get_contents()) {
4019 $this->Error('Some data has already been output, can\'t send PDF file');
4021 header('Content-Description: File Transfer');
4022 if (headers_sent()) {
4023 $this->Error('Some data has already been output to browser, can\'t send PDF file');
4025 header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4026 header("Pragma: public");
4027 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4028 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
4029 // force download dialog
4030 header("Content-Type: application/force-download");
4031 header("Content-Type: application/octet-stream", false);
4032 header("Content-Type: application/download", false);
4033 // use the Content-Disposition header to supply a recommended filename
4034 header('Content-Disposition: attachment; filename="'.basename($name).'";');
4035 header("Content-Transfer-Encoding: binary");
4036 header("Content-Length: ".strlen($this->buffer));
4041 //Save to local file
4042 $f = fopen($name, 'wb');
4044 $this->Error('Unable to create output file: '.$name);
4046 fwrite($f, $this->buffer,strlen($this->buffer));
4051 //Return as a string
4052 return $this->buffer;
4055 $this->Error('Incorrect output destination: '.$dest);
4062 * Check for locale-related bug
4065 function _dochecks() {
4066 //Check for locale-related bug
4068 $this->Error('Don\'t alter the locale before including class file');
4070 //Check for decimal separator
4071 if (sprintf('%.1f', 1.0) != '1.0') {
4072 setlocale(LC_NUMERIC, 'C');
4081 function _getfontpath() {
4082 if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
4083 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
4085 return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
4092 function _putpages() {
4093 $nb = count($this->pages);
4094 if (!empty($this->pagegroups)) {
4095 // do page number replacement
4096 foreach ($this->pagegroups as $k => $v) {
4097 $vu = $this->UTF8ToUTF16BE($v, false);
4098 $alias_a = $this->_escape($k);
4099 $alias_au = $this->_escape("{".$k."}");
4100 if ($this->isunicode) {
4101 $alias_b = $this->_escape($this->UTF8ToLatin1($k));
4102 $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$k."}"));
4103 $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
4104 $alias_cu = $this->_escape($this->utf8StrRev("{".$k."}", false, $this->tmprtl));
4106 for ($n = 1; $n <= $nb; $n++) {
4107 $this->pages[$n] = str_replace($alias_au, $vu, $this->pages[$n]);
4108 if ($this->isunicode) {
4109 $this->pages[$n] = str_replace($alias_bu, $vu, $this->pages[$n]);
4110 $this->pages[$n] = str_replace($alias_cu, $vu, $this->pages[$n]);
4111 $this->pages[$n] = str_replace($alias_b, $v, $this->pages[$n]);
4112 $this->pages[$n] = str_replace($alias_c, $v, $this->pages[$n]);
4114 $this->pages[$n] = str_replace($alias_a, $v, $this->pages[$n]);
4118 if (!empty($this->AliasNbPages)) {
4119 $nbu = $this->UTF8ToUTF16BE($nb, false); // replacement for unicode font
4120 $alias_a = $this->_escape($this->AliasNbPages);
4121 $alias_au = $this->_escape("{".$this->AliasNbPages."}");
4122 if ($this->isunicode) {
4123 $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
4124 $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$this->AliasNbPages."}"));
4125 $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
4126 $alias_cu = $this->_escape($this->utf8StrRev("{".$this->AliasNbPages."}", false, $this->tmprtl));
4128 //Replace number of pages
4129 for($n = 1; $n <= $nb; $n++) {
4130 $this->pages[$n] = str_replace($alias_au, $nbu, $this->pages[$n]);
4131 if ($this->isunicode) {
4132 $this->pages[$n] = str_replace($alias_bu, $nbu, $this->pages[$n]);
4133 $this->pages[$n] = str_replace($alias_cu, $nbu, $this->pages[$n]);
4134 $this->pages[$n] = str_replace($alias_b, $nb, $this->pages[$n]);
4135 $this->pages[$n] = str_replace($alias_c, $nb, $this->pages[$n]);
4137 $this->pages[$n] = str_replace($alias_a, $nb, $this->pages[$n]);
4140 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4141 for($n=1; $n <= $nb; $n++) {
4144 $this->_out('<</Type /Page');
4145 $this->_out('/Parent 1 0 R');
4146 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
4147 $this->_out('/Resources 2 0 R');
4148 $this->_putannots($n);
4149 $this->_out('/Contents '.($this->n + 1).' 0 R>>');
4150 $this->_out('endobj');
4152 $p = ($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n];
4154 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
4155 $this->_putstream($p);
4156 $this->_out('endobj');
4159 $this->offsets[1] = strlen($this->buffer);
4160 $this->_out('1 0 obj');
4161 $this->_out('<</Type /Pages');
4163 for($i=0; $i < $nb; $i++) {
4164 $kids .= (3+2*$i).' 0 R ';
4166 $this->_out($kids.']');
4167 $this->_out('/Count '.$nb);
4168 //$this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
4170 $this->_out('endobj');
4174 * Output Page Annotations.
4175 * See section 8.4 of PDF reference.
4176 * @param int $n page number
4178 * @author Nicola Asuni
4179 * @since 4.0.018 (2008-08-06)
4181 function _putannots($n) {
4182 if (isset($this->PageAnnots[$n])) {
4183 $annots = '/Annots [';
4184 foreach ($this->PageAnnots[$n] as $key => $pl) {
4185 $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
4186 $a = $pl['x'] * $this->k;
4187 $b = $this->hPt - $pl['y'] * $this->k;
4188 $c = $pl['w'] * $this->k;
4189 $d = $pl['h'] * $this->k;
4190 $rect = sprintf('%.2f %.2f %.2f %.2f', $a, $b, $a+$c, $b-$d);
4191 $annots .= '<</Type /Annot';
4192 $annots .= ' /Subtype /'.$pl['opt']['subtype'];
4193 $annots .= ' /Rect ['.$rect.']';
4194 $annots .= ' /Contents '.$this->_textstring($pl['txt']);
4195 //$annots .= ' /P ';
4196 $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
4197 $annots .= ' /M '.$this->_datestring('D:'.date('YmdHis'));
4198 if (isset($pl['opt']['f'])) {
4200 if (is_array($pl['opt']['f'])) {
4201 foreach ($pl['opt']['f'] as $f) {
4202 switch (strtolower($f)) {
4235 case 'togglenoview': {
4239 case 'lockedcontents': {
4249 $annots .= ' /F '.intval($val);
4251 //$annots .= ' /AP ';
4252 //$annots .= ' /AS ';
4253 $annots .= ' /Border [';
4254 if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
4255 $annots .= intval($pl['opt']['border'][0]).' ';
4256 $annots .= intval($pl['opt']['border'][1]).' ';
4257 $annots .= intval($pl['opt']['border'][2]);
4258 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
4260 foreach ($pl['opt']['border'][3] as $dash) {
4261 $annots .= intval($dash).' ';
4269 if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
4270 $annots .= ' /BS <<Type /Border';
4271 if (isset($pl['opt']['bs']['w'])) {
4272 $annots .= ' /W '.sprintf("%.4f", floatval($pl['opt']['bs']['w']));
4274 $bstyles = array('S', 'D', 'B', 'I', 'U');
4275 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $markups)) {
4276 $annots .= ' /S /'.$pl['opt']['bs']['s'];
4278 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
4280 foreach ($pl['opt']['bs']['d'] as $cord) {
4281 $cord = floatval($cord);
4282 $annots .= sprintf(" %.4f", $cord);
4288 if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
4289 $annots .= ' /BE <<';
4290 $bstyles = array('S', 'C');
4291 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
4292 $annots .= ' /S /'.$pl['opt']['bs']['s'];
4294 $annots .= ' /S /S';
4296 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
4297 $annots .= ' /I '.sprintf(" %.4f", $pl['opt']['be']['i']);
4302 if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
4303 foreach ($pl['opt']['c'] as $col) {
4304 $col = intval($col);
4305 $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
4306 $annots .= sprintf(" %.4f", $color);
4310 //$annots .= ' /StructParent ';
4311 //$annots .= ' /OC ';
4312 $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
4313 if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
4314 // this is a markup type
4315 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
4316 $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
4318 //$annots .= ' /Popup ';
4319 if (isset($pl['opt']['ca'])) {
4320 $annots .= ' /CA '.sprintf("%.4f", floatval($pl['opt']['ca']));
4322 if (isset($pl['opt']['rc'])) {
4323 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4325 $annots .= ' /CreationDate '.$this->_datestring('D:'.date('YmdHis'));
4326 //$annots .= ' /IRT ';
4327 if (isset($pl['opt']['subj'])) {
4328 $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
4330 //$annots .= ' /RT ';
4331 //$annots .= ' /IT ';
4332 //$annots .= ' /ExData ';
4334 switch (strtolower($pl['opt']['subtype'])) {
4336 if (isset($pl['opt']['open'])) {
4337 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
4339 $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
4340 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
4341 $annots .= ' /Name /'.$pl['opt']['name'];
4343 $annots .= ' /Name /Note';
4345 $statemodels = array('Marked', 'Review');
4346 if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
4347 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4349 $pl['opt']['statemodel'] = 'Marked';
4350 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4352 if ($pl['opt']['statemodel'] == 'Marked') {
4353 $states = array('Accepted', 'Unmarked');
4355 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
4357 if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
4358 $annots .= ' /State /'.$pl['opt']['state'];
4360 if ($pl['opt']['statemodel'] == 'Marked') {
4361 $annots .= ' /State /Unmarked';
4363 $annots .= ' /State /None';
4369 $annots .= ' /A <</S /URI /URI '.$this->_uristring($pl['txt']).'>>';
4370 $hmodes = array('N', 'I', 'O', 'P');
4371 if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
4372 $annots .= ' /H /'.$pl['opt']['h'];
4374 $annots .= ' /H /I';
4376 //$annots .= ' /Dest ';
4377 //$annots .= ' /PA ';
4378 //$annots .= ' /Quadpoints ';
4382 $annots .= ' /DA '.$this->_textstring($pl['txt']);
4383 if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
4384 $annots .= ' /Q '.intval($pl['opt']['q']);
4386 if (isset($pl['opt']['rc'])) {
4387 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4389 if (isset($pl['opt']['ds'])) {
4390 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
4392 if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
4393 $annots .= ' /CL [';
4394 foreach ($pl['opt']['cl'] as $cl) {
4395 $annots .= sprintf("%.4f ", $cl * $this->k);
4399 $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
4400 if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
4401 $annots .= ' /IT '.$pl['opt']['it'];
4403 if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
4404 $l = $pl['opt']['rd'][0] * $this->k;
4405 $r = $pl['opt']['rd'][1] * $this->k;
4406 $t = $pl['opt']['rd'][2] * $this->k;
4407 $b = $pl['opt']['rd'][3] * $this->k;
4408 $annots .= ' /RD ['.sprintf('%.2f %.2f %.2f %.2f', $l, $r, $t, $b).']';
4410 //$annots .= ' /LE ';
4413 // ... to be completed ...
4453 case 'fileattachment': {
4468 case 'printermark': {
4487 $this->_out($annots.']');
4496 function _putfonts() {
4498 foreach($this->diffs as $diff) {
4501 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
4502 $this->_out('endobj');
4504 $mqr = get_magic_quotes_runtime();
4505 set_magic_quotes_runtime(0);
4506 foreach($this->FontFiles as $file => $info) {
4507 //Font file embedding
4509 $this->FontFiles[$file]['n'] = $this->n;
4510 $font = file_get_contents($this->_getfontpath().strtolower($file));
4511 $compressed = (substr($file,-2)=='.z');
4512 if ((!$compressed) AND (isset($info['length2']))) {
4513 $header = (ord($font{0}) == 128);
4515 //Strip first binary header
4516 $font = substr($font,6);
4518 if ($header AND (ord($font{$info['length1']}) == 128)) {
4519 //Strip second binary header
4520 $font = substr($font, 0, $info['length1']).substr($font, $info['length1']+6);
4523 $this->_out('<</Length '.strlen($font));
4525 $this->_out('/Filter /FlateDecode');
4527 $this->_out('/Length1 '.$info['length1']);
4528 if (isset($info['length2'])) {
4529 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
4532 $this->_putstream($font);
4533 $this->_out('endobj');
4535 set_magic_quotes_runtime($mqr);
4536 foreach($this->fonts as $k => $font) {
4538 $this->fonts[$k]['n'] = $this->n + 1;
4539 $type = $font['type'];
4540 $name = $font['name'];
4541 if ($type == 'core') {
4544 $this->_out('<</Type /Font');
4545 $this->_out('/BaseFont /'.$name);
4546 $this->_out('/Subtype /Type1');
4547 if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
4548 $this->_out('/Encoding /WinAnsiEncoding');
4551 $this->_out('endobj');
4552 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
4553 //Additional Type1 or TrueType font
4555 $this->_out('<</Type /Font');
4556 $this->_out('/BaseFont /'.$name);
4557 $this->_out('/Subtype /'.$type);
4558 $this->_out('/FirstChar 32 /LastChar 255');
4559 $this->_out('/Widths '.($this->n + 1).' 0 R');
4560 $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
4562 if (isset($font['diff'])) {
4563 $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
4565 $this->_out('/Encoding /WinAnsiEncoding');
4569 $this->_out('endobj');
4574 for($i=32; $i <= 255; $i++) {
4575 //$s .= $cw[chr($i)].' ';
4578 $this->_out($s.']');
4579 $this->_out('endobj');
4582 $s = '<</Type /FontDescriptor /FontName /'.$name;
4583 foreach($font['desc'] as $k => $v) {
4584 $s .= ' /'.$k.' '.$v;
4586 $file = $font['file'];
4588 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
4590 $this->_out($s.'>>');
4591 $this->_out('endobj');
4593 //Allow for additional types
4594 $mtd = '_put'.strtolower($type);
4595 if (!method_exists($this, $mtd)) {
4596 $this->Error('Unsupported font type: '.$type);
4604 * Output CID-0 fonts.
4605 * @param array $font font data
4607 * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
4608 * @since 3.2.000 (2008-06-23)
4610 function _putcidfont0($font) {
4611 if (isset($font['cidinfo']['uni2cid'])) {
4612 // convert unicode to cid.
4613 $uni2cid = $font['cidinfo']['uni2cid'];
4615 foreach ($font['cw'] as $uni => $width) {
4616 if (isset($uni2cid[$uni])) {
4617 $cw[($uni2cid[$uni] + 31)] = $width;
4618 } elseif ($uni <= 255) {
4620 } // else unknown character
4623 $font = array_merge($font, array('cw'=>$cw));
4625 $longname = $name = $font['name'];
4626 $enc = $font['enc'];
4628 $longname .= "-$enc";
4631 $this->_out('<</Type /Font');
4632 $this->_out('/BaseFont /'.$longname);
4633 $this->_out('/Subtype /Type0');
4635 $this->_out('/Encoding /'.$enc);
4637 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
4639 $this->_out('endobj');
4641 $this->_out('<</Type /Font');
4642 $this->_out('/BaseFont /'.$name);
4643 $this->_out('/Subtype /CIDFontType0');
4644 $cidinfo = '/Registry ('.$font['cidinfo']['Registry'].') ';
4645 $cidinfo .= '/Ordering ('.$font['cidinfo']['Ordering'].') ';
4646 $cidinfo .= '/Supplement '.$font['cidinfo']['Supplement'];
4647 $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
4648 $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
4649 $codes = array_keys($font['cw']);
4650 $first = current($codes);
4651 $last = end($codes);
4652 $this->_out('/DW '.$font['dw']);
4656 for($i = $first; $i <= $last; $i++) {
4657 if (isset($font['cw'][$i]) AND (!$currange)) {
4658 $currange = $i - 31;
4659 } elseif (!isset($font['cw'][$i])) {
4663 $ranges[$currange][] = $font['cw'][$i];
4666 foreach($ranges as $k => $ws) {
4667 $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
4672 $this->_out('endobj');
4674 $s = '<</Type /FontDescriptor /FontName /'.$name;
4675 foreach($font['desc'] as $k => $v) {
4676 $s .= ' /'.$k.' '.$v;
4678 $this->_out($s.'>>');
4679 $this->_out('endobj');
4686 function _putimages() {
4687 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4688 reset($this->images);
4689 while (list($file, $info) = each($this->images)) {
4691 $this->images[$file]['n'] = $this->n;
4692 $this->_out('<</Type /XObject');
4693 $this->_out('/Subtype /Image');
4694 $this->_out('/Width '.$info['w']);
4695 $this->_out('/Height '.$info['h']);
4696 if (isset($info["masked"])) {
4697 $this->_out('/SMask '.($this->n-1).' 0 R');
4699 if ($info['cs'] == 'Indexed') {
4700 $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal']) / 3 - 1).' '.($this->n + 1).' 0 R]');
4702 $this->_out('/ColorSpace /'.$info['cs']);
4703 if ($info['cs'] == 'DeviceCMYK') {
4704 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
4707 $this->_out('/BitsPerComponent '.$info['bpc']);
4708 if (isset($info['f'])) {
4709 $this->_out('/Filter /'.$info['f']);
4711 if (isset($info['parms'])) {
4712 $this->_out($info['parms']);
4714 if (isset($info['trns']) and is_array($info['trns'])) {
4716 for($i=0; $i < count($info['trns']); $i++) {
4717 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
4719 $this->_out('/Mask ['.$trns.']');
4721 $this->_out('/Length '.strlen($info['data']).'>>');
4722 $this->_putstream($info['data']);
4723 unset($this->images[$file]['data']);
4724 $this->_out('endobj');
4726 if ($info['cs'] == 'Indexed') {
4728 $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
4729 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
4730 $this->_putstream($pal);
4731 $this->_out('endobj');
4737 * Output Spot Colors Resources.
4739 * @since 4.0.024 (2008-09-12)
4741 function _putspotcolors() {
4742 foreach ($this->spot_colors as $name => $color) {
4744 $this->spot_colors[$name]['n'] = $this->n;
4745 $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
4746 $this->_out('/DeviceCMYK <<');
4747 $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
4748 $this->_out(sprintf('/C1 [%.4f %.4f %.4f %.4f] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
4749 $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
4750 $this->_out('endobj');
4755 * Output object dictionary for images.
4758 function _putxobjectdict() {
4759 foreach($this->images as $image) {
4760 $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
4765 * Output Resources Dictionary.
4768 function _putresourcedict(){
4769 $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
4770 $this->_out('/Font <<');
4771 foreach($this->fonts as $font) {
4772 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
4775 $this->_out('/XObject <<');
4776 $this->_putxobjectdict();
4779 $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
4781 $this->_out('/ExtGState <<');
4782 foreach($this->extgstates as $k => $extgstate) {
4783 $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
4787 if (isset($this->gradients) AND (count($this->gradients) > 0)) {
4788 $this->_out('/Shading <<');
4789 foreach($this->gradients as $id => $grad) {
4790 $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
4795 if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
4796 $this->_out('/ColorSpace <<');
4797 foreach ($this->spot_colors as $color) {
4798 $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
4808 function _putresources() {
4809 $this->_putextgstates();
4812 $this->_putimages();
4813 $this->_putspotcolors();
4814 $this->_putshaders();
4815 //Resource dictionary
4816 $this->offsets[2] = strlen($this->buffer);
4817 $this->_out('2 0 obj');
4819 $this->_putresourcedict();
4821 $this->_out('endobj');
4822 $this->_putjavascript();
4823 $this->_putbookmarks();
4825 if ($this->encrypted) {
4827 $this->enc_obj_id = $this->n;
4829 $this->_putencryption();
4831 $this->_out('endobj');
4836 * Adds some Metadata information
4837 * (see Chapter 10.2 of PDF Reference)
4840 function _putinfo() {
4841 if (!empty($this->title)) {
4842 $this->_out('/Title '.$this->_textstring($this->title));
4844 if (!empty($this->author)) {
4845 $this->_out('/Author '.$this->_textstring($this->author));
4847 if (!empty($this->subject)) {
4848 $this->_out('/Subject '.$this->_textstring($this->subject));
4850 if (!empty($this->keywords)) {
4851 $this->_out('/Keywords '.$this->_textstring($this->keywords));
4853 if (!empty($this->creator)) {
4854 $this->_out('/Creator '.$this->_textstring($this->creator));
4856 if (defined('PDF_PRODUCER')) {
4857 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
4859 $this->_out('/CreationDate '.$this->_datestring('D:'.date('YmdHis')));
4860 $this->_out('/ModDate '.$this->_datestring('D:'.date('YmdHis')));
4864 * Format a date string for meta information
4865 * @param string $s date string to escape.
4866 * @return string escaped string.
4869 function _datestring($s) {
4870 if ($this->encrypted) {
4871 $s = $this->_RC4($this->_objectkey($this->n), $s);
4873 return '('. $this->_escape($s).')';
4880 function _putcatalog() {
4881 $this->_out('/Type /Catalog');
4882 $this->_out('/Pages 1 0 R');
4884 if ($this->ZoomMode == 'fullpage') {
4885 $this->_out('/OpenAction [3 0 R /Fit]');
4886 } elseif ($this->ZoomMode == 'fullwidth') {
4887 $this->_out('/OpenAction [3 0 R /FitH null]');
4888 } elseif ($this->ZoomMode == 'real') {
4889 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
4890 } elseif (!is_string($this->ZoomMode)) {
4891 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
4893 if (isset($this->LayoutMode) AND (!empty($this->LayoutMode))) {
4894 $this->_out('/PageLayout /'.$this->LayoutMode.'');
4896 if (isset($this->PageMode) AND (!empty($this->PageMode))) {
4897 $this->_out('/PageMode /'.$this->PageMode);
4899 if (isset($this->l['a_meta_language'])) {
4900 $this->_out('/Lang /'.$this->l['a_meta_language']);
4902 if (!empty($this->javascript)) {
4903 $this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
4905 if (count($this->outlines) > 0) {
4906 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
4907 $this->_out('/PageMode /UseOutlines');
4909 $this->_putviewerpreferences();
4910 $p = $this->n_ocg_print.' 0 R';
4911 $v = $this->n_ocg_view.' 0 R';
4912 $as = "<</Event /Print /OCGs [".$p." ".$v."] /Category [/Print]>> <</Event /View /OCGs [".$p." ".$v."] /Category [/View]>>";
4913 $this->_out("/OCProperties <</OCGs [".$p." ".$v."] /D <</ON [".$p."] /OFF [".$v."] /AS [".$as."]>>>>");
4914 $this->_putuserrights();
4918 * Output viewer preferences.
4919 * @author Nicola asuni
4920 * @since 3.1.000 (2008-06-09)
4923 function _putviewerpreferences() {
4924 $this->_out('/ViewerPreferences<<');
4926 $this->_out('/Direction /R2L');
4928 $this->_out('/Direction /L2R');
4930 if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
4931 $this->_out('/HideToolbar true');
4933 if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
4934 $this->_out('/HideMenubar true');
4936 if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
4937 $this->_out('/HideWindowUI true');
4939 if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
4940 $this->_out('/FitWindow true');
4942 if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
4943 $this->_out('/CenterWindow true');
4945 if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
4946 $this->_out('/DisplayDocTitle true');
4948 if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
4949 $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
4951 if (isset($this->viewer_preferences['ViewArea'])) {
4952 $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
4954 if (isset($this->viewer_preferences['ViewClip'])) {
4955 $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
4957 if (isset($this->viewer_preferences['PrintArea'])) {
4958 $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
4960 if (isset($this->viewer_preferences['PrintClip'])) {
4961 $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
4963 if (isset($this->viewer_preferences['PrintScaling'])) {
4964 $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
4966 if (isset($this->viewer_preferences['Duplex']) AND (!empty($this->viewer_preferences['Duplex']))) {
4967 $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
4969 if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
4970 if ($this->viewer_preferences['PickTrayByPDFSize']) {
4971 $this->_out('/PickTrayByPDFSize true');
4973 $this->_out('/PickTrayByPDFSize false');
4976 if (isset($this->viewer_preferences['PrintPageRange'])) {
4977 $PrintPageRangeNum = "";
4978 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
4979 $PrintPageRangeNum .= " ".($v-1)."";
4981 $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
4983 if (isset($this->viewer_preferences['NumCopies'])) {
4984 $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
4993 function _puttrailer() {
4994 $this->_out('/Size '.($this->n + 1));
4995 $this->_out('/Root '.$this->n.' 0 R');
4996 $this->_out('/Info '.($this->n - 1).' 0 R');
4997 if ($this->encrypted) {
4998 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
4999 $this->_out('/ID [()()]');
5004 * Output PDF header.
5007 function _putheader() {
5008 $this->_out('%PDF-'.$this->PDFVersion);
5012 * Output end of document (EOF).
5015 function _enddoc() {
5016 $this->_putheader();
5018 $this->_putresources();
5024 $this->_out('endobj');
5028 $this->_putcatalog();
5030 $this->_out('endobj');
5032 $o = strlen($this->buffer);
5033 $this->_out('xref');
5034 $this->_out('0 '.($this->n + 1));
5035 $this->_out('0000000000 65535 f ');
5036 for($i=1; $i <= $this->n; $i++) {
5037 $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i]));
5040 $this->_out('trailer');
5042 $this->_puttrailer();
5044 $this->_out('startxref');
5046 $this->_out('%%EOF');
5051 * Initialize a new page.
5052 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
5053 * @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>
5056 function _beginpage($orientation='', $format='') {
5058 $this->pages[$this->page] = ""; // this mark should be removed before output
5060 if (empty($orientation)) {
5061 if (isset($this->CurOrientation)) {
5062 $orientation = $this->CurOrientation;
5067 if (!empty($format)) {
5068 $this->setPageFormat($format, $orientation);
5070 $this->setPageOrientation($orientation);
5073 $this->x = $this->w - $this->rMargin;
5075 $this->x = $this->lMargin;
5077 $this->y = $this->tMargin;
5078 if ($this->newpagegroup){
5079 // start a new group
5080 $n = sizeof($this->pagegroups) + 1;
5081 $alias = "{nb".$n."}";
5082 $this->pagegroups[$alias] = 1;
5083 $this->currpagegroup = $alias;
5084 $this->newpagegroup = false;
5085 } elseif ($this->currpagegroup) {
5086 $this->pagegroups[$this->currpagegroup]++;
5094 function _endpage() {
5095 $this->setVisibility("all");
5100 * Begin a new object.
5103 function _newobj() {
5105 $this->offsets[$this->n] = strlen($this->buffer);
5106 $this->_out($this->n.' 0 obj');
5111 * @param int $x X coordinate
5112 * @param int $y Y coordinate
5113 * @param string $txt text to underline
5116 function _dounderline($x, $y, $txt) {
5117 $up = $this->CurrentFont['up'];
5118 $ut = $this->CurrentFont['ut'];
5119 $w = $this->GetStringWidth($txt);
5120 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);
5124 * Line through text.
5125 * @param int $x X coordinate
5126 * @param int $y Y coordinate
5127 * @param string $txt text to underline
5130 function _dolinethrough($x, $y, $txt) {
5131 $up = $this->CurrentFont['up'];
5132 $ut = $this->CurrentFont['ut'];
5133 $w = $this->GetStringWidth($txt);
5134 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);
5138 * Read a 4-byte integer from file.
5139 * @param string $f file name.
5140 * @return 4-byte integer
5143 function _freadint($f) {
5144 $a = unpack('Ni', fread($f,4));
5149 * Format a text string for meta information
5150 * @param string $s string to escape.
5151 * @return string escaped string.
5154 function _textstring($s) {
5155 if ($this->isunicode) {
5156 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5157 $s = $this->UTF8ToLatin1($s);
5159 //Convert string to UTF-16BE
5160 $s = $this->UTF8ToUTF16BE($s, true);
5163 if ($this->encrypted) {
5164 $s = $this->_RC4($this->_objectkey($this->n), $s);
5166 return '('. $this->_escape($s).')';
5170 * Format an URI string
5171 * @param string $s string to escape.
5172 * @return string escaped string.
5175 function _uristring($s) {
5176 if ($this->encrypted) {
5177 $s = $this->_RC4($this->_objectkey($this->n), $s);
5179 return '('.$this->_escape($s).')';
5183 * Format a text string
5184 * @param string $s string to escape.
5185 * @return string escaped string.
5188 function _escapetext($s) {
5189 if ($this->isunicode) {
5190 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5191 $s = $this->UTF8ToLatin1($s);
5193 //Convert string to UTF-16BE and reverse RTL language
5194 $s = $this->utf8StrRev($s, false, $this->tmprtl);
5197 return $this->_escape($s);
5201 * Add "\" before "\", "(" and ")"
5202 * @param string $s string to escape.
5203 * @return string escaped string.
5206 function _escape($s) {
5207 // the chr(13) substitution fixes the Bugs item #1421290.
5208 return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
5213 * @param string $s string to output.
5216 function _putstream($s) {
5217 if ($this->encrypted) {
5218 $s = $this->_RC4($this->_objectkey($this->n), $s);
5220 $this->_out('stream');
5222 $this->_out('endstream');
5226 * Output a string to the document.
5227 * @param string $s string to output.
5231 if ($this->state == 2) {
5232 if (isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
5233 // puts data before page footer
5234 $page = substr($this->pages[$this->page], 0, -$this->footerlen[$this->page]);
5235 $footer = substr($this->pages[$this->page], -$this->footerlen[$this->page]);
5236 $this->pages[$this->page] = $page." ".$s."\n".$footer;
5238 $this->pages[$this->page] .= $s."\n";
5241 $this->buffer .= $s."\n";
5246 * Adds unicode fonts.<br>
5247 * Based on PDF Reference 1.3 (section 5)
5249 * @author Nicola Asuni
5250 * @since 1.52.0.TC005 (2005-01-05)
5252 function _puttruetypeunicode($font) {
5254 // A composite font composed of other fonts, organized hierarchically
5256 $this->_out('<</Type /Font');
5257 $this->_out('/Subtype /Type0');
5258 $this->_out('/BaseFont /'.$font['name'].'');
5259 $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.
5260 $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
5261 $this->_out('/ToUnicode '.($this->n + 2).' 0 R');
5263 $this->_out('endobj');
5265 // A CIDFont whose glyph descriptions are based on TrueType font technology
5267 $this->_out('<</Type /Font');
5268 $this->_out('/Subtype /CIDFontType2');
5269 $this->_out('/BaseFont /'.$font['name'].'');
5270 $this->_out('/CIDSystemInfo '.($this->n + 2).' 0 R');
5271 $this->_out('/FontDescriptor '.($this->n + 3).' 0 R');
5272 if (isset($font['desc']['MissingWidth'])){
5273 $this->_out('/DW '.$font['desc']['MissingWidth'].''); // The default width for glyphs in the CIDFont MissingWidth
5276 foreach ($font['cw'] as $cid => $width) {
5277 $w .= ''.$cid.' ['.$width.'] '; // define a specific width for each individual CID
5279 $this->_out('/W ['.$w.']'); // A description of the widths for the glyphs in the CIDFont
5280 $this->_out('/CIDToGIDMap '.($this->n + 4).' 0 R');
5282 $this->_out('endobj');
5284 // is a stream object that contains the definition of the CMap
5285 // (PDF Reference 1.3 chap. 5.9)
5287 $this->_out('<</Length 345>>');
5288 $this->_out('stream');
5289 $this->_out('/CIDInit /ProcSet findresource begin');
5290 $this->_out('12 dict begin');
5291 $this->_out('begincmap');
5292 $this->_out('/CIDSystemInfo');
5293 $this->_out('<</Registry (Adobe)');
5294 $this->_out('/Ordering (UCS)');
5295 $this->_out('/Supplement 0');
5296 $this->_out('>> def');
5297 $this->_out('/CMapName /Adobe-Identity-UCS def');
5298 $this->_out('/CMapType 2 def');
5299 $this->_out('1 begincodespacerange');
5300 $this->_out('<0000> <FFFF>');
5301 $this->_out('endcodespacerange');
5302 $this->_out('1 beginbfrange');
5303 $this->_out('<0000> <FFFF> <0000>');
5304 $this->_out('endbfrange');
5305 $this->_out('endcmap');
5306 $this->_out('CMapName currentdict /CMap defineresource pop');
5309 $this->_out('endstream');
5310 $this->_out('endobj');
5311 // CIDSystemInfo dictionary
5312 // A dictionary containing entries that define the character collection of the CIDFont.
5314 $this->_out('<</Registry (Adobe)'); // A string identifying an issuer of character collections
5315 $this->_out('/Ordering (UCS)'); // A string that uniquely names a character collection issued by a specific registry
5316 $this->_out('/Supplement 0'); // The supplement number of the character collection.
5318 $this->_out('endobj');
5320 // A font descriptor describing the CIDFont default metrics other than its glyph widths
5322 $this->_out('<</Type /FontDescriptor');
5323 $this->_out('/FontName /'.$font['name']);
5324 foreach ($font['desc'] as $key => $value) {
5325 $this->_out('/'.$key.' '.$value);
5327 if ($font['file']) {
5328 // A stream containing a TrueType font program
5329 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
5332 $this->_out('endobj');
5333 // Embed CIDToGIDMap
5334 // A specification of the mapping from CIDs to glyph indices
5336 $ctgfile = $this->_getfontpath().strtolower($font['ctg']);
5337 if (!file_exists($ctgfile)) {
5338 $this->Error('Font file not found: '.$ctgfile);
5340 $size = filesize($ctgfile);
5341 $this->_out('<</Length '.$size.'');
5342 if (substr($ctgfile, -2) == '.z') { // check file extension
5343 /* Decompresses data encoded using the public-domain
5344 zlib/deflate compression method, reproducing the
5345 original text or binary data */
5346 $this->_out('/Filter /FlateDecode');
5349 $this->_putstream(file_get_contents($ctgfile));
5350 $this->_out('endobj');
5354 * Converts UTF-8 strings to codepoints array.<br>
5355 * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
5356 * Based on: http://www.faqs.org/rfcs/rfc3629.html
5358 * Char. number range | UTF-8 octet sequence
5359 * (hexadecimal) | (binary)
5360 * --------------------+-----------------------------------------------
5361 * 0000 0000-0000 007F | 0xxxxxxx
5362 * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
5363 * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
5364 * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
5365 * ---------------------------------------------------------------------
5368 * ---------------------------------------------------------------------
5369 * UTF8-octets = *( UTF8-char )
5370 * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
5372 * UTF8-2 = %xC2-DF UTF8-tail
5374 * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
5375 * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
5376 * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
5377 * %xF4 %x80-8F 2( UTF8-tail )
5378 * UTF8-tail = %x80-BF
5379 * ---------------------------------------------------------------------
5381 * @param string $str string to process.
5382 * @return array containing codepoints (UTF-8 characters values)
5384 * @author Nicola Asuni
5385 * @since 1.53.0.TC005 (2005-01-05)
5387 function UTF8StringToArray($str) {
5388 if (!$this->isunicode) {
5389 // split string into array of equivalent codes
5391 $strlen = strlen($str);
5392 for($i=0; $i < $strlen; $i++) {
5393 $strarr[] = ord($str{$i});
5397 $unicode = array(); // array containing unicode values
5398 $bytes = array(); // array containing single character byte sequences
5399 $numbytes = 1; // number of octetc needed to represent the UTF-8 character
5400 $str .= ""; // force $str to be a string
5401 $length = strlen($str);
5402 for($i = 0; $i < $length; $i++) {
5403 $char = ord($str{$i}); // get one string character at time
5404 if (count($bytes) == 0) { // get starting octect
5405 if ($char <= 0x7F) {
5406 $unicode[] = $char; // use the character "as is" because is ASCII
5408 } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
5409 $bytes[] = ($char - 0xC0) << 0x06;
5411 } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
5412 $bytes[] = ($char - 0xE0) << 0x0C;
5414 } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
5415 $bytes[] = ($char - 0xF0) << 0x12;
5418 // use replacement character for other invalid sequences
5419 $unicode[] = 0xFFFD;
5423 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
5424 $bytes[] = $char - 0x80;
5425 if (count($bytes) == $numbytes) {
5426 // compose UTF-8 bytes to a single unicode value
5428 for($j = 1; $j < $numbytes; $j++) {
5429 $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
5431 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
5432 /* The definition of UTF-8 prohibits encoding character numbers between
5433 U+D800 and U+DFFF, which are reserved for use with the UTF-16
5434 encoding form (as surrogate pairs) and do not directly represent
5436 $unicode[] = 0xFFFD; // use replacement character
5438 $unicode[] = $char; // add char to array
5440 // reset data for next char
5445 // use replacement character for other invalid sequences
5446 $unicode[] = 0xFFFD;
5455 * Converts UTF-8 strings to UTF16-BE.<br>
5456 * @param string $str string to process.
5457 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5460 * @author Nicola Asuni
5461 * @since 1.53.0.TC005 (2005-01-05)
5462 * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
5464 function UTF8ToUTF16BE($str, $setbom=true) {
5465 if (!$this->isunicode) {
5466 return $str; // string is not in unicode
5468 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5469 return $this->arrUTF8ToUTF16BE($unicode, $setbom);
5473 * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
5474 * @param string $str string to process.
5476 * @author Andrew Whitehead, Nicola Asuni
5478 * @since 3.2.000 (2008-06-23)
5480 function UTF8ToLatin1($str) {
5481 if (!$this->isunicode) {
5482 return $str; // string is not in unicode
5484 $outstr = ""; // string to be returned
5485 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5486 foreach ($unicode as $char) {
5487 if ($char == 0xFFFD) {
5489 } elseif ($char == 0x2022) {
5491 $outstr .= chr(183);
5492 } elseif ($char < 256) {
5493 $outstr .= chr($char);
5502 * Converts array of UTF-8 characters to UTF16-BE string.<br>
5503 * Based on: http://www.faqs.org/rfcs/rfc2781.html
5507 * Encoding of a single character from an ISO 10646 character value to
5508 * UTF-16 proceeds as follows. Let U be the character number, no greater
5511 * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
5514 * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
5515 * U' must be less than or equal to 0xFFFFF. That is, U' can be
5516 * represented in 20 bits.
5518 * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
5519 * 0xDC00, respectively. These integers each have 10 bits free to
5520 * encode the character value, for a total of 20 bits.
5522 * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
5523 * bits of W1 and the 10 low-order bits of U' to the 10 low-order
5524 * bits of W2. Terminate.
5526 * Graphically, steps 2 through 4 look like:
5527 * U' = yyyyyyyyyyxxxxxxxxxx
5528 * W1 = 110110yyyyyyyyyy
5529 * W2 = 110111xxxxxxxxxx
5531 * @param array $unicode array containing UTF-8 unicode values
5532 * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5535 * @author Nicola Asuni
5536 * @since 2.1.000 (2008-01-08)
5537 * @see UTF8ToUTF16BE()
5539 function arrUTF8ToUTF16BE($unicode, $setbom=true) {
5540 $outstr = ""; // string to be returned
5542 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
5544 foreach($unicode as $char) {
5545 if ($char == 0xFFFD) {
5546 $outstr .= "\xFF\xFD"; // replacement character
5547 } elseif ($char < 0x10000) {
5548 $outstr .= chr($char >> 0x08);
5549 $outstr .= chr($char & 0xFF);
5552 $w1 = 0xD800 | ($char >> 0x10);
5553 $w2 = 0xDC00 | ($char & 0x3FF);
5554 $outstr .= chr($w1 >> 0x08);
5555 $outstr .= chr($w1 & 0xFF);
5556 $outstr .= chr($w2 >> 0x08);
5557 $outstr .= chr($w2 & 0xFF);
5562 // ====================================================
5566 * @param array $font font
5569 function setHeaderFont($font) {
5570 $this->header_font = $font;
5576 * @since 4.0.012 (2008-07-24)
5578 function getHeaderFont() {
5579 return $this->header_font;
5584 * @param array $font font
5587 function setFooterFont($font) {
5588 $this->footer_font = $font;
5594 * @since 4.0.012 (2008-07-24)
5596 function getFooterFont() {
5597 return $this->footer_font;
5601 * Set language array.
5602 * @param array $language
5605 function setLanguageArray($language) {
5606 $this->l = $language;
5607 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
5611 * Returns the PDF data.
5613 function getPDFData() {
5614 if ($this->state < 3) {
5617 return $this->buffer;
5622 * @param string $tag tag name in lowercase. Supported tags are:<ul>
5623 * <li>b : bold text</li>
5624 * <li>i : italic</li>
5625 * <li>u : underlined</li>
5626 * <li>d : line-through</li></ul>
5627 * @param boolean $enable
5630 function setStyle($tag, $enable) {
5631 $this->$tag += ($enable ? 1 : -1);
5633 foreach(array('b', 'i', 'u', 'd') as $s) {
5634 if ($this->$s > 0) {
5638 $this->SetFont('', $style);
5642 * Output anchor link.
5643 * @param string $url link URL
5644 * @param string $name link name
5645 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
5646 * @param boolean $firstline if true prints only the first line and return the remaining string.
5647 * @return the number of cells used or the remaining text if $firstline = true;
5650 function addHtmlLink($url, $name, $fill=0, $firstline=false) {
5651 $prevcolor = $this->fgcolor;
5652 $this->SetTextColor(0, 0, 255);
5653 $this->setStyle('u', true);
5654 $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
5655 $this->setStyle('u', false);
5656 $this->SetTextColorArray($prevcolor);
5661 * 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).
5662 * @param string $color html color
5666 function convertHTMLColorToDec($color="#000000") {
5668 $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
5669 // set default color to be returned in case of error
5670 $returncolor = array ('R' => 0, 'G' => 0, 'B' => 0);
5671 if (empty($color)) {
5672 return $returncolor;
5674 if (substr(strtolower($color), 0, 3) == 'rgb') {
5675 $codes = substr($color, 4);
5676 $codes = str_replace(')', '', $codes);
5677 $returncolor = explode(',', $codes, 3);
5678 return $returncolor;
5680 if (substr($color, 0, 1) != "#") {
5681 // decode color name
5682 if (isset($webcolor[strtolower($color)])) {
5683 $color_code = $webcolor[strtolower($color)];
5685 return $returncolor;
5688 $color_code = substr($color, 1);
5690 switch (strlen($color_code)) {
5692 // three-digit hexadecimal representation
5693 $r = substr($color_code, 0, 1);
5694 $g = substr($color_code, 1, 1);
5695 $b = substr($color_code, 2, 1);
5696 $returncolor['R'] = hexdec($r.$r);
5697 $returncolor['G'] = hexdec($g.$g);
5698 $returncolor['B'] = hexdec($b.$b);
5702 // six-digit hexadecimal representation
5703 $returncolor['R'] = hexdec(substr($color_code, 0, 2));
5704 $returncolor['G'] = hexdec(substr($color_code, 2, 2));
5705 $returncolor['B'] = hexdec(substr($color_code, 4, 2));
5709 return $returncolor;
5713 * Converts pixels to Units.
5714 * @param int $px pixels
5715 * @return float millimeters
5718 function pixelsToUnits($px){
5719 return $px / $this->k;
5723 * Reverse function for htmlentities.
5724 * Convert entities in UTF-8.
5725 * @param $text_to_convert Text to convert.
5726 * @return string converted
5728 function unhtmlentities($text_to_convert) {
5729 if (!$this->isunicode) {
5730 return html_entity_decode($text_to_convert);
5732 return html_entity_decode_php4($text_to_convert);
5735 // ENCRYPTION METHODS ----------------------------------
5736 // SINCE 2.0.000 (2008-01-02)
5738 * Compute encryption key depending on object number where the encrypted data is stored
5739 * @param int $n object number
5740 * @since 2.0.000 (2008-01-02)
5742 function _objectkey($n) {
5743 return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);
5747 * Put encryption on PDF document.
5748 * @since 2.0.000 (2008-01-02)
5750 function _putencryption() {
5751 $this->_out('/Filter /Standard');
5752 $this->_out('/V 1');
5753 $this->_out('/R 2');
5754 $this->_out('/O ('.$this->_escape($this->Ovalue).')');
5755 $this->_out('/U ('.$this->_escape($this->Uvalue).')');
5756 $this->_out('/P '.$this->Pvalue);
5760 * Returns the input text exrypted using RC4 algorithm and the specified key.
5761 * RC4 is the standard encryption algorithm used in PDF format
5762 * @param string $key encryption key
5763 * @param String $text input text to be encrypted
5764 * @return String encrypted text
5765 * @since 2.0.000 (2008-01-02)
5766 * @author Klemen Vodopivec
5768 function _RC4($key, $text) {
5769 if ($this->last_rc4_key != $key) {
5770 $k = str_repeat($key, 256/strlen($key)+1);
5771 $rc4 = range(0,255);
5773 for ($i=0; $i < 256; $i++) {
5775 $j = ($j + $t + ord($k{$i})) % 256;
5776 $rc4[$i] = $rc4[$j];
5779 $this->last_rc4_key = $key;
5780 $this->last_rc4_key_c = $rc4;
5782 $rc4 = $this->last_rc4_key_c;
5784 $len = strlen($text);
5788 for ($i=0; $i < $len; $i++) {
5789 $a = ($a + 1) % 256;
5791 $b = ($b + $t) % 256;
5792 $rc4[$a] = $rc4[$b];
5794 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
5795 $out .= chr(ord($text{$i}) ^ $k);
5801 * Encrypts a string using MD5 and returns it's value as a binary string.
5802 * @param string $str input string
5803 * @return String MD5 encrypted binary string
5804 * @since 2.0.000 (2008-01-02)
5805 * @author Klemen Vodopivec
5807 function _md5_16($str) {
5808 return pack('H*',md5($str));
5812 * Compute O value (used for RC4 encryption)
5813 * @param String $user_pass user password
5814 * @param String $owner_pass user password
5815 * @return String O value
5816 * @since 2.0.000 (2008-01-02)
5817 * @author Klemen Vodopivec
5819 function _Ovalue($user_pass, $owner_pass) {
5820 $tmp = $this->_md5_16($owner_pass);
5821 $owner_RC4_key = substr($tmp,0,5);
5822 return $this->_RC4($owner_RC4_key, $user_pass);
5826 * Compute U value (used for RC4 encryption)
5827 * @return String U value
5828 * @since 2.0.000 (2008-01-02)
5829 * @author Klemen Vodopivec
5831 function _Uvalue() {
5832 return $this->_RC4($this->encryption_key, $this->padding);
5836 * Compute encryption key
5837 * @param String $user_pass user password
5838 * @param String $owner_pass user password
5839 * @param String $protection protection type
5840 * @since 2.0.000 (2008-01-02)
5841 * @author Klemen Vodopivec
5843 function _generateencryptionkey($user_pass, $owner_pass, $protection) {
5845 $user_pass = substr($user_pass.$this->padding,0,32);
5846 $owner_pass = substr($owner_pass.$this->padding,0,32);
5848 $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
5849 // Compute encyption key
5850 $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
5851 $this->encryption_key = substr($tmp,0,5);
5853 $this->Uvalue = $this->_Uvalue();
5855 $this->Pvalue = -(($protection^255)+1);
5859 * Set document protection
5860 * The permission array is composed of values taken from the following ones:
5861 * - copy: copy text and images to the clipboard
5862 * - print: print the document
5863 * - modify: modify it (except for annotations and forms)
5864 * - annot-forms: add annotations and forms
5865 * Remark: the protection against modification is for people who have the full Acrobat product.
5866 * 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.
5867 * 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.
5868 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
5869 * @param String $user_pass user password. Empty by default.
5870 * @param String $owner_pass owner password. If not specified, a random value is used.
5871 * @since 2.0.000 (2008-01-02)
5872 * @author Klemen Vodopivec
5874 function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
5875 $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
5877 foreach($permissions as $permission) {
5878 if (!isset($options[$permission])) {
5879 $this->Error('Incorrect permission: '.$permission);
5881 $protection += $options[$permission];
5883 if ($owner_pass === null) {
5884 $owner_pass = uniqid(rand());
5886 $this->encrypted = true;
5887 $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
5890 // END OF ENCRYPTION FUNCTIONS -------------------------
5892 // START TRANSFORMATIONS SECTION -----------------------
5893 // authors: Moritz Wagner, Andreas Wurmser, Nicola Asuni
5896 * Starts a 2D tranformation saving current graphic state.
5897 * This function must be called before scaling, mirroring, translation, rotation and skewing.
5898 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5899 * @since 2.1.000 (2008-01-07)
5900 * @see StartTransform(), StopTransform()
5902 function StartTransform() {
5907 * Stops a 2D tranformation restoring previous graphic state.
5908 * This function must be called after scaling, mirroring, translation, rotation and skewing.
5909 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5910 * @since 2.1.000 (2008-01-07)
5911 * @see StartTransform(), StopTransform()
5913 function StopTransform() {
5917 * Horizontal Scaling.
5918 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5919 * @param int $x abscissa of the scaling center. Default is current x position
5920 * @param int $y ordinate of the scaling center. Default is current y position
5921 * @since 2.1.000 (2008-01-07)
5922 * @see StartTransform(), StopTransform()
5924 function ScaleX($s_x, $x='', $y=''){
5925 $this->Scale($s_x, 100, $x, $y);
5930 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5931 * @param int $x abscissa of the scaling center. Default is current x position
5932 * @param int $y ordinate of the scaling center. Default is current y position
5933 * @since 2.1.000 (2008-01-07)
5934 * @see StartTransform(), StopTransform()
5936 function ScaleY($s_y, $x='', $y=''){
5937 $this->Scale(100, $s_y, $x, $y);
5941 * Vertical and horizontal proportional Scaling.
5942 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
5943 * @param int $x abscissa of the scaling center. Default is current x position
5944 * @param int $y ordinate of the scaling center. Default is current y position
5945 * @since 2.1.000 (2008-01-07)
5946 * @see StartTransform(), StopTransform()
5948 function ScaleXY($s, $x='', $y=''){
5949 $this->Scale($s, $s, $x, $y);
5953 * Vertical and horizontal non-proportional Scaling.
5954 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5955 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5956 * @param int $x abscissa of the scaling center. Default is current x position
5957 * @param int $y ordinate of the scaling center. Default is current y position
5958 * @since 2.1.000 (2008-01-07)
5959 * @see StartTransform(), StopTransform()
5961 function Scale($s_x, $s_y, $x='', $y=''){
5971 if (($s_x == 0) OR ($s_y == 0)) {
5972 $this->Error('Please do not use values equal to zero for scaling');
5974 $y = ($this->h - $y) * $this->k;
5976 //calculate elements of transformation matrix
5983 $tm[4] = $x * (1 - $s_x);
5984 $tm[5] = $y * (1 - $s_y);
5985 //scale the coordinate system
5986 $this->Transform($tm);
5990 * Horizontal Mirroring.
5991 * @param int $x abscissa of the point. Default is current x position
5992 * @since 2.1.000 (2008-01-07)
5993 * @see StartTransform(), StopTransform()
5995 function MirrorH($x=''){
5996 $this->Scale(-100, 100, $x);
6000 * Verical Mirroring.
6001 * @param int $y ordinate of the point. Default is current y position
6002 * @since 2.1.000 (2008-01-07)
6003 * @see StartTransform(), StopTransform()
6005 function MirrorV($y=''){
6006 $this->Scale(100, -100, '', $y);
6010 * Point reflection mirroring.
6011 * @param int $x abscissa of the point. Default is current x position
6012 * @param int $y ordinate of the point. Default is current y position
6013 * @since 2.1.000 (2008-01-07)
6014 * @see StartTransform(), StopTransform()
6016 function MirrorP($x='',$y=''){
6017 $this->Scale(-100, -100, $x, $y);
6021 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
6022 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
6023 * @param int $x abscissa of the point. Default is current x position
6024 * @param int $y ordinate of the point. Default is current y position
6025 * @since 2.1.000 (2008-01-07)
6026 * @see StartTransform(), StopTransform()
6028 function MirrorL($angle=0, $x='',$y=''){
6029 $this->Scale(-100, 100, $x, $y);
6030 $this->Rotate(-2*($angle-90), $x, $y);
6034 * Translate graphic object horizontally.
6035 * @param int $t_x movement to the right (or left for RTL)
6036 * @since 2.1.000 (2008-01-07)
6037 * @see StartTransform(), StopTransform()
6039 function TranslateX($t_x){
6040 $this->Translate($t_x, 0);
6044 * Translate graphic object vertically.
6045 * @param int $t_y movement to the bottom
6046 * @since 2.1.000 (2008-01-07)
6047 * @see StartTransform(), StopTransform()
6049 function TranslateY($t_y){
6050 $this->Translate(0, $t_y);
6054 * Translate graphic object horizontally and vertically.
6055 * @param int $t_x movement to the right
6056 * @param int $t_y movement to the bottom
6057 * @since 2.1.000 (2008-01-07)
6058 * @see StartTransform(), StopTransform()
6060 function Translate($t_x, $t_y){
6064 //calculate elements of transformation matrix
6069 $tm[4] = $t_x * $this->k;
6070 $tm[5] = -$t_y * $this->k;
6071 //translate the coordinate system
6072 $this->Transform($tm);
6077 * @param float $angle angle in degrees for counter-clockwise rotation
6078 * @param int $x abscissa of the rotation center. Default is current x position
6079 * @param int $y ordinate of the rotation center. Default is current y position
6080 * @since 2.1.000 (2008-01-07)
6081 * @see StartTransform(), StopTransform()
6083 function Rotate($angle, $x='', $y=''){
6094 $y = ($this->h - $y) * $this->k;
6096 //calculate elements of transformation matrix
6097 $tm[0] = cos(deg2rad($angle));
6098 $tm[1] = sin(deg2rad($angle));
6101 $tm[4] = $x + $tm[1] * $y - $tm[0] * $x;
6102 $tm[5] = $y - $tm[0] * $y - $tm[1] * $x;
6103 //rotate the coordinate system around ($x,$y)
6104 $this->Transform($tm);
6108 * Skew horizontally.
6109 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6110 * @param int $x abscissa of the skewing center. default is current x position
6111 * @param int $y ordinate of the skewing center. default is current y position
6112 * @since 2.1.000 (2008-01-07)
6113 * @see StartTransform(), StopTransform()
6115 function SkewX($angle_x, $x='', $y=''){
6116 $this->Skew($angle_x, 0, $x, $y);
6121 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6122 * @param int $x abscissa of the skewing center. default is current x position
6123 * @param int $y ordinate of the skewing center. default is current y position
6124 * @since 2.1.000 (2008-01-07)
6125 * @see StartTransform(), StopTransform()
6127 function SkewY($angle_y, $x='', $y=''){
6128 $this->Skew(0, $angle_y, $x, $y);
6133 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6134 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6135 * @param int $x abscissa of the skewing center. default is current x position
6136 * @param int $y ordinate of the skewing center. default is current y position
6137 * @since 2.1.000 (2008-01-07)
6138 * @see StartTransform(), StopTransform()
6140 function Skew($angle_x, $angle_y, $x='', $y=''){
6149 $angle_x = -$angle_x;
6151 if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
6152 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
6155 $y = ($this->h - $y) * $this->k;
6156 //calculate elements of transformation matrix
6158 $tm[1] = tan(deg2rad($angle_y));
6159 $tm[2] = tan(deg2rad($angle_x));
6161 $tm[4] = -$tm[2] * $y;
6162 $tm[5] = -$tm[1] * $x;
6163 //skew the coordinate system
6164 $this->Transform($tm);
6168 * Apply graphic transformations.
6169 * @since 2.1.000 (2008-01-07)
6170 * @see StartTransform(), StopTransform()
6172 function Transform($tm){
6173 $this->_out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
6176 // END TRANSFORMATIONS SECTION -------------------------
6179 // START GRAPHIC FUNCTIONS SECTION ---------------------
6180 // The following section is based on the code provided by David Hernandez Sanz
6183 * 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.
6184 * @param float $width The width.
6186 * @see Line(), Rect(), Cell(), MultiCell()
6188 function SetLineWidth($width) {
6190 $this->LineWidth = $width;
6191 $this->linestyleWidth = sprintf('%.2f w', ($width * $this->k));
6192 $this->_out($this->linestyleWidth);
6196 * Returns the current the line width.
6197 * @return int Line width
6198 * @since 2.1.000 (2008-01-07)
6199 * @see Line(), SetLineWidth()
6201 function GetLineWidth() {
6202 return $this->LineWidth;
6207 * @param array $style Line style. Array with keys among the following:
6209 * <li>width (float): Width of the line in user units.</li>
6210 * <li>cap (string): Type of cap to put on the line. Possible values are:
6211 * butt, round, square. The difference between "square" and "butt" is that
6212 * "square" projects a flat end past the end of the line.</li>
6213 * <li>join (string): Type of join. Possible values are: miter, round,
6215 * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
6216 * series of length values, which are the lengths of the on and off dashes.
6217 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
6218 * 1 off, 2 on, 1 off, ...</li>
6219 * <li>phase (integer): Modifier on the dash pattern which is used to shift
6220 * the point at which the pattern starts.</li>
6221 * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
6224 * @since 2.1.000 (2008-01-08)
6226 function SetLineStyle($style) {
6228 if (isset($width)) {
6229 $width_prev = $this->LineWidth;
6230 $this->SetLineWidth($width);
6231 $this->LineWidth = $width_prev;
6234 $ca = array("butt" => 0, "round"=> 1, "square" => 2);
6235 if (isset($ca[$cap])) {
6236 $this->linestyleCap = $ca[$cap]." J";
6237 $this->_out($this->linestyleCap);
6241 $ja = array("miter" => 0, "round" => 1, "bevel" => 2);
6242 if (isset($ja[$join])) {
6243 $this->linestyleJoin = $ja[$join]." j";
6244 $this->_out($this->linestyleJoin);
6250 if (ereg("^.+,", $dash)) {
6251 $tab = explode(",", $dash);
6253 $tab = array($dash);
6256 foreach ($tab as $i => $v) {
6258 $dash_string .= " ";
6260 $dash_string .= sprintf("%.2f", $v);
6263 if (!isset($phase) OR !$dash) {
6266 $this->linestyleDash = sprintf("[%s] %.2f d", $dash_string, $phase);
6267 $this->_out($this->linestyleDash);
6269 if (isset($color)) {
6270 $this->SetDrawColorArray($color);
6276 * @param float $x Abscissa of point.
6277 * @param float $y Ordinate of point.
6279 * @since 2.1.000 (2008-01-08)
6281 function _outPoint($x, $y) {
6285 $this->_out(sprintf("%.2f %.2f m", $x * $this->k, ($this->h - $y) * $this->k));
6289 * Draws a line from last draw point.
6290 * @param float $x Abscissa of end point.
6291 * @param float $y Ordinate of end point.
6293 * @since 2.1.000 (2008-01-08)
6295 function _outLine($x, $y) {
6299 $this->_out(sprintf("%.2f %.2f l", $x * $this->k, ($this->h - $y) * $this->k));
6303 * Draws a rectangle.
6304 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6305 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6306 * @param float $w Width.
6307 * @param float $h Height.
6308 * @param string $op options
6310 * @since 2.1.000 (2008-01-08)
6312 function _outRect($x, $y, $w, $h, $op) {
6314 $x = $this->w - $x - $w;
6316 $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
6320 * Draws a Bezier curve from last draw point.
6321 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
6322 * @param float $x1 Abscissa of control point 1.
6323 * @param float $y1 Ordinate of control point 1.
6324 * @param float $x2 Abscissa of control point 2.
6325 * @param float $y2 Ordinate of control point 2.
6326 * @param float $x3 Abscissa of end point.
6327 * @param float $y3 Ordinate of end point.
6329 * @since 2.1.000 (2008-01-08)
6331 function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
6333 $x1 = $this->w - $x1;
6334 $x2 = $this->w - $x2;
6335 $x3 = $this->w - $x3;
6337 $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));
6341 * Draws a line between two points.
6342 * @param float $x1 Abscissa of first point.
6343 * @param float $y1 Ordinate of first point.
6344 * @param float $x2 Abscissa of second point.
6345 * @param float $y2 Ordinate of second point.
6346 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6349 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
6351 function Line($x1, $y1, $x2, $y2, $style=array()) {
6353 $this->SetLineStyle($style);
6355 $this->_outPoint($x1, $y1);
6356 $this->_outLine($x2, $y2);
6361 * Draws a rectangle.
6362 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6363 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6364 * @param float $w Width.
6365 * @param float $h Height.
6366 * @param string $style Style of rendering. Possible values are:
6368 * <li>D or empty string: Draw (default).</li>
6370 * <li>DF or FD: Draw and fill.</li>
6371 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6372 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6374 * @param array $border_style Border style of rectangle. Array with keys among the following:
6376 * <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
6377 * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
6379 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
6380 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6381 * @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).
6384 * @see SetLineStyle()
6386 function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
6387 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6388 $this->SetFillColorArray($fill_color);
6393 $border_style = array();
6394 $this->_outRect($x, $y, $w, $h, $op);
6399 if ((!$border_style) OR (isset($border_style["all"]))) {
6401 if (isset($border_style["all"])) {
6402 $this->SetLineStyle($border_style["all"]);
6403 $border_style = array();
6408 $this->_outRect($x, $y, $w, $h, $op);
6421 if ((!$border_style) OR (isset($border_style["all"]))) {
6422 if (isset($border_style["all"]) AND $border_style["all"]) {
6423 $this->SetLineStyle($border_style["all"]);
6424 $border_style = array();
6426 $this->_outRect($x, $y, $w, $h, $op);
6431 if ($border_style) {
6432 $border_style2 = array();
6433 foreach ($border_style as $line => $value) {
6434 $lenght = strlen($line);
6435 for ($i = 0; $i < $lenght; $i++) {
6436 $border_style2[$line[$i]] = $value;
6439 $border_style = $border_style2;
6440 if (isset($border_style["L"]) AND $border_style["L"]) {
6441 $this->Line($x, $y, $x, $y + $h, $border_style["L"]);
6443 if (isset($border_style["T"]) AND $border_style["T"]) {
6444 $this->Line($x, $y, $x + $w, $y, $border_style["T"]);
6446 if (isset($border_style["R"]) AND $border_style["R"]) {
6447 $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style["R"]);
6449 if (isset($border_style["B"]) AND $border_style["B"]) {
6450 $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style["B"]);
6457 * Draws a Bezier curve.
6458 * The Bezier curve is a tangent to the line between the control points at
6459 * either end of the curve.
6460 * @param float $x0 Abscissa of start point.
6461 * @param float $y0 Ordinate of start point.
6462 * @param float $x1 Abscissa of control point 1.
6463 * @param float $y1 Ordinate of control point 1.
6464 * @param float $x2 Abscissa of control point 2.
6465 * @param float $y2 Ordinate of control point 2.
6466 * @param float $x3 Abscissa of end point.
6467 * @param float $y3 Ordinate of end point.
6468 * @param string $style Style of rendering. Possible values are:
6470 * <li>D or empty string: Draw (default).</li>
6472 * <li>DF or FD: Draw and fill.</li>
6473 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6474 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6476 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6477 * @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).
6479 * @see SetLineStyle()
6480 * @since 2.1.000 (2008-01-08)
6482 function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style="", $line_style=array(), $fill_color=array()) {
6483 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6484 $this->SetFillColorArray($fill_color);
6489 $line_style = array();
6511 $this->SetLineStyle($line_style);
6513 $this->_outPoint($x0, $y0);
6514 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6519 * Draws a poly-Bezier curve.
6520 * Each Bezier curve segment is a tangent to the line between the control points at
6521 * either end of the curve.
6522 * @param float $x0 Abscissa of start point.
6523 * @param float $y0 Ordinate of start point.
6524 * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
6525 * @param string $style Style of rendering. Possible values are:
6527 * <li>D or empty string: Draw (default).</li>
6529 * <li>DF or FD: Draw and fill.</li>
6530 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6531 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6533 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6534 * @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).
6536 * @see SetLineStyle()
6537 * @since 3.0008 (2008-05-12)
6539 function Polycurve($x0, $y0, $segments, $style="", $line_style=array(), $fill_color=array()) {
6540 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6541 $this->SetFillColorArray($fill_color);
6546 $line_style = array();
6568 $this->SetLineStyle($line_style);
6570 $this->_outPoint($x0, $y0);
6571 foreach ($segments as $segment) {
6572 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
6573 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6580 * An ellipse is formed from n Bezier curves.
6581 * @param float $x0 Abscissa of center point.
6582 * @param float $y0 Ordinate of center point.
6583 * @param float $rx Horizontal radius.
6584 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
6585 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6586 * @param float $astart: Angle start of draw line. Default value: 0.
6587 * @param float $afinish: Angle finish of draw line. Default value: 360.
6588 * @param string $style Style of rendering. Possible values are:
6590 * <li>D or empty string: Draw (default).</li>
6592 * <li>DF or FD: Draw and fill.</li>
6593 * <li>C: Draw close.</li>
6594 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6595 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6597 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6598 * @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).
6599 * @param integer $nc Number of curves used in ellipse. Default value: 8.
6601 * @since 2.1.000 (2008-01-08)
6603 function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6605 $this->StartTransform();
6606 $this->Rotate($angle, $x0, $y0);
6607 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6608 $this->StopTransform();
6612 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6613 $this->SetFillColorArray($fill_color);
6618 $line_style = array();
6627 $op = "s"; // Small "s" signifies closing the path as well
6644 $this->SetLineStyle($line_style);
6654 $astart = deg2rad((float) $astart);
6655 $afinish = deg2rad((float) $afinish);
6656 $total_angle = $afinish - $astart;
6657 $dt = $total_angle / $nc;
6660 $y0 = ($this->h - $y0) * $this->k;
6662 $a0 = $x0 + ($rx * cos($t1));
6663 $b0 = $y0 + ($ry * sin($t1));
6664 $c0 = -$rx * sin($t1);
6665 $d0 = $ry * cos($t1);
6666 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
6667 for ($i = 1; $i <= $nc; $i++) {
6668 // Draw this bit of the total curve
6669 $t1 = ($i * $dt) + $astart;
6670 $a1 = $x0 + ($rx * cos($t1));
6671 $b1 = $y0 + ($ry * sin($t1));
6672 $c1 = -$rx * sin($t1);
6673 $d1 = $ry * cos($t1);
6674 $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));
6686 * A circle is formed from n Bezier curves.
6687 * @param float $x0 Abscissa of center point.
6688 * @param float $y0 Ordinate of center point.
6689 * @param float $r Radius.
6690 * @param float $astart: Angle start of draw line. Default value: 0.
6691 * @param float $afinish: Angle finish of draw line. Default value: 360.
6692 * @param string $style Style of rendering. Possible values are:
6694 * <li>D or empty string: Draw (default).</li>
6696 * <li>DF or FD: Draw and fill.</li>
6697 * <li>C: Draw close.</li>
6698 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6699 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6701 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6702 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6703 * @param integer $nc Number of curves used in circle. Default value: 8.
6705 * @since 2.1.000 (2008-01-08)
6707 function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6708 $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6713 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
6714 * @param string $style Style of rendering. Possible values are:
6716 * <li>D or empty string: Draw (default).</li>
6718 * <li>DF or FD: Draw and fill.</li>
6719 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6720 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6722 * @param array $line_style Line style of polygon. Array with keys among the following:
6724 * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
6725 * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
6727 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
6728 * @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).
6730 * @since 2.1.000 (2008-01-08)
6732 function Polygon($p, $style="", $line_style=array(), $fill_color=array()) {
6733 $np = count($p) / 2;
6734 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6735 $this->SetFillColorArray($fill_color);
6739 $line_style = array();
6763 if (isset($line_style["all"])) {
6764 $this->SetLineStyle($line_style["all"]);
6765 } else { // 0 .. (np - 1), op = {B, S}
6769 $this->_outPoint($p[0], $p[1]);
6770 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6771 $this->_outLine($p[$i], $p[$i + 1]);
6773 $this->_outLine($p[0], $p[1]);
6776 $p[($np * 2)] = $p[0];
6777 $p[(($np * 2) + 1)] = $p[1];
6778 for ($i = 0; $i < $np; $i++) {
6779 if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
6780 $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
6786 $this->_outPoint($p[0], $p[1]);
6787 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6788 $this->_outLine($p[$i], $p[$i + 1]);
6790 $this->_outLine($p[0], $p[1]);
6796 * Draws a regular polygon.
6797 * @param float $x0 Abscissa of center point.
6798 * @param float $y0 Ordinate of center point.
6799 * @param float $r: Radius of inscribed circle.
6800 * @param integer $ns Number of sides.
6801 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
6802 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
6803 * @param string $style Style of rendering. Possible values are:
6805 * <li>D or empty string: Draw (default).</li>
6807 * <li>DF or FD: Draw and fill.</li>
6808 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6809 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6811 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6813 * <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
6814 * <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6816 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6817 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6818 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6820 * <li>D or empty string: Draw (default).</li>
6822 * <li>DF or FD: Draw and fill.</li>
6823 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6824 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6826 * @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).
6827 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6829 * @since 2.1.000 (2008-01-08)
6831 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()) {
6836 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6839 for ($i = 0; $i < $ns; $i++) {
6840 $a = $angle + ($i * 360 / $ns);
6841 $a_rad = deg2rad((float) $a);
6842 $p[] = $x0 + ($r * sin($a_rad));
6843 $p[] = $y0 + ($r * cos($a_rad));
6845 $this->Polygon($p, $style, $line_style, $fill_color);
6849 * Draws a star polygon
6850 * @param float $x0 Abscissa of center point.
6851 * @param float $y0 Ordinate of center point.
6852 * @param float $r Radius of inscribed circle.
6853 * @param integer $nv Number of vertices.
6854 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
6855 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6856 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
6857 * @param string $style Style of rendering. Possible values are:
6859 * <li>D or empty string: Draw (default).</li>
6861 * <li>DF or FD: Draw and fill.</li>
6862 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6863 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6865 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6867 * <li>all: Line style of all sides. Array like for
6868 * {@link SetLineStyle SetLineStyle}.</li>
6869 * <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6871 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6872 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6873 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6875 * <li>D or empty string: Draw (default).</li>
6877 * <li>DF or FD: Draw and fill.</li>
6878 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6879 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6881 * @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).
6882 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6884 * @since 2.1.000 (2008-01-08)
6886 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()) {
6891 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6895 for ($i = 0; $i < $nv; $i++) {
6896 $a = $angle + ($i * 360 / $nv);
6897 $a_rad = deg2rad((float) $a);
6898 $p2[] = $x0 + ($r * sin($a_rad));
6899 $p2[] = $y0 + ($r * cos($a_rad));
6906 $p[] = $p2[($i * 2) + 1];
6907 $visited[$i] = true;
6910 } while (!$visited[$i]);
6911 $this->Polygon($p, $style, $line_style, $fill_color);
6915 * Draws a rounded rectangle.
6916 * @param float $x Abscissa of upper-left corner.
6917 * @param float $y Ordinate of upper-left corner.
6918 * @param float $w Width.
6919 * @param float $h Height.
6920 * @param float $r Radius of the rounded corners.
6921 * @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").
6922 * @param string $style Style of rendering. Possible values are:
6924 * <li>D or empty string: Draw (default).</li>
6926 * <li>DF or FD: Draw and fill.</li>
6927 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6928 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6930 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6931 * @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).
6933 * @since 2.1.000 (2008-01-08)
6935 function RoundedRect($x, $y, $w, $h, $r, $round_corner="1111", $style="", $border_style=array(), $fill_color=array()) {
6936 if ("0000" == $round_corner) { // Not rounded
6937 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
6939 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6940 $this->SetFillColorArray($fill_color);
6944 $border_style = array();
6966 if ($border_style) {
6967 $this->SetLineStyle($border_style);
6969 $MyArc = 4 / 3 * (sqrt(2) - 1);
6970 $this->_outPoint($x + $r, $y);
6973 $this->_outLine($xc, $y);
6974 if ($round_corner[0]) {
6975 $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
6977 $this->_outLine($x + $w, $y);
6981 $this->_outLine($x + $w, $yc);
6982 if ($round_corner[1]) {
6983 $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
6985 $this->_outLine($x + $w, $y + $h);
6989 $this->_outLine($xc, $y + $h);
6990 if ($round_corner[2]) {
6991 $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
6993 $this->_outLine($x, $y + $h);
6997 $this->_outLine($x, $yc);
6998 if ($round_corner[3]) {
6999 $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
7001 $this->_outLine($x, $y);
7002 $this->_outLine($x + $r, $y);
7008 // END GRAPHIC FUNCTIONS SECTION -----------------------
7010 // BIDIRECTIONAL TEXT SECTION --------------------------
7012 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7013 * @param string $str string to manipulate.
7014 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7016 * @author Nicola Asuni
7017 * @since 2.1.000 (2008-01-08)
7019 function utf8StrRev($str, $setbom=false, $forcertl=false) {
7020 return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $forcertl), $setbom);
7024 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7025 * @param array $ta array of characters composing the string.
7026 * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7028 * @author Nicola Asuni
7029 * @since 2.4.000 (2008-03-06)
7031 function utf8Bidi($ta, $forcertl=false) {
7032 global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
7033 // paragraph embedding level
7037 // create string from array
7038 $str = $this->UTF8ArrSubString($ta);
7039 // check if string contains arabic text
7040 if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
7045 // check if string contains RTL text
7046 if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
7050 // get number of chars
7051 $numchars = count($ta);
7053 if ($forcertl == 'R') {
7055 } elseif ($forcertl == 'L') {
7058 // P2. In each paragraph, find the first character of type L, AL, or R.
7059 // 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.
7060 for ($i=0; $i < $numchars; $i++) {
7061 $type = $unicode[$ta[$i]];
7065 } elseif (($type == 'AL') OR ($type == 'R')) {
7072 // Current Embedding Level
7074 // directional override status
7076 $remember = array();
7077 // start-of-level-run
7078 $sor = $pel % 2 ? 'R' : 'L';
7081 //$levels = array(array('level' => $cel, 'sor' => $sor, 'eor' => '', 'chars' => array()));
7082 //$current_level = &$levels[count( $levels )-1];
7084 // Array of characters data
7085 $chardata = Array();
7087 // 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.
7088 // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
7089 for ($i=0; $i < $numchars; $i++) {
7090 if ($ta[$i] == K_RLE) {
7091 // X2. With each RLE, compute the least greater odd embedding level.
7092 // 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.
7093 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7094 $next_level = $cel + ($cel % 2) + 1;
7095 if ($next_level < 62) {
7096 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
7100 $eor = $cel % 2 ? 'R' : 'L';
7102 } elseif ($ta[$i] == K_LRE) {
7103 // X3. With each LRE, compute the least greater even embedding level.
7104 // 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.
7105 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7106 $next_level = $cel + 2 - ($cel % 2);
7107 if ( $next_level < 62 ) {
7108 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
7112 $eor = $cel % 2 ? 'R' : 'L';
7114 } elseif ($ta[$i] == K_RLO) {
7115 // X4. With each RLO, compute the least greater odd embedding level.
7116 // 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.
7117 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7118 $next_level = $cel + ($cel % 2) + 1;
7119 if ($next_level < 62) {
7120 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
7124 $eor = $cel % 2 ? 'R' : 'L';
7126 } elseif ($ta[$i] == K_LRO) {
7127 // X5. With each LRO, compute the least greater even embedding level.
7128 // 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.
7129 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7130 $next_level = $cel + 2 - ($cel % 2);
7131 if ( $next_level < 62 ) {
7132 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
7136 $eor = $cel % 2 ? 'R' : 'L';
7138 } elseif ($ta[$i] == K_PDF) {
7139 // 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.
7140 if (count($remember)) {
7141 $last = count($remember ) - 1;
7142 if (($remember[$last]['num'] == K_RLE) OR
7143 ($remember[$last]['num'] == K_LRE) OR
7144 ($remember[$last]['num'] == K_RLO) OR
7145 ($remember[$last]['num'] == K_LRO)) {
7146 $match = array_pop($remember);
7147 $cel = $match['cel'];
7148 $dos = $match['dos'];
7150 $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
7153 } elseif (($ta[$i] != K_RLE) AND
7154 ($ta[$i] != K_LRE) AND
7155 ($ta[$i] != K_RLO) AND
7156 ($ta[$i] != K_LRO) AND
7157 ($ta[$i] != K_PDF)) {
7158 // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
7159 // a. Set the level of the current character to the current embedding level.
7160 // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
7164 $chardir = $unicode[$ta[$i]];
7166 // stores string characters and other information
7167 $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
7169 } // end for each char
7171 // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
7172 // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
7173 // 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.
7175 // 3.3.3 Resolving Weak Types
7176 // 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.
7177 // Nonspacing marks are now resolved based on the previous characters.
7178 $numchars = count($chardata);
7180 // 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.
7181 $prevlevel = -1; // track level changes
7182 $levcount = 0; // counts consecutive chars at the same level
7183 for ($i=0; $i < $numchars; $i++) {
7184 if ($chardata[$i]['type'] == 'NSM') {
7186 $chardata[$i]['type'] = $chardata[$i]['sor'];
7188 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
7191 if ($chardata[$i]['level'] != $prevlevel) {
7196 $prevlevel = $chardata[$i]['level'];
7199 // 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.
7202 for ($i=0; $i < $numchars; $i++) {
7203 if ($chardata[$i]['char'] == 'EN') {
7204 for ($j=$levcount; $j >= 0; $j--) {
7205 if ($chardata[$j]['type'] == 'AL') {
7206 $chardata[$i]['type'] = 'AN';
7207 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
7212 if ($chardata[$i]['level'] != $prevlevel) {
7217 $prevlevel = $chardata[$i]['level'];
7220 // W3. Change all ALs to R.
7221 for ($i=0; $i < $numchars; $i++) {
7222 if ($chardata[$i]['type'] == 'AL') {
7223 $chardata[$i]['type'] = 'R';
7227 // 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.
7230 for ($i=0; $i < $numchars; $i++) {
7231 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7232 if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7233 $chardata[$i]['type'] = 'EN';
7234 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7235 $chardata[$i]['type'] = 'EN';
7236 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
7237 $chardata[$i]['type'] = 'AN';
7240 if ($chardata[$i]['level'] != $prevlevel) {
7245 $prevlevel = $chardata[$i]['level'];
7248 // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
7251 for ($i=0; $i < $numchars; $i++) {
7252 if ($chardata[$i]['type'] == 'ET') {
7253 if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
7254 $chardata[$i]['type'] = 'EN';
7257 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
7258 if ($chardata[$j]['type'] == 'EN') {
7259 $chardata[$i]['type'] = 'EN';
7261 } elseif ($chardata[$j]['type'] != 'ET') {
7268 if ($chardata[$i]['level'] != $prevlevel) {
7273 $prevlevel = $chardata[$i]['level'];
7276 // W6. Otherwise, separators and terminators change to Other Neutral.
7279 for ($i=0; $i < $numchars; $i++) {
7280 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
7281 $chardata[$i]['type'] = 'ON';
7283 if ($chardata[$i]['level'] != $prevlevel) {
7288 $prevlevel = $chardata[$i]['level'];
7291 //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.
7294 for ($i=0; $i < $numchars; $i++) {
7295 if ($chardata[$i]['char'] == 'EN') {
7296 for ($j=$levcount; $j >= 0; $j--) {
7297 if ($chardata[$j]['type'] == 'L') {
7298 $chardata[$i]['type'] = 'L';
7299 } elseif ($chardata[$j]['type'] == 'R') {
7304 if ($chardata[$i]['level'] != $prevlevel) {
7309 $prevlevel = $chardata[$i]['level'];
7312 // 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.
7315 for ($i=0; $i < $numchars; $i++) {
7316 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7317 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7318 $chardata[$i]['type'] = 'L';
7319 } elseif (($chardata[$i]['type'] == 'N') AND
7320 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7321 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7322 $chardata[$i]['type'] = 'R';
7323 } elseif ($chardata[$i]['type'] == 'N') {
7324 // N2. Any remaining neutrals take the embedding direction
7325 $chardata[$i]['type'] = $chardata[$i]['sor'];
7327 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7329 if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7330 $chardata[$i]['type'] = 'L';
7331 } elseif (($chardata[$i]['type'] == 'N') AND
7332 (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
7333 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7334 $chardata[$i]['type'] = 'R';
7335 } elseif ($chardata[$i]['type'] == 'N') {
7336 // N2. Any remaining neutrals take the embedding direction
7337 $chardata[$i]['type'] = $chardata[$i]['sor'];
7339 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
7341 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
7342 $chardata[$i]['type'] = 'L';
7343 } elseif (($chardata[$i]['type'] == 'N') AND
7344 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7345 (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
7346 $chardata[$i]['type'] = 'R';
7347 } elseif ($chardata[$i]['type'] == 'N') {
7348 // N2. Any remaining neutrals take the embedding direction
7349 $chardata[$i]['type'] = $chardata[$i]['sor'];
7351 } elseif ($chardata[$i]['type'] == 'N') {
7352 // N2. Any remaining neutrals take the embedding direction
7353 $chardata[$i]['type'] = $chardata[$i]['sor'];
7355 if ($chardata[$i]['level'] != $prevlevel) {
7360 $prevlevel = $chardata[$i]['level'];
7363 // 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.
7364 // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
7365 for ($i=0; $i < $numchars; $i++) {
7366 $odd = $chardata[$i]['level'] % 2;
7368 if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7369 $chardata[$i]['level'] += 1;
7372 if ($chardata[$i]['type'] == 'R') {
7373 $chardata[$i]['level'] += 1;
7374 } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7375 $chardata[$i]['level'] += 2;
7378 $maxlevel = max($chardata[$i]['level'],$maxlevel);
7381 // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
7382 // 1. Segment separators,
7383 // 2. Paragraph separators,
7384 // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
7385 // 4. Any sequence of white space characters at the end of the line.
7386 for ($i=0; $i < $numchars; $i++) {
7387 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
7388 $chardata[$i]['level'] = $pel;
7389 } elseif ($chardata[$i]['type'] == 'WS') {
7391 while ($j < $numchars) {
7392 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
7393 (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
7394 $chardata[$i]['level'] = $pel;
7396 } elseif ($chardata[$j]['type'] != 'WS') {
7405 // 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.
7407 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
7408 $alfletter = array(1570,1571,1573,1575);
7409 $chardata2 = $chardata;
7413 for ($i=0; $i < $numchars; $i++) {
7414 if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
7415 $charAL[$x] = $chardata[$i];
7416 $charAL[$x]['i'] = $i;
7417 $chardata[$i]['x'] = $x;
7422 for ($i=0; $i < $numchars; $i++) {
7423 $thischar = $chardata[$i];
7425 $prevchar = $chardata[($i-1)];
7429 if (($i+1) < $numchars) {
7430 $nextchar = $chardata[($i+1)];
7434 if ($unicode[$thischar['char']] == 'AL') {
7435 $x = $thischar['x'];
7437 $prevchar = $charAL[($x-1)];
7441 if (($x+1) < $numAL) {
7442 $nextchar = $charAL[($x+1)];
7447 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
7448 $arabicarr = $laa_array;
7451 $prevchar = $charAL[($x-2)];
7456 $arabicarr = $unicode_arlet;
7459 if (($prevchar !== false) AND ($nextchar !== false) AND
7460 (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7461 (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7462 ($prevchar['type'] == $thischar['type']) AND
7463 ($nextchar['type'] == $thischar['type']) AND
7464 ($nextchar['char'] != 1567)) {
7465 if (in_array($prevchar['char'], $endedletter)) {
7466 if (isset($arabicarr[$thischar['char']][2])) {
7468 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7471 if (isset($arabicarr[$thischar['char']][3])) {
7473 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
7476 } elseif (($nextchar !== false) AND
7477 (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7478 ($nextchar['type'] == $thischar['type']) AND
7479 ($nextchar['char'] != 1567)) {
7480 if (isset($arabicarr[$chardata[$i]['char']][2])) {
7482 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7484 } elseif ((($prevchar !== false) AND
7485 (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7486 ($prevchar['type'] == $thischar['type'])) OR
7487 (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
7489 if (($i > 1) AND ($thischar['char'] == 1607) AND
7490 ($chardata[$i-1]['char'] == 1604) AND
7491 ($chardata[$i-2]['char'] == 1604)) {
7493 // mark characters to delete with false
7494 $chardata2[$i-2]['char'] = false;
7495 $chardata2[$i-1]['char'] = false;
7496 $chardata2[$i]['char'] = 65010;
7498 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
7499 if (isset($arabicarr[$thischar['char']][0])) {
7501 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7504 if (isset($arabicarr[$thischar['char']][1])) {
7506 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
7510 } elseif (isset($arabicarr[$thischar['char']][0])) {
7512 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7516 // mark characters to delete with false
7517 $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
7519 } // end if AL (Arabic Letter)
7520 } // end for each char
7522 * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
7523 * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
7525 $cw = &$this->CurrentFont['cw'];
7526 for ($i=0; $i < ($numchars-1); $i++) {
7527 if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
7528 // check if the subtitution font is defined on current font
7529 if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
7530 $chardata2[$i]['char'] = false;
7531 $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
7535 // remove marked characters
7536 foreach($chardata2 as $key => $value) {
7537 if ($value['char'] === false) {
7538 unset($chardata2[$key]);
7541 $chardata = array_values($chardata2);
7542 $numchars = count($chardata);
7549 // 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.
7550 for ($j=$maxlevel; $j > 0; $j--) {
7551 $ordarray = Array();
7554 for ($i=0; $i < $numchars; $i++) {
7555 if ($chardata[$i]['level'] >= $j) {
7557 if (isset($unicode_mirror[$chardata[$i]['char']])) {
7558 // 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.
7559 $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
7561 $revarr[] = $chardata[$i];
7564 $revarr = array_reverse($revarr);
7565 $ordarray = array_merge($ordarray, $revarr);
7569 $ordarray[] = $chardata[$i];
7573 $revarr = array_reverse($revarr);
7574 $ordarray = array_merge($ordarray, $revarr);
7576 $chardata = $ordarray;
7579 $ordarray = array();
7580 for ($i=0; $i < $numchars; $i++) {
7581 $ordarray[] = $chardata[$i]['char'];
7587 // END OF BIDIRECTIONAL TEXT SECTION -------------------
7591 * @param string $txt bookmark description.
7592 * @param int $level bookmark level (minimum value is 0).
7593 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
7595 * @author Olivier Plathey, Nicola Asuni
7596 * @since 2.1.002 (2008-02-12)
7598 function Bookmark($txt, $level=0, $y=-1) {
7602 if (isset($this->outlines[0])) {
7603 $lastoutline = end($this->outlines);
7604 $maxlevel = $lastoutline['l'] + 1;
7608 if ($level > $maxlevel) {
7614 $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $this->PageNo());
7618 * Create a bookmark PDF string.
7620 * @author Olivier Plathey, Nicola Asuni
7621 * @since 2.1.002 (2008-02-12)
7623 function _putbookmarks() {
7624 $nb = count($this->outlines);
7630 foreach($this->outlines as $i => $o) {
7632 $parent = $lru[($o['l'] - 1)];
7633 //Set parent and last pointers
7634 $this->outlines[$i]['parent'] = $parent;
7635 $this->outlines[$parent]['last'] = $i;
7636 if ($o['l'] > $level) {
7637 //Level increasing: set first pointer
7638 $this->outlines[$parent]['first'] = $i;
7641 $this->outlines[$i]['parent'] = $nb;
7643 if (($o['l'] <= $level) AND ($i > 0)) {
7644 //Set prev and next pointers
7645 $prev = $lru[$o['l']];
7646 $this->outlines[$prev]['next'] = $i;
7647 $this->outlines[$i]['prev'] = $prev;
7654 foreach($this->outlines as $i => $o) {
7656 $this->_out('<</Title '.$this->_textstring($o['t']));
7657 $this->_out('/Parent '.($n+$o['parent']).' 0 R');
7658 if (isset($o['prev']))
7659 $this->_out('/Prev '.($n+$o['prev']).' 0 R');
7660 if (isset($o['next']))
7661 $this->_out('/Next '.($n+$o['next']).' 0 R');
7662 if (isset($o['first']))
7663 $this->_out('/First '.($n+$o['first']).' 0 R');
7664 if (isset($o['last']))
7665 $this->_out('/Last '.($n+$o['last']).' 0 R');
7666 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]', 1+2*$o['p'], ($this->h-$o['y'])*$this->k));
7667 $this->_out('/Count 0>>');
7668 $this->_out('endobj');
7672 $this->OutlineRoot=$this->n;
7673 $this->_out('<</Type /Outlines /First '.$n.' 0 R');
7674 $this->_out('/Last '.($n+$lru[0]).' 0 R>>');
7675 $this->_out('endobj');
7679 // --- JAVASCRIPT - FORMS ------------------------------
7684 * @author Johannes Güntert, Nicola Asuni
7685 * @since 2.1.002 (2008-02-12)
7687 function IncludeJS($script) {
7688 $this->javascript .= $script;
7692 * Create a javascript PDF string.
7694 * @author Johannes Güntert, Nicola Asuni
7695 * @since 2.1.002 (2008-02-12)
7697 function _putjavascript() {
7698 if (empty($this->javascript)) {
7701 // the following two lines are uded to avoid form fields duplication after saving
7702 $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2f,%.2f,%.2f,%.2f]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
7703 $js2 = "getField('tcpdfdocsaved').value = 'saved';";
7705 $this->n_js = $this->n;
7707 $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
7709 $this->_out('endobj');
7712 $this->_out('/S /JavaScript');
7713 $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
7715 $this->_out('endobj');
7719 * Convert color to javascript color.
7720 * @param string $color color name or #RRGGBB
7722 * @author Denis Van Nuffelen, Nicola Asuni
7723 * @since 2.1.002 (2008-02-12)
7725 function _JScolor($color) {
7726 static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
7727 if (substr($color,0,1) == '#') {
7728 return sprintf("['RGB',%.3f,%.3f,%.3f]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
7730 if (!in_array($color,$aColors)) {
7731 $this->Error('Invalid color: '.$color);
7733 return 'color.'.$color;
7737 * Adds a javascript form field.
7738 * @param string $type field type
7739 * @param string $name field name
7740 * @param int $x horizontal position
7741 * @param int $y vertical position
7742 * @param int $w width
7743 * @param int $h height
7744 * @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>
7746 * @author Denis Van Nuffelen, Nicola Asuni
7747 * @since 2.1.002 (2008-02-12)
7749 function _addfield($type, $name, $x, $y, $w, $h, $prop) {
7750 // the followind avoid fields duplication after saving the document
7751 $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
7753 $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";
7754 $this->javascript .= "f".$name.".textSize=".$this->FontSizePt.";\n";
7755 while (list($key, $val) = each($prop)) {
7756 if (strcmp(substr($key,-5),"Color") == 0) {
7757 $val = $this->_JScolor($val);
7759 $val = "'".$val."'";
7761 $this->javascript .= "f".$name.".".$key."=".$val.";\n";
7764 $this->javascript .= "}";
7768 * Creates a text field
7769 * @param string $name field name
7770 * @param int $w width
7771 * @param int $h height
7772 * @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>
7774 * @author Denis Van Nuffelen, Nicola Asuni
7775 * @since 2.1.002 (2008-02-12)
7777 function TextField($name, $w, $h, $prop=array()) {
7778 $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
7782 * Creates a RadioButton field
7783 * @param string $name field name
7784 * @param int $w width
7785 * @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>
7787 * @author Nicola Asuni
7788 * @since 2.2.003 (2008-03-03)
7790 function RadioButton($name, $w, $prop=array()) {
7791 if (!isset($prop['strokeColor'])) {
7792 $prop['strokeColor']='black';
7794 $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
7798 * Creates a List-box field
7799 * @param string $name field name
7800 * @param int $w width
7801 * @param int $h height
7802 * @param array $values array containing the list of values.
7803 * @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>
7805 * @author Nicola Asuni
7806 * @since 2.2.003 (2008-03-03)
7808 function ListBox($name, $w, $h, $values, $prop=array()) {
7809 if (!isset($prop['strokeColor'])) {
7810 $prop['strokeColor'] = 'ltGray';
7812 $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
7814 foreach($values as $value) {
7815 $s .= "'".addslashes($value)."',";
7817 $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7821 * Creates a Combo-box field
7822 * @param string $name field name
7823 * @param int $w width
7824 * @param int $h height
7825 * @param array $values array containing the list of values.
7826 * @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>
7828 * @author Denis Van Nuffelen, Nicola Asuni
7829 * @since 2.1.002 (2008-02-12)
7831 function ComboBox($name, $w, $h, $values, $prop=array()) {
7832 $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
7834 foreach($values as $value) {
7835 $s .= "'".addslashes($value)."',";
7837 $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7841 * Creates a CheckBox field
7842 * @param string $name field name
7843 * @param int $w width
7844 * @param boolean $checked define the initial state (default = false).
7845 * @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>
7847 * @author Denis Van Nuffelen, Nicola Asuni
7848 * @since 2.1.002 (2008-02-12)
7850 function CheckBox($name, $w, $checked=false, $prop=array()) {
7851 $prop['value'] = ($checked ? 'Yes' : 'Off');
7852 if (!isset($prop['strokeColor'])) {
7853 $prop['strokeColor'] = 'black';
7855 $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
7859 * Creates a button field
7860 * @param string $name field name
7861 * @param int $w width
7862 * @param int $h height
7863 * @param string $caption caption.
7864 * @param string $action action triggered by the button (JavaScript code).
7865 * @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>
7867 * @author Denis Van Nuffelen, Nicola Asuni
7868 * @since 2.1.002 (2008-02-12)
7870 function Button($name, $w, $h, $caption, $action, $prop=array()) {
7871 if (!isset($prop['strokeColor'])) {
7872 $prop['strokeColor'] = 'black';
7874 if (!isset($prop['borderStyle'])) {
7875 $prop['borderStyle'] = 'beveled';
7877 $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
7878 $this->javascript .= "f".$name.".buttonSetCaption('".addslashes($caption)."');\n";
7879 $this->javascript .= "f".$name.".setAction('MouseUp','".addslashes($action)."');\n";
7880 $this->javascript .= "f".$name.".highlight='push';\n";
7881 $this->javascript .= "f".$name.".print=false;\n";
7884 // END JAVASCRIPT - FORMS ------------------------------
7887 * Enable Write permissions for PDF Reader.
7889 * @author Nicola Asuni
7890 * @since 2.9.000 (2008-03-26)
7892 function _putuserrights() {
7896 $this->_out('/Perms');
7898 $this->_out('/UR3');
7900 //$this->_out('/SubFilter/adbe.pkcs7.detached/Filter/Adobe.PPKLite/Contents');
7901 //$this->_out('<0>');
7902 //$this->_out('/ByteRange[0 3]');
7903 $this->_out('/M '.$this->_datestring('D:'.date('YmdHis')));
7904 $this->_out('/Name(TCPDF)');
7905 $this->_out('/Reference[');
7907 $this->_out('/TransformParams');
7909 $this->_out('/Type/TransformParams');
7910 $this->_out('/V/2.2');
7911 if (!empty($this->ur_document)) {
7912 $this->_out('/Document['.$this->ur_document.']');
7914 if (!empty($this->ur_annots)) {
7915 $this->_out('/Annots['.$this->ur_annots.']');
7917 if (!empty($this->ur_form)) {
7918 $this->_out('/Form['.$this->ur_form.']');
7920 if (!empty($this->ur_signature)) {
7921 $this->_out('/Signature['.$this->ur_signature.']');
7924 $this->_out('/TransformMethod/UR3');
7925 $this->_out('/Type/SigRef');
7928 $this->_out('/Type/Sig');
7934 * Set User's Rights for PDF Reader
7935 * Check the PDF Reference 8.7.1 Transform Methods,
7936 * Table 8.105 Entries in the UR transform parameters dictionary
7937 * @param boolean $enable if true enable user's rights on PDF reader
7938 * @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.
7939 * @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.
7940 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
7941 * @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.
7943 * @author Nicola Asuni
7944 * @since 2.9.000 (2008-03-26)
7946 function setUserRights(
7948 $document="/FullSave",
7949 $annots="/Create/Delete/Modify/Copy/Import/Export",
7950 $form="/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate",
7951 $signature="/Modify") {
7952 $this->ur = $enable;
7953 $this->ur_document = $document;
7954 $this->ur_annots = $annots;
7955 $this->ur_form = $form;
7956 $this->ur_signature = $signature;
7960 * Create a new page group.
7961 * NOTE: call this function before calling AddPage()
7963 * @since 3.0.000 (2008-03-27)
7965 function startPageGroup() {
7966 $this->newpagegroup = true;
7970 * Return the current page in the group.
7971 * @return current page in the group
7973 * @since 3.0.000 (2008-03-27)
7975 function getGroupPageNo() {
7976 return $this->pagegroups[$this->currpagegroup];
7980 * Return the alias of the current page group
7981 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
7982 * (will be replaced by the total number of pages in this group).
7983 * @return alias of the current page group
7985 * @since 3.0.000 (2008-03-27)
7987 function getPageGroupAlias() {
7988 if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
7989 return "{".$this->currpagegroup."}";
7991 return $this->currpagegroup;
7995 * Put visibility settings.
7997 * @since 3.0.000 (2008-03-27)
7999 function _putocg() {
8001 $this->n_ocg_print = $this->n;
8002 $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
8003 $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
8004 $this->_out('endobj');
8006 $this->n_ocg_view=$this->n;
8007 $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
8008 $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
8009 $this->_out('endobj');
8013 * Set the visibility of the successive elements.
8014 * This can be useful, for instance, to put a background
8015 * image or color that will show on screen but won't print.
8016 * @param string $v visibility mode. Legal values are: all, print, screen.
8018 * @since 3.0.000 (2008-03-27)
8020 function setVisibility($v) {
8021 if ($this->openMarkedContent) {
8022 // close existing open marked-content
8024 $this->openMarkedContent = false;
8028 $this->_out('/OC /OC1 BDC');
8029 $this->openMarkedContent = true;
8033 $this->_out('/OC /OC2 BDC');
8034 $this->openMarkedContent = true;
8042 $this->Error('Incorrect visibility: '.$v);
8046 $this->visibility = $v;
8050 * Add transparency parameters to the current extgstate
8051 * @param array $params parameters
8052 * @return the number of extgstates
8054 * @since 3.0.000 (2008-03-27)
8056 function addExtGState($parms) {
8057 $n = count($this->extgstates) + 1;
8058 $this->extgstates[$n]['parms'] = $parms;
8064 * @param array $gs extgstate
8066 * @since 3.0.000 (2008-03-27)
8068 function setExtGState($gs) {
8069 $this->_out(sprintf('/GS%d gs', $gs));
8073 * Put extgstates for object transparency
8074 * @param array $gs extgstate
8076 * @since 3.0.000 (2008-03-27)
8078 function _putextgstates() {
8079 $ne = count($this->extgstates);
8080 for ($i = 1; $i <= $ne; $i++) {
8082 $this->extgstates[$i]['n'] = $this->n;
8083 $this->_out('<</Type /ExtGState');
8084 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
8085 $this->_out('/'.$k.' '.$v);
8088 $this->_out('endobj');
8093 * Set alpha for stroking (CA) and non-stroking (ca) operations.
8094 * @param float $alpha real value from 0 (transparent) to 1 (opaque)
8095 * @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
8097 * @since 3.0.000 (2008-03-27)
8099 function setAlpha($alpha, $bm='Normal') {
8100 $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
8101 $this->setExtGState($gs);
8105 * Set the default JPEG compression quality (1-100)
8106 * @param int $quality JPEG quality, integer between 1 and 100
8108 * @since 3.0.000 (2008-03-27)
8110 function setJPEGQuality($quality) {
8111 if (($quality < 1) OR ($quality > 100)) {
8114 $this->jpeg_quality = intval($quality);
8118 * Set the default number of columns in a row for HTML tables.
8119 * @param int $cols number of columns
8121 * @since 3.0.014 (2008-06-04)
8123 function setDefaultTableColumns($cols=4) {
8124 $this->default_table_columns = intval($cols);
8128 * Set the height of cell repect font height.
8129 * @param int $h cell proportion respect font height (typical value = 1.25).
8131 * @since 3.0.014 (2008-06-04)
8133 function setCellHeightRatio($h) {
8134 $this->cell_height_ratio = $h;
8138 * return the height of cell repect font height.
8140 * @since 4.0.012 (2008-07-24)
8142 function getCellHeightRatio() {
8143 return $this->cell_height_ratio;
8147 * Set the PDF version (check PDF reference for valid values).
8148 * Default value is 1.t
8150 * @since 3.1.000 (2008-06-09)
8152 function setPDFVersion($version="1.7") {
8153 $this->PDFVersion = $version;
8157 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
8158 * (see Section 8.1 of PDF reference, "Viewer Preferences").
8160 * <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>
8161 * <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>
8162 * <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>
8163 * <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>
8164 * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
8165 * <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>
8166 * <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>
8167 * <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>
8168 * <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>
8169 * <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>
8170 * <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>
8171 * <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>
8172 * <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>
8173 * <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>
8174 * <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>
8175 * <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>
8177 * @param array $preferences array of options.
8178 * @author Nicola Asuni
8180 * @since 3.1.000 (2008-06-09)
8182 function setViewerPreferences($preferences) {
8183 $this->viewer_preferences = $preferences;
8187 * Paints a linear colour gradient.
8188 * @param float $x abscissa of the top left corner of the rectangle.
8189 * @param float $y ordinate of the top left corner of the rectangle.
8190 * @param float $w width of the rectangle.
8191 * @param float $h height of the rectangle.
8192 * @param array $col1 first color (RGB components).
8193 * @param array $col2 second color (RGB components).
8194 * @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).
8195 * @author Andreas Würmser, Nicola Asuni
8196 * @since 3.1.000 (2008-06-09)
8199 function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
8200 $this->Clip($x, $y, $w, $h);
8201 $this->Gradient(2, $col1, $col2, $coords);
8205 * Paints a radial colour gradient.
8206 * @param float $x abscissa of the top left corner of the rectangle.
8207 * @param float $y ordinate of the top left corner of the rectangle.
8208 * @param float $w width of the rectangle.
8209 * @param float $h height of the rectangle.
8210 * @param array $col1 first color (RGB components).
8211 * @param array $col2 second color (RGB components).
8212 * @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.
8213 * @author Andreas Würmser, Nicola Asuni
8214 * @since 3.1.000 (2008-06-09)
8217 function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
8218 $this->Clip($x, $y, $w, $h);
8219 $this->Gradient(3, $col1, $col2, $coords);
8223 * Paints a coons patch mesh.
8224 * @param float $x abscissa of the top left corner of the rectangle.
8225 * @param float $y ordinate of the top left corner of the rectangle.
8226 * @param float $w width of the rectangle.
8227 * @param float $h height of the rectangle.
8228 * @param array $col1 first color (lower left corner) (RGB components).
8229 * @param array $col2 second color (lower right corner) (RGB components).
8230 * @param array $col3 third color (upper right corner) (RGB components).
8231 * @param array $col4 fourth color (upper left corner) (RGB components).
8232 * @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>
8233 * @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
8234 * @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
8235 * @author Andreas Würmser, Nicola Asuni
8236 * @since 3.1.000 (2008-06-09)
8239 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) {
8240 $this->Clip($x, $y, $w, $h);
8241 $n = count($this->gradients) + 1;
8242 $this->gradients[$n]['type'] = 6; //coons patch mesh
8243 //check the coords array if it is the simple array or the multi patch array
8244 if (!isset($coords[0]['f'])){
8245 //simple array -> convert to multi patch array
8246 if (!isset($col1[1])) {
8247 $col1[1] = $col1[2] = $col1[0];
8249 if (!isset($col2[1])) {
8250 $col2[1] = $col2[2] = $col2[0];
8252 if (!isset($col3[1])) {
8253 $col3[1] = $col3[2] = $col3[0];
8255 if (!isset($col4[1])) {
8256 $col4[1] = $col4[2] = $col4[0];
8258 $patch_array[0]['f'] = 0;
8259 $patch_array[0]['points'] = $coords;
8260 $patch_array[0]['colors'][0]['r'] = $col1[0];
8261 $patch_array[0]['colors'][0]['g'] = $col1[1];
8262 $patch_array[0]['colors'][0]['b'] = $col1[2];
8263 $patch_array[0]['colors'][1]['r'] = $col2[0];
8264 $patch_array[0]['colors'][1]['g'] = $col2[1];
8265 $patch_array[0]['colors'][1]['b'] = $col2[2];
8266 $patch_array[0]['colors'][2]['r'] = $col3[0];
8267 $patch_array[0]['colors'][2]['g'] = $col3[1];
8268 $patch_array[0]['colors'][2]['b'] = $col3[2];
8269 $patch_array[0]['colors'][3]['r'] = $col4[0];
8270 $patch_array[0]['colors'][3]['g'] = $col4[1];
8271 $patch_array[0]['colors'][3]['b'] = $col4[2];
8274 $patch_array = $coords;
8276 $bpcd = 65535; //16 BitsPerCoordinate
8277 //build the data stream
8278 $this->gradients[$n]['stream'] = "";
8279 for($i=0; $i < count($patch_array); $i++) {
8280 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
8281 for($j=0; $j < count($patch_array[$i]['points']); $j++) {
8282 //each point as 16 bit
8283 $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j]-$coords_min)/($coords_max-$coords_min))*$bpcd;
8284 if ($patch_array[$i]['points'][$j] < 0) {
8285 $patch_array[$i]['points'][$j] = 0;
8287 if ($patch_array[$i]['points'][$j] > $bpcd) {
8288 $patch_array[$i]['points'][$j] = $bpcd;
8290 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]/256));
8291 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]%256));
8293 for($j=0; $j < count($patch_array[$i]['colors']); $j++) {
8294 //each color component as 8 bit
8295 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
8296 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
8297 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
8300 //paint the gradient
8301 $this->_out('/Sh'.$n.' sh');
8302 //restore previous Graphic State
8307 * Set a rectangular clipping area.
8308 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
8309 * @param float $y ordinate of the top left corner of the rectangle.
8310 * @param float $w width of the rectangle.
8311 * @param float $h height of the rectangle.
8312 * @author Andreas Würmser, Nicola Asuni
8313 * @since 3.1.000 (2008-06-09)
8316 function Clip($x, $y, $w, $h){
8318 $x = $this->w - $x - $w;
8320 //save current Graphic State
8323 $s .= sprintf(' %.2f %.2f %.2f %.2f re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
8324 //set up transformation matrix for gradient
8325 $s .= sprintf(' %.3f 0 0 %.3f %.3f %.3f cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
8331 * @param int $type type of gradient.
8332 * @param array $col1 first color (RGB components).
8333 * @param array $col2 second color (RGB components).
8334 * @param array $coords array of coordinates.
8335 * @author Andreas Würmser, Nicola Asuni
8336 * @since 3.1.000 (2008-06-09)
8339 function Gradient($type, $col1, $col2, $coords){
8340 $n = count($this->gradients) + 1;
8341 $this->gradients[$n]['type'] = $type;
8342 if (!isset($col1[1])) {
8343 $col1[1]=$col1[2]=$col1[0];
8345 $this->gradients[$n]['col1'] = sprintf('%.3f %.3f %.3f', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
8346 if (!isset($col2[1])) {
8347 $col2[1] = $col2[2] = $col2[0];
8349 $this->gradients[$n]['col2'] = sprintf('%.3f %.3f %.3f', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
8350 $this->gradients[$n]['coords'] = $coords;
8351 //paint the gradient
8352 $this->_out('/Sh'.$n.' sh');
8353 //restore previous Graphic State
8359 * @author Andreas Würmser, Nicola Asuni
8360 * @since 3.1.000 (2008-06-09)
8363 function _putshaders() {
8364 foreach($this->gradients as $id => $grad) {
8365 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
8368 $this->_out('/FunctionType 2');
8369 $this->_out('/Domain [0.0 1.0]');
8370 $this->_out('/C0 ['.$grad['col1'].']');
8371 $this->_out('/C1 ['.$grad['col2'].']');
8372 $this->_out('/N 1');
8374 $this->_out('endobj');
8379 $this->_out('/ShadingType '.$grad['type']);
8380 $this->_out('/ColorSpace /DeviceRGB');
8381 if ($grad['type'] == 2) {
8382 $this->_out(sprintf('/Coords [%.3f %.3f %.3f %.3f]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
8383 $this->_out('/Function '.$f1.' 0 R');
8384 $this->_out('/Extend [true true] ');
8386 } elseif ($grad['type'] == 3) {
8387 //x0, y0, r0, x1, y1, r1
8388 //at this this time radius of inner circle is 0
8389 $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]));
8390 $this->_out('/Function '.$f1.' 0 R');
8391 $this->_out('/Extend [true true] ');
8393 } elseif ($grad['type'] == 6) {
8394 $this->_out('/BitsPerCoordinate 16');
8395 $this->_out('/BitsPerComponent 8');
8396 $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
8397 $this->_out('/BitsPerFlag 8');
8398 $this->_out('/Length '.strlen($grad['stream']));
8400 $this->_putstream($grad['stream']);
8402 $this->_out('endobj');
8403 $this->gradients[$id]['id'] = $this->n;
8409 * @author Maxime Delorme, Nicola Asuni
8410 * @since 3.1.000 (2008-06-09)
8413 function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
8415 $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));
8419 * Draw the sector of a circle.
8420 * It can be used for instance to render pie charts.
8421 * @param float $xc abscissa of the center.
8422 * @param float $yc ordinate of the center.
8423 * @param float $r radius.
8424 * @param float $a start angle (in degrees).
8425 * @param float $b end angle (in degrees).
8426 * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
8427 * @param float $cw: indicates whether to go clockwise (default: true).
8428 * @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.
8429 * @author Maxime Delorme, Nicola Asuni
8430 * @since 3.1.000 (2008-06-09)
8433 function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
8435 $xc = $this->w - $xc - $w;
8445 $a = ($a % 360) + 360;
8446 $b = ($b % 360) + 360;
8450 $b = $b / 360 * 2 * M_PI;
8451 $a = $a / 360 * 2 * M_PI;
8460 } elseif ($style=='FD' or $style=='DF') {
8466 $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
8468 //first put the center
8469 $this->_out(sprintf('%.2f %.2f m', ($xc)*$k, ($hp-$yc)*$k));
8470 //put the first point
8471 $this->_out(sprintf('%.2f %.2f l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
8473 if ($d < (M_PI/2)) {
8474 $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));
8477 $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
8478 $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));
8481 $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));
8484 $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) );
8487 $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));
8494 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
8495 * Only vector drawing is supported, not text or bitmap.
8496 * 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).
8497 * @param string $file Name of the file containing the image.
8498 * @param float $x Abscissa of the upper-left corner.
8499 * @param float $y Ordinate of the upper-left corner.
8500 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
8501 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
8502 * @param mixed $link URL or identifier returned by AddLink().
8503 * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
8504 * @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>
8505 * @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>
8506 * @author Valentin Schmidt, Nicola Asuni
8507 * @since 3.1.000 (2008-06-09)
8510 function ImageEps($file, $x, $y, $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='') {
8511 $data = file_get_contents($file);
8512 if ($data === false) {
8513 $this->Error('EPS file not found: '.$file);
8516 // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
8517 preg_match ('/%%Creator:([^\r\n]+)/', $data, $regs); # find Creator
8518 if (count($regs) > 1) {
8519 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
8520 if (strpos($version_str, 'Adobe Illustrator') !== false) {
8521 $versexp = explode(' ', $version_str);
8522 $version = (float)array_pop($versexp);
8523 if ($version >= 9) {
8524 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
8528 // strip binary bytes in front of PS-header
8529 $start = strpos($data, '%!PS-Adobe');
8531 $data = substr($data, $start);
8533 // find BoundingBox params
8534 preg_match ("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
8535 if (count($regs) > 1) {
8536 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
8538 $this->Error('No BoundingBox found in EPS file: '.$file);
8540 $start = strpos($data, '%%EndSetup');
8541 if ($start === false) {
8542 $start = strpos($data, '%%EndProlog');
8544 if ($start === false) {
8545 $start = strpos($data, '%%BoundingBox');
8547 $data = substr($data, $start);
8548 $end = strpos($data, '%%PageTrailer');
8550 $end = strpos($data, 'showpage');
8553 $data = substr($data, 0, $end);
8557 $scale_x = $w/(($x2-$x1)/$k);
8559 $scale_y = $h/(($y2-$y1)/$k);
8561 $scale_y = $scale_x;
8562 $h = ($y2-$y1)/$k * $scale_y;
8566 $scale_y = $h/(($y2-$y1)/$k);
8567 $scale_x = $scale_y;
8568 $w = ($x2-$x1)/$k * $scale_x;
8570 $w = ($x2 - $x1) / $k;
8571 $h = ($y2 - $y1) / $k;
8574 // Check whether we need a new page first as this does not fit
8575 if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
8576 // Automatic page break
8577 $this->AddPage($this->CurOrientation);
8578 // Reset coordinates to top fo next page
8579 //$x = $this->GetX();
8580 $y = $this->GetY() + $this->cMargin;
8582 // set bottomcoordinates
8583 $this->img_rb_y = $y + $h;
8586 if ($palign == 'L') {
8587 $ximg = $this->lMargin;
8588 // set right side coordinate
8589 $this->img_rb_x = $ximg + $w;
8590 } elseif ($palign == 'C') {
8591 $ximg = ($this->w - $x - $w) / 2;
8592 // set right side coordinate
8593 $this->img_rb_x = $ximg + $w;
8595 $ximg = $this->w - $x - $w;
8596 // set left side coordinate
8597 $this->img_rb_x = $ximg;
8600 if ($palign == 'R') {
8601 $ximg = $this->w - $this->rMargin - $w;
8602 // set left side coordinate
8603 $this->img_rb_x = $ximg;
8604 } elseif ($palign == 'C') {
8605 $ximg = ($this->w - $x - $w) / 2;
8606 // set right side coordinate
8607 $this->img_rb_x = $ximg + $w;
8610 // set right side coordinate
8611 $this->img_rb_x = $ximg + $w;
8614 if ($useBoundingBox){
8615 $dx = $ximg * $k - $x1;
8616 $dy = $y * $k - $y1;
8621 // save the current graphic state
8624 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy+($this->hPt - 2*$y*$k - ($y2-$y1))));
8626 if (isset($scale_x)) {
8627 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1*(1-$scale_x), $y2*(1-$scale_y)));
8629 // handle pc/unix/mac line endings
8630 $lines = split("\r\n|[\r\n]", $data);
8632 $cnt = count($lines);
8633 for ($i=0; $i < $cnt; $i++) {
8635 if (($line == '') OR ($line{0} == '%')) {
8638 $len = strlen($line);
8639 $chunks = explode(' ', $line);
8640 $cmd = array_pop($chunks);
8642 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
8643 $b = array_pop($chunks);
8644 $g = array_pop($chunks);
8645 $r = array_pop($chunks);
8646 $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!
8671 case 'x': {// custom fill color
8672 list($c,$m,$y,$k) = $chunks;
8673 $this->_out("$c $m $y $k k");
8676 case 'X': { // custom stroke color
8677 list($c,$m,$y,$k) = $chunks;
8678 $this->_out("$c $m $y $k K");
8686 $line{$len-1} = strtolower($cmd);
8692 $this->_out($cmd . '*');
8699 $max = min($i+5, $cnt);
8700 for ($j=$i+1; $j < $max; $j++)
8701 $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
8720 // restore previous graphic state
8723 $this->Link($ximg, $y, $w, $h, $link);
8725 // set pointer to align the successive text/objects
8729 $this->x = $this->img_rb_x;
8733 $this->y = $y + round($h/2);
8734 $this->x = $this->img_rb_x;
8738 $this->y = $this->img_rb_y;
8739 $this->x = $this->img_rb_x;
8743 $this->SetY($this->img_rb_y);
8750 $this->endlinex = $this->img_rb_x;
8754 * Set document barcode.
8755 * @param string $bc barcode
8757 function setBarcode($bc="") {
8758 $this->barcode = $bc;
8762 * Get current barcode.
8764 * @since 4.0.012 (2008-07-24)
8766 function getBarcode() {
8767 return $this->barcode;
8772 * @param string $code code to print
8773 * @param string $type type of barcode.
8774 * @param int $x x position in user units
8775 * @param int $y y position in user units
8776 * @param int $w width in user units
8777 * @param int $h height position in user units
8778 * @param float $xres width of the smallest bar in user units
8779 * @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>
8780 * @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>
8781 * @author Nicola Asuni
8782 * @since 3.1.000 (2008-06-09)
8785 function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
8789 $barcodeobj = new TCPDFbarcode($code, $type);
8790 $arrcode = $barcodeobj->getBarcodeArray();
8791 if ($arrcode === false) {
8792 $this->Error('Error in barcode string');
8794 // set default values
8795 if (!isset($style["position"])) {
8797 $style["position"] = "R";
8799 $style["position"] = "L";
8802 if (!isset($style["padding"])) {
8803 $style["padding"] = 0;
8805 if (!isset($style["fgcolor"])) {
8806 $style["fgcolor"] = array(0,0,0); // default black
8808 if (!isset($style["bgcolor"])) {
8809 $style["bgcolor"] = false; // default transparent
8811 if (!isset($style["border"])) {
8812 $style["border"] = false;
8814 if (!isset($style["text"])) {
8815 $style["text"] = false;
8818 if ($style["text"] AND isset($style["font"])) {
8819 $prevFontFamily = $this->FontFamily;
8820 $prevFontStyle = $this->FontStyle;
8821 $prevFontSizePt = $this->FontSizePt;
8822 if (isset($style["fontsize"])) {
8823 $fontsize = $style["fontsize"];
8827 $this->SetFont($style["font"], '', $fontsize);
8829 if (!isset($style["stretchtext"])) {
8830 $style["stretchtext"] = 4;
8832 // set foreground color
8833 $prevDrawColor = $this->DrawColor;
8834 $prevTextColor = $this->TextColor;
8835 $this->SetDrawColorArray($style["fgcolor"]);
8836 $this->SetTextColorArray($style["fgcolor"]);
8837 if (empty($w) OR ($w <= 0)) {
8839 $w = $this->x - $this->lMargin;
8841 $w = $this->w - $this->rMargin - $this->x;
8856 $fbw = ($arrcode["maxw"] * $xres) + (2 * $style["padding"]);
8857 $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style["padding"]);
8859 $h = 10 + $extraspace;
8861 if ((($y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
8862 //Automatic page break
8867 $this->_out('0 Tw');
8869 $this->AddPage($this->CurOrientation);
8872 $this->_out(sprintf('%.3f Tw',$ws * $k));
8877 // maximum bar heigth
8878 $barh = $h - $extraspace;
8879 switch ($style["position"]) {
8888 case "C": { // center
8889 $xdiff = (($w - $fbw) / 2);
8891 $xpos = $x - $w + $xdiff;
8893 $xpos = $x + $xdiff;
8897 case "R": { // right
8901 $xpos = $x + $w - $fbw;
8905 case "S": { // stretch
8907 $xres = ($w - (2 * $style["padding"])) / $arrcode["maxw"];
8917 $xpos = $xpos_rect + $style["padding"];
8919 // barcode is always printed in LTR direction
8920 $tempRTL = $this->rtl;
8922 // print background color
8923 if ($style["bgcolor"]) {
8924 $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style["bgcolor"]);
8925 } elseif ($style["border"]) {
8926 $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
8929 if ($arrcode !== false) {
8930 foreach ($arrcode["bcode"] as $k => $v) {
8931 $bw = ($v["w"] * $xres);
8933 // braw a vertical bar
8934 $ypos = $y + $style["padding"] + ($v["p"] * $barh / $arrcode["maxh"]);
8935 $this->Rect($xpos, $ypos, $bw, ($v["h"] * $barh / $arrcode["maxh"]), 'DF', array("L"=>0,"T"=>0,"R"=>0,"B"=>0), $style["fgcolor"]);
8941 if ($style["text"]) {
8943 $this->x = $xpos_text;
8944 $this->y = $y + $style["padding"] + $barh;
8945 $this->Cell(($arrcode["maxw"] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style["stretchtext"]);
8947 // restore original direction
8948 $this->rtl = $tempRTL;
8949 // restore previous font
8950 if ($style["text"] AND isset($style["font"])) {
8951 $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
8954 $this->DrawColor = $prevDrawColor;
8955 $this->TextColor = $prevTextColor;
8956 // set bottomcoordinates
8957 $this->img_rb_y = $y + $h;
8959 // set left side coordinate
8960 $this->img_rb_x = ($this->w - $x - $w);
8962 // set right side coordinate
8963 $this->img_rb_x = $x + $w;
8965 // set pointer to align the successive text/objects
8969 $this->x = $this->img_rb_x;
8973 $this->y = $y + round($h/2);
8974 $this->x = $this->img_rb_x;
8978 $this->y = $this->img_rb_y;
8979 $this->x = $this->img_rb_x;
8983 $this->SetY($this->img_rb_y);
8993 * This function is DEPRECATED, please use the new write1DBarcode() function.
8994 * @param int $x x position in user units
8995 * @param int $y y position in user units
8996 * @param int $w width in user units
8997 * @param int $h height position in user units
8998 * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
8999 * @param string $style barcode style
9000 * @param string $font font for text
9001 * @param int $xres x resolution
9002 * @param string $code code to print
9003 * @deprecated deprecated since version 3.1.000 (2008-06-10)
9004 * @see write1DBarcode()
9006 function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
9007 // convert old settings for the new write1DBarcode() function.
9013 "fgcolor" => array(0,0,0),
9021 $newstyle["border"] = true;
9024 $newstyle["bgcolor"] = false;
9027 $newstyle["position"] = "C";
9028 } elseif ($style & 8) {
9029 $newstyle["position"] = "L";
9030 } elseif ($style & 16) {
9031 $newstyle["position"] = "R";
9034 $newstyle["text"] = true;
9037 $newstyle["stretchtext"] = 4;
9039 $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
9043 * Returns an array containing current margins:
9045 <li>$ret['left'] = left margin</li>
9046 <li>$ret['right'] = right margin</li>
9047 <li>$ret['top'] = top margin</li>
9048 <li>$ret['bottom'] = bottom margin</li>
9049 <li>$ret['header'] = header margin</li>
9050 <li>$ret['footer'] = footer margin</li>
9051 <li>$ret['cell'] = cell margin</li>
9053 * @return array containing all margins measures
9054 * @since 3.2.000 (2008-06-23)
9056 function getMargins() {
9058 'left' => $this->lMargin,
9059 'right' => $this->rMargin,
9060 'top' => $this->tMargin,
9061 'bottom' => $this->bMargin,
9062 'header' => $this->header_margin,
9063 'footer' => $this->footer_margin,
9064 'cell' => $this->cMargin,
9070 * Returns an array containing original margins:
9072 <li>$ret['left'] = left margin</li>
9073 <li>$ret['right'] = right margin</li>
9075 * @return array containing all margins measures
9076 * @since 4.0.012 (2008-07-24)
9078 function getOriginalMargins() {
9080 'left' => $this->original_lMargin,
9081 'right' => $this->original_rMargin
9087 * Returns the current font size.
9088 * @return current font size
9089 * @since 3.2.000 (2008-06-23)
9091 function getFontSize() {
9092 return $this->FontSize;
9096 * Returns the current font size in points unit.
9097 * @return current font size in points unit
9098 * @since 3.2.000 (2008-06-23)
9100 function getFontSizePt() {
9101 return $this->FontSizePt;
9105 * Prints a cell (rectangular area) with optional borders, background color and html text string.
9106 * 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 />
9107 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
9108 * @param float $w Cell width. If 0, the cell extends up to the right margin.
9109 * @param float $h Cell minimum height. The cell extends automatically if needed.
9110 * @param float $x upper-left corner X coordinate
9111 * @param float $y upper-left corner Y coordinate
9112 * @param string $html html text to print. Default value: empty string.
9113 * @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>
9114 * @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>
9115 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
9116 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
9117 * @param boolean $reseth if true reset the last cell height (default true).
9118 * @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>
9120 * @see Multicell(), writeHTML()
9122 function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='') {
9123 return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true);
9127 * Returns the HTML DOM array.
9128 * <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>
9129 * @param string $html html code
9131 * @since 3.2.000 (2008-06-20)
9133 function getHtmlDomArray($html) {
9134 // remove all unsupported tags (the line below lists all supported tags)
9135 $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>");
9136 //replace carriage returns, newlines and tabs
9137 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ", "\\" => "\\\\");
9138 $html = strtr($html, $repTable);
9139 // remove extra spaces from tables
9140 $html = preg_replace('/[\s]*<\/table>[\s]*/', '</table>', $html);
9141 $html = preg_replace('/[\s]*<\/tr>[\s]*/', '</tr>', $html);
9142 $html = preg_replace('/[\s]*<tr/', '<tr', $html);
9143 $html = preg_replace('/[\s]*<\/th>[\s]*/', '</th>', $html);
9144 $html = preg_replace('/[\s]*<th/', '<th', $html);
9145 $html = preg_replace('/[\s]*<\/td>[\s]*/', '</td>', $html);
9146 $html = preg_replace('/[\s]*<td/', '<td', $html);
9147 $html = preg_replace('/<\/th>/', '<span></span></th>', $html);
9148 $html = preg_replace('/<\/td>/', '<span></span></td>', $html);
9149 // pattern for generic tag
9150 $tagpattern = '/(<[^>]+>)/Uu';
9151 // explodes the string
9152 $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
9156 // create an array of elements
9158 $dom[$key] = array();
9159 // set first void element
9160 $dom[$key]['tag'] = false;
9161 $dom[$key]['value'] = "";
9162 $dom[$key]['parent'] = 0;
9163 $dom[$key]['fontname'] = $this->FontFamily;
9164 $dom[$key]['fontstyle'] = $this->FontStyle;
9165 $dom[$key]['fontsize'] = $this->FontSizePt;
9166 $dom[$key]['bgcolor'] = false;
9167 $dom[$key]['fgcolor'] = $this->fgcolor;
9168 $dom[$key]['align'] = '';
9171 array_push($level, 0); // root
9172 while ($key <= $maxel) {
9174 $dom[$key] = array();
9176 $element = $a[($key-1)];
9177 if (preg_match($tagpattern, $element)) {
9179 $dom[$key]['tag'] = true;
9180 $element = substr($element, 1, -1);
9182 preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
9183 $dom[$key]['value'] = strtolower($tag[1]);
9184 if ($element{0} == '/') {
9186 $dom[$key]['opening'] = false;
9187 $dom[$key]['parent'] = end($level);
9189 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
9190 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
9191 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
9192 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
9193 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
9194 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
9195 // set the number of columns in table tag
9196 if (($dom[$key]['value'] == "tr") AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
9197 $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
9199 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9200 $dom[($dom[$key]['parent'])]['content'] = "";
9201 for ($i = ($dom[$key]['parent'] + 1); $i < $key; $i++) {
9202 $dom[($dom[$key]['parent'])]['content'] .= $a[($i-1)];
9208 $dom[$key]['opening'] = true;
9209 $dom[$key]['parent'] = end($level);
9210 if (substr($element, -1, 1) != '/') {
9211 // not self-closing tag
9212 array_push($level, $key);
9213 $dom[$key]['self'] = false;
9215 $dom[$key]['self'] = true;
9217 // copy some values from parent
9219 $dom[$key]['fontname'] = $dom[($dom[$key]['parent'])]['fontname'];
9220 $dom[$key]['fontstyle'] = $dom[($dom[$key]['parent'])]['fontstyle'];
9221 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'];
9222 $dom[$key]['bgcolor'] = $dom[($dom[$key]['parent'])]['bgcolor'];
9223 $dom[$key]['fgcolor'] = $dom[($dom[$key]['parent'])]['fgcolor'];
9224 $dom[$key]['align'] = $dom[($dom[$key]['parent'])]['align'];
9227 preg_match_all('/([^=\s]*)=["\']?([^"\']*)["\']?/', $element, $attr_array, PREG_PATTERN_ORDER);
9228 $dom[$key]['attribute'] = array(); // reset attribute array
9229 while (list($id, $name) = each($attr_array[1])) {
9230 $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
9232 // split style attributes
9233 if (isset($dom[$key]['attribute']['style'])) {
9234 // get style attributes
9235 preg_match_all('/([^:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
9236 $dom[$key]['style'] = array(); // reset style attribute array
9237 while (list($id, $name) = each($style_array[1])) {
9238 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
9240 // --- get some style attributes ---
9241 if (isset($dom[$key]['style']['font-family'])) {
9243 if (isset($dom[$key]['style']['font-family'])) {
9244 $fontslist = split(",", strtolower($dom[$key]['style']['font-family']));
9245 foreach($fontslist as $font) {
9246 $font = trim(strtolower($font));
9247 if (in_array($font, $this->fontlist)){
9248 $dom[$key]['fontname'] = $font;
9255 if (isset($dom[$key]['style']['font-size'])) {
9256 $fsize = trim($dom[$key]['style']['font-size']);
9259 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
9263 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
9267 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
9271 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
9275 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
9279 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
9283 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
9287 $dom[$key]['fontsize'] = intval($fsize);
9292 $dom[$key]['fontstyle'] = "";
9293 if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == "b")) {
9294 $dom[$key]['fontstyle'] .= "B";
9296 if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == "i")) {
9297 $dom[$key]['fontstyle'] .= "I";
9300 if (isset($dom[$key]['style']['color']) AND (!empty($dom[$key]['style']['color']))) {
9301 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
9304 if (isset($dom[$key]['style']['background-color']) AND (!empty($dom[$key]['style']['background-color']))) {
9305 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
9308 if (isset($dom[$key]['style']['text-decoration'])) {
9309 $decors = explode(" ", strtolower($dom[$key]['style']['text-decoration']));
9310 foreach ($decors as $dec) {
9312 if ($dec{0} == "u") {
9313 $dom[$key]['fontstyle'] .= "U";
9314 } elseif ($dec{0} == "l") {
9315 $dom[$key]['fontstyle'] .= "D";
9319 // check for width attribute
9320 if (isset($dom[$key]['style']['width'])) {
9321 $dom[$key]['width'] = intval($dom[$key]['style']['width']);
9323 // check for height attribute
9324 if (isset($dom[$key]['style']['height'])) {
9325 $dom[$key]['height'] = intval($dom[$key]['style']['height']);
9327 // check for text alignment
9328 if (isset($dom[$key]['style']['text-align'])) {
9329 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
9332 // check for font tag
9333 if ($dom[$key]['value'] == "font") {
9335 if (isset($dom[$key]['attribute']['face'])) {
9336 $fontslist = split(",", strtolower($dom[$key]['attribute']['face']));
9337 foreach($fontslist as $font) {
9338 $font = trim(strtolower($font));
9339 if (in_array($font, $this->fontlist)){
9340 $dom[$key]['fontname'] = $font;
9346 if (isset($dom[$key]['attribute']['size'])) {
9348 if ($dom[$key]['attribute']['size']{0} == "+") {
9349 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
9350 } elseif ($dom[$key]['attribute']['size']{0} == "-") {
9351 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
9353 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9356 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9360 if (($dom[$key]['value'] == "ul") OR ($dom[$key]['value'] == "ol") OR ($dom[$key]['value'] == "dl")) {
9361 // force natural alignment for lists
9363 $dom[$key]['align'] = "R";
9365 $dom[$key]['align'] = "L";
9368 if (($dom[$key]['value'] == "small") OR ($dom[$key]['value'] == "sup") OR ($dom[$key]['value'] == "sub")) {
9369 $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
9371 if (($dom[$key]['value'] == "strong") OR ($dom[$key]['value'] == "b")) {
9372 $dom[$key]['fontstyle'] .= "B";
9374 if (($dom[$key]['value'] == "em") OR ($dom[$key]['value'] == "i")) {
9375 $dom[$key]['fontstyle'] .= "I";
9377 if (($dom[$key]['value']{0} == "h") AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
9378 $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
9379 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
9380 $dom[$key]['fontstyle'] .= "B";
9382 if (($dom[$key]['value'] == "table")) {
9383 $dom[$key]['rows'] = 0; // number of rows
9384 $dom[$key]['trids'] = array(); // IDs of TR elements
9386 if (($dom[$key]['value'] == "tr")) {
9387 $dom[$key]['cols'] = 0;
9388 // store the number of rows on table element
9389 $dom[($dom[$key]['parent'])]['rows']++;
9390 // store the TR elements IDs on table element
9391 array_push($dom[($dom[$key]['parent'])]['trids'], $key);
9393 if (($dom[$key]['value'] == "th") OR ($dom[$key]['value'] == "td")) {
9394 if (isset($dom[$key]['attribute']['colspan'])) {
9395 $colspan = intval($dom[$key]['attribute']['colspan']);
9399 $dom[$key]['attribute']['colspan'] = $colspan;
9400 $dom[($dom[$key]['parent'])]['cols'] += $colspan;
9402 // set foreground color attribute
9403 if (isset($dom[$key]['attribute']['color']) AND (!empty($dom[$key]['attribute']['color']))) {
9404 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
9406 // set background color attribute
9407 if (isset($dom[$key]['attribute']['bgcolor']) AND (!empty($dom[$key]['attribute']['bgcolor']))) {
9408 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
9410 // check for width attribute
9411 if (isset($dom[$key]['attribute']['width'])) {
9412 $dom[$key]['width'] = intval($dom[$key]['attribute']['width']);
9414 // check for height attribute
9415 if (isset($dom[$key]['attribute']['height'])) {
9416 $dom[$key]['height'] = intval($dom[$key]['attribute']['height']);
9418 // check for text alignment
9419 if (isset($dom[$key]['attribute']['align']) AND (!empty($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
9420 $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
9422 } // end opening tag
9425 $dom[$key]['tag'] = false;
9426 $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
9427 $dom[$key]['parent'] = end($level);
9428 // calculate text width
9429 //$dom[$key]['width'] = $this->GetStringWidth($dom[$key]['value'], $dom[($dom[$key]['parent'])]['fontname'], $dom[($dom[$key]['parent'])]['fontstyle'], $dom[($dom[$key]['parent'])]['fontsize']);
9437 * Allows to preserve some HTML formatting (limited support).<br />
9438 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
9439 * 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,
9440 * @param string $html text to display
9441 * @param boolean $ln if true add a new line after text (default = true)
9442 * @param int $fill Indicates if the background must be painted (true) or transparent (false).
9443 * @param boolean $reseth if true reset the last cell height (default false).
9444 * @param boolean $cell if true add the default cMargin space to each Write (default false).
9445 * @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>
9447 function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
9448 // store current values
9449 $prevlMargin = $this->lMargin;
9450 $prevrMargin = $this->rMargin;
9451 $prevcMargin = $this->cMargin;
9452 $prevFontFamily = $this->FontFamily;
9453 $prevFontStyle = $this->FontStyle;
9454 $prevFontSizePt = $this->FontSizePt;
9455 $curfontname = $prevFontFamily;
9456 $curfontstyle = $prevFontStyle;
9457 $curfontsize = $prevFontSizePt;
9458 $prevbgcolor = $this->bgcolor;
9459 $prevfgcolor = $this->fgcolor;
9460 $this->newline = true;
9461 $minstartliney = $this->y;
9463 $startlinepage = $this->page;
9465 if (isset($this->footerlen[$this->page])) {
9466 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9468 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9470 $startlinepos = $this->footerpos[$this->page];
9474 $w = $this->x - $this->lMargin;
9476 $w = $this->w - $this->rMargin - $this->x;
9478 $w -= (2 * $this->cMargin);
9481 $this->x -= $this->cMargin;
9483 $this->x += $this->cMargin;
9486 $this->listindent = $this->GetStringWidth("0000");
9488 if ((empty($this->lasth))OR ($reseth)) {
9490 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9492 $dom = $this->getHtmlDomArray($html);
9493 $maxel = count($dom);
9495 while ($key < $maxel) {
9496 if ($dom[$key]['tag'] OR ($key == 0)) {
9497 if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
9498 $dom[$key]['align'] = ($this->rtl)?'R':'L';
9500 // vertically align image in line
9501 if ((!$this->newline) AND ($dom[$key]['value'] == 'img')
9502 AND (isset($dom[$key]['attribute']['height']))
9503 AND ($dom[$key]['attribute']['height'] > 0)
9505 $this->y += (($curfontsize / $this->k) - $this->pixelsToUnits($dom[$key]['attribute']['height']));
9506 $minstartliney = min($this->y, $minstartliney);
9507 } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
9508 // account for different font size
9509 $pfontname = $curfontname;
9510 $pfontstyle = $curfontstyle;
9511 $pfontsize = $curfontsize;
9512 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
9513 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
9514 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
9515 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
9516 $this->SetFont($fontname, $fontstyle, $fontsize);
9517 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9518 if (is_numeric($fontsize) AND ($fontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($fontsize != $curfontsize) AND (!$this->newline)) {
9519 $this->y += (($curfontsize - $fontsize) / $this->k);
9520 $minstartliney = min($this->y, $minstartliney);
9522 $curfontname = $fontname;
9523 $curfontstyle = $fontstyle;
9524 $curfontsize = $fontsize;
9527 if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
9528 $this->SetFillColorArray($dom[$key]['bgcolor']);
9531 $wfill = $fill | false;
9533 if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
9534 $this->SetTextColorArray($dom[$key]['fgcolor']);
9536 if (isset($dom[$key]['align'])) {
9537 $lalign = $dom[$key]['align'];
9539 if (empty($lalign)) {
9544 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
9546 // we are at the beginning of a new line
9547 if (isset($startlinex)) {
9548 $yshift = $minstartliney - $startliney;
9552 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9553 // the last line must be shifted to be aligned as requested
9554 $linew = abs($this->endlinex - $startlinex);
9555 $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9556 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9557 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9558 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9559 } elseif (isset($opentagpos)) {
9560 $midpos = $opentagpos;
9561 } elseif (isset($this->footerlen[$startlinepage])) {
9562 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9563 $midpos = $this->footerpos[$startlinepage];
9568 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9569 $pend = substr($this->pages[$startlinepage], $midpos);
9571 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9574 // calculate shifting amount
9575 $mdiff = abs($w - $linew);
9576 if ($plalign == "C") {
9578 $t_x = -($mdiff / 2);
9580 $t_x = ($mdiff / 2);
9582 } elseif (($plalign == "R") AND (!$this->rtl)) {
9583 // right alignment on LTR document
9585 } elseif (($plalign == "L") AND ($this->rtl)) {
9586 // left alignment on RTL document
9591 if (($t_x != 0) OR ($yshift < 0)) {
9593 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9594 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9595 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9596 // shift the annotations and links
9597 if (isset($this->PageAnnots[$this->page])) {
9598 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9599 if ($pac['y'] >= $minstartliney) {
9600 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9601 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9605 $this->y -= $yshift;
9609 $this->checkPageBreak($this->lasth);
9610 $this->SetFont($fontname, $fontstyle, $fontsize);
9612 $this->SetFillColorArray($this->bgcolor);
9614 $startlinex = $this->x;
9615 $startliney = $this->y;
9616 $minstartliney = $this->y;
9617 $startlinepage = $this->page;
9618 if (isset($endlinepos)) {
9619 $startlinepos = $endlinepos;
9622 if (isset($this->footerlen[$this->page])) {
9623 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9625 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9627 $startlinepos = $this->footerpos[$this->page];
9630 $this->newline = false;
9632 if (isset($opentagpos)) {
9635 if ($dom[$key]['tag']) {
9636 if ($dom[$key]['opening']) {
9637 // table content is handled in a special way
9638 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9639 $trid = $dom[$key]['parent'];
9640 $table_el = $dom[$trid]['parent'];
9641 if (!isset($dom[$table_el]['cols'])) {
9642 $dom[$table_el]['cols'] = $trid['cols'];
9644 // calculate cell width
9645 if (isset($dom[($dom[$key]['parent'])]['width'])) {
9646 $table_width = $this->pixelsToUnits($dom[($dom[$key]['parent'])]['width']);
9650 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
9651 $currentcmargin = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding']);
9653 $currentcmargin = 0;
9655 $this->cMargin = $currentcmargin;
9656 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
9657 $cellspacing = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing']);
9662 $cellspacingx = -$cellspacing;
9664 $cellspacingx = $cellspacing;
9666 $colspan = $dom[$key]['attribute']['colspan'];
9667 if (isset($dom[$key]['width'])) {
9668 $cellw = $this->pixelsToUnits($dom[$key]['width']);
9670 $cellw = ($colspan * ($table_width / $dom[$table_el]['cols']));
9672 $cellw -= $cellspacing;
9673 if (isset($dom[$key]['content'])) {
9674 $cell_content = $dom[$key]['content'];
9676 $cell_content = " ";
9678 $tagtype = $dom[$key]['value'];
9680 while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
9681 // move $key index forward
9684 if (!isset($dom[$trid]['startpage'])) {
9685 $dom[$trid]['startpage'] = $this->page;
9687 $this->setPage($dom[$trid]['startpage']);
9689 if (!isset($dom[$trid]['starty'])) {
9690 $dom[$trid]['starty'] = $this->y;
9692 $this->y = $dom[$trid]['starty'];
9694 if (!isset($dom[$trid]['startx'])) {
9695 $dom[$trid]['startx'] = $this->x;
9697 $this->x += ($cellspacingx / 2);
9698 if (isset($dom[$parentid]['attribute']['rowspan'])) {
9699 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
9703 // skip row-spanned cells started on the previous rows
9704 if (isset($dom[$table_el]['rowspans'])) {
9705 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9706 if (($trwsp['startx'] == $this->x) AND (($trwsp['starty'] < $this->y) OR ($trwsp['startpage'] < $this->page)) AND ($trwsp['rowspan'] > 0)) {
9707 $this->x = $trwsp['endx'] + $cellspacingx;
9711 // add rowspan information to table element
9713 if (isset($this->footerlen[$this->page])) {
9714 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9716 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9718 $trintmrkpos = $this->footerpos[$this->page];
9719 $trsid = array_push($dom[$table_el]['rowspans'], array('rowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startx' => $this->x, 'starty' => $this->y, 'intmrkpos' => $trintmrkpos));
9721 $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
9723 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
9725 // push background colors
9726 if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
9727 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
9730 // write the cell content
9731 $this->MultiCell($cellw, 0, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
9733 $this->cMargin = $currentcmargin;
9734 $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
9736 // update the end of row position
9737 if ($rowspan <= 1) {
9738 if (isset($dom[$trid]['endy'])) {
9739 if ($this->page == $dom[$trid]['endpage']) {
9740 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
9741 } elseif ($this->page > $dom[$trid]['endpage']) {
9742 $dom[$trid]['endy'] = $this->y;
9745 $dom[$trid]['endy'] = $this->y;
9747 if (isset($dom[$trid]['endpage'])) {
9748 $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
9750 $dom[$trid]['endpage'] = $this->page;
9753 // account for row-spanned cells
9754 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
9755 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
9756 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
9758 if (isset($dom[$table_el]['rowspans'])) {
9759 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9760 if ($trwsp['rowspan'] > 0) {
9761 if (isset($dom[$trid]['endpage'])) {
9762 if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
9763 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
9764 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[$trid]['endpage']) {
9765 $dom[$table_el]['rowspans'][$k]['endy'] = $trwsp['endy'];
9767 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
9768 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
9774 $this->x += ($cellspacingx / 2);
9776 // opening tag (or self-closing tag)
9777 if (!isset($opentagpos)) {
9778 if (isset($this->footerlen[$this->page])) {
9779 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9781 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9783 $opentagpos = $this->footerpos[$this->page];
9785 $this->openHTMLTagHandler($dom, $key, $cell);
9789 $this->closeHTMLTagHandler($dom, $key, $cell);
9791 } elseif (strlen($dom[$key]['value']) > 0) {
9793 if (!empty($this->lispacer)) {
9794 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
9795 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9796 $minstartliney = $this->y;
9798 $lspace = $this->GetStringWidth($this->lispacer." ");
9800 $this->x += $lspace;
9802 $this->x -= $lspace;
9804 $this->Write($this->lasth, $this->lispacer, '', false, '', false, 0, false);
9806 $this->lispacer = "";
9807 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
9808 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9809 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
9810 $this->y += (($pfontsize - $curfontsize) / $this->k);
9811 $minstartliney = min($this->y, $minstartliney);
9815 $this->htmlvspace = 0;
9817 if ($this->rtl OR $this->tmprtl) {
9818 $dom[$key]['value'] = rtrim($dom[$key]['value']);
9820 $dom[$key]['value'] = ltrim($dom[$key]['value']);
9826 $strrest = $this->addHtmlLink($this->HREF, $dom[$key]['value'], $wfill, true);
9828 $ctmpmargin = $this->cMargin;
9830 // write only until the end of the line and get the rest
9831 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, "", false, 0, true);
9832 $this->cMargin = $ctmpmargin;
9834 if (strlen($strrest) > 0) {
9835 // store the remaining string on the previous $key position
9836 $this->newline = true;
9839 $this->x -= $this->cMargin;
9841 $this->x += $this->cMargin;
9844 $dom[$key]['value'] = ltrim($strrest);
9849 } // end for each $key
9850 // align the last line
9851 if (isset($startlinex)) {
9852 $yshift = $minstartliney - $startliney;
9856 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9857 // the last line must be shifted to be aligned as requested
9858 $linew = abs($this->endlinex - $startlinex);
9859 $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9860 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9861 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9862 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9863 } elseif (isset($opentagpos)) {
9864 $midpos = $opentagpos;
9865 } elseif (isset($this->footerlen[$startlinepage])) {
9866 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9867 $midpos = $this->footerpos[$startlinepage];
9872 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9873 $pend = substr($this->pages[$startlinepage], $midpos);
9875 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9878 // calculate shifting amount
9879 $mdiff = abs($w - $linew);
9880 if ($plalign == "C") {
9882 $t_x = -($mdiff / 2);
9884 $t_x = ($mdiff / 2);
9886 } elseif (($plalign == "R") AND (!$this->rtl)) {
9887 // right alignment on LTR document
9889 } elseif (($plalign == "L") AND ($this->rtl)) {
9890 // left alignment on RTL document
9895 if (($t_x != 0) OR ($yshift < 0)) {
9897 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9898 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9899 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9900 // shift the annotations and links
9901 if (isset($this->PageAnnots[$this->page])) {
9902 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9903 if ($pac['y'] >= $minstartliney) {
9904 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9905 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9909 $this->y -= $yshift;
9913 if ($ln AND (!($cell AND ($dom[$key-1]['value'] == "table")))) {
9914 $this->Ln($this->lasth);
9916 // restore previous values
9917 $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
9918 $this->SetFillColorArray($prevbgcolor);
9919 $this->SetTextColorArray($prevfgcolor);
9920 $this->lMargin = $prevlMargin;
9921 $this->rMargin = $prevrMargin;
9922 $this->cMargin = $prevcMargin;
9927 * Process opening tags.
9928 * @param array $dom html dom array
9929 * @param int $key current element id
9930 * @param boolean $cell if true add the default cMargin space to each new line (default false).
9933 function openHTMLTagHandler(&$dom, $key, $cell=false) {
9935 $parent = $dom[($dom[$key]['parent'])];
9936 // check for text direction attribute
9937 if (isset($tag['attribute']['dir'])) {
9938 $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
9940 $this->tmprtl = false;
9943 switch($tag['value']) {
9945 $dom[$key]['rowspans'] = array();
9946 if (isset($tag['attribute']['cellpadding'])) {
9947 $this->oldcMargin = $this->cMargin;
9948 $this->cMargin = $this->pixelsToUnits($tag['attribute']['cellpadding']);
9953 // array of columns positions
9954 $dom[$key]['cellpos'] = array();
9962 $this->addHTMLVertSpace(1, $cell);
9963 $this->htmlvspace = 0;
9964 if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
9965 $hrWidth = $this->pixelsToUnits($tag['attribute']['width']);
9967 $hrWidth = $this->w - $this->lMargin - $this->rMargin;
9971 $prevlinewidth = $this->GetLineWidth();
9972 $this->Line($x, $y, $x + $hrWidth, $y);
9973 $this->SetLineWidth($prevlinewidth);
9974 $this->addHTMLVertSpace(1, $cell);
9978 $this->setStyle('b', true);
9982 $this->setStyle('i', true);
9986 $this->setStyle('u', true);
9990 $this->setStyle('d', true);
9994 if (array_key_exists('href', $tag['attribute'])) {
9995 $this->HREF = $tag['attribute']['href'];
10000 if (isset($tag['attribute']['src'])) {
10001 // replace relative path with real server path
10002 if ($tag['attribute']['src'][0] == '/') {
10003 $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
10005 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
10006 if (!isset($tag['attribute']['width'])) {
10007 $tag['attribute']['width'] = 0;
10009 if (!isset($tag['attribute']['height'])) {
10010 $tag['attribute']['height'] = 0;
10012 //if (!isset($tag['attribute']['align'])) {
10013 // the only alignment supported is "bottom"
10014 // further development is required for other modes.
10015 $tag['attribute']['align'] = 'bottom';
10017 switch($tag['attribute']['align']) {
10035 $fileinfo = pathinfo($tag['attribute']['src']);
10036 if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
10037 $type = strtolower($fileinfo['extension']);
10040 if (($type == "eps") OR ($type == "ai")) {
10041 $this->ImageEps($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', true, $align);
10043 $this->Image($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', '', $align);
10051 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
10055 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
10067 $this->addHTMLVertSpace(1, $cell);
10072 $this->rMargin += $this->listindent;
10074 $this->lMargin += $this->listindent;
10076 $this->addHTMLVertSpace(1, $cell);
10082 if ($tag['value'] == "ol") {
10083 $this->listordered[$this->listnum] = true;
10085 $this->listordered[$this->listnum] = false;
10087 $this->listcount[$this->listnum] = 0;
10089 $this->rMargin += $this->listindent;
10091 $this->lMargin += $this->listindent;
10096 $this->Ln('', $cell);
10097 if ($tag['value'] == 'li') {
10098 if ($this->listordered[$this->listnum]) {
10099 if (isset($tag['attribute']['value'])) {
10100 $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
10102 $this->listcount[$this->listnum]++;
10104 $this->lispacer = ".".($this->listcount[$this->listnum]);
10106 $this->lispacer = ($this->listcount[$this->listnum]).".";
10109 //unordered list symbol
10110 $this->lispacer = "-";
10113 $this->lispacer = "";
10117 case 'blockquote': {
10119 $this->rMargin += $this->listindent;
10121 $this->lMargin += $this->listindent;
10123 $this->addHTMLVertSpace(2, $cell);
10127 $this->Ln('', $cell);
10131 $this->addHTMLVertSpace(2, $cell);
10135 $this->addHTMLVertSpace(2, $cell);
10139 $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
10143 $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
10152 $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k);
10162 * Process closing tags.
10163 * @param array $dom html dom array
10164 * @param int $key current element id
10165 * @param boolean $cell if true add the default cMargin space to each new line (default false).
10166 * @access protected
10168 function closeHTMLTagHandler(&$dom, $key, $cell=false) {
10170 $parent = $dom[($dom[$key]['parent'])];
10172 switch($tag['value']) {
10178 $table_el = $dom[($dom[$key]['parent'])]['parent'];
10179 // update row-spanned cells
10180 if (isset($dom[$table_el]['rowspans'])) {
10181 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
10182 $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
10183 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
10184 if ($dom[$table_el]['rowspans'][$k]['endpage'] == $dom[($dom[$key]['parent'])]['endpage']) {
10185 $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
10186 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[($dom[$key]['parent'])]['endpage']) {
10187 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
10188 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
10193 $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
10194 $this->y = $dom[($dom[$key]['parent'])]['endy'];
10195 if (isset($dom[$table_el]['attribute']['cellspacing'])) {
10196 $cellspacing = $this->pixelsToUnits($dom[$table_el]['attribute']['cellspacing']);
10197 $this->y += $cellspacing;
10199 $this->Ln(0, $cell);
10200 $this->x = $dom[($dom[$key]['parent'])]['startx'];
10205 $table_el = $parent;
10206 if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
10207 OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
10213 foreach ($table_el['trids'] as $j => $trkey) {
10214 $parent = $dom[$trkey];
10215 $restspace = $this->getPageHeight() - $this->y - $this->getBreakMargin();
10216 // for each cell on the row
10217 foreach ($parent['cellpos'] as $k => $cellpos) {
10218 if (isset($cellpos['rowspanid'])) {
10219 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
10220 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
10221 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
10222 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
10223 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
10225 $endy = $parent['endy'];
10226 $startpage = $parent['startpage'];
10227 $endpage = $parent['endpage'];
10229 $this->setPage($startpage);
10230 $this->y = $parent['starty'];
10231 if ($endpage > $startpage) {
10232 // design borders around HTML cells.
10233 for ($page=$startpage; $page <= $endpage; $page++) {
10234 $this->setPage($page);
10235 if ($page == $startpage) {
10236 $this->y = $this->getPageHeight() - $restspace - $this->getBreakMargin();
10238 } elseif ($page == $endpage) {
10239 $this->y = $this->tMargin; // put cursor at the beginning of text
10240 $ch = $endy - $this->tMargin;
10242 $this->y = $this->tMargin; // put cursor at the beginning of text
10243 $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
10246 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10247 $this->SetFillColorArray($cellpos['bgcolor']);
10252 $cw = abs($cellpos['endx'] - $cellpos['startx']);
10253 $this->x = $cellpos['startx'];
10254 // design a cell around the text
10255 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10256 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10257 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10258 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10259 $this->intmrk[$this->page] += strlen($ccode."\n");
10262 $ch = $endy - $parent['starty'];
10263 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10264 $this->SetFillColorArray($cellpos['bgcolor']);
10269 $cw = abs($cellpos['endx'] - $cellpos['startx']);
10270 $this->x = $cellpos['startx'];
10271 $this->y = $parent['starty'];
10272 // design a cell around the text
10273 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10274 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10275 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10276 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10277 $this->intmrk[$this->page] += strlen($ccode."\n");
10280 if (isset($table_el['attribute']['cellspacing'])) {
10281 $cellspacing = $this->pixelsToUnits($table_el['attribute']['cellspacing']);
10282 $this->y += $cellspacing;
10284 $this->Ln(0, $cell);
10285 $this->x = $parent['startx'];
10287 if (isset($parent['cellpadding'])) {
10288 $this->cMargin = $this->oldcMargin;
10291 $this->lasth = $this->FontSize * $this->cell_height_ratio;
10295 $this->setStyle('b', false);
10299 $this->setStyle('i', false);
10303 $this->setStyle('u', false);
10307 $this->setStyle('d', false);
10315 $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
10319 $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
10323 $this->addHTMLVertSpace(1, $cell);
10326 case 'blockquote': {
10328 $this->rMargin -= $this->listindent;
10330 $this->lMargin -= $this->listindent;
10332 $this->addHTMLVertSpace(2, $cell);
10336 $this->addHTMLVertSpace(2, $cell);
10341 if ($this->listnum <= 0) {
10342 $this->listnum = 0;
10343 $this->addHTMLVertSpace(2, $cell);
10348 $this->lispacer = "";
10352 $this->lispacer = "";
10354 $this->rMargin -= $this->listindent;
10356 $this->lMargin -= $this->listindent;
10363 $this->lispacer = "";
10365 $this->rMargin -= $this->listindent;
10367 $this->lMargin -= $this->listindent;
10369 if ($this->listnum <= 0) {
10370 $this->listnum = 0;
10371 $this->addHTMLVertSpace(2, $cell);
10373 $this->lasth = $this->FontSize * $this->cell_height_ratio;
10377 $this->lispacer = "";
10386 $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k);
10393 $this->tmprtl = false;
10397 * Add vertical spaces if needed.
10398 * @param int $n number of spaces to add
10399 * @param boolean $cell if true add the default cMargin space to each new line (default false).
10400 * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
10401 * @access protected
10403 function addHTMLVertSpace($n, $cell=false, $h='') {
10404 if (is_string($h)) {
10405 $vsize = $n * $this->lasth;
10409 if ($vsize > $this->htmlvspace) {
10410 $this->Ln(($vsize - $this->htmlvspace), $cell);
10411 $this->htmlvspace = $vsize;
10415 } // END OF TCPDF CLASS
10417 //============================================================+
10419 //============================================================+