]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/tcpdf/tcpdf.php
Release 6.5.16
[Github/sugarcrm.git] / include / tcpdf / tcpdf.php
1 <?php
2
3 /*
4
5 Modification information for LGPL compliance
6
7 Fri Dec 2 2011 smalyshev - Added unserialize/destruct vulnerability protection
8
9 Mon May 30 16:16:13 2011 +0300 - alex-vlasov - Bug 41216 - currency is displayed on 2 lines instead of one when printing a quote to PDF
10
11 r57813 - 2010-08-19 10:34:44 -0700 (Thu, 19 Aug 2010) - kjing - Author: John Mertic <jmertic@sugarcrm.com>
12     Bug 39085 - When loading the opposite search panel via ajax on the ListViews, call the index action instead of the ListView action to avoid touching pre-MVC code by accident.
13
14 r56990 - 2010-06-16 13:05:36 -0700 (Wed, 16 Jun 2010) - kjing - snapshot "Mango" svn branch to a new one for GitHub sync
15
16 r56989 - 2010-06-16 13:01:33 -0700 (Wed, 16 Jun 2010) - kjing - defunt "Mango" svn dev branch before github cutover
17
18 r55980 - 2010-04-19 13:31:28 -0700 (Mon, 19 Apr 2010) - kjing - create Mango (6.1) based on windex
19
20 r53409 - 2010-01-03 19:31:15 -0800 (Sun, 03 Jan 2010) - roger - merge -r50376:HEAD from fuji_newtag_tmp
21
22 r51719 - 2009-10-22 10:18:00 -0700 (Thu, 22 Oct 2009) - mitani - Converted to Build 3  tags and updated the build system
23
24 r51634 - 2009-10-19 13:32:22 -0700 (Mon, 19 Oct 2009) - mitani - Windex is the branch for Sugar Sales 1.0 development
25
26 r51443 - 2009-10-12 13:34:36 -0700 (Mon, 12 Oct 2009) - jmertic - Bug 33332 - Made application PHP 5.3 compliant with E_DEPRECATED warnings on by:
27 - Changing all ereg function to either preg or simple string based ones
28 - No more references to magic quotes.
29 - Change all the session_unregister() functions to just unset() the correct session variable instead.
30
31 r50375 - 2009-08-24 18:07:43 -0700 (Mon, 24 Aug 2009) - dwong - branch kobe2 from tokyo r50372
32
33 r47904 - 2009-06-02 11:54:10 -0700 (Tue, 02 Jun 2009) - jenny - Adding changes that were made to the earlier version of this file to support jpg images.
34
35 r47900 - 2009-06-02 11:26:55 -0700 (Tue, 02 Jun 2009) - jenny - Updating with changes from bsoufflet.
36
37 r46662 - 2009-04-29 10:48:07 -0700 (Wed, 29 Apr 2009) - jenny - Invoking native jpg image support which isnt' automatically there.
38
39 r46617 - 2009-04-28 16:08:45 -0700 (Tue, 28 Apr 2009) - jenny - Fixing a bug in TCPDF that checks to see if the GD library is installed.
40
41 r46451 - 2009-04-23 16:57:40 -0700 (Thu, 23 Apr 2009) - jenny - tcpdf initial checkin.
42
43
44 */
45
46
47 //============================================================+
48 // File name   : tcpdf.php
49 // Begin       : 2002-08-03
50 // Last Update : 2009-05-28
51 // Author      : Nicola Asuni - info@tecnick.com - http://www.tcpdf.org
52 // Version     : 4.6.013
53 // License     : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
54 //      ----------------------------------------------------------------------------
55 //  Copyright (C) 2002-2009  Nicola Asuni - Tecnick.com S.r.l.
56 //
57 //      This program is free software: you can redistribute it and/or modify
58 //      it under the terms of the GNU Lesser General Public License as published by
59 //      the Free Software Foundation, either version 2.1 of the License, or
60 //      (at your option) any later version.
61 //
62 //      This program is distributed in the hope that it will be useful,
63 //      but WITHOUT ANY WARRANTY; without even the implied warranty of
64 //      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
65 //      GNU Lesser General Public License for more details.
66 //
67 //      You should have received a copy of the GNU Lesser General Public License
68 //      along with this program.  If not, see <http://www.gnu.org/licenses/>.
69 //
70 //      See LICENSE.TXT file for more information.
71 //  ----------------------------------------------------------------------------
72 //
73 // Description : This is a PHP class for generating PDF documents without
74 //               requiring external extensions.
75 //
76 // NOTE:
77 // This class was originally derived in 2002 from the Public
78 // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
79 // but now is almost entirely rewritten.
80 //
81 // Main features:
82 //  * no external libraries are required for the basic functions;
83 //      * supports all ISO page formats;
84 //      * supports custom page formats, margins and units of measure;
85 //      * supports UTF-8 Unicode and Right-To-Left languages;
86 //      * supports TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;
87 //      * supports document encryption;
88 //      * includes methods to publish some XHTML code;
89 //      * includes graphic (geometric) and transformation methods;
90 //      * includes Javascript and forms support;
91 //      * includes a method to print various barcode formats: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS;
92 //      * includes methods to set Bookmarks and print a Table of Content;
93 //      * includes methods to move and delete pages;
94 //      * includes methods for automatic page header and footer management;
95 //      * supports automatic page break;
96 //      * supports automatic page numbering and page groups;
97 //      * supports automatic line break and text justification;
98 //      * supports JPEG and PNG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/www/formats.html)
99 //      * supports stroke and clipping mode for text;
100 //      * supports clipping masks;
101 //      * supports Grayscale, RGB, CMYK, Spot Colors and Transparencies;
102 //      * supports several annotations, including links, text and file attachments;
103 //      * supports page compression (requires zlib extension);
104 //  * supports text hyphenation.
105 //  * supports transactions to UNDO commands.
106 //
107 // -----------------------------------------------------------
108 // THANKS TO:
109 //
110 // Olivier Plathey (http://www.fpdf.org) for original FPDF.
111 // Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support.
112 // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm.
113 // Warren Sherliker (wsherliker@gmail.com) for better image handling.
114 // dullus for text Justification.
115 // Bob Vincent (pillarsdotnet@users.sourceforge.net) for <li> value attribute.
116 // Patrick Benny for text stretch suggestion on Cell().
117 // Johannes G�ntert for JavaScript support.
118 // Denis Van Nuffelen for Dynamic Form.
119 // Jacek Czekaj for multibyte justification
120 // Anthony Ferrara for the reintroduction of legacy image methods.
121 // Sourceforge user 1707880 (hucste) for line-trough mode.
122 // Larry Stanbery for page groups.
123 // Martin Hall-May for transparency.
124 // Aaron C. Spike for Polycurve method.
125 // Mohamad Ali Golkar, Saleh AlMatrafe, Charles Abbott for Arabic and Persian support.
126 // Moritz Wagner and Andreas Wurmser for graphic functions.
127 // Andrew Whitehead for core fonts support.
128 // Esteban Jo�l Mar�n for OpenType font conversion.
129 // Teus Hagen for several suggestions and fixes.
130 // Yukihiro Nakadaira for CID-0 CJK fonts fixes.
131 // Kosmas Papachristos for some CSS improvements.
132 // Marcel Partap for some fixes.
133 // Won Kyu Park for several suggestions, fixes and patches.
134 // Anyone that has reported a bug or sent a suggestion.
135 //============================================================+
136
137 /**
138  * This is a PHP class for generating PDF documents without requiring external extensions.<br>
139  * TCPDF project (http://www.tcpdf.org) was originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
140  * <h3>TCPDF main features are:</h3>
141  * <ul>
142 * <li>no external libraries are required for the basic functions;</li>
143 * <li>supports all ISO page formats;</li>
144 * <li>supports custom page formats, margins and units of measure;</li>
145 * <li>supports UTF-8 Unicode and Right-To-Left languages;</li>
146 * <li>supports TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;</li>
147 * <li>supports document encryption;</li>
148 * <li>includes methods to publish some XHTML code;</li>
149 * <li>includes graphic (geometric) and transformation methods;</li>
150 * <li>includes Javascript and forms support;</li>
151 * <li>includes a method to print various barcode formats: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS;</li>
152 * <li>includes methods to set Bookmarks and print a Table of Content;</li>
153 * <li>includes methods to move and delete pages;</li>
154 * <li>includes methods for automatic page header and footer management;</li>
155 * <li>supports automatic page break;</li>
156 * <li>supports automatic page numbering and page groups;</li>
157 * <li>supports automatic line break and text justification;</li>
158 * <li>supports JPEG and PNG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/www/formats.html)</li>
159 * <li>supports stroke and clipping mode for text;</li>
160 * <li>supports clipping masks;</li>
161 * <li>supports Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
162 * <li>supports several annotations, including links, text and file attachments;</li>
163 * <li>supports page compression (requires zlib extension);</li>
164 * <li>supports text hyphenation.</li>
165 * <li>supports transactions to UNDO commands.</li>
166  * </ul>
167  * Tools to encode your unicode fonts are on fonts/utils directory.</p>
168  * @package com.tecnick.tcpdf
169  * @abstract Class for generating PDF files on-the-fly without requiring external extensions.
170  * @author Nicola Asuni
171  * @copyright 2002-2009 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
172  * @link http://www.tcpdf.org
173  * @license http://www.gnu.org/copyleft/lesser.html LGPL
174  * @version 4.6.013
175  */
176
177 /**
178  * main configuration file
179  */
180 require_once(dirname(__FILE__).'/config/tcpdf_config.php');
181
182 // includes some support files
183
184 /**
185  * unicode data
186  */
187 require_once(dirname(__FILE__).'/unicode_data.php');
188
189 /**
190  * html colors table
191  */
192 require_once(dirname(__FILE__).'/htmlcolors.php');
193
194 if (!class_exists('TCPDF', false)) {
195         /**
196          * define default PDF document producer
197          */
198         define('PDF_PRODUCER', 'TCPDF 4.6.013 (http://www.tcpdf.org)');
199
200         /**
201         * This is a PHP class for generating PDF documents without requiring external extensions.<br>
202         * TCPDF project (http://www.tcpdf.org) has been originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
203         * @name TCPDF
204         * @package com.tecnick.tcpdf
205         * @version 4.6.013
206         * @author Nicola Asuni - info@tecnick.com
207         * @link http://www.tcpdf.org
208         * @license http://www.gnu.org/copyleft/lesser.html LGPL
209         */
210         class TCPDF {
211
212                 // protected or Protected properties
213
214                 /**
215                 * @var current page number
216                 * @access protected
217                 */
218                 protected $page;
219
220                 /**
221                 * @var current object number
222                 * @access protected
223                 */
224                 protected $n;
225
226                 /**
227                 * @var array of object offsets
228                 * @access protected
229                 */
230                 protected $offsets;
231
232                 /**
233                 * @var buffer holding in-memory PDF
234                 * @access protected
235                 */
236                 protected $buffer;
237
238                 /**
239                 * @var array containing pages
240                 * @access protected
241                 */
242                 protected $pages = array();
243
244                 /**
245                 * @var current document state
246                 * @access protected
247                 */
248                 protected $state;
249
250                 /**
251                 * @var compression flag
252                 * @access protected
253                 */
254                 protected $compress;
255
256                 /**
257                 * @var current page orientation (P = Portrait, L = Landscape)
258                 * @access protected
259                 */
260                 protected $CurOrientation;
261
262                 /**
263                 * @var array that stores page dimensions and graphic status.<ul><li>$this->pagedim[$this->page]['w'] => page_width_in_points</li><li>$this->pagedim[$this->page]['h'] => height in points</li><li>$this->pagedim[$this->page]['wk'] => page_width_in_points</li><li>$this->pagedim[$this->page]['hk'] => height</li><li>$this->pagedim[$this->page]['tm'] => top_margin</li><li>$this->pagedim[$this->page]['bm'] => bottom_margin</li><li>$this->pagedim[$this->page]['lm'] => left_margin</li><li>$this->pagedim[$this->page]['rm'] => right_margin</li><li>$this->pagedim[$this->page]['pb'] => auto_page_break</li><li>$this->pagedim[$this->page]['or'] => page_orientation</li><li>$this->pagedim[$this->page]['olm'] => original_left_margin</li><li>$this->pagedim[$this->page]['orm'] => original_right_margin</li></ul>
264                 * @access protected
265                 */
266                 protected $pagedim = array();
267
268                 /**
269                 * @var scale factor (number of points in user unit)
270                 * @access protected
271                 */
272                 protected $k;
273
274                 /**
275                 * @var width of page format in points
276                 * @access protected
277                 */
278                 protected $fwPt;
279
280                 /**
281                 * @var height of page format in points
282                 * @access protected
283                 */
284                 protected $fhPt;
285
286                 /**
287                 * @var current width of page in points
288                 * @access protected
289                 */
290                 protected $wPt;
291
292                 /**
293                 * @var current height of page in points
294                 * @access protected
295                 */
296                 protected $hPt;
297
298                 /**
299                 * @var current width of page in user unit
300                 * @access protected
301                 */
302                 protected $w;
303
304                 /**
305                 * @var current height of page in user unit
306                 * @access protected
307                 */
308                 protected $h;
309
310                 /**
311                 * @var left margin
312                 * @access protected
313                 */
314                 protected $lMargin;
315
316                 /**
317                 * @var top margin
318                 * @access protected
319                 */
320                 protected $tMargin;
321
322                 /**
323                 * @var right margin
324                 * @access protected
325                 */
326                 protected $rMargin;
327
328                 /**
329                 * @var page break margin
330                 * @access protected
331                 */
332                 protected $bMargin;
333
334                 /**
335                 * @var cell internal padding
336                 * @access protected
337                 */
338                 //protected
339                 public $cMargin;
340
341                 /**
342                 * @var cell internal padding (previous value)
343                 * @access protected
344                 */
345                 protected $oldcMargin;
346
347                 /**
348                 * @var current horizontal position in user unit for cell positioning
349                 * @access protected
350                 */
351                 protected $x;
352
353                 /**
354                 * @var current vertical position in user unit for cell positioning
355                 * @access protected
356                 */
357                 protected $y;
358
359                 /**
360                 * @var height of last cell printed
361                 * @access protected
362                 */
363                 protected $lasth;
364
365                 /**
366                 * @var line width in user unit
367                 * @access protected
368                 */
369                 protected $LineWidth;
370
371                 /**
372                 * @var array of standard font names
373                 * @access protected
374                 */
375                 protected $CoreFonts;
376
377                 /**
378                 * @var array of used fonts
379                 * @access protected
380                 */
381                 protected $fonts = array();
382
383                 /**
384                 * @var array of font files
385                 * @access protected
386                 */
387                 protected $FontFiles = array();
388
389                 /**
390                 * @var array of encoding differences
391                 * @access protected
392                 */
393                 protected $diffs = array();
394
395                 /**
396                 * @var array of used images
397                 * @access protected
398                 */
399                 protected $images = array();
400
401                 /**
402                 * @var array of Annotations in pages
403                 * @access protected
404                 */
405                 protected $PageAnnots = array();
406
407                 /**
408                 * @var array of internal links
409                 * @access protected
410                 */
411                 protected $links = array();
412
413                 /**
414                 * @var current font family
415                 * @access protected
416                 */
417                 protected $FontFamily;
418
419                 /**
420                 * @var current font style
421                 * @access protected
422                 */
423                 protected $FontStyle;
424
425                 /**
426                 * @var current font ascent (distance between font top and baseline)
427                 * @access protected
428                 * @since 2.8.000 (2007-03-29)
429                 */
430                 protected $FontAscent;
431
432                 /**
433                 * @var current font descent (distance between font bottom and baseline)
434                 * @access protected
435                 * @since 2.8.000 (2007-03-29)
436                 */
437                 protected $FontDescent;
438
439                 /**
440                 * @var underlining flag
441                 * @access protected
442                 */
443                 protected $underline;
444
445                 /**
446                 * @var current font info
447                 * @access protected
448                 */
449                 protected $CurrentFont;
450
451                 /**
452                 * @var current font size in points
453                 * @access protected
454                 */
455                 protected $FontSizePt;
456
457                 /**
458                 * @var current font size in user unit
459                 * @access protected
460                 */
461                 protected $FontSize;
462
463                 /**
464                 * @var commands for drawing color
465                 * @access protected
466                 */
467                 protected $DrawColor;
468
469                 /**
470                 * @var commands for filling color
471                 * @access protected
472                 */
473                 protected $FillColor;
474
475                 /**
476                 * @var commands for text color
477                 * @access protected
478                 */
479                 protected $TextColor;
480
481                 /**
482                 * @var indicates whether fill and text colors are different
483                 * @access protected
484                 */
485                 protected $ColorFlag;
486
487                 /**
488                 * @var automatic page breaking
489                 * @access protected
490                 */
491                 protected $AutoPageBreak;
492
493                 /**
494                 * @var threshold used to trigger page breaks
495                 * @access protected
496                 */
497                 protected $PageBreakTrigger;
498
499                 /**
500                 * @var flag set when processing footer
501                 * @access protected
502                 */
503                 protected $InFooter = false;
504
505                 /**
506                 * @var zoom display mode
507                 * @access protected
508                 */
509                 protected $ZoomMode;
510
511                 /**
512                 * @var layout display mode
513                 * @access protected
514                 */
515                 protected $LayoutMode;
516
517                 /**
518                 * @var title
519                 * @access protected
520                 */
521                 protected $title = '';
522
523                 /**
524                 * @var subject
525                 * @access protected
526                 */
527                 protected $subject = '';
528
529                 /**
530                 * @var author
531                 * @access protected
532                 */
533                 protected $author = '';
534
535                 /**
536                 * @var keywords
537                 * @access protected
538                 */
539                 protected $keywords = '';
540
541                 /**
542                 * @var creator
543                 * @access protected
544                 */
545                 protected $creator = '';
546
547                 /**
548                 * @var alias for total number of pages
549                 * @access protected
550                 */
551                 protected $AliasNbPages = '{nb}';
552
553                 /**
554                 * @var alias for page number
555                 * @access protected
556                 */
557                 protected $AliasNumPage = '{pnb}';
558
559                 /**
560                 * @var right-bottom corner X coordinate of inserted image
561                 * @since 2002-07-31
562                 * @author Nicola Asuni
563                 * @access protected
564                 */
565                 protected $img_rb_x;
566
567                 /**
568                 * @var right-bottom corner Y coordinate of inserted image
569                 * @since 2002-07-31
570                 * @author Nicola Asuni
571                 * @access protected
572                 */
573                 protected $img_rb_y;
574
575                 /**
576                 * @var adjusting factor to convert pixels to user units.
577                 * @since 2004-06-14
578                 * @author Nicola Asuni
579                 * @access protected
580                 */
581                 protected $imgscale = 1;
582
583                 /**
584                 * @var boolean set to true when the input text is unicode (require unicode fonts)
585                 * @since 2005-01-02
586                 * @author Nicola Asuni
587                 * @access protected
588                 */
589                 protected $isunicode = false;
590
591                 /**
592                 * @var PDF version
593                 * @since 1.5.3
594                 * @access protected
595                 */
596                 protected $PDFVersion = '1.7';
597
598
599                 // ----------------------
600
601                 /**
602                  * @var Minimum distance between header and top page margin.
603                  * @access protected
604                  */
605                 protected $header_margin;
606
607                 /**
608                  * @var Minimum distance between footer and bottom page margin.
609                  * @access protected
610                  */
611                 protected $footer_margin;
612
613                 /**
614                  * @var original left margin value
615                  * @access protected
616                  * @since 1.53.0.TC013
617                  */
618                 protected $original_lMargin;
619
620                 /**
621                  * @var original right margin value
622                  * @access protected
623                  * @since 1.53.0.TC013
624                  */
625                 protected $original_rMargin;
626
627                 /**
628                  * @var Header font.
629                  * @access protected
630                  */
631                 protected $header_font;
632
633                 /**
634                  * @var Footer font.
635                  * @access protected
636                  */
637                 protected $footer_font;
638
639                 /**
640                  * @var Language templates.
641                  * @access protected
642                  */
643                 protected $l;
644
645                 /**
646                  * @var Barcode to print on page footer (only if set).
647                  * @access protected
648                  */
649                 protected $barcode = false;
650
651                 /**
652                  * @var If true prints header
653                  * @access protected
654                  */
655                 protected $print_header = true;
656
657                 /**
658                  * @var If true prints footer.
659                  * @access protected
660                  */
661                 protected $print_footer = true;
662
663                 /**
664                  * @var Header image logo.
665                  * @access protected
666                  */
667                 protected $header_logo = '';
668
669                 /**
670                  * @var Header image logo width in mm.
671                  * @access protected
672                  */
673                 protected $header_logo_width = 30;
674
675                 /**
676                  * @var String to print as title on document header.
677                  * @access protected
678                  */
679                 protected $header_title = '';
680
681                 /**
682                  * @var String to print on document header.
683                  * @access protected
684                  */
685                 protected $header_string = '';
686
687                 /**
688                  * @var Default number of columns for html table.
689                  * @access protected
690                  */
691                 protected $default_table_columns = 4;
692
693
694                 // variables for html parser
695
696                 /**
697                  * @var HTML PARSER: array to store current link and rendering styles.
698                  * @access protected
699                  */
700                 protected $HREF = array();
701
702                 /**
703                  * @var store a list of available fonts on filesystem.
704                  * @access protected
705                  */
706                 protected $fontlist = array();
707
708                 /**
709                  * @var current foreground color
710                  * @access protected
711                  */
712                 protected $fgcolor;
713
714                 /**
715                  * @var HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
716                  * @access protected
717                  */
718                 protected $listordered = array();
719
720                 /**
721                  * @var HTML PARSER: array count list items on nested lists.
722                  * @access protected
723                  */
724                 protected $listcount = array();
725
726                 /**
727                  * @var HTML PARSER: current list nesting level.
728                  * @access protected
729                  */
730                 protected $listnum = 0;
731
732                 /**
733                  * @var HTML PARSER: indent amount for lists.
734                  * @access protected
735                  */
736                 protected $listindent;
737
738                 /**
739                  * @var current background color
740                  * @access protected
741                  */
742                 protected $bgcolor;
743
744                 /**
745                  * @var Store temporary font size in points.
746                  * @access protected
747                  */
748                 protected $tempfontsize = 10;
749
750                 /**
751                  * @var spacer for LI tags.
752                  * @access protected
753                  */
754                 protected $lispacer = '';
755
756                 /**
757                  * @var default encoding
758                  * @access protected
759                  * @since 1.53.0.TC010
760                  */
761                 protected $encoding = 'UTF-8';
762
763                 /**
764                  * @var PHP internal encoding
765                  * @access protected
766                  * @since 1.53.0.TC016
767                  */
768                 protected $internal_encoding;
769
770                 /**
771                  * @var indicates if the document language is Right-To-Left
772                  * @access protected
773                  * @since 2.0.000
774                  */
775                 protected $rtl = false;
776
777                 /**
778                  * @var used to force RTL or LTR string inversion
779                  * @access protected
780                  * @since 2.0.000
781                  */
782                 protected $tmprtl = false;
783
784                 // --- Variables used for document encryption:
785
786                 /**
787                  * Indicates whether document is protected
788                  * @access protected
789                  * @since 2.0.000 (2008-01-02)
790                  */
791                 protected $encrypted;
792
793                 /**
794                  * U entry in pdf document
795                  * @access protected
796                  * @since 2.0.000 (2008-01-02)
797                  */
798                 protected $Uvalue;
799
800                 /**
801                  * O entry in pdf document
802                  * @access protected
803                  * @since 2.0.000 (2008-01-02)
804                  */
805                 protected $Ovalue;
806
807                 /**
808                  * P entry in pdf document
809                  * @access protected
810                  * @since 2.0.000 (2008-01-02)
811                  */
812                 protected $Pvalue;
813
814                 /**
815                  * encryption object id
816                  * @access protected
817                  * @since 2.0.000 (2008-01-02)
818                  */
819                 protected $enc_obj_id;
820
821                 /**
822                  * last RC4 key encrypted (cached for optimisation)
823                  * @access protected
824                  * @since 2.0.000 (2008-01-02)
825                  */
826                 protected $last_rc4_key;
827
828                 /**
829                  * last RC4 computed key
830                  * @access protected
831                  * @since 2.0.000 (2008-01-02)
832                  */
833                 protected $last_rc4_key_c;
834
835                 /**
836                  * RC4 padding
837                  * @access protected
838                  */
839                 protected $padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
840
841                 /**
842                  * RC4 encryption key
843                  * @access protected
844                  */
845                 protected $encryption_key;
846
847                 // --- bookmark ---
848
849                 /**
850                  * Outlines for bookmark
851                  * @access protected
852                  * @since 2.1.002 (2008-02-12)
853                  */
854                 protected $outlines = array();
855
856                 /**
857                  * Outline root for bookmark
858                  * @access protected
859                  * @since 2.1.002 (2008-02-12)
860                  */
861                 protected $OutlineRoot;
862
863
864                 // --- javascript and form ---
865
866                 /**
867                  * javascript code
868                  * @access protected
869                  * @since 2.1.002 (2008-02-12)
870                  */
871                 protected $javascript = '';
872
873                 /**
874                  * javascript counter
875                  * @access protected
876                  * @since 2.1.002 (2008-02-12)
877                  */
878                 protected $n_js;
879
880                 /**
881                  * line trough state
882                  * @access protected
883                  * @since 2.8.000 (2008-03-19)
884                  */
885                 protected $linethrough;
886
887                 // --- Variables used for User's Rights ---
888                 // See PDF reference chapter 8.7 Digital Signatures
889
890                 /**
891                  * If true enables user's rights on PDF reader
892                  * @access protected
893                  * @since 2.9.000 (2008-03-26)
894                  */
895                 protected $ur;
896
897                 /**
898                  * Names specifying additional document-wide usage rights for the document.
899                  * @access protected
900                  * @since 2.9.000 (2008-03-26)
901                  */
902                 protected $ur_document;
903
904                 /**
905                  * Names specifying additional annotation-related usage rights for the document.
906                  * @access protected
907                  * @since 2.9.000 (2008-03-26)
908                  */
909                 protected $ur_annots;
910
911                 /**
912                  * Names specifying additional form-field-related usage rights for the document.
913                  * @access protected
914                  * @since 2.9.000 (2008-03-26)
915                  */
916                 protected $ur_form;
917
918                 /**
919                  * Names specifying additional signature-related usage rights for the document.
920                  * @access protected
921                  * @since 2.9.000 (2008-03-26)
922                  */
923                 protected $ur_signature;
924
925                 /**
926                  * Dot Per Inch Document Resolution (do not change)
927                  * @access protected
928                  * @since 3.0.000 (2008-03-27)
929                  */
930                 protected $dpi = 72;
931
932                 /**
933                  * Array of page numbers were a new page group was started
934                  * @access protected
935                  * @since 3.0.000 (2008-03-27)
936                  */
937                 protected $newpagegroup = array();
938
939                 /**
940                  * Contains the number of pages of the groups
941                  * @access protected
942                  * @since 3.0.000 (2008-03-27)
943                  */
944                 protected $pagegroups;
945
946                 /**
947                  * Contains the alias of the current page group
948                  * @access protected
949                  * @since 3.0.000 (2008-03-27)
950                  */
951                 protected $currpagegroup;
952
953                 /**
954                  * Restrict the rendering of some elements to screen or printout.
955                  * @access protected
956                  * @since 3.0.000 (2008-03-27)
957                  */
958                 protected $visibility = 'all';
959
960                 /**
961                  * Print visibility.
962                  * @access protected
963                  * @since 3.0.000 (2008-03-27)
964                  */
965                 protected $n_ocg_print;
966
967                 /**
968                  * View visibility.
969                  * @access protected
970                  * @since 3.0.000 (2008-03-27)
971                  */
972                 protected $n_ocg_view;
973
974                 /**
975                  * Array of transparency objects and parameters.
976                  * @access protected
977                  * @since 3.0.000 (2008-03-27)
978                  */
979                 protected $extgstates;
980
981                 /**
982                  * Set the default JPEG compression quality (1-100)
983                  * @access protected
984                  * @since 3.0.000 (2008-03-27)
985                  */
986                 protected $jpeg_quality;
987
988                 /**
989                  * Default cell height ratio.
990                  * @access protected
991                  * @since 3.0.014 (2008-05-23)
992                  */
993                 protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
994
995                 /**
996                  * PDF viewer preferences.
997                  * @access protected
998                  * @since 3.1.000 (2008-06-09)
999                  */
1000                 protected $viewer_preferences;
1001
1002                 /**
1003                  * A name object specifying how the document should be displayed when opened.
1004                  * @access protected
1005                  * @since 3.1.000 (2008-06-09)
1006                  */
1007                 protected $PageMode;
1008
1009                 /**
1010                  * Array for storing gradient information.
1011                  * @access protected
1012                  * @since 3.1.000 (2008-06-09)
1013                  */
1014                 protected $gradients = array();
1015
1016                 /**
1017                  * Array used to store positions inside the pages buffer.
1018                  * keys are the page numbers
1019                  * @access protected
1020                  * @since 3.2.000 (2008-06-26)
1021                  */
1022                 protected $intmrk = array();
1023
1024                 /**
1025                  * Array used to store footer positions of each page.
1026                  * @access protected
1027                  * @since 3.2.000 (2008-07-01)
1028                  */
1029                 protected $footerpos = array();
1030
1031
1032                 /**
1033                  * Array used to store footer lenght of each page.
1034                  * @access protected
1035                  * @since 4.0.014 (2008-07-29)
1036                  */
1037                 protected $footerlen = array();
1038
1039                 /**
1040                  * True if a newline is created.
1041                  * @access protected
1042                  * @since 3.2.000 (2008-07-01)
1043                  */
1044                 protected $newline = true;
1045
1046                 /**
1047                  * End position of the latest inserted line
1048                  * @access protected
1049                  * @since 3.2.000 (2008-07-01)
1050                  */
1051                 protected $endlinex = 0;
1052
1053                 /**
1054                  * PDF string for last line width
1055                  * @access protected
1056                  * @since 4.0.006 (2008-07-16)
1057                  */
1058                 protected $linestyleWidth = '';
1059
1060                 /**
1061                  * PDF string for last line width
1062                  * @access protected
1063                  * @since 4.0.006 (2008-07-16)
1064                  */
1065                 protected $linestyleCap = '0 J';
1066
1067                 /**
1068                  * PDF string for last line width
1069                  * @access protected
1070                  * @since 4.0.006 (2008-07-16)
1071                  */
1072                 protected $linestyleJoin = '0 j';
1073
1074                 /**
1075                  * PDF string for last line width
1076                  * @access protected
1077                  * @since 4.0.006 (2008-07-16)
1078                  */
1079                 protected $linestyleDash = '[] 0 d';
1080
1081                 /**
1082                  * True if marked-content sequence is open
1083                  * @access protected
1084                  * @since 4.0.013 (2008-07-28)
1085                  */
1086                 protected $openMarkedContent = false;
1087
1088                 /**
1089                  * Count the latest inserted vertical spaces on HTML
1090                  * @access protected
1091                  * @since 4.0.021 (2008-08-24)
1092                  */
1093                 protected $htmlvspace = 0;
1094
1095                 /**
1096                  * Array of Spot colors
1097                  * @access protected
1098                  * @since 4.0.024 (2008-09-12)
1099                  */
1100                 protected $spot_colors = array();
1101
1102                 /**
1103                  * Symbol used for HTML unordered list items
1104                  * @access protected
1105                  * @since 4.0.028 (2008-09-26)
1106                  */
1107                 protected $lisymbol = '';
1108
1109                 /**
1110                  * String used to mark the beginning and end of EPS image blocks
1111                  * @access protected
1112                  * @since 4.1.000 (2008-10-18)
1113                  */
1114                 protected $epsmarker = 'x#!#EPS#!#x';
1115
1116                 /**
1117                  * Array of transformation matrix
1118                  * @access protected
1119                  * @since 4.2.000 (2008-10-29)
1120                  */
1121                 protected $transfmatrix = array();
1122
1123                 /**
1124                  * Booklet mode for double-sided pages
1125                  * @access protected
1126                  * @since 4.2.000 (2008-10-29)
1127                  */
1128                 protected $booklet = false;
1129
1130                 /**
1131                  * Epsilon value used for float calculations
1132                  * @access protected
1133                  * @since 4.2.000 (2008-10-29)
1134                  */
1135                 protected $feps = 0.001;
1136
1137                 /**
1138                  * Array used for custom vertical spaces for HTML tags
1139                  * @access protected
1140                  * @since 4.2.001 (2008-10-30)
1141                  */
1142                 protected $tagvspaces = array();
1143
1144                 /**
1145                  * @var HTML PARSER: custom indent amount for lists.
1146                  * Negative value means disabled.
1147                  * @access protected
1148                  * @since 4.2.007 (2008-11-12)
1149                  */
1150                 protected $customlistindent = -1;
1151
1152                 /**
1153                  * @var if true keeps the border open for the cell sides that cross the page.
1154                  * @access protected
1155                  * @since 4.2.010 (2008-11-14)
1156                  */
1157                 protected $opencell = true;
1158
1159                 /**
1160                  * @var array of files to embedd
1161                  * @access protected
1162                  * @since 4.4.000 (2008-12-07)
1163                  */
1164                 protected $embeddedfiles = array();
1165
1166                 /**
1167                  * @var boolean true when inside html pre tag
1168                  * @access protected
1169                  * @since 4.4.001 (2008-12-08)
1170                  */
1171                 protected $premode = false;
1172
1173                 /**
1174                  * Array used to store positions of graphics transformation blocks inside the page buffer.
1175                  * keys are the page numbers
1176                  * @access protected
1177                  * @since 4.4.002 (2008-12-09)
1178                  */
1179                 protected $transfmrk = array();
1180
1181                 /**
1182                  * Default color for html links
1183                  * @access protected
1184                  * @since 4.4.003 (2008-12-09)
1185                  */
1186                 protected $htmlLinkColorArray = array(0, 0, 255);
1187
1188                 /**
1189                  * Default font style to add to html links
1190                  * @access protected
1191                  * @since 4.4.003 (2008-12-09)
1192                  */
1193                 protected $htmlLinkFontStyle = 'U';
1194
1195                 /**
1196                  * Counts the number of pages.
1197                  * @access protected
1198                  * @since 4.5.000 (2008-12-31)
1199                  */
1200                 protected $numpages = 0;
1201
1202                 /**
1203                  * Array containing page lenghts in bytes.
1204                  * @access protected
1205                  * @since 4.5.000 (2008-12-31)
1206                  */
1207                 protected $pagelen = array();
1208
1209                 /**
1210                  * Counts the number of pages.
1211                  * @access protected
1212                  * @since 4.5.000 (2008-12-31)
1213                  */
1214                 protected $numimages = 0;
1215
1216                 /**
1217                  * Store the image keys.
1218                  * @access protected
1219                  * @since 4.5.000 (2008-12-31)
1220                  */
1221                 protected $imagekeys = array();
1222
1223                 /**
1224                  * Lenght of the buffer in bytes.
1225                  * @access protected
1226                  * @since 4.5.000 (2008-12-31)
1227                  */
1228                 protected $bufferlen = 0;
1229
1230                 /**
1231                  * If true enables disk caching.
1232                  * @access protected
1233                  * @since 4.5.000 (2008-12-31)
1234                  */
1235                 protected $diskcache = false;
1236
1237                 /**
1238                  * Counts the number of fonts.
1239                  * @access protected
1240                  * @since 4.5.000 (2009-01-02)
1241                  */
1242                 protected $numfonts = 0;
1243
1244                 /**
1245                  * Store the font keys.
1246                  * @access protected
1247                  * @since 4.5.000 (2009-01-02)
1248                  */
1249                 protected $fontkeys = array();
1250
1251                 /**
1252                  * Store the fage status (true when opened, false when closed).
1253                  * @access protected
1254                  * @since 4.5.000 (2009-01-02)
1255                  */
1256                 protected $pageopen = array();
1257
1258                 /**
1259                  * Default monospaced font
1260                  * @access protected
1261                  * @since 4.5.025 (2009-03-10)
1262                  */
1263                 protected $default_monospaced_font = 'courier';
1264
1265                 /**
1266                  * Used to store a cloned copy of the current class object
1267                  * @access protected
1268                  * @since 4.5.029 (2009-03-19)
1269                  */
1270                 protected $objcopy;
1271
1272                 /**
1273                  * Array used to store the lenghts of cache files
1274                  * @access protected
1275                  * @since 4.5.029 (2009-03-19)
1276                  */
1277                 protected $cache_file_lenght = array();
1278
1279                 /**
1280                  * Table header content to be repeated on each new page
1281                  * @access protected
1282                  * @since 4.5.030 (2009-03-20)
1283                  */
1284                 protected $thead = '';
1285
1286                 /**
1287                  * Distance between the top of page and end of table headers on a new page.
1288                  * @access protected
1289                  * @since 4.5.030 (2009-03-20)
1290                  */
1291                 protected $theadMargin = '';
1292
1293                 /**
1294                  * Cache array for UTF8StringToArray() method.
1295                  * @access protected
1296                  * @since 4.5.037 (2009-04-07)
1297                  */
1298                 protected $cache_UTF8StringToArray = array();
1299
1300                 /**
1301                  * Maximum size of cache array used for UTF8StringToArray() method.
1302                  * @access protected
1303                  * @since 4.5.037 (2009-04-07)
1304                  */
1305                 protected $cache_maxsize_UTF8StringToArray = 8;
1306
1307                 /**
1308                  * Current size of cache array used for UTF8StringToArray() method.
1309                  * @access protected
1310                  * @since 4.5.037 (2009-04-07)
1311                  */
1312                 protected $cache_size_UTF8StringToArray = 0;
1313
1314                 /**
1315                  * If true enables document signing
1316                  * @access protected
1317                  * @since 4.6.005 (2009-04-24)
1318                  */
1319                 protected $sign = false;
1320
1321                 /**
1322                  * Signature data
1323                  * @access protected
1324                  * @since 4.6.005 (2009-04-24)
1325                  */
1326                 protected $signature_data = array();
1327
1328                 /**
1329                  * Signature max lenght
1330                  * @access protected
1331                  * @since 4.6.005 (2009-04-24)
1332                  */
1333                 protected $signature_max_lenght = 5120;
1334
1335                 /**
1336                  * Regular expression used to find blank characters used for word-wrapping.
1337                  * @access protected
1338                  * @since 4.6.006 (2009-04-28)
1339                  */
1340                 protected $re_spaces = '/[\s\p{Z}\p{Lo}]/';
1341
1342                 //------------------------------------------------------------
1343                 // METHODS
1344                 //------------------------------------------------------------
1345
1346                 /**
1347                  * This is the class constructor.
1348                  * It allows to set up the page format, the orientation and
1349                  * the measure unit used in all the methods (except for the font sizes).
1350                  * @since 1.0
1351                  * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
1352                  * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
1353                  * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
1354                  * @param boolean $unicode TRUE means that the input text is unicode (default = true)
1355                  * @param boolean $diskcache if TRUE reduce the RAM memory usage by caching temporary data on filesystem (slower).
1356                  * @param String $encoding charset encoding; default is UTF-8
1357                  * @access public
1358                  */
1359                 public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false) {
1360                         /* Set internal character encoding to ASCII */
1361                         if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
1362                                 $this->internal_encoding = mb_internal_encoding();
1363                                 mb_internal_encoding('ASCII');
1364                         }
1365                         // set disk caching
1366                         $this->diskcache = $diskcache ? true : false;
1367                         // set language direction
1368                         $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
1369                         $this->tmprtl = false;
1370                         //Some checks
1371                         $this->_dochecks();
1372                         //Initialization of properties
1373                         $this->isunicode = $unicode;
1374                         $this->page = 0;
1375                         $this->transfmrk[0] = array();
1376                         $this->pagedim = array();
1377                         $this->n = 2;
1378                         $this->buffer = '';
1379                         $this->pages = array();
1380                         $this->state = 0;
1381                         $this->fonts = array();
1382                         $this->FontFiles = array();
1383                         $this->diffs = array();
1384                         $this->images = array();
1385                         $this->links = array();
1386                         $this->gradients = array();
1387                         $this->InFooter = false;
1388                         $this->lasth = 0;
1389                         $this->FontFamily = 'helvetica';
1390                         $this->FontStyle = '';
1391                         $this->FontSizePt = 12;
1392                         $this->underline = false;
1393                         $this->linethrough = false;
1394                         $this->DrawColor = '0 G';
1395                         $this->FillColor = '0 g';
1396                         $this->TextColor = '0 g';
1397                         $this->ColorFlag = false;
1398                         // encryption values
1399                         $this->encrypted = false;
1400                         $this->last_rc4_key = '';
1401                         $this->padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
1402                         //Standard Unicode fonts
1403                         $this->CoreFonts = array(
1404                                 'courier'=>'Courier',
1405                                 'courierB'=>'Courier-Bold',
1406                                 'courierI'=>'Courier-Oblique',
1407                                 'courierBI'=>'Courier-BoldOblique',
1408                                 'helvetica'=>'Helvetica',
1409                                 'helveticaB'=>'Helvetica-Bold',
1410                                 'helveticaI'=>'Helvetica-Oblique',
1411                                 'helveticaBI'=>'Helvetica-BoldOblique',
1412                                 'times'=>'Times-Roman',
1413                                 'timesB'=>'Times-Bold',
1414                                 'timesI'=>'Times-Italic',
1415                                 'timesBI'=>'Times-BoldItalic',
1416                                 'symbol'=>'Symbol',
1417                                 'zapfdingbats'=>'ZapfDingbats'
1418                         );
1419                         //Set scale factor
1420                         $this->setPageUnit($unit);
1421                         // set page format and orientation
1422                         $this->setPageFormat($format, $orientation);
1423                         //Page margins (1 cm)
1424                         $margin = 28.35 / $this->k;
1425                         $this->SetMargins($margin, $margin);
1426                         //Interior cell margin
1427                         $this->cMargin = $margin / 10;
1428                         //Line width (0.2 mm)
1429                         $this->LineWidth = 0.57 / $this->k;
1430                         $this->linestyleWidth = sprintf('%.2F w', ($this->LineWidth * $this->k));
1431                         $this->linestyleCap = '0 J';
1432                         $this->linestyleJoin = '0 j';
1433                         $this->linestyleDash = '[] 0 d';
1434                         //Automatic page break
1435                         $this->SetAutoPageBreak(true, (2 * $margin));
1436                         //Full width display mode
1437                         $this->SetDisplayMode('fullwidth');
1438                         //Compression
1439                         $this->SetCompression(true);
1440                         //Set default PDF version number
1441                         $this->PDFVersion = '1.7';
1442                         $this->encoding = $encoding;
1443                         $this->HREF = array();
1444                         $this->getFontsList();
1445                         $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
1446                         $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
1447                         $this->extgstates = array();
1448                         // user's rights
1449                         $this->sign = false;
1450                         $this->ur = false;
1451                         $this->ur_document = '/FullSave';
1452                         $this->ur_annots = '/Create/Delete/Modify/Copy/Import/Export';
1453                         $this->ur_form = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
1454                         $this->ur_signature = '/Modify';
1455                         // set default JPEG quality
1456                         $this->jpeg_quality = 75;
1457                         // initialize some settings
1458                         $this->utf8Bidi(array(''), '');
1459                         // set default font
1460                         $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
1461                         // check if PCRE Unicode support is enabled
1462                         if (@preg_match('/\pL/u', 'a') == 1) {
1463                                 // PCRE unicode support is turned ON
1464                                 // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
1465                                 // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
1466                                 // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
1467                                 $this->re_spaces = '/[\s\p{Z}\p{Lo}]/';
1468                         } else {
1469                                 // PCRE unicode support is turned OFF
1470                                 $this->re_spaces = '/[\s]/';
1471                         }
1472                 }
1473
1474                 /**
1475                  * Default destructor.
1476                  * @access public
1477                  * @since 1.53.0.TC016
1478                  */
1479                 public function __destruct() {
1480                         // restore internal encoding
1481                         if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
1482                                 mb_internal_encoding($this->internal_encoding);
1483                         }
1484                         // unset all class variables
1485                         $this->_destroy(true);
1486                 }
1487
1488         /**
1489          * This is needed to prevent unserialize vulnerability
1490          */
1491         public function __wakeup()
1492         {
1493             // clean all properties
1494             foreach(get_object_vars($this) as $k => $v) {
1495                 $this->$k = null;
1496             }
1497             throw new Exception("Not a serializable object");
1498         }
1499
1500                 /**
1501                  * Set the units of measure for the document.
1502                  * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
1503                  * @access public
1504                  * @since 3.0.015 (2008-06-06)
1505                  */
1506                 public function setPageUnit($unit) {
1507                 //Set scale factor
1508                         switch (strtolower($unit)) {
1509                                 // points
1510                                 case 'px':
1511                                 case 'pt': {
1512                                         $this->k = 1;
1513                                         break;
1514                                 }
1515                                 // millimeters
1516                                 case 'mm': {
1517                                         $this->k = $this->dpi / 25.4;
1518                                         break;
1519                                 }
1520                                 // centimeters
1521                                 case 'cm': {
1522                                         $this->k = $this->dpi / 2.54;
1523                                         break;
1524                                 }
1525                                 // inches
1526                                 case 'in': {
1527                                         $this->k = $this->dpi;
1528                                         break;
1529                                 }
1530                                 // unsupported unit
1531                                 default : {
1532                                         $this->Error('Incorrect unit: '.$unit);
1533                                         break;
1534                                 }
1535                         }
1536                         if (isset($this->CurOrientation)) {
1537                                         $this->setPageOrientation($this->CurOrientation);
1538                         }
1539                 }
1540
1541                 /**
1542                 * Set the page format
1543                 * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
1544                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1545                 * @access public
1546                 * @since 3.0.015 (2008-06-06)
1547                 */
1548                 public function setPageFormat($format, $orientation='P') {
1549                         //Page format
1550                         if (is_string($format)) {
1551                                 // Page formats (45 standard ISO paper formats and 4 american common formats).
1552                                 // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm)
1553                                 switch (strtoupper($format)) {
1554                                         case '4A0': {$format = array(4767.87,6740.79); break;}
1555                                         case '2A0': {$format = array(3370.39,4767.87); break;}
1556                                         case 'A0': {$format = array(2383.94,3370.39); break;}
1557                                         case 'A1': {$format = array(1683.78,2383.94); break;}
1558                                         case 'A2': {$format = array(1190.55,1683.78); break;}
1559                                         case 'A3': {$format = array(841.89,1190.55); break;}
1560                                         case 'A4': default: {$format = array(595.28,841.89); break;}
1561                                         case 'A5': {$format = array(419.53,595.28); break;}
1562                                         case 'A6': {$format = array(297.64,419.53); break;}
1563                                         case 'A7': {$format = array(209.76,297.64); break;}
1564                                         case 'A8': {$format = array(147.40,209.76); break;}
1565                                         case 'A9': {$format = array(104.88,147.40); break;}
1566                                         case 'A10': {$format = array(73.70,104.88); break;}
1567                                         case 'B0': {$format = array(2834.65,4008.19); break;}
1568                                         case 'B1': {$format = array(2004.09,2834.65); break;}
1569                                         case 'B2': {$format = array(1417.32,2004.09); break;}
1570                                         case 'B3': {$format = array(1000.63,1417.32); break;}
1571                                         case 'B4': {$format = array(708.66,1000.63); break;}
1572                                         case 'B5': {$format = array(498.90,708.66); break;}
1573                                         case 'B6': {$format = array(354.33,498.90); break;}
1574                                         case 'B7': {$format = array(249.45,354.33); break;}
1575                                         case 'B8': {$format = array(175.75,249.45); break;}
1576                                         case 'B9': {$format = array(124.72,175.75); break;}
1577                                         case 'B10': {$format = array(87.87,124.72); break;}
1578                                         case 'C0': {$format = array(2599.37,3676.54); break;}
1579                                         case 'C1': {$format = array(1836.85,2599.37); break;}
1580                                         case 'C2': {$format = array(1298.27,1836.85); break;}
1581                                         case 'C3': {$format = array(918.43,1298.27); break;}
1582                                         case 'C4': {$format = array(649.13,918.43); break;}
1583                                         case 'C5': {$format = array(459.21,649.13); break;}
1584                                         case 'C6': {$format = array(323.15,459.21); break;}
1585                                         case 'C7': {$format = array(229.61,323.15); break;}
1586                                         case 'C8': {$format = array(161.57,229.61); break;}
1587                                         case 'C9': {$format = array(113.39,161.57); break;}
1588                                         case 'C10': {$format = array(79.37,113.39); break;}
1589                                         case 'RA0': {$format = array(2437.80,3458.27); break;}
1590                                         case 'RA1': {$format = array(1729.13,2437.80); break;}
1591                                         case 'RA2': {$format = array(1218.90,1729.13); break;}
1592                                         case 'RA3': {$format = array(864.57,1218.90); break;}
1593                                         case 'RA4': {$format = array(609.45,864.57); break;}
1594                                         case 'SRA0': {$format = array(2551.18,3628.35); break;}
1595                                         case 'SRA1': {$format = array(1814.17,2551.18); break;}
1596                                         case 'SRA2': {$format = array(1275.59,1814.17); break;}
1597                                         case 'SRA3': {$format = array(907.09,1275.59); break;}
1598                                         case 'SRA4': {$format = array(637.80,907.09); break;}
1599                                         case 'LETTER': {$format = array(612.00,792.00); break;}
1600                                         case 'LEGAL': {$format = array(612.00,1008.00); break;}
1601                                         case 'EXECUTIVE': {$format = array(521.86,756.00); break;}
1602                                         case 'FOLIO': {$format = array(612.00,936.00); break;}
1603                                 }
1604                                 $this->fwPt = $format[0];
1605                                 $this->fhPt = $format[1];
1606                         } else {
1607                                 $this->fwPt = $format[0] * $this->k;
1608                                 $this->fhPt = $format[1] * $this->k;
1609                         }
1610                         $this->setPageOrientation($orientation);
1611                 }
1612
1613                 /**
1614                 * Set page orientation.
1615                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1616                 * @param boolean $autopagebreak Boolean indicating if auto-page-break mode should be on or off.
1617                 * @param float $bottommargin bottom margin of the page.
1618                 * @access public
1619                 * @since 3.0.015 (2008-06-06)
1620                 */
1621                 public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
1622                         $orientation = strtoupper($orientation);
1623                         if (($orientation == 'P') OR ($orientation == 'PORTRAIT')) {
1624                                 $this->CurOrientation = 'P';
1625                                 $this->wPt = $this->fwPt;
1626                                 $this->hPt = $this->fhPt;
1627                         } elseif (($orientation == 'L') OR ($orientation == 'LANDSCAPE')) {
1628                                 $this->CurOrientation = 'L';
1629                                 $this->wPt = $this->fhPt;
1630                                 $this->hPt = $this->fwPt;
1631                         } else {
1632                                 $this->Error('Incorrect orientation: '.$orientation);
1633                         }
1634                         $this->w = $this->wPt / $this->k;
1635                         $this->h = $this->hPt / $this->k;
1636                         if ($this->empty_string($autopagebreak)) {
1637                                 if (isset($this->AutoPageBreak)) {
1638                                         $autopagebreak = $this->AutoPageBreak;
1639                                 } else {
1640                                         $autopagebreak = true;
1641                                 }
1642                         }
1643                         if ($this->empty_string($bottommargin)) {
1644                                 if (isset($this->bMargin)) {
1645                                         $bottommargin = $this->bMargin;
1646                                 } else {
1647                                         // default value = 2 cm
1648                                         $bottommargin = 2 * 28.35 / $this->k;
1649                                 }
1650                         }
1651                         $this->SetAutoPageBreak($autopagebreak, $bottommargin);
1652                         // store page dimensions
1653                         $this->pagedim[$this->page] = array('w' => $this->wPt, 'h' => $this->hPt, 'wk' => $this->w, 'hk' => $this->h, 'tm' => $this->tMargin, 'bm' => $bottommargin, 'lm' => $this->lMargin, 'rm' => $this->rMargin, 'pb' => $autopagebreak, 'or' => $this->CurOrientation, 'olm' => $this->original_lMargin, 'orm' => $this->original_rMargin);
1654                 }
1655
1656                 /**
1657                  * Enable or disable Right-To-Left language mode
1658                  * @param Boolean $enable if true enable Right-To-Left language mode.
1659                  * @access public
1660                 * @since 2.0.000 (2008-01-03)
1661                  */
1662                 public function setRTL($enable) {
1663                         $this->rtl = $enable ? true : false;
1664                         $this->tmprtl = false;
1665                 }
1666
1667                 /**
1668                  * Return the RTL status
1669                  * @return boolean
1670                  * @access public
1671                  * @since 4.0.012 (2008-07-24)
1672                  */
1673                 public function getRTL() {
1674                         return $this->rtl;
1675                 }
1676
1677                 /**
1678                 * Force temporary RTL language direction
1679                 * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL
1680                 * @access public
1681                 * @since 2.1.000 (2008-01-09)
1682                 */
1683                 public function setTempRTL($mode) {
1684                         switch ($mode) {
1685                                 case false:
1686                                 case 'L':
1687                                 case 'R': {
1688                                         $this->tmprtl = $mode;
1689                                 }
1690                         }
1691                 }
1692
1693                 /**
1694                 * Set the last cell height.
1695                 * @param float $h cell height.
1696                 * @author Nicola Asuni
1697                 * @access public
1698                 * @since 1.53.0.TC034
1699                 */
1700                 public function setLastH($h) {
1701                         $this->lasth = $h;
1702                 }
1703
1704                 /**
1705                 * Get the last cell height.
1706                 * @return last cell height
1707                 * @access public
1708                 * @since 4.0.017 (2008-08-05)
1709                 */
1710                 public function getLastH() {
1711                         return $this->lasth;
1712                 }
1713
1714                 /**
1715                 * Set the adjusting factor to convert pixels to user units.
1716                 * @param float $scale adjusting factor to convert pixels to user units.
1717                 * @author Nicola Asuni
1718                 * @access public
1719                 * @since 1.5.2
1720                 */
1721                 public function setImageScale($scale) {
1722                         $this->imgscale = $scale;
1723                 }
1724
1725                 /**
1726                 * Returns the adjusting factor to convert pixels to user units.
1727                 * @return float adjusting factor to convert pixels to user units.
1728                 * @author Nicola Asuni
1729                 * @access public
1730                 * @since 1.5.2
1731                 */
1732                 public function getImageScale() {
1733                         return $this->imgscale;
1734                 }
1735
1736                 /**
1737                 * Returns an array of page dimensions:
1738                 * <ul><li>$this->pagedim[$this->page]['w'] => page_width_in_points</li><li>$this->pagedim[$this->page]['h'] => height in points</li><li>$this->pagedim[$this->page]['wk'] => page_width_in_points</li><li>$this->pagedim[$this->page]['hk'] => height</li><li>$this->pagedim[$this->page]['tm'] => top_margin</li><li>$this->pagedim[$this->page]['bm'] => bottom_margin</li><li>$this->pagedim[$this->page]['lm'] => left_margin</li><li>$this->pagedim[$this->page]['rm'] => right_margin</li><li>$this->pagedim[$this->page]['pb'] => auto_page_break</li><li>$this->pagedim[$this->page]['or'] => page_orientation</li><li>$this->pagedim[$this->page]['olm'] => original_left_margin</li><li>$this->pagedim[$this->page]['orm'] => original_right_margin</li></ul>
1739                 * @param int $pagenum page number (empty = current page)
1740                 * @return array of page dimensions.
1741                 * @author Nicola Asuni
1742                 * @access public
1743                 * @since 4.5.027 (2009-03-16)
1744                 */
1745                 public function getPageDimensions($pagenum='') {
1746                         if (empty($pagenum)) {
1747                                 $pagenum = $this->page;
1748                         }
1749                         return $this->pagedim[$pagenum];
1750                 }
1751
1752                 /**
1753                 * Returns the page width in units.
1754                 * @param int $pagenum page number (empty = current page)
1755                 * @return int page width.
1756                 * @author Nicola Asuni
1757                 * @access public
1758                 * @since 1.5.2
1759                 * @see getPageDimensions()
1760                 */
1761                 public function getPageWidth($pagenum='') {
1762                         if (empty($pagenum)) {
1763                                 return $this->w;
1764                         }
1765                         return $this->pagedim[$pagenum]['w'];
1766                 }
1767
1768                 /**
1769                 * Returns the page height in units.
1770                 * @param int $pagenum page number (empty = current page)
1771                 * @return int page height.
1772                 * @author Nicola Asuni
1773                 * @access public
1774                 * @since 1.5.2
1775                 * @see getPageDimensions()
1776                 */
1777                 public function getPageHeight($pagenum='') {
1778                         if (empty($pagenum)) {
1779                                 return $this->h;
1780                         }
1781                         return $this->pagedim[$pagenum]['h'];
1782                 }
1783
1784                 /**
1785                 * Returns the page break margin.
1786                 * @param int $pagenum page number (empty = current page)
1787                 * @return int page break margin.
1788                 * @author Nicola Asuni
1789                 * @access public
1790                 * @since 1.5.2
1791                 * @see getPageDimensions()
1792                 */
1793                 public function getBreakMargin($pagenum='') {
1794                         if (empty($pagenum)) {
1795                                 return $this->bMargin;
1796                         }
1797                         return $this->pagedim[$pagenum]['bm'];
1798                 }
1799
1800                 /**
1801                 * Returns the scale factor (number of points in user unit).
1802                 * @return int scale factor.
1803                 * @author Nicola Asuni
1804                 * @access public
1805                 * @since 1.5.2
1806                 */
1807                 public function getScaleFactor() {
1808                         return $this->k;
1809                 }
1810
1811                 /**
1812                 * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
1813                 * @param float $left Left margin.
1814                 * @param float $top Top margin.
1815                 * @param float $right Right margin. Default value is the left one.
1816                 * @access public
1817                 * @since 1.0
1818                 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
1819                 */
1820                 public function SetMargins($left, $top, $right=-1) {
1821                         //Set left, top and right margins
1822                         $this->lMargin = $left;
1823                         $this->tMargin = $top;
1824                         if ($right == -1) {
1825                                 $right = $left;
1826                         }
1827                         $this->rMargin = $right;
1828                 }
1829
1830                 /**
1831                 * Defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin.
1832                 * @param float $margin The margin.
1833                 * @access public
1834                 * @since 1.4
1835                 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1836                 */
1837                 public function SetLeftMargin($margin) {
1838                         //Set left margin
1839                         $this->lMargin=$margin;
1840                         if (($this->page > 0) AND ($this->x < $margin)) {
1841                                 $this->x = $margin;
1842                         }
1843                 }
1844
1845                 /**
1846                 * Defines the top margin. The method can be called before creating the first page.
1847                 * @param float $margin The margin.
1848                 * @access public
1849                 * @since 1.5
1850                 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1851                 */
1852                 public function SetTopMargin($margin) {
1853                         //Set top margin
1854                         $this->tMargin=$margin;
1855                         if (($this->page > 0) AND ($this->y < $margin)) {
1856                                 $this->y = $margin;
1857                         }
1858                 }
1859
1860                 /**
1861                 * Defines the right margin. The method can be called before creating the first page.
1862                 * @param float $margin The margin.
1863                 * @access public
1864                 * @since 1.5
1865                 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1866                 */
1867                 public function SetRightMargin($margin) {
1868                         $this->rMargin=$margin;
1869                         if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
1870                                 $this->x = $this->w - $margin;
1871                         }
1872                 }
1873
1874                 /**
1875                 * Set the internal Cell padding.
1876                 * @param float $pad internal padding.
1877                 * @access public
1878                 * @since 2.1.000 (2008-01-09)
1879                 * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1880                 */
1881                 public function SetCellPadding($pad) {
1882                         $this->cMargin = $pad;
1883                 }
1884
1885                 /**
1886                 * Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm.
1887                 * @param boolean $auto Boolean indicating if mode should be on or off.
1888                 * @param float $margin Distance from the bottom of the page.
1889                 * @access public
1890                 * @since 1.0
1891                 * @see Cell(), MultiCell(), AcceptPageBreak()
1892                 */
1893                 public function SetAutoPageBreak($auto, $margin=0) {
1894                         //Set auto page break mode and triggering margin
1895                         $this->AutoPageBreak = $auto;
1896                         $this->bMargin = $margin;
1897                         $this->PageBreakTrigger = $this->h - $margin;
1898                 }
1899
1900                 /**
1901                 * Defines the way the document is to be displayed by the viewer.
1902                 * @param mixed $zoom The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul>
1903                 * @param string $layout The page layout. Possible values are:<ul><li>SinglePage Display one page at a time</li><li>OneColumn Display the pages in one column</li><li>TwoColumnLeft Display the pages in two columns, with odd-numbered pages on the left</li><li>TwoColumnRight Display the pages in two columns, with odd-numbered pages on the right</li><li>TwoPageLeft (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the left</li><li>TwoPageRight (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the right</li></ul>
1904                 * @param string $mode A name object specifying how the document should be displayed when opened:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>FullScreen Full-screen mode, with no menu bar, window controls, or any other window visible</li><li>UseOC (PDF 1.5) Optional content group panel visible</li><li>UseAttachments (PDF 1.6) Attachments panel visible</li></ul>
1905                 * @access public
1906                 * @since 1.2
1907                 */
1908                 public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
1909                         //Set display mode in viewer
1910                         if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
1911                                 $this->ZoomMode = $zoom;
1912                         } else {
1913                                 $this->Error('Incorrect zoom display mode: '.$zoom);
1914                         }
1915                         switch ($layout) {
1916                                 case 'default':
1917                                 case 'single':
1918                                 case 'SinglePage': {
1919                                         $this->LayoutMode = 'SinglePage';
1920                                         break;
1921                                 }
1922                                 case 'continuous':
1923                                 case 'OneColumn': {
1924                                         $this->LayoutMode = 'OneColumn';
1925                                         break;
1926                                 }
1927                                 case 'two':
1928                                 case 'TwoColumnLeft': {
1929                                         $this->LayoutMode = 'TwoColumnLeft';
1930                                         break;
1931                                 }
1932                                 case 'TwoColumnRight': {
1933                                         $this->LayoutMode = 'TwoColumnRight';
1934                                         break;
1935                                 }
1936                                 case 'TwoPageLeft': {
1937                                         $this->LayoutMode = 'TwoPageLeft';
1938                                         break;
1939                                 }
1940                                 case 'TwoPageRight': {
1941                                         $this->LayoutMode = 'TwoPageRight';
1942                                         break;
1943                                 }
1944                                 default: {
1945                                         $this->LayoutMode = 'SinglePage';
1946                                 }
1947                         }
1948                         switch ($mode) {
1949                                 case 'UseNone': {
1950                                         $this->PageMode = 'UseNone';
1951                                         break;
1952                                 }
1953                                 case 'UseOutlines': {
1954                                         $this->PageMode = 'UseOutlines';
1955                                         break;
1956                                 }
1957                                 case 'UseThumbs': {
1958                                         $this->PageMode = 'UseThumbs';
1959                                         break;
1960                                 }
1961                                 case 'FullScreen': {
1962                                         $this->PageMode = 'FullScreen';
1963                                         break;
1964                                 }
1965                                 case 'UseOC': {
1966                                         $this->PageMode = 'UseOC';
1967                                         break;
1968                                 }
1969                                 case '': {
1970                                         $this->PageMode = 'UseAttachments';
1971                                         break;
1972                                 }
1973                                 default: {
1974                                         $this->PageMode = 'UseNone';
1975                                 }
1976                         }
1977                 }
1978
1979                 /**
1980                 * Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default.
1981                 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
1982                 * @param boolean $compress Boolean indicating if compression must be enabled.
1983                 * @access public
1984                 * @since 1.4
1985                 */
1986                 public function SetCompression($compress) {
1987                         //Set page compression
1988                         if (function_exists('gzcompress')) {
1989                                 $this->compress = $compress;
1990                         } else {
1991                                 $this->compress = false;
1992                         }
1993                 }
1994
1995                 /**
1996                 * Defines the title of the document.
1997                 * @param string $title The title.
1998                 * @access public
1999                 * @since 1.2
2000                 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
2001                 */
2002                 public function SetTitle($title) {
2003                         //Title of document
2004                         $this->title = $title;
2005                 }
2006
2007                 /**
2008                 * Defines the subject of the document.
2009                 * @param string $subject The subject.
2010                 * @access public
2011                 * @since 1.2
2012                 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
2013                 */
2014                 public function SetSubject($subject) {
2015                         //Subject of document
2016                         $this->subject = $subject;
2017                 }
2018
2019                 /**
2020                 * Defines the author of the document.
2021                 * @param string $author The name of the author.
2022                 * @access public
2023                 * @since 1.2
2024                 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
2025                 */
2026                 public function SetAuthor($author) {
2027                         //Author of document
2028                         $this->author = $author;
2029                 }
2030
2031                 /**
2032                 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
2033                 * @param string $keywords The list of keywords.
2034                 * @access public
2035                 * @since 1.2
2036                 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
2037                 */
2038                 public function SetKeywords($keywords) {
2039                         //Keywords of document
2040                         $this->keywords = $keywords;
2041                 }
2042
2043                 /**
2044                 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
2045                 * @param string $creator The name of the creator.
2046                 * @access public
2047                 * @since 1.2
2048                 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
2049                 */
2050                 public function SetCreator($creator) {
2051                         //Creator of document
2052                         $this->creator = $creator;
2053                 }
2054
2055                 /**
2056                 * This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid.
2057                 * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
2058                 * @param string $msg The error message
2059                 * @access public
2060                 * @since 1.0
2061                 */
2062                 public function Error($msg) {
2063                         // unset all class variables
2064                         $this->_destroy(true);
2065                         // exit program and print error
2066                         die('<strong>TCPDF ERROR: </strong>'.$msg);
2067                 }
2068
2069                 /**
2070                 * This method begins the generation of the PDF document.
2071                 * It is not necessary to call it explicitly because AddPage() does it automatically.
2072                 * Note: no page is created by this method
2073                 * @access public
2074                 * @since 1.0
2075                 * @see AddPage(), Close()
2076                 */
2077                 public function Open() {
2078                         //Begin document
2079                         $this->state = 1;
2080                 }
2081
2082                 /**
2083                 * Terminates the PDF document.
2084                 * It is not necessary to call this method explicitly because Output() does it automatically.
2085                 * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
2086                 * @access public
2087                 * @since 1.0
2088                 * @see Open(), Output()
2089                 */
2090                 public function Close() {
2091                         if ($this->state == 3) {
2092                                 return;
2093                         }
2094                         if ($this->page == 0) {
2095                                 $this->AddPage();
2096                         }
2097                         // close page
2098                         $this->endPage();
2099                         // close document
2100                         $this->_enddoc();
2101                         // unset all class variables (except critical ones)
2102                         $this->_destroy(false);
2103                 }
2104
2105                 /**
2106                 * Move pointer at the specified document page and update page dimensions.
2107                 * @param int $pnum page number
2108                 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
2109                 * @access public
2110                 * @since 2.1.000 (2008-01-07)
2111                 * @see getPage(), lastpage(), getNumPages()
2112                 */
2113                 public function setPage($pnum, $resetmargins=false) {
2114                         if ($pnum == $this->page) {
2115                                 return;
2116                         }
2117                         if (($pnum > 0) AND ($pnum <= $this->numpages)) {
2118                                 $this->state = 2;
2119                                 // save current graphic settings
2120                                 //$gvars = $this->getGraphicVars();
2121                                 $oldpage = $this->page;
2122                                 $this->page = $pnum;
2123                                 $this->wPt = $this->pagedim[$this->page]['w'];
2124                                 $this->hPt = $this->pagedim[$this->page]['h'];
2125                                 $this->w = $this->wPt / $this->k;
2126                                 $this->h = $this->hPt / $this->k;
2127                                 $this->tMargin = $this->pagedim[$this->page]['tm'];
2128                                 $this->bMargin = $this->pagedim[$this->page]['bm'];
2129                                 $this->original_lMargin = $this->pagedim[$this->page]['olm'];
2130                                 $this->original_rMargin = $this->pagedim[$this->page]['orm'];
2131                                 $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
2132                                 $this->CurOrientation = $this->pagedim[$this->page]['or'];
2133                                 $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
2134                                 // restore graphic settings
2135                                 //$this->setGraphicVars($gvars);
2136                                 if ($resetmargins) {
2137                                         $this->lMargin = $this->pagedim[$this->page]['olm'];
2138                                         $this->rMargin = $this->pagedim[$this->page]['orm'];
2139                                         $this->SetY($this->tMargin);
2140                                 } else {
2141                                         // account for booklet mode
2142                                         if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
2143                                                 $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
2144                                                 $this->lMargin += $deltam;
2145                                                 $this->rMargin -= $deltam;
2146                                         }
2147                                 }
2148                         } else {
2149                                 $this->Error('Wrong page number on setPage() function.');
2150                         }
2151                 }
2152
2153                 /**
2154                 * Reset pointer to the last document page.
2155                 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
2156                 * @access public
2157                 * @since 2.0.000 (2008-01-04)
2158                 * @see setPage(), getPage(), getNumPages()
2159                 */
2160                 public function lastPage($resetmargins=false) {
2161                         $this->setPage($this->getNumPages(), $resetmargins);
2162                 }
2163
2164                 /**
2165                 * Get current document page number.
2166                 * @return int page number
2167                 * @access public
2168                 * @since 2.1.000 (2008-01-07)
2169                 * @see setPage(), lastpage(), getNumPages()
2170                 */
2171                 public function getPage() {
2172                         return $this->page;
2173                 }
2174
2175
2176                 /**
2177                 * Get the total number of insered pages.
2178                 * @return int number of pages
2179                 * @access public
2180                 * @since 2.1.000 (2008-01-07)
2181                 * @see setPage(), getPage(), lastpage()
2182                 */
2183                 public function getNumPages() {
2184                         return $this->numpages;
2185                 }
2186
2187                 /**
2188                 * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer (if enabled). Then the page is added, the current position set to the top-left corner according to the left and top margins (or top-right if in RTL mode), and Header() is called to display the header (if enabled).
2189                 * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
2190                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
2191                 * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
2192                 * @access public
2193                 * @since 1.0
2194                 * @see startPage(), endPage()
2195                 */
2196                 public function AddPage($orientation='', $format='') {
2197                         if (!isset($this->original_lMargin)) {
2198                                 $this->original_lMargin = $this->lMargin;
2199                         }
2200                         if (!isset($this->original_rMargin)) {
2201                                 $this->original_rMargin = $this->rMargin;
2202                         }
2203                         // terminate previous page
2204                         $this->endPage();
2205                         // start new page
2206                         $this->startPage($orientation, $format);
2207                 }
2208
2209                 /**
2210                 * Terminate the current page
2211                 * @access protected
2212                 * @since 4.2.010 (2008-11-14)
2213                 * @see startPage(), AddPage()
2214                 */
2215                 protected function endPage() {
2216                         // check if page is already closed
2217                         if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
2218                                 return;
2219                         }
2220                         $this->InFooter = true;
2221                         // print page footer
2222                         $this->setFooter();
2223                         // close page
2224                         $this->_endpage();
2225                         // mark page as closed
2226                         $this->pageopen[$this->page] = false;
2227                         $this->InFooter = false;
2228                 }
2229
2230                 /**
2231                 * Starts a new page to the document. The page must be closed using the endPage() function.
2232                 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
2233                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
2234                 * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
2235                 * @access protected
2236                 * @since 4.2.010 (2008-11-14)
2237                 * @see endPage(), AddPage()
2238                 */
2239                 protected function startPage($orientation='', $format='') {
2240                         if ($this->numpages > $this->page) {
2241                                 // this page has been already added
2242                                 $this->setPage($this->page + 1);
2243                                 $this->SetY($this->tMargin);
2244                                 return;
2245                         }
2246                         // start a new page
2247                         if ($this->state == 0) {
2248                                 $this->Open();
2249                         }
2250                         ++$this->numpages;
2251                         $this->swapMargins($this->booklet);
2252                         // save current graphic settings
2253                         $gvars = $this->getGraphicVars();
2254                         // start new page
2255                         $this->_beginpage($orientation, $format);
2256                         // mark page as open
2257                         $this->pageopen[$this->page] = true;
2258                         // restore graphic settings
2259                         $this->setGraphicVars($gvars);
2260                         // mark this point
2261                         $this->setPageMark();
2262                         // print page header
2263                         $this->setHeader();
2264                         // restore graphic settings
2265                         $this->setGraphicVars($gvars);
2266                         // mark this point
2267                         $this->setPageMark();
2268                         // print table header (if any)
2269                         $this->setTableHeader();
2270                 }
2271
2272                 /**
2273                  * Set start-writing mark on current page for multicell borders and fills.
2274                  * This function must be called after calling Image() function for a background image.
2275                  * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
2276                  * @access public
2277                  * @since 4.0.016 (2008-07-30)
2278                  */
2279                 public function setPageMark() {
2280                         $this->intmrk[$this->page] = $this->pagelen[$this->page];
2281                 }
2282
2283                 /**
2284                  * Set header data.
2285                  * @param string $ln header image logo
2286                  * @param string $lw header image logo width in mm
2287                  * @param string $ht string to print as title on document header
2288                  * @param string $hs string to print on document header
2289                  * @access public
2290                  */
2291                 public function setHeaderData($ln='', $lw=0, $ht='', $hs='') {
2292                         $this->header_logo = $ln;
2293                         $this->header_logo_width = $lw;
2294                         $this->header_title = $ht;
2295                         $this->header_string = $hs;
2296                 }
2297
2298                 /**
2299                  * Returns header data:
2300                  * <ul><li>$ret['logo'] = logo image</li><li>$ret['logo_width'] = width of the image logo in user units</li><li>$ret['title'] = header title</li><li>$ret['string'] = header description string</li></ul>
2301                  * @return array()
2302                  * @access public
2303                  * @since 4.0.012 (2008-07-24)
2304                  */
2305                 public function getHeaderData() {
2306                         $ret = array();
2307                         $ret['logo'] = $this->header_logo;
2308                         $ret['logo_width'] = $this->header_logo_width;
2309                         $ret['title'] = $this->header_title;
2310                         $ret['string'] = $this->header_string;
2311                         return $ret;
2312                 }
2313
2314                 /**
2315                  * Set header margin.
2316                  * (minimum distance between header and top page margin)
2317                  * @param int $hm distance in user units
2318                  * @access public
2319                  */
2320                 public function setHeaderMargin($hm=10) {
2321                         $this->header_margin = $hm;
2322                 }
2323
2324                 /**
2325                  * Returns header margin in user units.
2326                  * @return float
2327                  * @since 4.0.012 (2008-07-24)
2328                  * @access public
2329                  */
2330                 public function getHeaderMargin() {
2331                         return $this->header_margin;
2332                 }
2333
2334                 /**
2335                  * Set footer margin.
2336                  * (minimum distance between footer and bottom page margin)
2337                  * @param int $fm distance in user units
2338                  * @access public
2339                  */
2340                 public function setFooterMargin($fm=10) {
2341                         $this->footer_margin = $fm;
2342                 }
2343
2344                 /**
2345                  * Returns footer margin in user units.
2346                  * @return float
2347                  * @since 4.0.012 (2008-07-24)
2348                  * @access public
2349                  */
2350                 public function getFooterMargin() {
2351                         return $this->footer_margin;
2352                 }
2353                 /**
2354                  * Set a flag to print page header.
2355                  * @param boolean $val set to true to print the page header (default), false otherwise.
2356                  * @access public
2357                  */
2358                 public function setPrintHeader($val=true) {
2359                         $this->print_header = $val;
2360                 }
2361
2362                 /**
2363                  * Set a flag to print page footer.
2364                  * @param boolean $value set to true to print the page footer (default), false otherwise.
2365                  * @access public
2366                  */
2367                 public function setPrintFooter($val=true) {
2368                         $this->print_footer = $val;
2369                 }
2370
2371                 /**
2372                  * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
2373                  * @return float
2374                  * @access public
2375                  */
2376                 public function getImageRBX() {
2377                         return $this->img_rb_x;
2378                 }
2379
2380                 /**
2381                  * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
2382                  * @return float
2383                  * @access public
2384                  */
2385                 public function getImageRBY() {
2386                         return $this->img_rb_y;
2387                 }
2388
2389                 /**
2390                  * This method is used to render the page header.
2391                  * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2392                  * @access public
2393                  */
2394                 public function Header() {
2395                         $ormargins = $this->getOriginalMargins();
2396                         $headerfont = $this->getHeaderFont();
2397                         $headerdata = $this->getHeaderData();
2398                         if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
2399                                 $this->Image(K_PATH_IMAGES.$headerdata['logo'], $this->GetX(), $this->getHeaderMargin(), $headerdata['logo_width']);
2400                                 $imgy = $this->getImageRBY();
2401                         } else {
2402                                 $imgy = $this->GetY();
2403                         }
2404                         $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2);
2405                         // set starting margin for text data cell
2406                         if ($this->getRTL()) {
2407                                 $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1);
2408                         } else {
2409                                 $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1);
2410                         }
2411                         $this->SetTextColor(0, 0, 0);
2412                         // header title
2413                         $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
2414                         $this->SetX($header_x);
2415                         $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
2416                         // header string
2417                         $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
2418                         $this->SetX($header_x);
2419                         $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false);
2420                         // print an ending header line
2421                         $this->SetLineStyle(array('width' => 0.85 / $this->getScaleFactor(), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
2422                         $this->SetY((2.835 / $this->getScaleFactor()) + max($imgy, $this->GetY()));
2423                         if ($this->getRTL()) {
2424                                 $this->SetX($ormargins['right']);
2425                         } else {
2426                                 $this->SetX($ormargins['left']);
2427                         }
2428                         $this->Cell(0, 0, '', 'T', 0, 'C');
2429                 }
2430
2431                 /**
2432                  * This method is used to render the page footer.
2433                  * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2434                  * @access public
2435                  */
2436                 public function Footer() {
2437                         $cur_y = $this->GetY();
2438                         $ormargins = $this->getOriginalMargins();
2439                         $this->SetTextColor(0, 0, 0);
2440                         //set style for cell border
2441                         $line_width = 0.85 / $this->getScaleFactor();
2442                         $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
2443                         //print document barcode
2444                         $barcode = $this->getBarcode();
2445                         if (!empty($barcode)) {
2446                                 $this->Ln($line_width);
2447                                 $barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right'])/3);
2448                                 $this->write1DBarcode($barcode, 'C128B', $this->GetX(), $cur_y + $line_width, $barcode_width, (($this->getFooterMargin() / 3) - $line_width), 0.3, '', '');
2449                         }
2450                         if (empty($this->pagegroups)) {
2451                                 $pagenumtxt = $this->l['w_page'].' '.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
2452                         } else {
2453                                 $pagenumtxt = $this->l['w_page'].' '.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
2454                         }
2455                         $this->SetY($cur_y);
2456                         //Print page number
2457                         if ($this->getRTL()) {
2458                                 $this->SetX($ormargins['right']);
2459                                 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
2460                         } else {
2461                                 $this->SetX($ormargins['left']);
2462                                 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R');
2463                         }
2464                 }
2465
2466                 /**
2467                  * This method is used to render the page header.
2468                  * @access protected
2469                  * @since 4.0.012 (2008-07-24)
2470                  */
2471                 protected function setHeader() {
2472                         if ($this->print_header) {
2473                                 $lasth = $this->lasth;
2474                                 $this->_out('q');
2475                                 $this->rMargin = $this->original_rMargin;
2476                                 $this->lMargin = $this->original_lMargin;
2477                                 $this->cMargin = 0;
2478                                 //set current position
2479                                 if ($this->rtl) {
2480                                         $this->SetXY($this->original_rMargin, $this->header_margin);
2481                                 } else {
2482                                         $this->SetXY($this->original_lMargin, $this->header_margin);
2483                                 }
2484                                 $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
2485                                 $this->Header();
2486                                 //restore position
2487                                 if ($this->rtl) {
2488                                         $this->SetXY($this->original_rMargin, $this->tMargin);
2489                                 } else {
2490                                         $this->SetXY($this->original_lMargin, $this->tMargin);
2491                                 }
2492                                 $this->_out('Q');
2493                                 $this->lasth = $lasth;
2494                         }
2495                 }
2496
2497                 /**
2498                  * This method is used to render the page footer.
2499                  * @access protected
2500                  * @since 4.0.012 (2008-07-24)
2501                  */
2502                 protected function setFooter() {
2503                         //Page footer
2504                         // save current graphic settings
2505                         $gvars = $this->getGraphicVars();
2506                         // mark this point
2507                         $this->footerpos[$this->page] = $this->pagelen[$this->page];
2508                         $this->_out("\n");
2509                         if ($this->print_footer) {
2510                                 $lasth = $this->lasth;
2511                                 $this->_out('q');
2512                                 $this->rMargin = $this->original_rMargin;
2513                                 $this->lMargin = $this->original_lMargin;
2514                                 $this->cMargin = 0;
2515                                 //set current position
2516                                 $footer_y = $this->h - $this->footer_margin;
2517                                 if ($this->rtl) {
2518                                         $this->SetXY($this->original_rMargin, $footer_y);
2519                                 } else {
2520                                         $this->SetXY($this->original_lMargin, $footer_y);
2521                                 }
2522                                 $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
2523                                 $this->Footer();
2524                                 //restore position
2525                                 if ($this->rtl) {
2526                                         $this->SetXY($this->original_rMargin, $this->tMargin);
2527                                 } else {
2528                                         $this->SetXY($this->original_lMargin, $this->tMargin);
2529                                 }
2530                                 $this->_out('Q');
2531                                 $this->lasth = $lasth;
2532                         }
2533                         // restore graphic settings
2534                         $this->setGraphicVars($gvars);
2535                         // calculate footer lenght
2536                         $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
2537                 }
2538
2539                 /**
2540                  * This method is used to render the table header on new page (if any).
2541                  * @access protected
2542                  * @since 4.5.030 (2009-03-25)
2543                  */
2544                 protected function setTableHeader() {
2545                         if (!$this->empty_string($this->theadMargin)) {
2546                                 // restore the original top-margin
2547                                 $this->tMargin = $this->theadMargin;
2548                                 $this->pagedim[$this->page]['tm'] = $this->theadMargin;
2549                                 $this->y = $this->theadMargin;
2550                         }
2551                         if (!$this->empty_string($this->thead)) {
2552                                 // print table header
2553                                 $this->writeHTML($this->thead, false, false, false, false, '');
2554                                 // set new top margin to skip the table headers
2555                                 if (!isset($this->theadMargin) OR ($this->empty_string($this->theadMargin))) {
2556                                         $this->theadMargin = $this->tMargin;
2557                                 }
2558                                 $this->tMargin = $this->y;
2559                                 $this->pagedim[$this->page]['tm'] = $this->tMargin;
2560                         }
2561                 }
2562
2563                 /**
2564                 * Returns the current page number.
2565                 * @return int page number
2566                 * @access public
2567                 * @since 1.0
2568                 * @see AliasNbPages(), getAliasNbPages()
2569                 */
2570                 public function PageNo() {
2571                         return $this->page;
2572                 }
2573
2574                 /**
2575                 * Defines a new spot color.
2576                 * It can be expressed in RGB components or gray scale.
2577                 * The method can be called before the first page is created and the value is retained from page to page.
2578                 * @param int $c Cyan color for CMYK. Value between 0 and 255
2579                 * @param int $m Magenta color for CMYK. Value between 0 and 255
2580                 * @param int $y Yellow color for CMYK. Value between 0 and 255
2581                 * @param int $k Key (Black) color for CMYK. Value between 0 and 255
2582                 * @access public
2583                 * @since 4.0.024 (2008-09-12)
2584                 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2585                 */
2586                 public function AddSpotColor($name, $c, $m, $y, $k) {
2587                         if (!isset($this->spot_colors[$name])) {
2588                                 $i = 1 + count($this->spot_colors);
2589                                 $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k);
2590                         }
2591                 }
2592
2593                 /**
2594                 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
2595                 * It can be expressed in RGB components or gray scale.
2596                 * The method can be called before the first page is created and the value is retained from page to page.
2597                 * @param array $color array of colors
2598                 * @access public
2599                 * @since 3.1.000 (2008-06-11)
2600                 * @see SetDrawColor()
2601                 */
2602                 public function SetDrawColorArray($color) {
2603                         if (isset($color)) {
2604                                 $color = array_values($color);
2605                                 $r = isset($color[0]) ? $color[0] : -1;
2606                                 $g = isset($color[1]) ? $color[1] : -1;
2607                                 $b = isset($color[2]) ? $color[2] : -1;
2608                                 $k = isset($color[3]) ? $color[3] : -1;
2609                                 if ($r >= 0) {
2610                                         $this->SetDrawColor($r, $g, $b, $k);
2611                                 }
2612                         }
2613                 }
2614
2615                 /**
2616                 * Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
2617                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2618                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2619                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2620                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2621                 * @access public
2622                 * @since 1.3
2623                 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
2624                 */
2625                 public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2626                         // set default values
2627                         if (!is_numeric($col1)) {
2628                                 $col1 = 0;
2629                         }
2630                         if (!is_numeric($col2)) {
2631                                 $col2 = -1;
2632                         }
2633                         if (!is_numeric($col3)) {
2634                                 $col3 = -1;
2635                         }
2636                         if (!is_numeric($col4)) {
2637                                 $col4 = -1;
2638                         }
2639                         //Set color for all stroking operations
2640                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2641                                 // Grey scale
2642                                 $this->DrawColor = sprintf('%.3F G', $col1/255);
2643                         } elseif ($col4 == -1) {
2644                                 // RGB
2645                                 $this->DrawColor = sprintf('%.3F %.3F %.3F RG', $col1/255, $col2/255, $col3/255);
2646                         } else {
2647                                 // CMYK
2648                                 $this->DrawColor = sprintf('%.3F %.3F %.3F %.3F K', $col1/100, $col2/100, $col3/100, $col4/100);
2649                         }
2650                         if ($this->page > 0) {
2651                                 $this->_out($this->DrawColor);
2652                         }
2653                 }
2654
2655                 /**
2656                 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
2657                 * @param string $name name of the spot color
2658                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2659                 * @access public
2660                 * @since 4.0.024 (2008-09-12)
2661                 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2662                 */
2663                 public function SetDrawSpotColor($name, $tint=100) {
2664                         if (!isset($this->spot_colors[$name])) {
2665                                 $this->Error('Undefined spot color: '.$name);
2666                         }
2667                         $this->DrawColor = sprintf('/CS%d CS %.3F SCN', $this->spot_colors[$name]['i'], $tint/100);
2668                         if ($this->page > 0) {
2669                                 $this->_out($this->DrawColor);
2670                         }
2671                 }
2672
2673                 /**
2674                 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
2675                 * It can be expressed in RGB components or gray scale.
2676                 * The method can be called before the first page is created and the value is retained from page to page.
2677                 * @param array $color array of colors
2678                 * @access public
2679                 * @since 3.1.000 (2008-6-11)
2680                 * @see SetFillColor()
2681                 */
2682                 public function SetFillColorArray($color) {
2683                         if (isset($color)) {
2684                                 $color = array_values($color);
2685                                 $r = isset($color[0]) ? $color[0] : -1;
2686                                 $g = isset($color[1]) ? $color[1] : -1;
2687                                 $b = isset($color[2]) ? $color[2] : -1;
2688                                 $k = isset($color[3]) ? $color[3] : -1;
2689                                 if ($r >= 0) {
2690                                         $this->SetFillColor($r, $g, $b, $k);
2691                                 }
2692                         }
2693                 }
2694
2695                 /**
2696                 * Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
2697                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2698                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2699                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2700                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2701                 * @access public
2702                 * @since 1.3
2703                 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
2704                 */
2705                 public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2706                         // set default values
2707                         if (!is_numeric($col1)) {
2708                                 $col1 = 0;
2709                         }
2710                         if (!is_numeric($col2)) {
2711                                 $col2 = -1;
2712                         }
2713                         if (!is_numeric($col3)) {
2714                                 $col3 = -1;
2715                         }
2716                         if (!is_numeric($col4)) {
2717                                 $col4 = -1;
2718                         }
2719                         //Set color for all filling operations
2720                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2721                                 // Grey scale
2722                                 $this->FillColor = sprintf('%.3F g', $col1/255);
2723                                 $this->bgcolor = array('G' => $col1);
2724                         } elseif ($col4 == -1) {
2725                                 // RGB
2726                                 $this->FillColor = sprintf('%.3F %.3F %.3F rg', $col1/255, $col2/255, $col3/255);
2727                                 $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2728                         } else {
2729                                 // CMYK
2730                                 $this->FillColor = sprintf('%.3F %.3F %.3F %.3F k', $col1/100, $col2/100, $col3/100, $col4/100);
2731                                 $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2732                         }
2733                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2734                         if ($this->page > 0) {
2735                                 $this->_out($this->FillColor);
2736                         }
2737                 }
2738
2739                 /**
2740                 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
2741                 * @param string $name name of the spot color
2742                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2743                 * @access public
2744                 * @since 4.0.024 (2008-09-12)
2745                 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
2746                 */
2747                 public function SetFillSpotColor($name, $tint=100) {
2748                         if (!isset($this->spot_colors[$name])) {
2749                                 $this->Error('Undefined spot color: '.$name);
2750                         }
2751                         $this->FillColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], $tint/100);
2752                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2753                         if ($this->page > 0) {
2754                                 $this->_out($this->FillColor);
2755                         }
2756                 }
2757
2758                 /**
2759                 * Defines the color used for text. It can be expressed in RGB components or gray scale.
2760                 * The method can be called before the first page is created and the value is retained from page to page.
2761                 * @param array $color array of colors
2762                 * @access public
2763                 * @since 3.1.000 (2008-6-11)
2764                 * @see SetFillColor()
2765                 */
2766                 public function SetTextColorArray($color) {
2767                         if (isset($color)) {
2768                                 $color = array_values($color);
2769                                 $r = isset($color[0]) ? $color[0] : -1;
2770                                 $g = isset($color[1]) ? $color[1] : -1;
2771                                 $b = isset($color[2]) ? $color[2] : -1;
2772                                 $k = isset($color[3]) ? $color[3] : -1;
2773                                 if ($r >= 0) {
2774                                         $this->SetTextColor($r, $g, $b, $k);
2775                                 }
2776                         }
2777                 }
2778
2779                 /**
2780                 * Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
2781                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2782                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2783                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2784                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2785                 * @access public
2786                 * @since 1.3
2787                 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
2788                 */
2789                 public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2790                         // set default values
2791                         if (!is_numeric($col1)) {
2792                                 $col1 = 0;
2793                         }
2794                         if (!is_numeric($col2)) {
2795                                 $col2 = -1;
2796                         }
2797                         if (!is_numeric($col3)) {
2798                                 $col3 = -1;
2799                         }
2800                         if (!is_numeric($col4)) {
2801                                 $col4 = -1;
2802                         }
2803                         //Set color for text
2804                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2805                                 // Grey scale
2806                                 $this->TextColor = sprintf('%.3F g', $col1/255);
2807                                 $this->fgcolor = array('G' => $col1);
2808                         } elseif ($col4 == -1) {
2809                                 // RGB
2810                                 $this->TextColor = sprintf('%.3F %.3F %.3F rg', $col1/255, $col2/255, $col3/255);
2811                                 $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2812                         } else {
2813                                 // CMYK
2814                                 $this->TextColor = sprintf('%.3F %.3F %.3F %.3F k', $col1/100, $col2/100, $col3/100, $col4/100);
2815                                 $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2816                         }
2817                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2818                 }
2819
2820                 /**
2821                 * Defines the spot color used for text.
2822                 * @param string $name name of the spot color
2823                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2824                 * @access public
2825                 * @since 4.0.024 (2008-09-12)
2826                 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
2827                 */
2828                 public function SetTextSpotColor($name, $tint=100) {
2829                         if (!isset($this->spot_colors[$name])) {
2830                                 $this->Error('Undefined spot color: '.$name);
2831                         }
2832                         $this->TextColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], $tint/100);
2833                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2834                         if ($this->page > 0) {
2835                                 $this->_out($this->TextColor);
2836                         }
2837                 }
2838
2839                 /**
2840                 * Returns the length of a string in user unit. A font must be selected.<br>
2841                 * @param string $s The string whose length is to be computed
2842                 * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
2843                 * @param string $fontstyle Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li></ul> or any combination. The default value is regular.
2844                 * @param float $fontsize Font size in points. The default value is the current size.
2845                 * @return int string length
2846                 * @author Nicola Asuni
2847                 * @access public
2848                 * @since 1.2
2849                 */
2850                 public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0) {
2851                         return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $s, $this->tmprtl), $fontname, $fontstyle, $fontsize);
2852                 }
2853
2854                 /**
2855                 * Returns the string length of an array of chars in user unit. A font must be selected.<br>
2856                 * @param string $arr The array of chars whose total length is to be computed
2857                 * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
2858                 * @param string $fontstyle Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li></ul> or any combination. The default value is regular.
2859                 * @param float $fontsize Font size in points. The default value is the current size.
2860                 * @return int string length
2861                 * @author Nicola Asuni
2862                 * @access public
2863                 * @since 2.4.000 (2008-03-06)
2864                 */
2865                 public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0) {
2866                         // store current values
2867                         if (!$this->empty_string($fontname)) {
2868                                 $prev_FontFamily = $this->FontFamily;
2869                                 $prev_FontStyle = $this->FontStyle;
2870                                 $prev_FontSizePt = $this->FontSizePt;
2871                                 $this->SetFont($fontname, $fontstyle, $fontsize);
2872                         }
2873                         $w = 0;
2874                         foreach ($sa as $char) {
2875                                 $w += $this->GetCharWidth($char);
2876                         }
2877                         // restore previous values
2878                         if (!$this->empty_string($fontname)) {
2879                                 $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt);
2880                         }
2881                         return $w;
2882                 }
2883
2884                 /**
2885                 * Returns the length of the char in user unit for the current font.<br>
2886                 * @param int $char The char code whose length is to be returned
2887                 * @return int char width
2888                 * @author Nicola Asuni
2889                 * @access public
2890                 * @since 2.4.000 (2008-03-06)
2891                 */
2892                 public function GetCharWidth($char) {
2893                         if ($char == 173) {
2894                                 // SHY character will not be printed
2895                                 return (0);
2896                         }
2897                         $cw = &$this->CurrentFont['cw'];
2898                         if (isset($cw[$char])) {
2899                                 $w = $cw[$char];
2900                         } elseif (isset($this->CurrentFont['dw'])) {
2901                                 // default width
2902                                 $w = $this->CurrentFont['dw'];
2903                         } elseif (isset($cw[32])) {
2904                                 // default width
2905                                 $dw = $cw[32];
2906                         } else {
2907                                 $w = 600;
2908                         }
2909                         return ($w * $this->FontSize / 1000);
2910                 }
2911
2912                 /**
2913                 * Returns the numbero of characters in a string.
2914                 * @param string $s The input string.
2915                 * @return int number of characters
2916                 * @access public
2917                 * @since 2.0.0001 (2008-01-07)
2918                 */
2919                 public function GetNumChars($s) {
2920                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
2921                                 return count($this->UTF8StringToArray($s));
2922                         }
2923                         return strlen($s);
2924                 }
2925
2926                 /**
2927                 * Fill the list of available fonts ($this->fontlist).
2928                 * @access protected
2929                 * @since 4.0.013 (2008-07-28)
2930                 */
2931                 protected function getFontsList() {
2932                         $fontsdir = opendir($this->_getfontpath());
2933                         while (($file = readdir($fontsdir)) !== false) {
2934                                 if (substr($file, -4) == '.php') {
2935                                         array_push($this->fontlist, strtolower(basename($file, '.php')));
2936                                 }
2937                         }
2938                         closedir($fontsdir);
2939                 }
2940
2941                 /**
2942                 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
2943                 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
2944                 * The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.
2945                 * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
2946                 * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
2947                 * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
2948                 * @return array containing the font data, or false in case of error.
2949                 * @access public
2950                 * @since 1.5
2951                 * @see SetFont()
2952                 */
2953                 public function AddFont($family, $style='', $fontfile='') {
2954                         if ($this->empty_string($family)) {
2955                                 if (!$this->empty_string($this->FontFamily)) {
2956                                         $family = $this->FontFamily;
2957                                 } else {
2958                                         $this->Error('Empty font family');
2959                                 }
2960                         }
2961                         $family = strtolower($family);
2962                         if ((!$this->isunicode) AND ($family == 'arial')) {
2963                                 $family = 'helvetica';
2964                         }
2965                         if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
2966                                 $style = '';
2967                         }
2968                         $tempstyle = strtoupper($style);
2969                         $style = '';
2970                         // underline
2971                         if (strpos($tempstyle, 'U') !== false) {
2972                                 $this->underline = true;
2973                         } else {
2974                                 $this->underline = false;
2975                         }
2976                         // line through (deleted)
2977                         if (strpos($tempstyle, 'D') !== false) {
2978                                 $this->linethrough = true;
2979                         } else {
2980                                 $this->linethrough = false;
2981                         }
2982                         // bold
2983                         if (strpos($tempstyle, 'B') !== false) {
2984                                 $style .= 'B';
2985                         }
2986                         // oblique
2987                         if (strpos($tempstyle, 'I') !== false) {
2988                                 $style .= 'I';
2989                         }
2990                         $bistyle = $style;
2991                         $fontkey = $family.$style;
2992                         $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '');
2993                         $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
2994                         // check if the font has been already added
2995                         if ($this->getFontBuffer($fontkey) !== false) {
2996                                 return $fontdata;
2997                         }
2998                         if (isset($type)) {
2999                                 unset($type);
3000                         }
3001                         if (isset($cw)) {
3002                                 unset($cw);
3003                         }
3004                         // get specified font directory (if any)
3005                         $fontdir = '';
3006                         if (!$this->empty_string($fontfile)) {
3007                                 $fontdir = dirname($fontfile);
3008                                 if ($this->empty_string($fontdir) OR ($fontdir == '.')) {
3009                                         $fontdir = '';
3010                                 } else {
3011                                         $fontdir .= '/';
3012                                 }
3013                         }
3014                         // search and include font file
3015                         if ($this->empty_string($fontfile) OR (!file_exists($fontfile))) {
3016                                 // build a standard filenames for specified font
3017                                 $fontfile1 = str_replace(' ', '', $family).strtolower($style).'.php';
3018                                 $fontfile2 = str_replace(' ', '', $family).'.php';
3019                                 // search files on various directories
3020                                 if (file_exists($fontdir.$fontfile1)) {
3021                                         $fontfile = $fontdir.$fontfile1;
3022                                 } elseif (file_exists($this->_getfontpath().$fontfile1)) {
3023                                         $fontfile = $this->_getfontpath().$fontfile1;
3024                                 } elseif (file_exists($fontfile1)) {
3025                                         $fontfile = $fontfile1;
3026                                 } elseif (file_exists($fontdir.$fontfile2)) {
3027                                         $fontfile = $fontdir.$fontfile2;
3028                                 } elseif (file_exists($this->_getfontpath().$fontfile2)) {
3029                                         $fontfile = $this->_getfontpath().$fontfile2;
3030                                 } else {
3031                                         $fontfile = $fontfile2;
3032                                 }
3033                         }
3034                         // include font file
3035                         if (file_exists($fontfile)) {
3036                                 include($fontfile);
3037                         } else {
3038                                 $this->Error('Could not include font definition file: '.$family.'');
3039                         }
3040                         // check font parameters
3041                         if ((!isset($type)) OR (!isset($cw))) {
3042                                 $this->Error('The font definition file has a bad format: '.$fontfile.'');
3043                         }
3044                         if (!isset($file)) {
3045                                 $file = '';
3046                         }
3047                         if (!isset($enc)) {
3048                                 $enc = '';
3049                         }
3050                         if (!isset($dw) OR $this->empty_string($dw)) {
3051                                 // set default width
3052                                 if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
3053                                         $dw = $desc['MissingWidth'];
3054                                 } elseif (isset($cw[32])) {
3055                                         $dw = $cw[32];
3056                                 } else {
3057                                         $dw = 600;
3058                                 }
3059                         }
3060                         ++$this->numfonts;
3061                         // register CID font (all styles at once)
3062                         if ($type == 'cidfont0') {
3063                                 $file = ''; // not embedded
3064                                 $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
3065                                 $sname = $name.$styles[$bistyle];
3066                                 if ((strpos($bistyle, 'B') !== false) AND (isset($desc['StemV'])) AND ($desc['StemV'] == 70)) {
3067                                         $desc['StemV'] = 120;
3068                                 }
3069                                 $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => $type, 'name' => $sname, 'desc' => $desc, 'cidinfo' => $cidinfo, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc));
3070                         } elseif ($type == 'core') {
3071                                 $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => 'core', 'name' => $this->CoreFonts[$fontkey], 'up' => -100, 'ut' => 50, 'cw' => $cw, 'dw' => $dw));
3072                         } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
3073                                 $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => $type, 'name' => $name, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'file' => $file, 'enc' => $enc, 'desc' => $desc));
3074                         } elseif ($type == 'TrueTypeUnicode') {
3075                                 $this->setFontBuffer($fontkey, array('i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc, 'file' => $file, 'ctg' => $ctg));
3076                         } else {
3077                                 $this->Error('Unknow font type: '.$type.'');
3078                         }
3079                         if (isset($diff) AND (!empty($diff))) {
3080                                 //Search existing encodings
3081                                 $d = 0;
3082                                 $nb = count($this->diffs);
3083                                 for ($i=1; $i <= $nb; ++$i) {
3084                                         if ($this->diffs[$i] == $diff) {
3085                                                 $d = $i;
3086                                                 break;
3087                                         }
3088                                 }
3089                                 if ($d == 0) {
3090                                         $d = $nb + 1;
3091                                         $this->diffs[$d] = $diff;
3092                                 }
3093                                 $this->setFontSubBuffer($fontkey, 'diff', $d);
3094                         }
3095                         if (!$this->empty_string($file)) {
3096                                 if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
3097                                         $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir);
3098                                 } elseif ($type != 'core') {
3099                                         $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir);
3100                                 }
3101                         }
3102                         return $fontdata;
3103                 }
3104
3105                 /**
3106                 * Sets the font used to print character strings.
3107                 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
3108                 * The method can be called before the first page is created and the font is retained from page to page.
3109                 * If you just wish to change the current font size, it is simpler to call SetFontSize().
3110                 * Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this:<ul><li>They are in the current directory (the one where the running script lies)</li><li>They are in one of the directories defined by the include_path parameter</li><li>They are in the directory defined by the K_PATH_FONTS constant</li></ul><br />
3111                 * @param string $family Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained.
3112                 * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.
3113                 * @param float $size Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
3114                 * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
3115                 * @access public
3116                 * @since 1.0
3117                 * @see AddFont(), SetFontSize()
3118                 */
3119                 public function SetFont($family, $style='', $size=0, $fontfile='') {
3120                         //Select a font; size given in points
3121                         if ($size == 0) {
3122                                 $size = $this->FontSizePt;
3123                         }
3124                         // try to add font (if not already added)
3125                         $fontdata = $this->AddFont($family, $style, $fontfile);
3126                         $this->FontFamily = $fontdata['family'];
3127                         $this->FontStyle = $fontdata['style'];
3128                         $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
3129                         $this->SetFontSize($size);
3130                 }
3131
3132                 /**
3133                 * Defines the size of the current font.
3134                 * @param float $size The size (in points)
3135                 * @access public
3136                 * @since 1.0
3137                 * @see SetFont()
3138                 */
3139                 public function SetFontSize($size) {
3140                         //Set font size in points
3141                         $this->FontSizePt = $size;
3142                         $this->FontSize = $size / $this->k;
3143                         if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
3144                                 $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000;
3145                         } else {
3146                                 $this->FontAscent = 0.8 * $this->FontSize;
3147                         }
3148                         if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] > 0)) {
3149                                 $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000;
3150                         } else {
3151                                 $this->FontDescent = 0.2 * $this->FontSize;
3152                         }
3153                         if (($this->page > 0) AND (isset($this->CurrentFont['i']))) {
3154                                 $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
3155                         }
3156                 }
3157
3158                 /**
3159                 * Defines the default monospaced font.
3160                 * @param string $font Font name.
3161                 * @access public
3162                 * @since 4.5.025
3163                 */
3164                 public function SetDefaultMonospacedFont($font) {
3165                         $this->default_monospaced_font = $font;
3166                 }
3167
3168                 /**
3169                 * Creates a new internal link and returns its identifier. An internal link is a clickable area which directs to another place within the document.<br />
3170                 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
3171                 * @access public
3172                 * @since 1.5
3173                 * @see Cell(), Write(), Image(), Link(), SetLink()
3174                 */
3175                 public function AddLink() {
3176                         //Create a new internal link
3177                         $n = count($this->links) + 1;
3178                         $this->links[$n] = array(0, 0);
3179                         return $n;
3180                 }
3181
3182                 /**
3183                 * Defines the page and position a link points to.
3184                 * @param int $link The link identifier returned by AddLink()
3185                 * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
3186                 * @param int $page Number of target page; -1 indicates the current page. This is the default value
3187                 * @access public
3188                 * @since 1.5
3189                 * @see AddLink()
3190                 */
3191                 public function SetLink($link, $y=0, $page=-1) {
3192                         if ($y == -1) {
3193                                 $y = $this->y;
3194                         }
3195                         if ($page == -1) {
3196                                 $page = $this->page;
3197                         }
3198                         $this->links[$link] = array($page, $y);
3199                 }
3200
3201                 /**
3202                 * Puts a link on a rectangular area of the page.
3203                 * Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image.
3204                 * @param float $x Abscissa of the upper-left corner of the rectangle
3205                 * @param float $y Ordinate of the upper-left corner of the rectangle
3206                 * @param float $w Width of the rectangle
3207                 * @param float $h Height of the rectangle
3208                 * @param mixed $link URL or identifier returned by AddLink()
3209                 * @param int $spaces number of spaces on the text to link
3210                 * @access public
3211                 * @since 1.5
3212                 * @see AddLink(), Annotation(), Cell(), Write(), Image()
3213                 */
3214                 public function Link($x, $y, $w, $h, $link, $spaces=0) {
3215                         $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
3216                 }
3217
3218                 /**
3219                 * Puts a markup annotation on a rectangular area of the page.
3220                 * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
3221                 * @param float $x Abscissa of the upper-left corner of the rectangle
3222                 * @param float $y Ordinate of the upper-left corner of the rectangle
3223                 * @param float $w Width of the rectangle
3224                 * @param float $h Height of the rectangle
3225                 * @param string $text annotation text or alternate content
3226                 * @param array $opt array of options (see section 8.4 of PDF reference 1.7).
3227                 * @param int $spaces number of spaces on the text to link
3228                 * @access public
3229                 * @since 4.0.018 (2008-08-06)
3230                 */
3231                 public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
3232                         // recalculate coordinates to account for graphic transformations
3233                         if (isset($this->transfmatrix)) {
3234                                 $maxid = count($this->transfmatrix) - 1;
3235                                 for ($i=$maxid; $i >= 0; $i--) {
3236                                         $ctm = $this->transfmatrix[$i];
3237                                         if (isset($ctm['a'])) {
3238                                                 $x = $x * $this->k;
3239                                                 $y = ($this->h - $y) * $this->k;
3240                                                 $w = $w * $this->k;
3241                                                 $h = $h * $this->k;
3242                                                 // top left
3243                                                 $xt = $x;
3244                                                 $yt = $y;
3245                                                 $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
3246                                                 $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
3247                                                 // top right
3248                                                 $xt = $x + $w;
3249                                                 $yt = $y;
3250                                                 $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
3251                                                 $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
3252                                                 // bottom left
3253                                                 $xt = $x;
3254                                                 $yt = $y - $h;
3255                                                 $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
3256                                                 $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
3257                                                 // bottom right
3258                                                 $xt = $x + $w;
3259                                                 $yt = $y - $h;
3260                                                 $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
3261                                                 $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
3262                                                 // new coordinates (rectangle area)
3263                                                 $x = min($x1, $x2, $x3, $x4);
3264                                                 $y = max($y1, $y2, $y3, $y4);
3265                                                 $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
3266                                                 $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
3267                                                 $x = $x / $this->k;
3268                                                 $y = $this->h - ($y / $this->k);
3269                                         }
3270                                 }
3271                         }
3272                         $this->PageAnnots[$this->page][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
3273                         if (($opt['Subtype'] == 'FileAttachment') AND (!$this->empty_string($opt['FS'])) AND file_exists($opt['FS']) AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
3274                                 $this->embeddedfiles[basename($opt['FS'])] = array('file' => $opt['FS'], 'n' => (count($this->embeddedfiles) + 100000));
3275                         }
3276                 }
3277
3278                 /**
3279                 * Embedd the attached files.
3280                 * @since 4.4.000 (2008-12-07)
3281                 * @access protected
3282                 * @see Annotation()
3283                 */
3284                 protected function _putEmbeddedFiles() {
3285                         reset($this->embeddedfiles);
3286                         foreach ($this->embeddedfiles as $filename => $filedata) {
3287                                 $data = file_get_contents($filedata['file']);
3288                                 $filter = '';
3289                                 if ($this->compress) {
3290                                         $data = gzcompress($data);
3291                                         $filter = ' /Filter /FlateDecode';
3292                                 }
3293                                 $this->offsets[$filedata['n']] = $this->bufferlen;
3294                                 $this->_out($filedata['n'].' 0 obj');
3295                                 $this->_out('<</Type /EmbeddedFile'.$filter.' /Length '.strlen($data).' >>');
3296                                 $this->_putstream($data);
3297                                 $this->_out('endobj');
3298                         }
3299                 }
3300
3301                 /**
3302                 * Prints a character string.
3303                 * The origin is on the left of the first charcter, on the baseline.
3304                 * This method allows to place a string precisely on the page.
3305                 * @param float $x Abscissa of the origin
3306                 * @param float $y Ordinate of the origin
3307                 * @param string $txt String to print
3308                 * @param int $stroke outline size in points (0 = disable)
3309                 * @param boolean $clip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
3310                 * @access public
3311                 * @since 1.0
3312                 * @deprecated deprecated since version 4.3.005 (2008-11-25)
3313                 * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
3314                 */
3315                 public function Text($x, $y, $txt, $stroke=0, $clip=false) {
3316                         //Output a string
3317                         if ($this->rtl) {
3318                                 // bidirectional algorithm (some chars may be changed affecting the line length)
3319                                 $s = $this->utf8Bidi($this->UTF8StringToArray($txt), $txt, $this->tmprtl);
3320                                 $l = $this->GetArrStringWidth($s);
3321                                 $xr = $this->w - $x - $this->GetArrStringWidth($s);
3322                         } else {
3323                                 $xr = $x;
3324                         }
3325                         $opt = '';
3326                         if (($stroke > 0) AND (!$clip)) {
3327                                 $opt .= '1 Tr '.intval($stroke).' w ';
3328                         } elseif (($stroke > 0) AND $clip) {
3329                                 $opt .= '5 Tr '.intval($stroke).' w ';
3330                         } elseif ($clip) {
3331                                 $opt .= '7 Tr ';
3332                         }
3333                         $s = sprintf('BT %.2F %.2F Td %s(%s) Tj ET 0 Tr', $xr * $this->k, ($this->h-$y) * $this->k, $opt, $this->_escapetext($txt));
3334                         if ($this->underline AND ($txt!='')) {
3335                                 $s .= ' '.$this->_dounderline($xr, $y, $txt);
3336                         }
3337                         if ($this->linethrough AND ($txt!='')) {
3338                                 $s .= ' '.$this->_dolinethrough($xr, $y, $txt);
3339                         }
3340                         if ($this->ColorFlag AND (!$clip)) {
3341                                 $s='q '.$this->TextColor.' '.$s.' Q';
3342                         }
3343                         $this->_out($s);
3344                 }
3345
3346                 /**
3347                 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
3348                 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
3349                 * This method is called automatically and should not be called directly by the application.
3350                 * @return boolean
3351                 * @access public
3352                 * @since 1.4
3353                 * @see SetAutoPageBreak()
3354                 */
3355                 public function AcceptPageBreak() {
3356                         return $this->AutoPageBreak;
3357                 }
3358
3359                 /**
3360                 * Add page if needed.
3361                 * @param float $h Cell height. Default value: 0.
3362                 * @param mixed $y starting y position, leave empty for current position.
3363                 * @return boolean true in case of page break, false otherwise.
3364                 * @since 3.2.000 (2008-07-01)
3365                 * @access protected
3366                 */
3367                 protected function checkPageBreak($h=0, $y='') {
3368                         if ($this->empty_string($y)) {
3369                                 $y = $this->y;
3370                         }
3371                         if ((($y + $h) > $this->PageBreakTrigger) AND (!$this->InFooter) AND ($this->AcceptPageBreak())) {
3372                                 //Automatic page break
3373                                 $x = $this->x;
3374                                 $this->AddPage($this->CurOrientation);
3375                                 $this->y = $this->tMargin;
3376                                 $oldpage = $this->page - 1;
3377                                 if ($this->rtl) {
3378                                         if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
3379                                                 $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
3380                                         } else {
3381                                                 $this->x = $x;
3382                                         }
3383                                 } else {
3384                                         if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
3385                                                 $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
3386                                         } else {
3387                                                 $this->x = $x;
3388                                         }
3389                                 }
3390                                 return true;
3391                         }
3392                         return false;
3393                 }
3394
3395                 /**
3396                 * Prints a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
3397                 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
3398                 * @param float $w Cell width. If 0, the cell extends up to the right margin.
3399                 * @param float $h Cell height. Default value: 0.
3400                 * @param string $txt String to print. Default value: empty string.
3401                 * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
3402                 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
3403                 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
3404                 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
3405                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3406                 * @param mixed $link URL or identifier returned by AddLink().
3407                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
3408                 * @param boolean $ignore_min_height if true ignore automatic minimum height value.
3409                 * @access public
3410                 * @since 1.0
3411                 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
3412                 */
3413                 public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false) {
3414                         //$min_cell_height = $this->FontAscent + $this->FontDescent;
3415                         $min_cell_height = $this->FontSize * $this->cell_height_ratio;
3416                         if ($h < $min_cell_height) {
3417                                 $h = $min_cell_height;
3418                         }
3419                         $this->checkPageBreak($h);
3420                         $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height));
3421                 }
3422
3423                 /**
3424                 * Removes SHY characters from text.
3425                 * @param string $txt input string
3426                 * @return string without SHY characters.
3427                 * @access public
3428                 * @since (4.5.019) 2009-02-28
3429                 */
3430                 public function removeSHY($txt='') {
3431                         /*
3432                         * Unicode Data
3433                         * Name : SOFT HYPHEN, commonly abbreviated as SHY
3434                         * HTML Entity (decimal): &#173;
3435                         * HTML Entity (hex): &#xad;
3436                         * HTML Entity (named): &shy;
3437                         * How to type in Microsoft Windows: [Alt +00AD] or [Alt 0173]
3438                         * UTF-8 (hex): 0xC2 0xAD (c2ad)
3439                         * UTF-8 character: chr(194).chr(173)
3440                         */
3441                         $txt = preg_replace('/([\\xc2]{1}[\\xad]{1})/', '', $txt);
3442                         if (!$this->isunicode) {
3443                                 $txt = preg_replace('/([\\xad]{1})/', '', $txt);
3444                         }
3445                         return $txt;
3446                 }
3447
3448                 /**
3449                 * Returns the PDF string code to print a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
3450                 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
3451                 * @param float $w Cell width. If 0, the cell extends up to the right margin.
3452                 * @param float $h Cell height. Default value: 0.
3453                 * @param string $txt String to print. Default value: empty string.
3454                 * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
3455                 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
3456                 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
3457                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3458                 * @param mixed $link URL or identifier returned by AddLink().
3459                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
3460                 * @param boolean $ignore_min_height if true ignore automatic minimum height value.
3461                 * @access protected
3462                 * @since 1.0
3463                 * @see Cell()
3464                 */
3465                 protected function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false) {
3466                         $txt = $this->removeSHY($txt);
3467                         $rs = ''; //string to be returned
3468                         if (!$ignore_min_height) {
3469                                 $min_cell_height = $this->FontSize * $this->cell_height_ratio;
3470                                 if ($h < $min_cell_height) {
3471                                         $h = $min_cell_height;
3472                                 }
3473                         }
3474                         $k = $this->k;
3475                         if ($this->empty_string($w) OR ($w <= 0)) {
3476                                 if ($this->rtl) {
3477                                         $w = $this->x - $this->lMargin;
3478                                 } else {
3479                                         $w = $this->w - $this->rMargin - $this->x;
3480                                 }
3481                         }
3482                         $s = '';
3483                         if (($fill == 1) OR ($border == 1)) {
3484                                 if ($fill == 1) {
3485                                         $op = ($border == 1) ? 'B' : 'f';
3486                                 } else {
3487                                         $op = 'S';
3488                                 }
3489                                 if ($this->rtl) {
3490                                         $xk = (($this->x  - $w) * $k);
3491                                 } else {
3492                                         $xk = ($this->x * $k);
3493                                 }
3494                                 $s .= sprintf('%.2F %.2F %.2F %.2F re %s ', $xk, (($this->h - $this->y) * $k), ($w * $k), (-$h * $k), $op);
3495                         }
3496                         if (is_string($border)) {
3497                                 $lm = ($this->LineWidth / 2);
3498                                 $x = $this->x;
3499                                 $y = $this->y;
3500                                 if (strpos($border,'L') !== false) {
3501                                         if ($this->rtl) {
3502                                                 $xk = ($x - $w) * $k;
3503                                         } else {
3504                                                 $xk = $x * $k;
3505                                         }
3506                                         $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - $y + $lm) * $k), $xk, (($this->h - ($y + $h + $lm)) * $k));
3507                                 }
3508                                 if (strpos($border,'T') !== false) {
3509                                         if ($this->rtl) {
3510                                                 $xk = ($x - $w + $lm) * $k;
3511                                                 $xwk = ($x - $lm) * $k;
3512                                         } else {
3513                                                 $xk = ($x - $lm) * $k;
3514                                                 $xwk = ($x + $w + $lm) * $k;
3515                                         }
3516                                         $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - $y) * $k), $xwk, (($this->h - $y) * $k));
3517                                 }
3518                                 if (strpos($border,'R') !== false) {
3519                                         if ($this->rtl) {
3520                                                 $xk = $x * $k;
3521                                         } else {
3522                                                 $xk = ($x + $w) * $k;
3523                                         }
3524                                         $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - $y + $lm) * $k), $xk, (($this->h - ($y + $h + $lm))* $k));
3525                                 }
3526                                 if (strpos($border,'B') !== false) {
3527                                         if ($this->rtl) {
3528                                                 $xk = ($x - $w + $lm) * $k;
3529                                                 $xwk = ($x - $lm) * $k;
3530                                         } else {
3531                                                 $xk = ($x - $lm) * $k;
3532                                                 $xwk = ($x + $w + $lm) * $k;
3533                                         }
3534                                         $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $xk, (($this->h - ($y + $h)) * $k), $xwk, (($this->h - ($y + $h)) * $k));
3535                                 }
3536                         }
3537                         if ($txt != '') {
3538                                 // text lenght
3539                                 $width = $this->GetStringWidth($txt);
3540                                 // ratio between cell lenght and text lenght
3541                                 $ratio = ($w - (2 * $this->cMargin)) / $width;
3542
3543                                 // stretch text if required
3544                                 if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) {
3545                                         if ($stretch > 2) {
3546                                                 // spacing
3547                                                 //Calculate character spacing in points
3548                                                 $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1);
3549                                                 //Set character spacing
3550                                                 $rs .= sprintf('BT %.2F Tc ET ', $char_space);
3551                                         } else {
3552                                                 // scaling
3553                                                 //Calculate horizontal scaling
3554                                                 $horiz_scale = $ratio * 100.0;
3555                                                 //Set horizontal scaling
3556                                                 $rs .= sprintf('BT %.2F Tz ET ', $horiz_scale);
3557                                         }
3558                                         $align = '';
3559                                         $width = $w - (2 * $this->cMargin);
3560                                 } else {
3561                                         $stretch == 0;
3562                                 }
3563                                 if ($align == 'L') {
3564                                         if ($this->rtl) {
3565                                                 $dx = $w - $width - $this->cMargin;
3566                                         } else {
3567                                                 $dx = $this->cMargin;
3568                                         }
3569                                 } elseif ($align == 'R') {
3570                                         if ($this->rtl) {
3571                                                 $dx = $this->cMargin;
3572                                         } else {
3573                                                 $dx = $w - $width - $this->cMargin;
3574                                         }
3575                                 } elseif ($align == 'C') {
3576                                         $dx = ($w - $width) / 2;
3577                                 } elseif ($align == 'J') {
3578                                         if ($this->rtl) {
3579                                                 $dx = $w - $width - $this->cMargin;
3580                                         } else {
3581                                                 $dx = $this->cMargin;
3582                                         }
3583                                 } else {
3584                                         $dx = $this->cMargin;
3585                                 }
3586                                 if ($this->ColorFlag) {
3587                                         $s .= 'q '.$this->TextColor.' ';
3588                                 }
3589                                 $txt2 = $this->_escapetext($txt);
3590                                 if ($this->rtl) {
3591                                         $xdk = ($this->x - $dx - $width) * $k;
3592                                 } else {
3593                                         $xdk = ($this->x + $dx) * $k;
3594                                 }
3595                                 // Justification
3596                                 if ($align == 'J') {
3597                                         // count number of spaces
3598                                         $ns = substr_count($txt, ' ');
3599                                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
3600                                                 // get string width without spaces
3601                                                 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
3602                                                 // calculate average space width
3603                                                 $spacewidth = ($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1) / $this->FontSize / $this->k;
3604                                                 // set word position to be used with TJ operator
3605                                                 $txt2 = str_replace(chr(0).' ', ') '.(-2830 * $spacewidth).' (', $txt2);
3606                                         } else {
3607                                                 // get string width
3608                                                 $width = $this->GetStringWidth($txt);
3609                                                 $spacewidth = (($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1)) * $this->k;
3610                                                 $rs .= sprintf('BT %.3F Tw ET ', $spacewidth);
3611                                         }
3612                                 }
3613                                 // calculate approximate position of the font base line
3614                                 //$basefonty = $this->y + (($h + $this->FontAscent - $this->FontDescent)/2);
3615                                 $basefonty = $this->y + ($h/2) + ($this->FontSize/3);
3616                                 // print text
3617                                 $s .= sprintf('BT %.2F %.2F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
3618                                 if ($this->rtl) {
3619                                         $xdx = $this->x - $dx - $width;
3620                                 } else {
3621                                         $xdx = $this->x + $dx;
3622                                 }
3623                                 if ($this->underline)  {
3624                                         $s .= ' '.$this->_dounderline($xdx, $basefonty, $txt);
3625                                 }
3626                                 if ($this->linethrough) {
3627                                         $s .= ' '.$this->_dolinethrough($xdx, $basefonty, $txt);
3628                                 }
3629                                 if ($this->ColorFlag) {
3630                                         $s .= ' Q';
3631                                 }
3632                                 if ($link) {
3633                                         $this->Link($xdx, $this->y + (($h - $this->FontSize)/2), $width, $this->FontSize, $link, substr_count($txt, chr(32)));
3634                                 }
3635                         }
3636                         // output cell
3637                         if ($s) {
3638                                 // output cell
3639                                 $rs .= $s;
3640                                 // reset text stretching
3641                                 if ($stretch > 2) {
3642                                         //Reset character horizontal spacing
3643                                         $rs .= ' BT 0 Tc ET';
3644                                 } elseif ($stretch > 0) {
3645                                         //Reset character horizontal scaling
3646                                         $rs .= ' BT 100 Tz ET';
3647                                 }
3648                         }
3649                         // reset word spacing
3650                         if (!(($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) AND ($align == 'J')) {
3651                                 $rs .= ' BT 0 Tw ET';
3652                         }
3653                         $this->lasth = $h;
3654                         if ($ln > 0) {
3655                                 //Go to the beginning of the next line
3656                                 $this->y += $h;
3657                                 if ($ln == 1) {
3658                                         if ($this->rtl) {
3659                                                 $this->x = $this->w - $this->rMargin;
3660                                         } else {
3661                                                 $this->x = $this->lMargin;
3662                                         }
3663                                 }
3664                         } else {
3665                                 // go left or right by case
3666                                 if ($this->rtl) {
3667                                         $this->x -= $w;
3668                                 } else {
3669                                         $this->x += $w;
3670                                 }
3671                         }
3672                         $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
3673                         $rs = $gstyles.$rs;
3674                         return $rs;
3675                 }
3676
3677                 /**
3678                 * This method allows printing text with line breaks.
3679                 * They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other.<br />
3680                 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
3681                 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
3682                 * @param float $h Cell minimum height. The cell extends automatically if needed.
3683                 * @param string $txt String to print
3684                 * @param mixed $border Indicates if borders must be drawn around the cell block. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
3685                 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value when $ishtml=false)</li></ul>
3686                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3687                 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul>
3688                 * @param int $x x position in user units
3689                 * @param int $y y position in user units
3690                 * @param boolean $reseth if true reset the last cell height (default true).
3691                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
3692                 * @param boolean $ishtml set to true if $txt is HTML content (default = false).
3693                 * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
3694                 * @param float $maxh maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature. This feature works only when $ishtml=false.
3695                 * @return int Return the number of cells or 1 for html mode.
3696                 * @access public
3697                 * @since 1.3
3698                 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
3699                 */
3700                 public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $addpage=true) {
3701                         if ($this->empty_string($this->lasth) OR $reseth) {
3702                                 //set row height
3703                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
3704                         }
3705                         if (!$this->empty_string($y)) {
3706                                 $this->SetY($y);
3707                         } else {
3708                                 $y = $this->GetY();
3709                         }
3710                         // should not add page for each cell
3711             if ($addpage) {
3712                             // check for page break
3713                 $this->checkPageBreak($h);
3714             }
3715                         $y = $this->GetY();
3716                         // get current page number
3717                         $startpage = $this->page;
3718                         if (!$this->empty_string($x)) {
3719                                 $this->SetX($x);
3720                         } else {
3721                                 $x = $this->GetX();
3722                         }
3723                         if ($this->empty_string($w) OR ($w <= 0)) {
3724                                 if ($this->rtl) {
3725                                         $w = $this->x - $this->lMargin;
3726                                 } else {
3727                                         $w = $this->w - $this->rMargin - $this->x;
3728                                 }
3729                         }
3730                         // store original margin values
3731                         $lMargin = $this->lMargin;
3732                         $rMargin = $this->rMargin;
3733                         if ($this->rtl) {
3734                                 $this->SetRightMargin($this->w - $this->x);
3735                                 $this->SetLeftMargin($this->x - $w);
3736                         } else {
3737                                 $this->SetLeftMargin($this->x);
3738                                 $this->SetRightMargin($this->w - $this->x - $w);
3739                         }
3740                         $starty = $this->y;
3741                         if ($autopadding) {
3742                                 // Adjust internal padding
3743                                 if ($this->cMargin < ($this->LineWidth / 2)) {
3744                                         $this->cMargin = ($this->LineWidth / 2);
3745                                 }
3746                                 // Add top space if needed
3747                                 if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3748                                         $this->y += $this->LineWidth / 2;
3749                                 }
3750                                 // add top padding
3751                                 $this->y += $this->cMargin;
3752                         }
3753                         if ($ishtml) {
3754                                 // ******* Write HTML text
3755                                 $this->writeHTML($txt, true, 0, $reseth, true, $align);
3756                                 $nl = 1;
3757                         } else {
3758                                 // ******* Write text
3759                                 $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, false, $maxh);
3760                         }
3761                         if ($autopadding) {
3762                                 // add bottom padding
3763                                 $this->y += $this->cMargin;
3764                                 // Add bottom space if needed
3765                                 if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3766                                         $this->y += $this->LineWidth / 2;
3767                                 }
3768                         }
3769                         // Get end-of-text Y position
3770                         $currentY = $this->y;
3771                         // get latest page number
3772                         $endpage = $this->page;
3773                         // check if a new page has been created
3774                         if ($endpage > $startpage) {
3775                                 // design borders around HTML cells.
3776                                 for ($page=$startpage; $page <= $endpage; ++$page) {
3777                                         $this->setPage($page);
3778                                         if ($page == $startpage) {
3779                                                 $this->y = $starty; // put cursor at the beginning of cell on the first page
3780                                                 $h = $this->getPageHeight() - $starty - $this->getBreakMargin();
3781                                                 $cborder = $this->getBorderMode($border, $position='start');
3782                                         } elseif ($page == $endpage) {
3783                                                 $this->y = $this->tMargin; // put cursor at the beginning of last page
3784                                                 $h = $currentY - $this->tMargin;
3785                                                 $this->currentY = $currentY;
3786                                                 $cborder = $this->getBorderMode($border, $position='end');
3787                                         } else {
3788                                                 $this->y = $this->tMargin; // put cursor at the beginning of the current page
3789                                                 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
3790                                                 $cborder = $this->getBorderMode($border, $position='middle');
3791                                         }
3792                                         $nx = $x;
3793                                         // account for margin changes
3794                                         if ($page > $startpage) {
3795                                                 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
3796                                                         $nx = $x + ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
3797                                                 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
3798                                                         $nx = $x + ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
3799                                                 }
3800                                         }
3801                                         $this->SetX($nx);
3802                                         $ccode = $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, false);
3803                                         if ($cborder OR $fill) {
3804                                                 $pagebuff = $this->getPageBuffer($this->page);
3805                                                 $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
3806                                                 $pend = substr($pagebuff, $this->intmrk[$this->page]);
3807                                                 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
3808                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
3809                                         }
3810                                 }
3811                         } else {
3812                                 $h = max($h, ($currentY - $y));
3813                                 // put cursor at the beginning of text
3814                                 $this->SetY($y);
3815                                 $this->SetX($x);
3816                                 // design a cell around the text
3817                                 $ccode = $this->getCellCode($w, $h, '', $border, 1, '', $fill, '', 0, true);
3818                                 if ($border OR $fill) {
3819                                         if (end($this->transfmrk[$this->page]) !== false) {
3820                                                 $pagemarkkey = key($this->transfmrk[$this->page]);
3821                                                 $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
3822                                         } elseif ($this->InFooter) {
3823                                                 $pagemark = &$this->footerpos[$this->page];
3824                                         } else {
3825                                                 $pagemark = &$this->intmrk[$this->page];
3826                                         }
3827                                         $pagebuff = $this->getPageBuffer($this->page);
3828                                         $pstart = substr($pagebuff, 0, $pagemark);
3829                                         $pend = substr($pagebuff, $pagemark);
3830                                         $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
3831                                         $pagemark += strlen($ccode."\n");
3832                                 }
3833                         }
3834                         // Get end-of-cell Y position
3835                         $currentY = $this->GetY();
3836                         // restore original margin values
3837                         $this->SetLeftMargin($lMargin);
3838                         $this->SetRightMargin($rMargin);
3839                         if ($ln > 0) {
3840                                 //Go to the beginning of the next line
3841                                 $this->SetY($currentY);
3842                                 if ($ln == 2) {
3843                                         $this->SetX($x + $w);
3844                                 }
3845                         } else {
3846                                 // go left or right by case
3847                                 $this->setPage($startpage);
3848                                 $this->y = $y;
3849                                 $this->SetX($x + $w);
3850                         }
3851                         return $nl;
3852                 }
3853
3854                 /**
3855                 * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages)
3856                 * @param mixed $border Indicates if borders must be drawn around the cell block. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
3857                 * @param string multicell position: 'start', 'middle', 'end'
3858                 * @return border mode
3859                 * @access protected
3860                 * @since 4.4.002 (2008-12-09)
3861                 */
3862                 protected function getBorderMode($border, $position='start') {
3863                         if ((!$this->opencell) AND ($border == 1)) {
3864                                 return 1;
3865                         }
3866                         $cborder = '';
3867                         switch ($position) {
3868                                 case 'start': {
3869                                         if ($border == 1) {
3870                                                 $cborder = 'LTR';
3871                                         } else {
3872                                                 if (!(false === strpos($border, 'L'))) {
3873                                                         $cborder .= 'L';
3874                                                 }
3875                                                 if (!(false === strpos($border, 'T'))) {
3876                                                         $cborder .= 'T';
3877                                                 }
3878                                                 if (!(false === strpos($border, 'R'))) {
3879                                                         $cborder .= 'R';
3880                                                 }
3881                                                 if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
3882                                                         $cborder .= 'B';
3883                                                 }
3884                                         }
3885                                         break;
3886                                 }
3887                                 case 'middle': {
3888                                         if ($border == 1) {
3889                                                 $cborder = 'LR';
3890                                         } else {
3891                                                 if (!(false === strpos($border, 'L'))) {
3892                                                         $cborder .= 'L';
3893                                                 }
3894                                                 if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
3895                                                         $cborder .= 'T';
3896                                                 }
3897                                                 if (!(false === strpos($border, 'R'))) {
3898                                                         $cborder .= 'R';
3899                                                 }
3900                                                 if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
3901                                                         $cborder .= 'B';
3902                                                 }
3903                                         }
3904                                         break;
3905                                 }
3906                                 case 'end': {
3907                                         if ($border == 1) {
3908                                                 $cborder = 'LRB';
3909                                         } else {
3910                                                 if (!(false === strpos($border, 'L'))) {
3911                                                         $cborder .= 'L';
3912                                                 }
3913                                                 if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
3914                                                         $cborder .= 'T';
3915                                                 }
3916                                                 if (!(false === strpos($border, 'R'))) {
3917                                                         $cborder .= 'R';
3918                                                 }
3919                                                 if (!(false === strpos($border, 'B'))) {
3920                                                         $cborder .= 'B';
3921                                                 }
3922                                         }
3923                                         break;
3924                                 }
3925                                 default: {
3926                                         $cborder = $border;
3927                                         break;
3928                                 }
3929                         }
3930                         return $cborder;
3931                 }
3932
3933                 /**
3934                 * This method returns the estimated number of lines required to print the text.
3935                 * @param string $txt text to print
3936                 * @param float $w width of cell. If 0, they extend up to the right margin of the page.
3937                 * @return int Return the estimated number of lines.
3938                 * @access public
3939                 * @since 4.5.011
3940                 */
3941                 public function getNumLines($txt, $w=0) {
3942                         $lines = 0;
3943                         if ($this->empty_string($w) OR ($w <= 0)) {
3944                                 if ($this->rtl) {
3945                                         $w = $this->x - $this->lMargin;
3946                                 } else {
3947                                         $w = $this->w - $this->rMargin - $this->x;
3948                                 }
3949                         }
3950                         // max column width
3951                         $wmax = $w - (2 * $this->cMargin);
3952                         // remove carriage returns
3953                         $txt = str_replace("\r", '', $txt);
3954                         // remove last newline (if any)
3955                         if (substr($txt,-1) == "\n") {
3956                                 $txt = substr($txt, 0, -1);
3957                         }
3958                         // divide text in blocks
3959                         $txtblocks = explode("\n", $txt);
3960                         // for each block;
3961                         foreach ($txtblocks as $block) {
3962                                 // estimate the number of lines
3963                                 $lines += $this->empty_string($block) ? 1 : (ceil($this->GetStringWidth($block) / $wmax));
3964                         }
3965                         return $lines;
3966                 }
3967
3968                 /**
3969                 * This method prints text from the current position.<br />
3970                 * @param float $h Line height
3971                 * @param string $txt String to print
3972                 * @param mixed $link URL or identifier returned by AddLink()
3973                 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
3974                 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
3975                 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
3976                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
3977                 * @param boolean $firstline if true prints only the first line and return the remaining string.
3978                 * @param boolean $firstblock if true the string is the starting of a line.
3979                 * @param float $maxh maximum height. The remaining unprinted text will be returned. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
3980                 * @return mixed Return the number of cells or the remaining string if $firstline = true.
3981                 * @access public
3982                 * @since 1.5
3983                 */
3984                 public function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0) {
3985                         if (strlen($txt) == 0) {
3986                                 $txt = ' ';
3987                         }
3988                         // remove carriage returns
3989                         $s = str_replace("\r", '', $txt);
3990
3991                         // check if string contains arabic text
3992                         if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
3993                                 $arabic = true;
3994                         } else {
3995                                 $arabic = false;
3996                         }
3997                         // check if string contains RTL text
3998                         if ($arabic OR $this->tmprtl OR preg_match(K_RE_PATTERN_RTL, $txt)) {
3999                                 $rtlmode = true;
4000                         } else {
4001                                 $rtlmode = false;
4002                         }
4003                         // get a char width
4004                         $chrwidth = $this->GetCharWidth('.');
4005                         // get array of unicode values
4006                         $chars = $this->UTF8StringToArray($s);
4007                         // get array of chars
4008                         $uchars = $this->UTF8ArrayToUniArray($chars);
4009                         // get the number of characters
4010                         $nb = count($chars);
4011                         // replacement for SHY character (minus symbol)
4012                         $shy_replacement = 45;
4013                         $shy_replacement_char = $this->unichr($shy_replacement);
4014                         // widht for SHY replacement
4015                         $shy_replacement_width = $this->GetCharWidth($shy_replacement);
4016                         // store current position
4017                         $prevx = $this->x;
4018                         $prevy = $this->y;
4019                         // max Y
4020                         $maxy = $this->y + $maxh - $h - (2 * $this->cMargin);
4021                         // calculate remaining line width ($w)
4022                         if ($this->rtl) {
4023                                 $w = $this->x - $this->lMargin;
4024                         } else {
4025                                 $w = $this->w - $this->rMargin - $this->x;
4026                         }
4027                         // max column width
4028                         $wmax = $w - (2 * $this->cMargin);
4029                         if ($chrwidth > $wmax) {
4030                                 // a single character do not fit on column
4031                                 return '';
4032                         }
4033                         $i = 0; // character position
4034                         $j = 0; // current starting position
4035                         $sep = -1; // position of the last blank space
4036                         $shy = false; // true if the last blank is a soft hypen (SHY)
4037                         $l = 0; // current string lenght
4038                         $nl = 0; //number of lines
4039                         $linebreak = false;
4040                         // for each character
4041                         while ($i < $nb) {
4042                                 if (($maxh > 0) AND ($this->y >= $maxy) ) {
4043                                         $firstline = true;
4044                                 }
4045                                 //Get the current character
4046                                 $c = $chars[$i];
4047                                 if ($c == 10) { // 10 = "\n" = new line
4048                                         //Explicit line break
4049                                         if ($align == 'J') {
4050                                                 if ($this->rtl) {
4051                                                         $talign = 'R';
4052                                                 } else {
4053                                                         $talign = 'L';
4054                                                 }
4055                                         } else {
4056                                                 $talign = $align;
4057                                         }
4058                                         $tmpstr = $this->UniArrSubString($uchars, $j, $i);
4059                                         if ($firstline) {
4060                                                 $startx = $this->x;
4061                                                 $tmparr = array_slice($chars, $j, $i);
4062                                                 if ($rtlmode) {
4063                                                         $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4064                                                 }
4065                                                 $linew = $this->GetArrStringWidth($tmparr);
4066                                                 unset($tmparr);
4067                                                 if ($this->rtl) {
4068                                                         $this->endlinex = $startx - $linew;
4069                                                 } else {
4070                                                         $this->endlinex = $startx + $linew;
4071                                                 }
4072                                                 $w = $linew;
4073                                                 $tmpcmargin = $this->cMargin;
4074                                                 if ($maxh == 0) {
4075                                                         $this->cMargin = 0;
4076                                                 }
4077                                         }
4078                                         $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
4079                                         unset($tmpstr);
4080                                         if ($firstline) {
4081                                                 $this->cMargin = $tmpcmargin;
4082                                                 return ($this->UniArrSubString($uchars, $i));
4083                                         }
4084                                         ++$nl;
4085                                         $j = $i + 1;
4086                                         $l = 0;
4087                                         $sep = -1;
4088                                         $shy = false;
4089                                         // account for margin changes
4090                                         if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
4091                                                 // AcceptPageBreak() may be overriden on extended classed to include margin changes
4092                                                 $this->AcceptPageBreak();
4093                                         }
4094                                         $w = $this->getRemainingWidth();
4095                                         $wmax = $w - (2 * $this->cMargin);
4096                                 } else {
4097                                         // 160 is the non-breaking space.
4098                                         // 173 is SHY (Soft Hypen).
4099                                         // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
4100                                         // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
4101                                         // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
4102                                         if (($c != 160) AND (($c == 173) OR preg_match($this->re_spaces, $this->unichr($c)))) {
4103                                                 // update last blank space position
4104                                                 $sep = $i;
4105                                                 // check if is a SHY
4106                                                 if ($c == 173) {
4107                                                         $shy = true;
4108                                                 } else {
4109                                                         $shy = false;
4110                                                 }
4111                                         }
4112                                         // update string length
4113                                         if ((($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) AND ($arabic)) {
4114                                                 // with bidirectional algorithm some chars may be changed affecting the line length
4115                                                 // *** very slow ***
4116                                                 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), '', $this->tmprtl));
4117                                         } else {
4118                                                 $l += $this->GetCharWidth($c);
4119                                         }
4120                                         if (!$stretch && (($l > $wmax) OR ($shy AND (($l + $shy_replacement_width) > $wmax))) ) {
4121                                                 // we have reached the end of column
4122                                                 if ($sep == -1) {
4123                                                         // check if the line was already started
4124                                                         if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $chrwidth)))
4125                                                                 OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $chrwidth)))) {
4126                                                                 // print a void cell and go to next line
4127                                                                 $this->Cell($w, $h, '', 0, 1);
4128                                                                 $linebreak = true;
4129                                                                 if ($firstline) {
4130                                                                         return ($this->UniArrSubString($uchars, $j));
4131                                                                 }
4132                                                         } else {
4133                                                                 // truncate the word because do not fit on column
4134                                                                 $tmpstr = $this->UniArrSubString($uchars, $j, $i);
4135                                                                 if ($firstline) {
4136                                                                         $startx = $this->x;
4137                                                                         $tmparr = array_slice($chars, $j, $i);
4138                                                                         if ($rtlmode) {
4139                                                                                 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4140                                                                         }
4141                                                                         $linew = $this->GetArrStringWidth($tmparr);
4142                                                                         unset($tmparr);
4143                                                                         if ($this->rtl) {
4144                                                                                 $this->endlinex = $startx - $linew;
4145                                                                         } else {
4146                                                                                 $this->endlinex = $startx + $linew;
4147                                                                         }
4148                                                                         $w = $linew;
4149                                                                         $tmpcmargin = $this->cMargin;
4150                                                                         if ($maxh == 0) {
4151                                                                                 $this->cMargin = 0;
4152                                                                         }
4153                                                                 }
4154                                                                 $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
4155                                                                 unset($tmpstr);
4156                                                                 if ($firstline) {
4157                                                                         $this->cMargin = $tmpcmargin;
4158                                                                         return ($this->UniArrSubString($uchars, $i));
4159                                                                 }
4160                                                                 $j = $i;
4161                                                                 --$i;
4162                                                         }
4163                                                 } else {
4164                                                         // word wrapping
4165                                                         if ($this->rtl AND (!$firstblock)) {
4166                                                                 $endspace = 1;
4167                                                         } else {
4168                                                                 $endspace = 0;
4169                                                         }
4170                                                         if ($shy) {
4171                                                                 // add hypen (minus symbol) at the end of the line
4172                                                                 $shy_width = $shy_replacement_width;
4173                                                                 if ($this->rtl) {
4174                                                                         $shy_char_left = $shy_replacement_char;
4175                                                                         $shy_char_right = '';
4176                                                                 } else {
4177                                                                         $shy_char_left = '';
4178                                                                         $shy_char_right = $shy_replacement_char;
4179                                                                 }
4180                                                         } else {
4181                                                                 $shy_width = 0;
4182                                                                 $shy_char_left = '';
4183                                                                 $shy_char_right = '';
4184                                                         }
4185                                                         $tmpstr = $this->UniArrSubString($uchars, $j, ($sep + $endspace));
4186                                                         if ($firstline) {
4187                                                                 $startx = $this->x;
4188                                                                 $tmparr = array_slice($chars, $j, ($sep + $endspace));
4189                                                                 if ($rtlmode) {
4190                                                                         $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4191                                                                 }
4192                                                                 $linew = $this->GetArrStringWidth($tmparr);
4193                                                                 unset($tmparr);
4194                                                                 if ($this->rtl) {
4195                                                                         $this->endlinex = $startx - $linew - $shy_width;
4196                                                                 } else {
4197                                                                         $this->endlinex = $startx + $linew + $shy_width;
4198                                                                 }
4199                                                                 $w = $linew;
4200                                                                 $tmpcmargin = $this->cMargin;
4201                                                                 if ($maxh == 0) {
4202                                                                         $this->cMargin = 0;
4203                                                                 }
4204                                                         }
4205                                                         // print the line
4206                                                         $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
4207                                                         unset($tmpstr);
4208                                                         if ($firstline) {
4209                                                                 // return the remaining text
4210                                                                 $this->cMargin = $tmpcmargin;
4211                                                                 return ($this->UniArrSubString($uchars, ($sep + $endspace)));
4212                                                         }
4213                                                         $i = $sep;
4214                                                         $sep = -1;
4215                                                         $shy = false;
4216                                                         $j = ($i+1);
4217                                                 }
4218                                                 // account for margin changes
4219                                                 if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
4220                                                         // AcceptPageBreak() may be overriden on extended classed to include margin changes
4221                                                         $this->AcceptPageBreak();
4222                                                 }
4223                                                 $w = $this->getRemainingWidth();
4224                                                 $wmax = $w - (2 * $this->cMargin);
4225                                                 if ($linebreak) {
4226                                                         $linebreak = false;
4227                                                 } else {
4228                                                         ++$nl;
4229                                                         $l = 0;
4230                                                 }
4231                                         }
4232                                 }
4233                                 ++$i;
4234                         } // end while i < nb
4235                         // print last substring (if any)
4236                         if ($l > 0) {
4237                             if (!$stretch)
4238                             {
4239                                 switch ($align) {
4240                                         case 'J':
4241                                         case 'C': {
4242                                                 $w = $w;
4243                                                 break;
4244                                         }
4245                                         case 'L': {
4246                                                 if ($this->rtl) {
4247                                                         $w = $w;
4248                                                 } else {
4249                                                         $w = $l;
4250                                                 }
4251                                                 break;
4252                                         }
4253                                         case 'R': {
4254                                                 if ($this->rtl) {
4255                                                         $w = $l;
4256                                                 } else {
4257                                                         $w = $w;
4258                                                 }
4259                                                 break;
4260                                         }
4261                                         default: {
4262                                                 $w = $l;
4263                                                 break;
4264                                         }
4265                                 }
4266                             }
4267                                 $tmpstr = $this->UniArrSubString($uchars, $j, $nb);
4268                                 if ($firstline) {
4269                                         $startx = $this->x;
4270                                         $tmparr = array_slice($chars, $j, $nb);
4271                                         if ($rtlmode) {
4272                                                 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4273                                         }
4274                                         $linew = $this->GetArrStringWidth($tmparr);
4275                                         unset($tmparr);
4276                                         if ($this->rtl) {
4277                                                 $this->endlinex = $startx - $linew;
4278                                         } else {
4279                                                 $this->endlinex = $startx + $linew;
4280                                         }
4281                                         if (!$stretch)
4282                                             $w = $linew;
4283                                         $tmpcmargin = $this->cMargin;
4284                                         if ($maxh == 0) {
4285                                                 $this->cMargin = 0;
4286                                         }
4287                                 }
4288                                 $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
4289                                 unset($tmpstr);
4290                                 if ($firstline) {
4291                                         $this->cMargin = $tmpcmargin;
4292                                         return ($this->UniArrSubString($uchars, $nb));
4293                                 }
4294                                 ++$nl;
4295                         }
4296                         if ($firstline) {
4297                                 return '';
4298                         }
4299                         return $nl;
4300                 }
4301
4302                 /**
4303                 * Returns the remaining width between the current position and margins.
4304                 * @return int Return the remaining width
4305                 * @access protected
4306                 */
4307                 protected function getRemainingWidth() {
4308                         if ($this->rtl) {
4309                                 return ($this->x - $this->lMargin);
4310                         } else {
4311                                 return ($this->w - $this->rMargin - $this->x);
4312                         }
4313                 }
4314
4315                 /**
4316                 * Extract a slice of the $strarr array and return it as string.
4317                 * @param string $strarr The input array of characters.
4318                 * @param int $start the starting element of $strarr.
4319                 * @param int $end first element that will not be returned.
4320                 * @return Return part of a string
4321                 * @access public
4322                 */
4323                 public function UTF8ArrSubString($strarr, $start='', $end='') {
4324                         if (strlen($start) == 0) {
4325                                 $start = 0;
4326                         }
4327                         if (strlen($end) == 0) {
4328                                 $end = count($strarr);
4329                         }
4330                         $string = '';
4331                         for ($i=$start; $i < $end; ++$i) {
4332                                 $string .= $this->unichr($strarr[$i]);
4333                         }
4334                         return $string;
4335                 }
4336
4337                 /**
4338                 * Extract a slice of the $uniarr array and return it as string.
4339                 * @param string $uniarr The input array of characters.
4340                 * @param int $start the starting element of $strarr.
4341                 * @param int $end first element that will not be returned.
4342                 * @return Return part of a string
4343                 * @access public
4344                 * @since 4.5.037 (2009-04-07)
4345                 */
4346                 public function UniArrSubString($uniarr, $start='', $end='') {
4347                         if (strlen($start) == 0) {
4348                                 $start = 0;
4349                         }
4350                         if (strlen($end) == 0) {
4351                                 $end = count($uniarr);
4352                         }
4353                         $string = '';
4354                         for ($i=$start; $i < $end; ++$i) {
4355                                 $string .= $uniarr[$i];
4356                         }
4357                         return $string;
4358                 }
4359
4360                 /**
4361                 * Convert an array of UTF8 values to array of unicode characters
4362                 * @param string $ta The input array of UTF8 values.
4363                 * @return Return array of unicode characters
4364                 * @access public
4365                 * @since 4.5.037 (2009-04-07)
4366                 */
4367                 public function UTF8ArrayToUniArray($ta) {
4368                         return array_map(array($this, 'unichr'), $ta);
4369                 }
4370
4371                 /**
4372                 * Returns the unicode caracter specified by UTF-8 code
4373                 * @param int $c UTF-8 code
4374                 * @return Returns the specified character.
4375                 * @author Miguel Perez, Nicola Asuni
4376                 * @access public
4377                 * @since 2.3.000 (2008-03-05)
4378                 */
4379                 public function unichr($c) {
4380                         if (!$this->isunicode) {
4381                                 return chr($c);
4382                         } elseif ($c <= 0x7F) {
4383                                 // one byte
4384                                 return chr($c);
4385                         } elseif ($c <= 0x7FF) {
4386                                 // two bytes
4387                                 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
4388                         } elseif ($c <= 0xFFFF) {
4389                                 // three bytes
4390                                 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
4391                         } elseif ($c <= 0x10FFFF) {
4392                                 // four bytes
4393                                 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
4394                         } else {
4395                                 return '';
4396                         }
4397                 }
4398
4399                 /**
4400                 * Puts an image in the page.
4401                 * The upper-left corner must be given.
4402                 * The dimensions can be specified in different ways:<ul>
4403                 * <li>explicit width and height (expressed in user unit)</li>
4404                 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
4405                 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
4406                 * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
4407                 * The format can be specified explicitly or inferred from the file extension.<br />
4408                 * It is possible to put a link on the image.<br />
4409                 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
4410                 * @param string $file Name of the file containing the image.
4411                 * @param float $x Abscissa of the upper-left corner.
4412                 * @param float $y Ordinate of the upper-left corner.
4413                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
4414                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
4415                 * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
4416                 * @param mixed $link URL or identifier returned by AddLink().
4417                 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
4418                 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
4419                 * @param int $dpi dot-per-inch resolution used on resize
4420                 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
4421                 * @param boolean $ismask true if this image is a mask, false otherwise
4422                 * @param mixed $imgmask image object returned by this function or false
4423                 * @param mixed $border Indicates if borders must be drawn around the image. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
4424                 * @param boolean $fitbox If true scale image dimensions proportionally to fit within the ($w, $h) box.
4425                 * @return image information
4426                 * @access public
4427                 * @since 1.1
4428         *
4429         * peter d: Upgrading tcpdf to the latest version causes the whole thing to blow up since we have modifications to the original source as well as sugarpdf which
4430         * also extend from this. The only option is to add a workaround for some of the bugs in this function.
4431                 */
4432                 public function Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false) {
4433                         if ($x === '') {
4434                                 $x = $this->x;
4435                         }
4436                         if ($y === '') {
4437                                 $y = $this->y;
4438                         }
4439                         // get image dimensions
4440                         $imsize = @getimagesize($file);
4441                         if ($imsize === FALSE) {
4442                                 // encode spaces on filename
4443                                 $file = str_replace(' ', '%20', $file);
4444                                 $imsize = @getimagesize($file);
4445                                 if ($imsize === FALSE) {
4446                                         $this->Error('[Image] No such file or directory in '.$file);
4447                                 }
4448                         }
4449                         // get original image width and height in pixels
4450                         list($pixw, $pixh) = $imsize;
4451                         // calculate image width and height on document
4452                         if (($w <= 0) AND ($h <= 0)) {
4453                                 // convert image size to document unit
4454                                 $w = $this->pixelsToUnits($pixw);
4455                                 $h = $this->pixelsToUnits($pixh);
4456                         } elseif ($w <= 0) {
4457                                 $w = $h * $pixw / $pixh;
4458                         } elseif ($h <= 0) {
4459                                 $h = $w * $pixh / $pixw;
4460                         } elseif ($fitbox AND ($w > 0) AND ($h > 0)) {
4461                                 // scale image dimensions proportionally to fit within the ($w, $h) box
4462                 // NOTE: This section doesn't actually work very well, use the resize = true case I added.
4463                                 if ((($w * $pixh) / ($h * $pixw)) < 1) {
4464                                         $h = $w * $pixh / $pixw;
4465                                 } else {
4466                                         $w = $h * $pixw / $pixh;
4467                                 }
4468                         } else if ($resize) { // Added resize case
4469                 // Note: The issue here is that $w and $h represent abstract sizes, we pass it in as pixels,
4470                 // but tcpdf treats it as document units.
4471                 $wratio = $pixw / $w;
4472                 $hratio = $pixh / $h;
4473
4474                 // Check if our image exceeds the boundaries of $w and $h
4475                 if ($wratio > 1 AND $hratio > 1) {
4476                     $favoredRatio = ($wratio > $hratio) ? $wratio : $hratio;
4477                 } else if ($wratio > 1) {
4478                     $favoredRatio = $wratio;
4479                 } else if ($hratio > 1) {
4480                     $favoredRatio = $hratio;
4481                 } else {
4482                     $favoredRatio = 1;
4483                     $resize = false;
4484                 }
4485
4486                 // Calculate the new boundaries that also happen to fit the box..
4487                 // Dividing by the unit conversion $this->k seems to make the size not blow up
4488                 // later down in the code.
4489                 $w = $pixw / $favoredRatio / $this->k;
4490                 $h = $pixh / $favoredRatio / $this->k;
4491             }
4492                         // calculate new minimum dimensions in pixels
4493                         $neww = round($w * $this->k * $dpi / $this->dpi);
4494                         $newh = round($h * $this->k * $dpi / $this->dpi);
4495
4496                         // check if resize is necessary (resize is used only to reduce the image)
4497
4498             // - commmented out by pete d.
4499             // this is not a good way of checking for resize. and it might overwrite resize if the flag is enabled.
4500                         // if (($neww * $newh) >= ($pixw * $pixh)) {
4501                         //      $resize = false;
4502                         // }
4503
4504                         // check if image has been already added on document
4505                         if (!in_array($file, $this->imagekeys)) {
4506                                 //First use of image, get info
4507                                 if ($type == '') {
4508                                         $fileinfo = pathinfo($file);
4509                                         if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
4510                                                 $type = $fileinfo['extension'];
4511                                         } else {
4512                                                 $this->Error('Image file has no extension and no type was specified: '.$file);
4513                                         }
4514                                 }
4515                                 $type = strtolower($type);
4516                                 if ($type == 'jpg') {
4517                                         $type = 'jpeg';
4518                                 }
4519                                 $mqr = get_magic_quotes_runtime();
4520                                 //set_magic_quotes_runtime(0);
4521                                 // Specific image handlers
4522                                 $mtd = '_parse'.$type;
4523                                 // GD image handler function
4524                                 $gdfunction = 'imagecreatefrom'.$type;
4525                                 $info = false;
4526                                 if ((method_exists($this, $mtd)) AND (!($resize AND function_exists($gdfunction)))) {
4527                                         // TCPDF image functions
4528                                         $info = $this->$mtd($file);
4529                                         if ($info == 'pngalpha') {
4530                                                 return $this->ImagePngAlpha($file, $x, $y, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign);
4531                                         }
4532                                 }
4533                                 if (!$info) {
4534                                         if (function_exists($gdfunction)) {
4535                                                 // GD library
4536                                                 $img = $gdfunction($file);
4537                                                 if ($resize) {
4538                                                         $imgr = imagecreatetruecolor($neww, $newh);
4539                                                         imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
4540                                                         $info = $this->_toJPEG($imgr);
4541                                                 } else {
4542                                                         $info = $this->_toJPEG($img);
4543                                                 }
4544                                         } elseif (extension_loaded('imagick')) {
4545                                                 // ImageMagick library
4546                                                 $img = new Imagick();
4547                                                 $img->readImage($file);
4548                                                 if ($resize) {
4549                                                         $img->resizeImage($neww, $newh, 10, 1, false);
4550                                                 }
4551                                                 $img->setCompressionQuality($this->jpeg_quality);
4552                                                 $img->setImageFormat('jpeg');
4553                                                 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
4554                                                 $img->writeImage($tempname);
4555                                                 $info = $this->_parsejpeg($tempname);
4556                                                 unlink($tempname);
4557                                                 $img->destroy();
4558                                         }
4559                                         else if ($type == 'jpeg') {
4560                                                 $info = $this->_parsejpeg($file);
4561                                         }
4562                                         else {
4563                                                 return;
4564                                         }
4565                                 }
4566                                 if ($info === false) {
4567                                         //If false, we cannot process image
4568                                         return;
4569                                 }
4570                                 //set_magic_quotes_runtime($mqr);
4571                                 if ($ismask) {
4572                                         // force grayscale
4573                                         $info['cs'] = 'DeviceGray';
4574                                 }
4575                                 $info['i'] = $this->numimages + 1;
4576                                 if ($imgmask !== false) {
4577                                         $info['masked'] = $imgmask;
4578                                 }
4579                                 // add image to document
4580                                 $this->setImageBuffer($file, $info);
4581                         } else {
4582                                 $info = $this->getImageBuffer($file);
4583                         }
4584                         // Check whether we need a new page first as this does not fit
4585                         if ($this->checkPageBreak($h, $y)) {
4586                                 $y = $this->GetY() + $this->cMargin;
4587                         }
4588                         // set bottomcoordinates
4589                         $this->img_rb_y = $y + $h;
4590                         // set alignment
4591                         if ($this->rtl) {
4592                                 if ($palign == 'L') {
4593                                         $ximg = $this->lMargin;
4594                                         // set right side coordinate
4595                                         $this->img_rb_x = $ximg + $w;
4596                                 } elseif ($palign == 'C') {
4597                                         $ximg = ($this->w - $x - $w) / 2;
4598                                         // set right side coordinate
4599                                         $this->img_rb_x = $ximg + $w;
4600                                 } else {
4601                                         $ximg = $this->w - $x - $w;
4602                                         // set left side coordinate
4603                                         $this->img_rb_x = $ximg;
4604                                 }
4605                         } else {
4606                                 if ($palign == 'R') {
4607                                         $ximg = $this->w - $this->rMargin - $w;
4608                                         // set left side coordinate
4609                                         $this->img_rb_x = $ximg;
4610                                 } elseif ($palign == 'C') {
4611                                         $ximg = ($this->w - $x - $w) / 2;
4612                                         // set right side coordinate
4613                                         $this->img_rb_x = $ximg + $w;
4614                                 } else {
4615                                         $ximg = $x;
4616                                         // set right side coordinate
4617                                         $this->img_rb_x = $ximg + $w;
4618                                 }
4619                         }
4620                         if ($ismask) {
4621                                 // embed hidden, ouside the canvas
4622                                 $xkimg = ($this->pagedim[$this->page]['w'] + 10);
4623                         } else {
4624                                 $xkimg = $ximg * $this->k;
4625                         }
4626                         $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%d Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
4627                         if (!empty($border)) {
4628                                 $bx = $x;
4629                                 $by = $y;
4630                                 $this->x = $ximg;
4631                                 $this->y = $y;
4632                                 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
4633                                 $this->x = $bx;
4634                                 $this->y = $by;
4635                         }
4636                         if ($link) {
4637                                 $this->Link($ximg, $y, $w, $h, $link, 0);
4638                         }
4639                         // set pointer to align the successive text/objects
4640                         switch($align) {
4641                                 case 'T': {
4642                                         $this->y = $y;
4643                                         $this->x = $this->img_rb_x;
4644                                         break;
4645                                 }
4646                                 case 'M': {
4647                                         $this->y = $y + round($h/2);
4648                                         $this->x = $this->img_rb_x;
4649                                         break;
4650                                 }
4651                                 case 'B': {
4652                                         $this->y = $this->img_rb_y;
4653                                         $this->x = $this->img_rb_x;
4654                                         break;
4655                                 }
4656                                 case 'N': {
4657                                         $this->SetY($this->img_rb_y);
4658                                         break;
4659                                 }
4660                                 default:{
4661                                         break;
4662                                 }
4663                         }
4664                         $this->endlinex = $this->img_rb_x;
4665                         return $info['i'];
4666                 }
4667
4668                 /**
4669                 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
4670                 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
4671                 * @param string $file Image file name.
4672                 * @param image $image Image object.
4673                 * return image JPEG image object.
4674                 * @access protected
4675                 */
4676                 protected function _toJPEG($image) {
4677                         $tempname = tempnam(K_PATH_CACHE, 'jpg_');
4678                         imagejpeg($image, $tempname, $this->jpeg_quality);
4679                         imagedestroy($image);
4680                         $retvars = $this->_parsejpeg($tempname);
4681                         // tidy up by removing temporary image
4682                         unlink($tempname);
4683                         return $retvars;
4684                 }
4685
4686                 /**
4687                 * Extract info from a JPEG file without using the GD library.
4688                 * @param string $file image file to parse
4689                 * @return array structure containing the image data
4690                 * @access protected
4691                 */
4692                 protected function _parsejpeg($file) {
4693                         $a = getimagesize($file);
4694                         if (empty($a)) {
4695                                 $this->Error('Missing or incorrect image file: '.$file);
4696                         }
4697                         if ($a[2] != 2) {
4698                                 $this->Error('Not a JPEG file: '.$file);
4699                         }
4700                         if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
4701                                 $colspace = 'DeviceRGB';
4702                         } elseif ($a['channels'] == 4) {
4703                                 $colspace = 'DeviceCMYK';
4704                         } else {
4705                                 $colspace = 'DeviceGray';
4706                         }
4707                         $bpc = isset($a['bits']) ? $a['bits'] : 8;
4708                         $data = file_get_contents($file);
4709                         return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
4710                 }
4711
4712                 /**
4713                 * Extract info from a PNG file without using the GD library.
4714                 * @param string $file image file to parse
4715                 * @return array structure containing the image data
4716                 * @access protected
4717                 */
4718                 protected function _parsepng($file) {
4719                         $f = fopen($file, 'rb');
4720                         if ($f === false) {
4721                                 $this->Error('Can\'t open image file: '.$file);
4722                         }
4723                         //Check signature
4724                         if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
4725                                 $this->Error('Not a PNG file: '.$file);
4726                         }
4727                         //Read header chunk
4728                         fread($f, 4);
4729                         if (fread($f, 4) != 'IHDR') {
4730                                 $this->Error('Incorrect PNG file: '.$file);
4731                         }
4732                         $w = $this->_freadint($f);
4733                         $h = $this->_freadint($f);
4734                         $bpc = ord(fread($f, 1));
4735                         if ($bpc > 8) {
4736                                 //$this->Error('16-bit depth not supported: '.$file);
4737                                 fclose($f);
4738                                 return false;
4739                         }
4740                         $ct = ord(fread($f, 1));
4741                         if ($ct == 0) {
4742                                 $colspace = 'DeviceGray';
4743                         } elseif ($ct == 2) {
4744                                 $colspace = 'DeviceRGB';
4745                         } elseif ($ct == 3) {
4746                                 $colspace = 'Indexed';
4747                         } else {
4748                                 // alpha channel
4749                                 fclose($f);
4750                                 return 'pngalpha';
4751                         }
4752                         if (ord(fread($f, 1)) != 0) {
4753                                 //$this->Error('Unknown compression method: '.$file);
4754                                 fclose($f);
4755                                 return false;
4756                         }
4757                         if (ord(fread($f, 1)) != 0) {
4758                                 //$this->Error('Unknown filter method: '.$file);
4759                                 fclose($f);
4760                                 return false;
4761                         }
4762                         if (ord(fread($f, 1)) != 0) {
4763                                 //$this->Error('Interlacing not supported: '.$file);
4764                                 fclose($f);
4765                                 return false;
4766                         }
4767                         fread($f, 4);
4768                         $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
4769                         //Scan chunks looking for palette, transparency and image data
4770                         $pal = '';
4771                         $trns = '';
4772                         $data = '';
4773                         do {
4774                                 $n = $this->_freadint($f);
4775                                 $type = fread($f, 4);
4776                                 if ($type == 'PLTE') {
4777                                         //Read palette
4778                                         $pal = $this->rfread($f, $n);
4779                                         fread($f, 4);
4780                                 } elseif ($type == 'tRNS') {
4781                                         //Read transparency info
4782                                         $t = $this->rfread($f, $n);
4783                                         if ($ct == 0) {
4784                                                 $trns = array(ord(substr($t, 1, 1)));
4785                                         } elseif ($ct == 2) {
4786                                                 $trns = array(ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1)));
4787                                         } else {
4788                                                 $pos = strpos($t, chr(0));
4789                                                 if ($pos !== false) {
4790                                                         $trns = array($pos);
4791                                                 }
4792                                         }
4793                                         fread($f, 4);
4794                                 } elseif ($type == 'IDAT') {
4795                                         //Read image data block
4796                                         $data .= $this->rfread($f, $n);
4797                                         fread($f, 4);
4798                                 } elseif ($type == 'IEND') {
4799                                         break;
4800                                 } else {
4801                                         $this->rfread($f, $n + 4);
4802                                 }
4803                         } while ($n);
4804                         if (($colspace == 'Indexed') AND (empty($pal))) {
4805                                 //$this->Error('Missing palette in '.$file);
4806                                 fclose($f);
4807                                 return false;
4808                         }
4809                         fclose($f);
4810                         return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
4811                 }
4812
4813                 /**
4814                 * Binary-safe and URL-safe file read.
4815                 * Reads up to length  bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met: length bytes have been read; EOF (end of file) is reached.
4816                 * @param resource $handle
4817                 * @param int $length
4818                 * @return Returns the read string or FALSE in case of error.
4819                 * @author Nicola Asuni
4820                 * @access protected
4821                 * @since 4.5.027 (2009-03-16)
4822                 */
4823                 protected function rfread($handle, $length) {
4824                         $data = fread($handle, $length);
4825                         if ($data === false) {
4826                                 return false;
4827                         }
4828                         $rest = $length - strlen($data);
4829                         if ($rest > 0) {
4830                                 $data .= $this->rfread($handle, $rest);
4831                         }
4832                         return $data;
4833                 }
4834
4835                 /**
4836                 * Extract info from a PNG image with alpha channel using the GD library.
4837                 * @param string $file Name of the file containing the image.
4838                 * @param float $x Abscissa of the upper-left corner.
4839                 * @param float $y Ordinate of the upper-left corner.
4840                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
4841                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
4842                 * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
4843                 * @param mixed $link URL or identifier returned by AddLink().
4844                 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
4845                 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
4846                 * @param int $dpi dot-per-inch resolution used on resize
4847                 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
4848                 * @author Valentin Schmidt, Nicola Asuni
4849                 * @access protected
4850                 * @since 4.3.007 (2008-12-04)
4851                 * @see Image()
4852                 */
4853                 protected function ImagePngAlpha($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
4854                         // get image size
4855                         list($wpx, $hpx) = getimagesize($file);
4856                         // generate images
4857                         $img = imagecreatefrompng($file);
4858                         $imgalpha = imagecreate($wpx, $hpx);
4859                         // generate gray scale pallete
4860                         for ($c = 0; $c < 256; ++$c) {
4861                                 ImageColorAllocate($imgalpha, $c, $c, $c);
4862                         }
4863                         // extract alpha channel
4864                         for ($xpx = 0; $xpx < $wpx; ++$xpx) {
4865                                 for ($ypx = 0; $ypx < $hpx; ++$ypx) {
4866                                         $colorindex = imagecolorat($img, $xpx, $ypx);
4867                                         $col = imagecolorsforindex($img, $colorindex);
4868                                         imagesetpixel($imgalpha, $xpx, $ypx, $this->getGDgamma((127 - $col['alpha']) * 255 / 127));
4869                                 }
4870                         }
4871                         // create temp alpha file
4872                         $tempfile_alpha = tempnam(K_PATH_CACHE, 'mska_');
4873                         imagepng($imgalpha, $tempfile_alpha);
4874                         imagedestroy($imgalpha);
4875                         // extract image without alpha channel
4876                         $imgplain = imagecreatetruecolor($wpx, $hpx);
4877                         imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
4878                         // create temp image file
4879                         $tempfile_plain = tempnam(K_PATH_CACHE, 'mskp_');
4880                         imagepng($imgplain, $tempfile_plain);
4881                         imagedestroy($imgplain);
4882                         // embed mask image
4883                         $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
4884                         // embed image, masked with previously embedded mask
4885                         $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
4886                         // remove temp files
4887                         unlink($tempfile_alpha);
4888                         unlink($tempfile_plain);
4889                 }
4890
4891                 /**
4892                 * Correct the gamma value to be used with GD library
4893                 * @param float $v the gamma value to be corrected
4894                 * @access protected
4895                 * @since 4.3.007 (2008-12-04)
4896                 */
4897                 protected function getGDgamma($v) {
4898                         return (pow(($v / 255), 2.2) * 255);
4899                 }
4900
4901                 /**
4902                 * Performs a line break.
4903                 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
4904                 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
4905                 * @param boolean $cell if true add a cMargin to the x coordinate
4906                 * @access public
4907                 * @since 1.0
4908                 * @see Cell()
4909                 */
4910                 public function Ln($h='', $cell=false) {
4911                         //Line feed; default value is last cell height
4912                         if ($cell) {
4913                                 $cellmargin = $this->cMargin;
4914                         } else {
4915                                 $cellmargin = 0;
4916                         }
4917                         if ($this->rtl) {
4918                                 $this->x = $this->w - $this->rMargin - $cellmargin;
4919                         } else {
4920                                 $this->x = $this->lMargin + $cellmargin;
4921                         }
4922                         if (is_string($h)) {
4923                                 $this->y += $this->lasth;
4924                         } else {
4925                                 $this->y += $h;
4926                         }
4927                         $this->newline = true;
4928                 }
4929
4930                 /**
4931                 * Returns the relative X value of current position.
4932                 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
4933                 * @return float
4934                 * @access public
4935                 * @since 1.2
4936                 * @see SetX(), GetY(), SetY()
4937                 */
4938                 public function GetX() {
4939                         //Get x position
4940                         if ($this->rtl) {
4941                                 return ($this->w - $this->x);
4942                         } else {
4943                                 return $this->x;
4944                         }
4945                 }
4946
4947                 /**
4948                 * Returns the absolute X value of current position.
4949                 * @return float
4950                 * @access public
4951                 * @since 1.2
4952                 * @see SetX(), GetY(), SetY()
4953                 */
4954                 public function GetAbsX() {
4955                         return $this->x;
4956                 }
4957
4958                 /**
4959                 * Returns the ordinate of the current position.
4960                 * @return float
4961                 * @access public
4962                 * @since 1.0
4963                 * @see SetY(), GetX(), SetX()
4964                 */
4965                 public function GetY() {
4966                         //Get y position
4967                         return $this->y;
4968                 }
4969
4970                 /**
4971                 * Defines the abscissa of the current position.
4972                 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
4973                 * @param float $x The value of the abscissa.
4974                 * @access public
4975                 * @since 1.2
4976                 * @see GetX(), GetY(), SetY(), SetXY()
4977                 */
4978                 public function SetX($x) {
4979                         //Set x position
4980                         if ($this->rtl) {
4981                                 if ($x >= 0) {
4982                                         $this->x = $this->w - $x;
4983                                 } else {
4984                                         $this->x = abs($x);
4985                                 }
4986                         } else {
4987                                 if ($x >= 0) {
4988                                         $this->x = $x;
4989                                 } else {
4990                                         $this->x = $this->w + $x;
4991                                 }
4992                         }
4993                         if ($this->x < 0) {
4994                                 $this->x = 0;
4995                         }
4996                         if ($this->x > $this->w) {
4997                                 $this->x = $this->w;
4998                         }
4999                 }
5000
5001                 /**
5002                 * Moves the current abscissa back to the left margin and sets the ordinate.
5003                 * If the passed value is negative, it is relative to the bottom of the page.
5004                 * @param float $y The value of the ordinate.
5005                 * @param bool $resetx if true (default) reset the X position.
5006                 * @access public
5007                 * @since 1.0
5008                 * @see GetX(), GetY(), SetY(), SetXY()
5009                 */
5010                 public function SetY($y, $resetx=true) {
5011                         if ($resetx) {
5012                                 //reset x
5013                                 if ($this->rtl) {
5014                                         $this->x = $this->w - $this->rMargin;
5015                                 } else {
5016                                         $this->x = $this->lMargin;
5017                                 }
5018                         }
5019                         if ($y >= 0) {
5020                                 $this->y = $y;
5021                         } else {
5022                                 $this->y = $this->h + $y;
5023                         }
5024                         if ($this->y < 0) {
5025                                 $this->y = 0;
5026                         }
5027                         if ($this->y > $this->h) {
5028                                 $this->y = $this->h;
5029                         }
5030                 }
5031
5032                 /**
5033                 * Defines the abscissa and ordinate of the current position.
5034                 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
5035                 * @param float $x The value of the abscissa
5036                 * @param float $y The value of the ordinate
5037                 * @access public
5038                 * @since 1.2
5039                 * @see SetX(), SetY()
5040                 */
5041                 public function SetXY($x, $y) {
5042                         //Set x and y positions
5043                         $this->SetY($y);
5044                         $this->SetX($x);
5045                 }
5046
5047                 /**
5048                 * Send the document to a given destination: string, local file or browser.
5049                 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
5050                 * The method first calls Close() if necessary to terminate the document.
5051                 * @param string $name The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
5052                 * @param string $dest Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local file with the name given by name.</li><li>S: return the document as a string. name is ignored.</li></ul>
5053                 * @access public
5054                 * @since 1.0
5055                 * @see Close()
5056                 */
5057                 public function Output($name='doc.pdf', $dest='I') {
5058                         //Output PDF to some destination
5059                         //Finish document if necessary
5060                         if ($this->state < 3) {
5061                                 $this->Close();
5062                         }
5063                         //Normalize parameters
5064                         if (is_bool($dest)) {
5065                                 $dest = $dest ? 'D' : 'F';
5066                         }
5067                         $dest = strtoupper($dest);
5068                         if ($dest != 'F') {
5069                                 $name = preg_replace('/[\s]+/', '_', $name);
5070                                 $name = preg_replace('/[^a-zA-Z0-9\._-\x{4e00}-\x{9fa5}]/u', '', $name);
5071                         }
5072                         if ($this->sign) {
5073                                 // *** apply digital signature to the document ***
5074                                 // get the document content
5075                                 $pdfdoc = $this->getBuffer();
5076                                 // remove last newline
5077                                 $pdfdoc = substr($pdfdoc, 0, -1);
5078                                 // Remove the original buffer
5079                                 if (isset($this->diskcache) AND $this->diskcache) {
5080                                         // remove buffer file from cache
5081                                         unlink($this->buffer);
5082                                 }
5083                                 unset($this->buffer);
5084                                 // remove filler space
5085                                 $tmppos = strpos($pdfdoc, '/ByteRange[0 ********** ********** **********]') + 58;
5086                                 $pdfdoc = substr($pdfdoc, 0, $tmppos).substr($pdfdoc, $tmppos + $this->signature_max_lenght);
5087                                 // define the ByteRange
5088                                 $byte_range = array();
5089                                 $byte_range[0] = 0;
5090                                 $byte_range[1] = $tmppos - 1;
5091                                 $byte_range[2] = $byte_range[1] + $this->signature_max_lenght;
5092                                 $byte_range[3] = strlen($pdfdoc) - $byte_range[1];
5093                                 // replace the ByteRange
5094                                 $byterange = sprintf('/ByteRange[0 %010u %010u %010u]', $byte_range[1], $byte_range[2], $byte_range[3]);
5095                                 $pdfdoc = str_replace('/ByteRange[0 ********** ********** **********]', $byterange, $pdfdoc);
5096                                 // write the document to a temporary folder
5097                                 $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_');
5098                                 $f = fopen($tempdoc, 'wb');
5099                                 if (!$f) {
5100                                         $this->Error('Unable to create temporary file: '.$tempdoc);
5101                                 }
5102                                 $pdfdoc_lenght = strlen($pdfdoc);
5103                                 fwrite($f, $pdfdoc, $pdfdoc_lenght);
5104                                 fclose($f);
5105                                 // get digital signature.
5106                                 // IS THE FOLLOWING PROCEDURE CORRECT? THE SIGNED DOCUMENTS ARE NOT VALID!
5107                                 $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_');
5108                                 if (empty($this->signature_data['extracerts'])) {
5109                                         openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
5110                                 } else {
5111                                         openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED, $this->signature_data['extracerts']);
5112                                 }
5113                                 unlink($tempdoc);
5114                                 // read signature
5115                                 $signature = file_get_contents($tempsign, false, null, $pdfdoc_lenght);
5116                                 unlink($tempsign);
5117                                 // extract signature
5118                                 $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
5119                                 $tmparr = explode("\n\n", $signature);
5120                                 $signature = $tmparr[1];
5121                                 unset($tmparr);
5122                                 // decode signature
5123                                 $signature = base64_decode(trim($signature));
5124                                 // convert signature to hex
5125                                 $signature = current(unpack('H*', $signature));
5126                                 $signature = str_pad($signature, $this->signature_max_lenght, '0');
5127                                 // Add signature to the document
5128                                 $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).$signature.substr($pdfdoc, (0 - $byte_range[3]));
5129                                 $this->diskcache = false;
5130                                 $this->buffer = &$pdfdoc;
5131                                 $this->bufferlen = strlen($pdfdoc);
5132                         }
5133                         switch($dest) {
5134                                 case 'I': {
5135                                         // Send PDF to the standard output
5136                                         if (ob_get_contents()) {
5137                                                 $this->Error('Some data has already been output, can\'t send PDF file');
5138                                         }
5139                                         if (php_sapi_name() != 'cli') {
5140                                                 //We send to a browser
5141                                                 header('Content-Type: application/pdf');
5142                                                 if (headers_sent()) {
5143                                                         $this->Error('Some data has already been output to browser, can\'t send PDF file');
5144                                                 }
5145                                                 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
5146                                                 header('Pragma: public');
5147                                                 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
5148                                                 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
5149                                                 header('Content-Length: '.$this->bufferlen);
5150                                                 header('Content-Disposition: inline; filename="'.basename($name).'";');
5151                                         }
5152                                         echo $this->getBuffer();
5153                                         break;
5154                                 }
5155                                 case 'D': {
5156                                         // Download PDF as file
5157                                         if (ob_get_contents()) {
5158                                                 $this->Error('Some data has already been output, can\'t send PDF file');
5159                                         }
5160                                         header('Content-Description: File Transfer');
5161                                         if (headers_sent()) {
5162                                                 $this->Error('Some data has already been output to browser, can\'t send PDF file');
5163                                         }
5164                                         header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
5165                                         header('Pragma: public');
5166                                         header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
5167                                         header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
5168                                         // force download dialog
5169                                         header('Content-Type: application/force-download');
5170                                         header('Content-Type: application/octet-stream', false);
5171                                         header('Content-Type: application/download', false);
5172                                         header('Content-Type: application/pdf', false);
5173                                         // use the Content-Disposition header to supply a recommended filename
5174                                         header('Content-Disposition: attachment; filename="'.basename($name).'";');
5175                                         header('Content-Transfer-Encoding: binary');
5176                                         header('Content-Length: '.$this->bufferlen);
5177                                         echo $this->getBuffer();
5178                                         break;
5179                                 }
5180                                 case 'F': {
5181                                         // Save PDF to a local file
5182                                         if ($this->diskcache) {
5183                                                 copy($this->buffer, $name);
5184                                         } else {
5185                                                 $f = fopen($name, 'wb');
5186                                                 if (!$f) {
5187                                                         $this->Error('Unable to create output file: '.$name);
5188                                                 }
5189                                                 fwrite($f, $this->getBuffer(), $this->bufferlen);
5190                                                 fclose($f);
5191                                         }
5192                                         break;
5193                                 }
5194                                 case 'S': {
5195                                         // Returns PDF as a string
5196                                         return $this->getBuffer();
5197                                 }
5198                                 default: {
5199                                         $this->Error('Incorrect output destination: '.$dest);
5200                                 }
5201                         }
5202                         return '';
5203                 }
5204
5205                 /**
5206                  * Unset all class variables except the following critical variables: internal_encoding, state, bufferlen, buffer and diskcache.
5207                  * @param boolean $destroyall if true destroys all class variables, otherwise preserves critical variables.
5208                  * @param boolean $preserve_objcopy if true preserves the objcopy variable
5209                  * @access public
5210                  * @since 4.5.016 (2009-02-24)
5211                  */
5212                 public function _destroy($destroyall=false, $preserve_objcopy=false) {
5213                         if ($destroyall AND isset($this->diskcache) AND $this->diskcache AND (!$preserve_objcopy) AND (!$this->empty_string($this->buffer))) {
5214                                 // remove buffer file from cache
5215                                 unlink($this->buffer);
5216                         }
5217                         foreach (array_keys(get_object_vars($this)) as $val) {
5218                                 if ($destroyall OR (
5219                                         ($val != 'internal_encoding')
5220                                         AND ($val != 'state')
5221                                         AND ($val != 'bufferlen')
5222                                         AND ($val != 'buffer')
5223                                         AND ($val != 'diskcache')
5224                                         AND ($val != 'sign')
5225                                         AND ($val != 'signature_data')
5226                                         AND ($val != 'signature_max_lenght')
5227                                         )) {
5228                                         if (!$preserve_objcopy OR ($val != 'objcopy')) {
5229                                                 unset($this->$val);
5230                                         }
5231                                 }
5232                         }
5233                 }
5234
5235                 /**
5236                 * Check for locale-related bug
5237                 * @access protected
5238                 */
5239                 protected function _dochecks() {
5240                         //Check for locale-related bug
5241                         if (1.1 == 1) {
5242                                 $this->Error('Don\'t alter the locale before including class file');
5243                         }
5244                         //Check for decimal separator
5245                         if (sprintf('%.1F', 1.0) != '1.0') {
5246                                 setlocale(LC_NUMERIC, 'C');
5247                         }
5248                 }
5249
5250                 /**
5251                 * Return fonts path
5252                 * @return string
5253                 * @access protected
5254                 */
5255                 protected function _getfontpath() {
5256                         if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
5257                                 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
5258                         }
5259                         return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
5260                 }
5261
5262                 /**
5263                 * Output pages.
5264                 * @access protected
5265                 */
5266                 protected function _putpages() {
5267                         $nb = $this->numpages;
5268                         if (!empty($this->AliasNbPages)) {
5269                                 $nbs = $this->formatPageNumber($nb);
5270                                 $nbu = $this->UTF8ToUTF16BE($nbs, false); // replacement for unicode font
5271                                 $alias_a = $this->_escape($this->AliasNbPages);
5272                                 $alias_au = $this->_escape('{'.$this->AliasNbPages.'}');
5273                                 if ($this->isunicode) {
5274                                         $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
5275                                         $alias_bu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNbPages.'}'));
5276                                         $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
5277                                         $alias_cu = $this->_escape($this->utf8StrRev('{'.$this->AliasNbPages.'}', false, $this->tmprtl));
5278                                 }
5279                         }
5280                         if (!empty($this->AliasNumPage)) {
5281                                 $alias_pa = $this->_escape($this->AliasNumPage);
5282                                 $alias_pau = $this->_escape('{'.$this->AliasNumPage.'}');
5283                                 if ($this->isunicode) {
5284                                         $alias_pb = $this->_escape($this->UTF8ToLatin1($this->AliasNumPage));
5285                                         $alias_pbu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNumPage.'}'));
5286                                         $alias_pc = $this->_escape($this->utf8StrRev($this->AliasNumPage, false, $this->tmprtl));
5287                                         $alias_pcu = $this->_escape($this->utf8StrRev('{'.$this->AliasNumPage.'}', false, $this->tmprtl));
5288                                 }
5289                         }
5290                         $pagegroupnum = 0;
5291                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
5292                         for ($n=1; $n <= $nb; ++$n) {
5293                                 $temppage = $this->getPageBuffer($n);
5294                                 if (!empty($this->pagegroups)) {
5295                                         if(isset($this->newpagegroup[$n])) {
5296                                                 $pagegroupnum = 0;
5297                                         }
5298                                         ++$pagegroupnum;
5299                                         foreach ($this->pagegroups as $k => $v) {
5300                                                 // replace total pages group numbers
5301                                                 $vs = $this->formatPageNumber($v);
5302                                                 $vu = $this->UTF8ToUTF16BE($vs, false);
5303                                                 $alias_ga = $this->_escape($k);
5304                                                 $alias_gau = $this->_escape('{'.$k.'}');
5305                                                 if ($this->isunicode) {
5306                                                         $alias_gb = $this->_escape($this->UTF8ToLatin1($k));
5307                                                         $alias_gbu = $this->_escape($this->UTF8ToLatin1('{'.$k.'}'));
5308                                                         $alias_gc = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
5309                                                         $alias_gcu = $this->_escape($this->utf8StrRev('{'.$k.'}', false, $this->tmprtl));
5310                                                 }
5311                                                 $temppage = str_replace($alias_gau, $vu, $temppage);
5312                                                 if ($this->isunicode) {
5313                                                         $temppage = str_replace($alias_gbu, $vu, $temppage);
5314                                                         $temppage = str_replace($alias_gcu, $vu, $temppage);
5315                                                         $temppage = str_replace($alias_gb, $vs, $temppage);
5316                                                         $temppage = str_replace($alias_gc, $vs, $temppage);
5317                                                 }
5318                                                 $temppage = str_replace($alias_ga, $vs, $temppage);
5319                                                 // replace page group numbers
5320                                                 $pvs = $this->formatPageNumber($pagegroupnum);
5321                                                 $pvu = $this->UTF8ToUTF16BE($pvs, false);
5322                                                 $pk = str_replace('{nb', '{pnb', $k);
5323                                                 $alias_pga = $this->_escape($pk);
5324                                                 $alias_pgau = $this->_escape('{'.$pk.'}');
5325                                                 if ($this->isunicode) {
5326                                                         $alias_pgb = $this->_escape($this->UTF8ToLatin1($pk));
5327                                                         $alias_pgbu = $this->_escape($this->UTF8ToLatin1('{'.$pk.'}'));
5328                                                         $alias_pgc = $this->_escape($this->utf8StrRev($pk, false, $this->tmprtl));
5329                                                         $alias_pgcu = $this->_escape($this->utf8StrRev('{'.$pk.'}', false, $this->tmprtl));
5330                                                 }
5331                                                 $temppage = str_replace($alias_pgau, $pvu, $temppage);
5332                                                 if ($this->isunicode) {
5333                                                         $temppage = str_replace($alias_pgbu, $pvu, $temppage);
5334                                                         $temppage = str_replace($alias_pgcu, $pvu, $temppage);
5335                                                         $temppage = str_replace($alias_pgb, $pvs, $temppage);
5336                                                         $temppage = str_replace($alias_pgc, $pvs, $temppage);
5337                                                 }
5338                                                 $temppage = str_replace($alias_pga, $pvs, $temppage);
5339                                         }
5340                                 }
5341                                 if (!empty($this->AliasNbPages)) {
5342                                         // replace total pages number
5343                                         $temppage = str_replace($alias_au, $nbu, $temppage);
5344                                         if ($this->isunicode) {
5345                                                 $temppage = str_replace($alias_bu, $nbu, $temppage);
5346                                                 $temppage = str_replace($alias_cu, $nbu, $temppage);
5347                                                 $temppage = str_replace($alias_b, $nbs, $temppage);
5348                                                 $temppage = str_replace($alias_c, $nbs, $temppage);
5349                                         }
5350                                         $temppage = str_replace($alias_a, $nbs, $temppage);
5351                                 }
5352                                 if (!empty($this->AliasNumPage)) {
5353                                         // replace page number
5354                                         $pnbs = $this->formatPageNumber($n);
5355                                         $pnbu = $this->UTF8ToUTF16BE($pnbs, false); // replacement for unicode font
5356                                         $temppage = str_replace($alias_pau, $pnbu, $temppage);
5357                                         if ($this->isunicode) {
5358                                                 $temppage = str_replace($alias_pbu, $pnbu, $temppage);
5359                                                 $temppage = str_replace($alias_pcu, $pnbu, $temppage);
5360                                                 $temppage = str_replace($alias_pb, $pnbs, $temppage);
5361                                                 $temppage = str_replace($alias_pc, $pnbs, $temppage);
5362                                         }
5363                                         $temppage = str_replace($alias_pa, $pnbs, $temppage);
5364                                 }
5365                                 $temppage = str_replace($this->epsmarker, '', $temppage);
5366                                 //$this->setPageBuffer($n, $temppage);
5367                                 //Page
5368                                 $this->_newobj();
5369                                 $this->_out('<</Type /Page');
5370                                 $this->_out('/Parent 1 0 R');
5371                                 $this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
5372                                 $this->_out('/Resources 2 0 R');
5373                                 $this->_putannots($n);
5374                                 $this->_out('/Contents '.($this->n + 1).' 0 R>>');
5375                                 $this->_out('endobj');
5376                                 //Page content
5377                                 $p = ($this->compress) ? gzcompress($temppage) : $temppage;
5378                                 $this->_newobj();
5379                                 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
5380                                 $this->_putstream($p);
5381                                 $this->_out('endobj');
5382                                 if ($this->diskcache) {
5383                                         // remove temporary files
5384                                         unlink($this->pages[$n]);
5385                                 }
5386                         }
5387                         //Pages root
5388                         $this->offsets[1] = $this->bufferlen;
5389                         $this->_out('1 0 obj');
5390                         $this->_out('<</Type /Pages');
5391                         $kids='/Kids [';
5392                         for ($i=0; $i < $nb; ++$i) {
5393                                 $kids .= (3 + (2 * $i)).' 0 R ';
5394                         }
5395                         $this->_out($kids.']');
5396                         $this->_out('/Count '.$nb);
5397                         //$this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
5398                         $this->_out('>>');
5399                         $this->_out('endobj');
5400                 }
5401
5402                 /**
5403                 * Output Page Annotations.
5404                 * !!! THIS FUNCTION IS NOT YET COMPLETED !!!
5405                 * See section 8.4 of PDF reference.
5406                 * @param int $n page number
5407                 * @access protected
5408                 * @author Nicola Asuni
5409                 * @since 4.0.018 (2008-08-06)
5410                 */
5411                 protected function _putannots($n) {
5412                         if (isset($this->PageAnnots[$n])) {
5413                                 $annots = '/Annots [';
5414                                 foreach ($this->PageAnnots[$n] as $key => $pl) {
5415                                         $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
5416                                         $a = $pl['x'] * $this->k;
5417                                         $b = $this->pagedim[$n]['h'] - ($pl['y']  * $this->k);
5418                                         $c = $pl['w'] * $this->k;
5419                                         $d = $pl['h'] * $this->k;
5420                                         $rect = sprintf('%.2F %.2F %.2F %.2F', $a, $b, $a+$c, $b-$d);
5421                                         $annots .= "\n";
5422                                         $annots .= '<</Type /Annot';
5423                                         $annots .= ' /Subtype /'.$pl['opt']['subtype'];
5424                                         $annots .= ' /Rect ['.$rect.']';
5425                                         $annots .= ' /Contents '.$this->_textstring($pl['txt']);
5426                                         //$annots .= ' /P ';
5427                                         $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
5428                                         $annots .= ' /M '.$this->_datastring('D:'.date('YmdHis'));
5429                                         if (isset($pl['opt']['f'])) {
5430                                                 $val = 0;
5431                                                 if (is_array($pl['opt']['f'])) {
5432                                                         foreach ($pl['opt']['f'] as $f) {
5433                                                                 switch (strtolower($f)) {
5434                                                                         case 'invisible': {
5435                                                                                 $val += 1 << 0;
5436                                                                                 break;
5437                                                                         }
5438                                                                         case 'hidden': {
5439                                                                                 $val += 1 << 1;
5440                                                                                 break;
5441                                                                         }
5442                                                                         case 'print': {
5443                                                                                 $val += 1 << 2;
5444                                                                                 break;
5445                                                                         }
5446                                                                         case 'nozoom': {
5447                                                                                 $val += 1 << 3;
5448                                                                                 break;
5449                                                                         }
5450                                                                         case 'norotate': {
5451                                                                                 $val += 1 << 4;
5452                                                                                 break;
5453                                                                         }
5454                                                                         case 'noview': {
5455                                                                                 $val += 1 << 5;
5456                                                                                 break;
5457                                                                         }
5458                                                                         case 'readonly': {
5459                                                                                 $val += 1 << 6;
5460                                                                                 break;
5461                                                                         }
5462                                                                         case 'locked': {
5463                                                                                 $val += 1 << 8;
5464                                                                                 break;
5465                                                                         }
5466                                                                         case 'togglenoview': {
5467                                                                                 $val += 1 << 9;
5468                                                                                 break;
5469                                                                         }
5470                                                                         case 'lockedcontents': {
5471                                                                                 $val += 1 << 10;
5472                                                                                 break;
5473                                                                         }
5474                                                                         default: {
5475                                                                                 break;
5476                                                                         }
5477                                                                 }
5478                                                         }
5479                                                 }
5480                                                 $annots .= ' /F '.intval($val);
5481                                         }
5482                                         //$annots .= ' /AP ';
5483                                         //$annots .= ' /AS ';
5484                                         $annots .= ' /Border [';
5485                                         if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
5486                                                 $annots .= intval($pl['opt']['border'][0]).' ';
5487                                                 $annots .= intval($pl['opt']['border'][1]).' ';
5488                                                 $annots .= intval($pl['opt']['border'][2]);
5489                                                 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
5490                                                         $annots .= ' [';
5491                                                         foreach ($pl['opt']['border'][3] as $dash) {
5492                                                                 $annots .= intval($dash).' ';
5493                                                         }
5494                                                         $annots .= ']';
5495                                                 }
5496                                         } else {
5497                                                 $annots .= '0 0 0';
5498                                         }
5499                                         $annots .= ']';
5500                                         if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
5501                                                 $annots .= ' /BS <<Type /Border';
5502                                                 if (isset($pl['opt']['bs']['w'])) {
5503                                                         $annots .= ' /W '.sprintf("%.4F", floatval($pl['opt']['bs']['w']));
5504                                                 }
5505                                                 $bstyles = array('S', 'D', 'B', 'I', 'U');
5506                                                 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
5507                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
5508                                                 }
5509                                                 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
5510                                                         $annots .= ' /D [';
5511                                                         foreach ($pl['opt']['bs']['d'] as $cord) {
5512                                                                 $cord = floatval($cord);
5513                                                                 $annots .= sprintf(" %.4F", $cord);
5514                                                         }
5515                                                         $annots .= ']';
5516                                                 }
5517                                                 $annots .= '>> ';
5518                                         }
5519                                         if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
5520                                                 $annots .= ' /BE <<';
5521                                                 $bstyles = array('S', 'C');
5522                                                 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
5523                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
5524                                                 } else {
5525                                                         $annots .= ' /S /S';
5526                                                 }
5527                                                 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
5528                                                         $annots .= ' /I '.sprintf(" %.4F", $pl['opt']['be']['i']);
5529                                                 }
5530                                                 $annots .= '>>';
5531                                         }
5532                                         $annots .= ' /C [';
5533                                         if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
5534                                                 foreach ($pl['opt']['c'] as $col) {
5535                                                         $col = intval($col);
5536                                                         $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
5537                                                         $annots .= sprintf(" %.4F", $color);
5538                                                 }
5539                                         }
5540                                         $annots .= ']';
5541                                         //$annots .= ' /StructParent ';
5542                                         //$annots .= ' /OC ';
5543                                         $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight',  'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
5544                                         if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
5545                                                 // this is a markup type
5546                                                 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
5547                                                         $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
5548                                                 }
5549                                                 //$annots .= ' /Popup ';
5550                                                 if (isset($pl['opt']['ca'])) {
5551                                                         $annots .= ' /CA '.sprintf("%.4F", floatval($pl['opt']['ca']));
5552                                                 }
5553                                                 if (isset($pl['opt']['rc'])) {
5554                                                         $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
5555                                                 }
5556                                                 $annots .= ' /CreationDate '.$this->_datastring('D:'.date('YmdHis'));
5557                                                 //$annots .= ' /IRT ';
5558                                                 if (isset($pl['opt']['subj'])) {
5559                                                         $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
5560                                                 }
5561                                                 //$annots .= ' /RT ';
5562                                                 //$annots .= ' /IT ';
5563                                                 //$annots .= ' /ExData ';
5564                                         }
5565                                         switch (strtolower($pl['opt']['subtype'])) {
5566                                                 case 'text': {
5567                                                         if (isset($pl['opt']['open'])) {
5568                                                                 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
5569                                                         }
5570                                                         $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
5571                                                         if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5572                                                                 $annots .= ' /Name /'.$pl['opt']['name'];
5573                                                         } else {
5574                                                                 $annots .= ' /Name /Note';
5575                                                         }
5576                                                         $statemodels = array('Marked', 'Review');
5577                                                         if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
5578                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
5579                                                         } else {
5580                                                                 $pl['opt']['statemodel'] = 'Marked';
5581                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
5582                                                         }
5583                                                         if ($pl['opt']['statemodel'] == 'Marked') {
5584                                                                 $states = array('Accepted', 'Unmarked');
5585                                                         } else {
5586                                                                 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
5587                                                         }
5588                                                         if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
5589                                                                 $annots .= ' /State /'.$pl['opt']['state'];
5590                                                         } else {
5591                                                                 if ($pl['opt']['statemodel'] == 'Marked') {
5592                                                                         $annots .= ' /State /Unmarked';
5593                                                                 } else {
5594                                                                         $annots .= ' /State /None';
5595                                                                 }
5596                                                         }
5597                                                         break;
5598                                                 }
5599                                                 case 'link': {
5600                                                         if(is_string($pl['txt'])) {
5601                                                                 // external URI link
5602                                                                 $annots .= ' /A <</S /URI /URI '.$this->_datastring($pl['txt']).'>>';
5603                                                         } else {
5604                                                                 // internal link
5605                                                                 $l = $this->links[$pl['txt']];
5606                                                                 $annots .= sprintf(' /Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $l[0])), ($this->pagedim[$l[0]]['h'] - ($l[1] * $this->k)));
5607                                                         }
5608                                                         $hmodes = array('N', 'I', 'O', 'P');
5609                                                         if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
5610                                                                 $annots .= ' /H /'.$pl['opt']['h'];
5611                                                         } else {
5612                                                                 $annots .= ' /H /I';
5613                                                         }
5614                                                         //$annots .= ' /PA ';
5615                                                         //$annots .= ' /Quadpoints ';
5616                                                         break;
5617                                                 }
5618                                                 case 'freetext': {
5619                                                         $annots .= ' /DA '.$this->_textstring($pl['txt']);
5620                                                         if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
5621                                                                 $annots .= ' /Q '.intval($pl['opt']['q']);
5622                                                         }
5623                                                         if (isset($pl['opt']['rc'])) {
5624                                                                 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
5625                                                         }
5626                                                         if (isset($pl['opt']['ds'])) {
5627                                                                 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
5628                                                         }
5629                                                         if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
5630                                                                 $annots .= ' /CL [';
5631                                                                 foreach ($pl['opt']['cl'] as $cl) {
5632                                                                         $annots .= sprintf("%.4F ", $cl * $this->k);
5633                                                                 }
5634                                                                 $annots .= ']';
5635                                                         }
5636                                                         $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
5637                                                         if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
5638                                                                 $annots .= ' /IT '.$pl['opt']['it'];
5639                                                         }
5640                                                         if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
5641                                                                 $l = $pl['opt']['rd'][0] * $this->k;
5642                                                                 $r = $pl['opt']['rd'][1] * $this->k;
5643                                                                 $t = $pl['opt']['rd'][2] * $this->k;
5644                                                                 $b = $pl['opt']['rd'][3] * $this->k;
5645                                                                 $annots .= ' /RD ['.sprintf('%.2F %.2F %.2F %.2F', $l, $r, $t, $b).']';
5646                                                         }
5647                                                         //$annots .= ' /LE ';
5648                                                         break;
5649                                                 }
5650                                                 // ... to be completed ...
5651                                                 case 'line': {
5652                                                         break;
5653                                                 }
5654                                                 case 'square': {
5655                                                         break;
5656                                                 }
5657                                                 case 'circle': {
5658                                                         break;
5659                                                 }
5660                                                 case 'polygon': {
5661                                                         break;
5662                                                 }
5663                                                 case 'polyline': {
5664                                                         break;
5665                                                 }
5666                                                 case 'highlight': {
5667                                                         break;
5668                                                 }
5669                                                 case 'underline': {
5670                                                         break;
5671                                                 }
5672                                                 case 'squiggly': {
5673                                                         break;
5674                                                 }
5675                                                 case 'strikeout': {
5676                                                         break;
5677                                                 }
5678                                                 case 'stamp': {
5679                                                         break;
5680                                                 }
5681                                                 case 'caret': {
5682                                                         break;
5683                                                 }
5684                                                 case 'ink': {
5685                                                         break;
5686                                                 }
5687                                                 case 'popup': {
5688                                                         break;
5689                                                 }
5690                                                 case 'fileattachment': {
5691                                                         if (!isset($pl['opt']['fs'])) {
5692                                                                 break;
5693                                                         }
5694                                                         $filename = basename($pl['opt']['fs']);
5695                                                         if (isset($this->embeddedfiles[$filename]['n'])) {
5696                                                                 $annots .= ' /FS <</Type /Filespec /F '.$this->_datastring($filename).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
5697                                                                 $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
5698                                                                 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5699                                                                         $annots .= ' /Name /'.$pl['opt']['name'];
5700                                                                 } else {
5701                                                                         $annots .= ' /Name /PushPin';
5702                                                                 }
5703                                                         }
5704                                                         break;
5705                                                 }
5706                                                 case 'sound': {
5707                                                         if (!isset($pl['opt']['sound'])) {
5708                                                                 break;
5709                                                         }
5710                                                         $filename = basename($pl['opt']['sound']);
5711                                                         if (isset($this->embeddedfiles[$filename]['n'])) {
5712                                                                 // ... TO BE COMPLETED ...
5713                                                                 $iconsapp = array('Speaker', 'Mic');
5714                                                                 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5715                                                                         $annots .= ' /Name /'.$pl['opt']['name'];
5716                                                                 } else {
5717                                                                         $annots .= ' /Name /Speaker';
5718                                                                 }
5719                                                         }
5720                                                         break;
5721                                                 }
5722                                                 case 'movie': {
5723                                                         break;
5724                                                 }
5725                                                 case 'widget': {
5726                                                         if (isset($pl['opt']['h'])) {
5727                                                                 $annots .= ' /H '.intval($pl['opt']['h']);
5728                                                         }
5729                                                         if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk']))) {
5730                                                                 $annots .= ' /MK <<';
5731                                                                 // ... TO BE COMPLETED ...
5732                                                                 $annots .= '>>';
5733                                                         }
5734                                                         break;
5735                                                 }
5736                                                 case 'screen': {
5737                                                         break;
5738                                                 }
5739                                                 case 'printermark': {
5740                                                         break;
5741                                                 }
5742                                                 case 'trapnet': {
5743                                                         break;
5744                                                 }
5745                                                 case 'watermark': {
5746                                                         break;
5747                                                 }
5748                                                 case '3d': {
5749                                                         break;
5750                                                 }
5751                                                 default: {
5752                                                         break;
5753                                                 }
5754                                         }
5755
5756                                 $annots .= '>>';
5757                                 }
5758                                 $annots .= "\n]";
5759                                 $this->_out($annots);
5760                         }
5761                 }
5762
5763                 /**
5764                 * Output fonts.
5765                 * @access protected
5766                 */
5767                 protected function _putfonts() {
5768                         $nf = $this->n;
5769                         foreach ($this->diffs as $diff) {
5770                                 //Encodings
5771                                 $this->_newobj();
5772                                 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
5773                                 $this->_out('endobj');
5774                         }
5775                         $mqr = get_magic_quotes_runtime();
5776                         //set_magic_quotes_runtime(0);
5777                         foreach ($this->FontFiles as $file => $info) {
5778                                 // search and get font file to embedd
5779                                 $fontdir = $info['fontdir'];
5780                                 $file = strtolower($file);
5781                                 $fontfile = '';
5782                                 // search files on various directories
5783                                 if (file_exists($fontdir.$file)) {
5784                                         $fontfile = $fontdir.$file;
5785                                 } elseif (file_exists($this->_getfontpath().$file)) {
5786                                         $fontfile = $this->_getfontpath().$file;
5787                                 } elseif (file_exists($file)) {
5788                                         $fontfile = $file;
5789                                 }
5790                                 if (!$this->empty_string($fontfile)) {
5791                                         $font = file_get_contents($fontfile);
5792                                         $compressed = (substr($file, -2) == '.z');
5793                                         if ((!$compressed) AND (isset($info['length2']))) {
5794                                                 $header = (ord($font{0}) == 128);
5795                                                 if ($header) {
5796                                                         //Strip first binary header
5797                                                         $font = substr($font, 6);
5798                                                 }
5799                                                 if ($header AND (ord($font{$info['length1']}) == 128)) {
5800                                                         //Strip second binary header
5801                                                         $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
5802                                                 }
5803                                         }
5804                                         $this->_newobj();
5805                                         $this->FontFiles[$file]['n'] = $this->n;
5806                                         $this->_out('<</Length '.strlen($font));
5807                                         if ($compressed) {
5808                                                 $this->_out('/Filter /FlateDecode');
5809                                         }
5810                                         $this->_out('/Length1 '.$info['length1']);
5811                                         if (isset($info['length2'])) {
5812                                                 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
5813                                         }
5814                                         $this->_out('>>');
5815                                         $this->_putstream($font);
5816                                         $this->_out('endobj');
5817                                 }
5818                         }
5819                         //set_magic_quotes_runtime($mqr);
5820                         foreach ($this->fontkeys as $k) {
5821                                 //Font objects
5822                                 $this->setFontSubBuffer($k, 'n', $this->n + 1);
5823                                 $font = $this->getFontBuffer($k);
5824                                 $type = $font['type'];
5825                                 $name = $font['name'];
5826                                 if ($type == 'core') {
5827                                         //Standard font
5828                                         $this->_newobj();
5829                                         $this->_out('<</Type /Font');
5830                                         $this->_out('/BaseFont /'.$name);
5831                                         $this->_out('/Subtype /Type1');
5832                                         if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
5833                                                 $this->_out('/Encoding /WinAnsiEncoding');
5834                                         }
5835                                         $this->_out('>>');
5836                                         $this->_out('endobj');
5837                                 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
5838                                         //Additional Type1 or TrueType font
5839                                         $this->_newobj();
5840                                         $this->_out('<</Type /Font');
5841                                         $this->_out('/BaseFont /'.$name);
5842                                         $this->_out('/Subtype /'.$type);
5843                                         $this->_out('/FirstChar 32 /LastChar 255');
5844                                         $this->_out('/Widths '.($this->n + 1).' 0 R');
5845                                         $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
5846                                         if ($font['enc']) {
5847                                                 if (isset($font['diff'])) {
5848                                                         $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
5849                                                 } else {
5850                                                         $this->_out('/Encoding /WinAnsiEncoding');
5851                                                 }
5852                                         }
5853                                         $this->_out('>>');
5854                                         $this->_out('endobj');
5855                                         // Widths
5856                                         $this->_newobj();
5857                                         $cw = &$font['cw'];
5858                                         $s = '[';
5859                                         for ($i = 32; $i < 256; ++$i) {
5860                                                 $s .= $cw[$i].' ';
5861                                         }
5862                                         $this->_out($s.']');
5863                                         $this->_out('endobj');
5864                                         //Descriptor
5865                                         $this->_newobj();
5866                                         $s = '<</Type /FontDescriptor /FontName /'.$name;
5867                                         foreach ($font['desc'] as $k => $v) {
5868                                                 $s .= ' /'.$k.' '.$v.'';
5869                                         }
5870                                         if (!$this->empty_string($font['file'])) {
5871                                                 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
5872                                         }
5873                                         $this->_out($s.'>>');
5874                                         $this->_out('endobj');
5875                                 } else {
5876                                         //Allow for additional types
5877                                         $mtd = '_put'.strtolower($type);
5878                                         if (!method_exists($this, $mtd)) {
5879                                                 $this->Error('Unsupported font type: '.$type);
5880                                         }
5881                                         $this->$mtd($font);
5882                                 }
5883                         }
5884                 }
5885
5886                 /**
5887                 * Outputs font widths
5888                 * @parameter array $font font data
5889                 * @parameter int $cidoffset offset for CID values
5890                 * @author Nicola Asuni
5891                 * @access protected
5892                 * @since 4.4.000 (2008-12-07)
5893                 */
5894                 protected function _putfontwidths($font, $cidoffset=0) {
5895                         ksort($font['cw']);
5896                         $rangeid = 0;
5897                         $range = array();
5898                         $prevcid = -2;
5899                         $prevwidth = -1;
5900                         $interval = false;
5901                         // for each character
5902                         foreach ($font['cw'] as $cid => $width) {
5903                                 $cid -= $cidoffset;
5904                                 if ($width != $font['dw']) {
5905                                         if ($cid == ($prevcid + 1)) {
5906                                                 // consecutive CID
5907                                                 if ($width == $prevwidth) {
5908                                                         if ($width == $range[$rangeid][0]) {
5909                                                                 $range[$rangeid][] = $width;
5910                                                         } else {
5911                                                                 array_pop($range[$rangeid]);
5912                                                                 // new range
5913                                                                 $rangeid = $prevcid;
5914                                                                 $range[$rangeid] = array();
5915                                                                 $range[$rangeid][] = $prevwidth;
5916                                                                 $range[$rangeid][] = $width;
5917                                                         }
5918                                                         $interval = true;
5919                                                         $range[$rangeid]['interval'] = true;
5920                                                 } else {
5921                                                         if ($interval) {
5922                                                                 // new range
5923                                                                 $rangeid = $cid;
5924                                                                 $range[$rangeid] = array();
5925                                                                 $range[$rangeid][] = $width;
5926                                                         } else {
5927                                                                 $range[$rangeid][] = $width;
5928                                                         }
5929                                                         $interval = false;
5930                                                 }
5931                                         } else {
5932                                                 // new range
5933                                                 $rangeid = $cid;
5934                                                 $range[$rangeid] = array();
5935                                                 $range[$rangeid][] = $width;
5936                                                 $interval = false;
5937                                         }
5938                                         $prevcid = $cid;
5939                                         $prevwidth = $width;
5940                                 }
5941                         }
5942                         // optimize ranges
5943                         $prevk = -1;
5944                         $nextk = -1;
5945                         $prevint = false;
5946                         foreach ($range as $k => $ws) {
5947                                 $cws = count($ws);
5948                                 if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) {
5949                                         if (isset($range[$k]['interval'])) {
5950                                                 unset($range[$k]['interval']);
5951                                         }
5952                                         $range[$prevk] = array_merge($range[$prevk], $range[$k]);
5953                                         unset($range[$k]);
5954                                 } else {
5955                                         $prevk = $k;
5956                                 }
5957                                 $nextk = $k + $cws;
5958                                 if (isset($ws['interval'])) {
5959                                         if ($cws > 3) {
5960                                                 $prevint = true;
5961                                         } else {
5962                                                 $prevint = false;
5963                                         }
5964                                         unset($range[$k]['interval']);
5965                                         --$nextk;
5966                                 } else {
5967                                         $prevint = false;
5968                                 }
5969                         }
5970                         // output data
5971                         $w = '';
5972                         foreach ($range as $k => $ws) {
5973                                 if (count(array_count_values($ws)) == 1) {
5974                                         // interval mode is more compact
5975                                         $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0];
5976                                 } else {
5977                                         // range mode
5978                                         $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
5979                                 }
5980                         }
5981                         $this->_out('/W ['.$w.' ]');
5982                 }
5983
5984                 /**
5985                 * Adds unicode fonts.<br>
5986                 * Based on PDF Reference 1.3 (section 5)
5987                 * @parameter array $font font data
5988                 * @access protected
5989                 * @author Nicola Asuni
5990                 * @since 1.52.0.TC005 (2005-01-05)
5991                 */
5992                 protected function _puttruetypeunicode($font) {
5993                         // Type0 Font
5994                         // A composite font composed of other fonts, organized hierarchically
5995                         $this->_newobj();
5996                         $this->_out('<</Type /Font');
5997                         $this->_out('/Subtype /Type0');
5998                         $this->_out('/BaseFont /'.$font['name'].'');
5999                         $this->_out('/Encoding /Identity-H'); //The horizontal identity mapping for 2-byte CIDs; may be used with CIDFonts using any Registry, Ordering, and Supplement values.
6000                         $this->_out('/ToUnicode /Identity-H');
6001                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
6002                         $this->_out('>>');
6003                         $this->_out('endobj');
6004                         // CIDFontType2
6005                         // A CIDFont whose glyph descriptions are based on TrueType font technology
6006                         $this->_newobj();
6007                         $this->_out('<</Type /Font');
6008                         $this->_out('/Subtype /CIDFontType2');
6009                         $this->_out('/BaseFont /'.$font['name'].'');
6010                         // A dictionary containing entries that define the character collection of the CIDFont.
6011                         $cidinfo = '/Registry '.$this->_datastring('Adobe');
6012                         $cidinfo .= ' /Ordering '.$this->_datastring('Identity');
6013                         $cidinfo .= ' /Supplement 0';
6014                         $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
6015                         $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
6016                         $this->_out('/DW '.$font['dw'].''); // default width
6017                         $this->_putfontwidths($font, 0);
6018                         $this->_out('/CIDToGIDMap '.($this->n + 2).' 0 R');
6019                         $this->_out('>>');
6020                         $this->_out('endobj');
6021                         // Font descriptor
6022                         // A font descriptor describing the CIDFont default metrics other than its glyph widths
6023                         $this->_newobj();
6024                         $this->_out('<</Type /FontDescriptor');
6025                         $this->_out('/FontName /'.$font['name']);
6026                         foreach ($font['desc'] as $key => $value) {
6027                                 $this->_out('/'.$key.' '.$value);
6028                         }
6029                         $fontdir = '';
6030                         if (!$this->empty_string($font['file'])) {
6031                                 // A stream containing a TrueType font
6032                                 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
6033                                 $fontdir = $this->FontFiles[$font['file']]['fontdir'];
6034                         }
6035                         $this->_out('>>');
6036                         $this->_out('endobj');
6037                         $this->_newobj();
6038                         if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
6039                                 // Embed CIDToGIDMap
6040                                 // A specification of the mapping from CIDs to glyph indices
6041                                 // search and get CTG font file to embedd
6042                                 $ctgfile = strtolower($font['ctg']);
6043                                 // search and get ctg font file to embedd
6044                                 $fontfile = '';
6045                                 // search files on various directories
6046                                 if (file_exists($fontdir.$ctgfile)) {
6047                                         $fontfile = $fontdir.$ctgfile;
6048                                 } elseif (file_exists($this->_getfontpath().$ctgfile)) {
6049                                         $fontfile = $this->_getfontpath().$ctgfile;
6050                                 } elseif (file_exists($ctgfile)) {
6051                                         $fontfile = $ctgfile;
6052                                 }
6053                                 if ($this->empty_string($fontfile)) {
6054                                         $this->Error('Font file not found: '.$ctgfile);
6055                                 }
6056                                 $size = filesize($fontfile);
6057                                 $this->_out('<</Length '.$size.'');
6058                                 if (substr($fontfile, -2) == '.z') { // check file extension
6059                                         // Decompresses data encoded using the public-domain
6060                                         // zlib/deflate compression method, reproducing the
6061                                         // original text or binary data
6062                                         $this->_out('/Filter /FlateDecode');
6063                                 }
6064                                 $this->_out('>>');
6065                                 $this->_putstream(file_get_contents($fontfile));
6066                         }
6067                         $this->_out('endobj');
6068                 }
6069
6070                 /**
6071                  * Output CID-0 fonts.
6072                  * @param array $font font data
6073                  * @access protected
6074                  * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
6075                  * @since 3.2.000 (2008-06-23)
6076                  */
6077                 protected function _putcidfont0($font) {
6078                         $cidoffset = 31;
6079                         if (isset($font['cidinfo']['uni2cid'])) {
6080                                 // convert unicode to cid.
6081                                 $uni2cid = $font['cidinfo']['uni2cid'];
6082                                 $cw = array();
6083                                 foreach ($font['cw'] as $uni => $width) {
6084                                         if (isset($uni2cid[$uni])) {
6085                                                 $cw[($uni2cid[$uni] + $cidoffset)] = $width;
6086                                         } elseif ($uni < 256) {
6087                                                 $cw[$uni] = $width;
6088                                         } // else unknown character
6089                                 }
6090                                 $font = array_merge($font, array('cw' => $cw));
6091                         }
6092                         $name = $font['name'];
6093                         $enc = $font['enc'];
6094                         if ($enc) {
6095                                 $longname = $name.'-'.$enc;
6096                         } else {
6097                                 $longname = $name;
6098                         }
6099                         $this->_newobj();
6100                         $this->_out('<</Type /Font');
6101                         $this->_out('/BaseFont /'.$longname);
6102                         $this->_out('/Subtype /Type0');
6103                         if ($enc) {
6104                                 $this->_out('/Encoding /'.$enc);
6105                         }
6106                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
6107                         $this->_out('>>');
6108                         $this->_out('endobj');
6109                         $this->_newobj();
6110                         $this->_out('<</Type /Font');
6111                         $this->_out('/BaseFont /'.$name);
6112                         $this->_out('/Subtype /CIDFontType0');
6113                         $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry']);
6114                         $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering']);
6115                         $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
6116                         $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
6117                         $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
6118                         $this->_out('/DW '.$font['dw']);
6119                         $this->_putfontwidths($font, $cidoffset);
6120                         $this->_out('>>');
6121                         $this->_out('endobj');
6122                         $this->_newobj();
6123                         $s = '<</Type /FontDescriptor /FontName /'.$name;
6124                         foreach ($font['desc'] as $k => $v) {
6125                                 if ($k != 'Style') {
6126                                         $s .= ' /'.$k.' '.$v.'';
6127                                 }
6128                         }
6129                         $this->_out($s.'>>');
6130                         $this->_out('endobj');
6131                 }
6132
6133                 /**
6134                  * Output images.
6135                  * @access protected
6136                  */
6137                 protected function _putimages() {
6138                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
6139                         foreach ($this->imagekeys as $file) {
6140                                 $info = $this->getImageBuffer($file);
6141                                 $this->_newobj();
6142                                 $this->setImageSubBuffer($file, 'n', $this->n);
6143                                 $this->_out('<</Type /XObject');
6144                                 $this->_out('/Subtype /Image');
6145                                 $this->_out('/Width '.$info['w']);
6146                                 $this->_out('/Height '.$info['h']);
6147                                 if (isset($info['masked'])) {
6148                                         $this->_out('/SMask '.($this->n - 1).' 0 R');
6149                                 }
6150                                 if ($info['cs'] == 'Indexed') {
6151                                         $this->_out('/ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]');
6152                                 } else {
6153                                         $this->_out('/ColorSpace /'.$info['cs']);
6154                                         if ($info['cs'] == 'DeviceCMYK') {
6155                                                 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
6156                                         }
6157                                 }
6158                                 $this->_out('/BitsPerComponent '.$info['bpc']);
6159                                 if (isset($info['f'])) {
6160                                         $this->_out('/Filter /'.$info['f']);
6161                                 }
6162                                 if (isset($info['parms'])) {
6163                                         $this->_out($info['parms']);
6164                                 }
6165                                 if (isset($info['trns']) AND is_array($info['trns'])) {
6166                                         $trns='';
6167                                         $count_info = count($info['trns']);
6168                                         for ($i=0; $i < $count_info; ++$i) {
6169                                                 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
6170                                         }
6171                                         $this->_out('/Mask ['.$trns.']');
6172                                 }
6173                                 $this->_out('/Length '.strlen($info['data']).'>>');
6174                                 $this->_putstream($info['data']);
6175                                 $this->_out('endobj');
6176                                 //Palette
6177                                 if ($info['cs'] == 'Indexed') {
6178                                         $this->_newobj();
6179                                         $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
6180                                         $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
6181                                         $this->_putstream($pal);
6182                                         $this->_out('endobj');
6183                                 }
6184                         }
6185                 }
6186
6187                 /**
6188                 * Output Spot Colors Resources.
6189                 * @access protected
6190                 * @since 4.0.024 (2008-09-12)
6191                 */
6192                 protected function _putspotcolors() {
6193                         foreach ($this->spot_colors as $name => $color) {
6194                                 $this->_newobj();
6195                                 $this->spot_colors[$name]['n'] = $this->n;
6196                                 $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
6197                                 $this->_out('/DeviceCMYK <<');
6198                                 $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
6199                                 $this->_out(sprintf('/C1 [%.4F %.4F %.4F %.4F] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
6200                                 $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
6201                                 $this->_out('endobj');
6202                         }
6203                 }
6204
6205                 /**
6206                 * Output object dictionary for images.
6207                 * @access protected
6208                 */
6209                 protected function _putxobjectdict() {
6210                         foreach ($this->imagekeys as $file) {
6211                                 $info = $this->getImageBuffer($file);
6212                                 $this->_out('/I'.$info['i'].' '.$info['n'].' 0 R');
6213                         }
6214                 }
6215
6216                 /**
6217                 * Output Resources Dictionary.
6218                 * @access protected
6219                 */
6220                 protected function _putresourcedict() {
6221                         $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
6222                         $this->_out('/Font <<');
6223                         foreach ($this->fontkeys as $fontkey) {
6224                                 $font = $this->getFontBuffer($fontkey);
6225                                 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
6226                         }
6227                         $this->_out('>>');
6228                         $this->_out('/XObject <<');
6229                         $this->_putxobjectdict();
6230                         $this->_out('>>');
6231                         // visibility
6232                         $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
6233                         // transparency
6234                         $this->_out('/ExtGState <<');
6235                         foreach ($this->extgstates as $k => $extgstate) {
6236                                 $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
6237                         }
6238                         $this->_out('>>');
6239                         // gradients
6240                         if (isset($this->gradients) AND (count($this->gradients) > 0)) {
6241                                 $this->_out('/Shading <<');
6242                                 foreach ($this->gradients as $id => $grad) {
6243                                         $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
6244                                 }
6245                                 $this->_out('>>');
6246                         }
6247                         // spot colors
6248                         if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
6249                                 $this->_out('/ColorSpace <<');
6250                                 foreach ($this->spot_colors as $color) {
6251                                         $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
6252                                 }
6253                                 $this->_out('>>');
6254                         }
6255                 }
6256
6257                 /**
6258                 * Output Resources.
6259                 * @access protected
6260                 */
6261                 protected function _putresources() {
6262                         $this->_putextgstates();
6263                         $this->_putocg();
6264                         $this->_putfonts();
6265                         $this->_putimages();
6266                         $this->_putspotcolors();
6267                         $this->_putshaders();
6268                         //Resource dictionary
6269                         $this->offsets[2] = $this->bufferlen;
6270                         $this->_out('2 0 obj');
6271                         $this->_out('<<');
6272                         $this->_putresourcedict();
6273                         $this->_out('>>');
6274                         $this->_out('endobj');
6275                         $this->_putjavascript();
6276                         $this->_putbookmarks();
6277                         $this->_putEmbeddedFiles();
6278                         // encryption
6279                         if ($this->encrypted) {
6280                                 $this->_newobj();
6281                                 $this->enc_obj_id = $this->n;
6282                                 $this->_out('<<');
6283                                 $this->_putencryption();
6284                                 $this->_out('>>');
6285                                 $this->_out('endobj');
6286                         }
6287                 }
6288
6289                 /**
6290                 * Adds some Metadata information
6291                 * (see Chapter 10.2 of PDF Reference)
6292                 * @access protected
6293                 */
6294                 protected function _putinfo() {
6295                         if (!$this->empty_string($this->title)) {
6296                                 $this->_out('/Title '.$this->_textstring($this->title));
6297                         }
6298                         if (!$this->empty_string($this->author)) {
6299                                 $this->_out('/Author '.$this->_textstring($this->author));
6300                         }
6301                         if (!$this->empty_string($this->subject)) {
6302                                 $this->_out('/Subject '.$this->_textstring($this->subject));
6303                         }
6304                         if (!$this->empty_string($this->keywords)) {
6305                                 $this->_out('/Keywords '.$this->_textstring($this->keywords));
6306                         }
6307                         if (!$this->empty_string($this->creator)) {
6308                                 $this->_out('/Creator '.$this->_textstring($this->creator));
6309                         }
6310                         if (defined('PDF_PRODUCER')) {
6311                                 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
6312                         }
6313                         $this->_out('/CreationDate '.$this->_datastring('D:'.date('YmdHis')));
6314                         $this->_out('/ModDate '.$this->_datastring('D:'.date('YmdHis')));
6315                 }
6316
6317                 /**
6318                 * Output Catalog.
6319                 * @access protected
6320                 */
6321                 protected function _putcatalog() {
6322                         $this->_out('/Type /Catalog');
6323                         $this->_out('/Pages 1 0 R');
6324                         if ($this->ZoomMode == 'fullpage') {
6325                                 $this->_out('/OpenAction [3 0 R /Fit]');
6326                         } elseif ($this->ZoomMode == 'fullwidth') {
6327                                 $this->_out('/OpenAction [3 0 R /FitH null]');
6328                         } elseif ($this->ZoomMode == 'real') {
6329                                 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
6330                         } elseif (!is_string($this->ZoomMode)) {
6331                                 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
6332                         }
6333                         if (isset($this->LayoutMode) AND (!$this->empty_string($this->LayoutMode))) {
6334                                 $this->_out('/PageLayout /'.$this->LayoutMode.'');
6335                         }
6336                         if (isset($this->PageMode) AND (!$this->empty_string($this->PageMode))) {
6337                                 $this->_out('/PageMode /'.$this->PageMode);
6338                         }
6339                         if (isset($this->l['a_meta_language'])) {
6340                                 $this->_out('/Lang /'.$this->l['a_meta_language']);
6341                         }
6342                         $this->_out('/Names <<');
6343                         if (!$this->empty_string($this->javascript)) {
6344                                 $this->_out('/JavaScript '.($this->n_js).' 0 R');
6345                         }
6346                         $this->_out('>>');
6347                         if (count($this->outlines) > 0) {
6348                                 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
6349                                 $this->_out('/PageMode /UseOutlines');
6350                         }
6351                         $this->_putviewerpreferences();
6352                         $p = $this->n_ocg_print.' 0 R';
6353                         $v = $this->n_ocg_view.' 0 R';
6354                         $as = '<</Event /Print /OCGs ['.$p.' '.$v.'] /Category [/Print]>> <</Event /View /OCGs ['.$p.' '.$v.'] /Category [/View]>>';
6355                         $this->_out('/OCProperties <</OCGs ['.$p.' '.$v.'] /D <</ON ['.$p.'] /OFF ['.$v.'] /AS ['.$as.']>>>>');
6356                 }
6357
6358                 /**
6359                 * Output viewer preferences.
6360                 * @author Nicola asuni
6361                 * @since 3.1.000 (2008-06-09)
6362                 * @access protected
6363                 */
6364                 protected function _putviewerpreferences() {
6365                         $this->_out('/ViewerPreferences<<');
6366                         if ($this->rtl) {
6367                                 $this->_out('/Direction /R2L');
6368                         } else {
6369                                 $this->_out('/Direction /L2R');
6370                         }
6371                         if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
6372                                 $this->_out('/HideToolbar true');
6373                         }
6374                         if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
6375                                 $this->_out('/HideMenubar true');
6376                         }
6377                         if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
6378                                 $this->_out('/HideWindowUI true');
6379                         }
6380                         if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
6381                                 $this->_out('/FitWindow true');
6382                         }
6383                         if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
6384                                 $this->_out('/CenterWindow true');
6385                         }
6386                         if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
6387                                 $this->_out('/DisplayDocTitle true');
6388                         }
6389                         if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
6390                                 $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
6391                         }
6392                         if (isset($this->viewer_preferences['ViewArea'])) {
6393                                 $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
6394                         }
6395                         if (isset($this->viewer_preferences['ViewClip'])) {
6396                                 $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
6397                         }
6398                         if (isset($this->viewer_preferences['PrintArea'])) {
6399                                 $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
6400                         }
6401                         if (isset($this->viewer_preferences['PrintClip'])) {
6402                                 $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
6403                         }
6404                         if (isset($this->viewer_preferences['PrintScaling'])) {
6405                                 $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
6406                         }
6407                         if (isset($this->viewer_preferences['Duplex']) AND (!$this->empty_string($this->viewer_preferences['Duplex']))) {
6408                                 $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
6409                         }
6410                         if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
6411                                 if ($this->viewer_preferences['PickTrayByPDFSize']) {
6412                                         $this->_out('/PickTrayByPDFSize true');
6413                                 } else {
6414                                         $this->_out('/PickTrayByPDFSize false');
6415                                 }
6416                         }
6417                         if (isset($this->viewer_preferences['PrintPageRange'])) {
6418                                 $PrintPageRangeNum = '';
6419                                 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
6420                                         $PrintPageRangeNum .= ' '.($v - 1).'';
6421                                 }
6422                                 $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
6423                         }
6424                         if (isset($this->viewer_preferences['NumCopies'])) {
6425                                 $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
6426                         }
6427                         $this->_out('>>');
6428                 }
6429
6430                 /**
6431                 * Output trailer.
6432                 * @access protected
6433                 */
6434                 protected function _puttrailer() {
6435                         $this->_out('/Size '.($this->n + 1));
6436                         $this->_out('/Root '.$this->n.' 0 R');
6437                         $this->_out('/Info '.($this->n - 1).' 0 R');
6438                         if ($this->encrypted) {
6439                                 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
6440                                 $this->_out('/ID [()()]');
6441                         }
6442                 }
6443
6444                 /**
6445                 * Output PDF header.
6446                 * @access protected
6447                 */
6448                 protected function _putheader() {
6449                         $this->_out('%PDF-'.$this->PDFVersion);
6450                 }
6451
6452                 /**
6453                 * Output end of document (EOF).
6454                 * @access protected
6455                 */
6456                 protected function _enddoc() {
6457                         $this->state = 1;
6458                         $this->_putheader();
6459                         $this->_putpages();
6460                         $this->_putresources();
6461                         //Info
6462                         $this->_newobj();
6463                         $this->_out('<<');
6464                         $this->_putinfo();
6465                         $this->_out('>>');
6466                         $this->_out('endobj');
6467                         //Catalog
6468                         $this->_newobj();
6469                         $this->_out('<<');
6470                         $this->_putcatalog();
6471                         $this->_putcertification();
6472                         $this->_putuserrights();
6473                         $this->_out('>>');
6474                         $this->_out('endobj');
6475                         //Cross-ref
6476                         $o = $this->bufferlen;
6477                         $this->_out('xref');
6478                         $this->_out('0 '.($this->n + 1));
6479                         $this->_out('0000000000 65535 f ');
6480                         for ($i=1; $i <= $this->n; ++$i) {
6481                                 $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
6482                         }
6483                         if (isset($this->embeddedfiles) AND count($this->embeddedfiles) > 0) {
6484                                 $this->_out('100000 '.count($this->embeddedfiles));
6485                                 foreach ($this->embeddedfiles as $filename => $filedata) {
6486                                         $this->_out(sprintf('%010d 00000 n ', $this->offsets[$filedata['n']]));
6487                                 }
6488                         }
6489                         //Trailer
6490                         $this->_out('trailer');
6491                         $this->_out('<<');
6492                         $this->_puttrailer();
6493                         $this->_out('>>');
6494                         $this->_out('startxref');
6495                         $this->_out($o);
6496                         $this->_out('%%EOF');
6497                         $this->state = 3; // end-of-doc
6498                         if ($this->diskcache) {
6499                                 // remove temporary files used for images
6500                                 foreach ($this->imagekeys as $key) {
6501                                         // remove temporary files
6502                                         unlink($this->images[$key]);
6503                                 }
6504                                 foreach ($this->fontkeys as $key) {
6505                                         // remove temporary files
6506                                         unlink($this->fonts[$key]);
6507                                 }
6508                         }
6509                 }
6510
6511                 /**
6512                 * Initialize a new page.
6513                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
6514                 * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
6515                 * @access protected
6516                 */
6517                 protected function _beginpage($orientation='', $format='') {
6518                         ++$this->page;
6519                         $this->setPageBuffer($this->page, '');
6520                         // initialize array for graphics tranformation positions inside a page buffer
6521                         $this->transfmrk[$this->page] = array();
6522                         $this->state = 2;
6523                         if ($this->empty_string($orientation)) {
6524                                 if (isset($this->CurOrientation)) {
6525                                         $orientation = $this->CurOrientation;
6526                                 } else {
6527                                         $orientation = 'P';
6528                                 }
6529                         }
6530                         if ($this->empty_string($format)) {
6531                                 $this->setPageOrientation($orientation);
6532                         } else {
6533                                 $this->setPageFormat($format, $orientation);
6534                         }
6535                         if ($this->rtl) {
6536                                 $this->x = $this->w - $this->rMargin;
6537                         } else {
6538                                 $this->x = $this->lMargin;
6539                         }
6540                         $this->y = $this->tMargin;
6541                         if (isset($this->newpagegroup[$this->page])) {
6542                                 // start a new group
6543                                 $n = sizeof($this->pagegroups) + 1;
6544                                 $alias = '{nb'.$n.'}';
6545                                 $this->pagegroups[$alias] = 1;
6546                                 $this->currpagegroup = $alias;
6547                         } elseif ($this->currpagegroup) {
6548                                 ++$this->pagegroups[$this->currpagegroup];
6549                         }
6550                 }
6551
6552                 /**
6553                 * Mark end of page.
6554                 * @access protected
6555                 */
6556                 protected function _endpage() {
6557                         $this->setVisibility('all');
6558                         $this->state = 1;
6559                 }
6560
6561                 /**
6562                 * Begin a new object.
6563                 * @access protected
6564                 */
6565                 protected function _newobj() {
6566                         ++$this->n;
6567                         $this->offsets[$this->n] = $this->bufferlen;
6568                         $this->_out($this->n.' 0 obj');
6569                 }
6570
6571                 /**
6572                 * Underline text.
6573                 * @param int $x X coordinate
6574                 * @param int $y Y coordinate
6575                 * @param string $txt text to underline
6576                 * @access protected
6577                 */
6578                 protected function _dounderline($x, $y, $txt) {
6579                         $up = $this->CurrentFont['up'];
6580                         $ut = $this->CurrentFont['ut'];
6581                         $w = $this->GetStringWidth($txt);
6582                         return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ($this->h - ($y - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
6583                 }
6584
6585                 /**
6586                 * Line through text.
6587                 * @param int $x X coordinate
6588                 * @param int $y Y coordinate
6589                 * @param string $txt text to linethrough
6590                 * @access protected
6591                 */
6592                 protected function _dolinethrough($x, $y, $txt) {
6593                         $up = $this->CurrentFont['up'];
6594                         $ut = $this->CurrentFont['ut'];
6595                         $w = $this->GetStringWidth($txt);
6596                         return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ($this->h - ($y - ($this->FontSize/2) - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
6597                 }
6598
6599                 /**
6600                 * Read a 4-byte integer from file.
6601                 * @param string $f file name.
6602                 * @return 4-byte integer
6603                 * @access protected
6604                 */
6605                 protected function _freadint($f) {
6606                         $a = unpack('Ni', fread($f, 4));
6607                         return $a['i'];
6608                 }
6609
6610                 /**
6611                 * Add "\" before "\", "(" and ")"
6612                 * @param string $s string to escape.
6613                 * @return string escaped string.
6614                 * @access protected
6615                 */
6616                 protected function _escape($s) {
6617                         // the chr(13) substitution fixes the Bugs item #1421290.
6618                         return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
6619                 }
6620
6621                 /**
6622                 * Format a date string for meta information
6623                 * @param string $s date string to escape.
6624                 * @return string escaped string.
6625                 * @access protected
6626                 */
6627                 protected function _datastring($s) {
6628                         if ($this->encrypted) {
6629                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
6630                         }
6631                         return '('. $this->_escape($s).')';
6632                 }
6633
6634                 /**
6635                 * Format a text string for meta information
6636                 * @param string $s string to escape.
6637                 * @return string escaped string.
6638                 * @access protected
6639                 */
6640                 protected function _textstring($s) {
6641                         if ($this->isunicode) {
6642                                 //Convert string to UTF-16BE
6643                                 $s = $this->UTF8ToUTF16BE($s, true);
6644                         }
6645                         return $this->_datastring($s);
6646                 }
6647
6648                 /**
6649                 * Format a text string
6650                 * @param string $s string to escape.
6651                 * @return string escaped string.
6652                 * @access protected
6653                 */
6654                 protected function _escapetext($s) {
6655                         if ($this->isunicode) {
6656                                 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
6657                                         $s = $this->UTF8ToLatin1($s);
6658                                 } else {
6659                                         //Convert string to UTF-16BE and reverse RTL language
6660                                         $s = $this->utf8StrRev($s, false, $this->tmprtl);
6661                                 }
6662                         }
6663                         return $this->_escape($s);
6664                 }
6665
6666                 /**
6667                 * Output a stream.
6668                 * @param string $s string to output.
6669                 * @access protected
6670                 */
6671                 protected function _putstream($s) {
6672                         if ($this->encrypted) {
6673                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
6674                         }
6675                         $this->_out('stream');
6676                         $this->_out($s);
6677                         $this->_out('endstream');
6678                 }
6679
6680                 /**
6681                 * Output a string to the document.
6682                 * @param string $s string to output.
6683                 * @access protected
6684                 */
6685                 protected function _out($s) {
6686                         if ($this->state == 2) {
6687                                 if ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
6688                                         // puts data before page footer
6689                                         $pagebuff = $this->getPageBuffer($this->page);
6690                                         $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
6691                                         $footer = substr($pagebuff, -$this->footerlen[$this->page]);
6692                                         $this->setPageBuffer($this->page, $page.$s."\n".$footer);
6693                                         // update footer position
6694                                         $this->footerpos[$this->page] += strlen($s."\n");
6695                                 } else {
6696                                         $this->setPageBuffer($this->page, $s."\n", true);
6697                                 }
6698                         } else {
6699                                 $this->setBuffer($s."\n");
6700                         }
6701                 }
6702
6703                  /**
6704                  * Converts UTF-8 strings to codepoints array.<br>
6705                  * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
6706                  * Based on: http://www.faqs.org/rfcs/rfc3629.html
6707                  * <pre>
6708                  *        Char. number range  |        UTF-8 octet sequence
6709                  *       (hexadecimal)    |              (binary)
6710                  *    --------------------+-----------------------------------------------
6711                  *    0000 0000-0000 007F | 0xxxxxxx
6712                  *    0000 0080-0000 07FF | 110xxxxx 10xxxxxx
6713                  *    0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
6714                  *    0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
6715                  *    ---------------------------------------------------------------------
6716                  *
6717                  *   ABFN notation:
6718                  *   ---------------------------------------------------------------------
6719                  *   UTF8-octets = *( UTF8-char )
6720                  *   UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
6721                  *   UTF8-1      = %x00-7F
6722                  *   UTF8-2      = %xC2-DF UTF8-tail
6723                  *
6724                  *   UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
6725                  *                 %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
6726                  *   UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
6727                  *                 %xF4 %x80-8F 2( UTF8-tail )
6728                  *   UTF8-tail   = %x80-BF
6729                  *   ---------------------------------------------------------------------
6730                  * </pre>
6731                  * @param string $str string to process.
6732                  * @return array containing codepoints (UTF-8 characters values)
6733                  * @access protected
6734                  * @author Nicola Asuni
6735                  * @since 1.53.0.TC005 (2005-01-05)
6736                  */
6737                 protected function UTF8StringToArray($str) {
6738                         if (isset($this->cache_UTF8StringToArray['_'.$str])) {
6739                                 // return cached value
6740                                 return($this->cache_UTF8StringToArray['_'.$str]);
6741                         }
6742                         // check cache size
6743                         if ($this->cache_size_UTF8StringToArray >= $this->cache_maxsize_UTF8StringToArray) {
6744                                 // remove first element
6745                                 array_shift($this->cache_UTF8StringToArray);
6746                         }
6747                         ++$this->cache_size_UTF8StringToArray;
6748                         if (!$this->isunicode) {
6749                                 // split string into array of equivalent codes
6750                                 $strarr = array();
6751                                 $strlen = strlen($str);
6752                                 for ($i=0; $i < $strlen; ++$i) {
6753                                         $strarr[] = ord($str{$i});
6754                                 }
6755                                 // insert new value on cache
6756                                 $this->cache_UTF8StringToArray['_'.$str] = $strarr;
6757                                 return $strarr;
6758                         }
6759                         $unicode = array(); // array containing unicode values
6760                         $bytes  = array(); // array containing single character byte sequences
6761                         $numbytes  = 1; // number of octetc needed to represent the UTF-8 character
6762                         $str .= ''; // force $str to be a string
6763                         $length = strlen($str);
6764                         for ($i = 0; $i < $length; ++$i) {
6765                                 $char = ord($str{$i}); // get one string character at time
6766                                 if (count($bytes) == 0) { // get starting octect
6767                                         if ($char <= 0x7F) {
6768                                                 $unicode[] = $char; // use the character "as is" because is ASCII
6769                                                 $numbytes = 1;
6770                                         } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
6771                                                 $bytes[] = ($char - 0xC0) << 0x06;
6772                                                 $numbytes = 2;
6773                                         } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
6774                                                 $bytes[] = ($char - 0xE0) << 0x0C;
6775                                                 $numbytes = 3;
6776                                         } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
6777                                                 $bytes[] = ($char - 0xF0) << 0x12;
6778                                                 $numbytes = 4;
6779                                         } else {
6780                                                 // use replacement character for other invalid sequences
6781                                                 $unicode[] = 0xFFFD;
6782                                                 $bytes = array();
6783                                                 $numbytes = 1;
6784                                         }
6785                                 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
6786                                         $bytes[] = $char - 0x80;
6787                                         if (count($bytes) == $numbytes) {
6788                                                 // compose UTF-8 bytes to a single unicode value
6789                                                 $char = $bytes[0];
6790                                                 for ($j = 1; $j < $numbytes; ++$j) {
6791                                                         $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
6792                                                 }
6793                                                 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
6794                                                         /* The definition of UTF-8 prohibits encoding character numbers between
6795                                                         U+D800 and U+DFFF, which are reserved for use with the UTF-16
6796                                                         encoding form (as surrogate pairs) and do not directly represent
6797                                                         characters. */
6798                                                         $unicode[] = 0xFFFD; // use replacement character
6799                                                 } else {
6800                                                         $unicode[] = $char; // add char to array
6801                                                 }
6802                                                 // reset data for next char
6803                                                 $bytes = array();
6804                                                 $numbytes = 1;
6805                                         }
6806                                 } else {
6807                                         // use replacement character for other invalid sequences
6808                                         $unicode[] = 0xFFFD;
6809                                         $bytes = array();
6810                                         $numbytes = 1;
6811                                 }
6812                         }
6813                         // insert new value on cache
6814                         $this->cache_UTF8StringToArray['_'.$str] = $unicode;
6815                         return $unicode;
6816                 }
6817
6818                 /**
6819                  * Converts UTF-8 strings to UTF16-BE.<br>
6820                  * @param string $str string to process.
6821                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
6822                  * @return string
6823                  * @access protected
6824                  * @author Nicola Asuni
6825                  * @since 1.53.0.TC005 (2005-01-05)
6826                  * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
6827                  */
6828                 protected function UTF8ToUTF16BE($str, $setbom=true) {
6829                         if (!$this->isunicode) {
6830                                 return $str; // string is not in unicode
6831                         }
6832                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
6833                         return $this->arrUTF8ToUTF16BE($unicode, $setbom);
6834                 }
6835
6836                 /**
6837                  * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
6838                  * @param string $str string to process.
6839                  * @return string
6840                  * @author Andrew Whitehead, Nicola Asuni
6841                  * @access protected
6842                  * @since 3.2.000 (2008-06-23)
6843                  */
6844                 protected function UTF8ToLatin1($str) {
6845                         global $utf8tolatin;
6846                         if (!$this->isunicode) {
6847                                 return $str; // string is not in unicode
6848                         }
6849                         $outstr = ''; // string to be returned
6850                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
6851                         foreach ($unicode as $char) {
6852                                 if ($char < 256) {
6853                                         $outstr .= chr($char);
6854                                 } elseif (array_key_exists($char, $utf8tolatin)) {
6855                                         // map from UTF-8
6856                                         $outstr .= chr($utf8tolatin[$char]);
6857                                 } elseif ($char == 0xFFFD) {
6858                                         // skip
6859                                 } else {
6860                                         $outstr .= '?';
6861                                 }
6862                         }
6863                         return $outstr;
6864                 }
6865
6866                 /**
6867                  * Converts array of UTF-8 characters to UTF16-BE string.<br>
6868                  * Based on: http://www.faqs.org/rfcs/rfc2781.html
6869                  * <pre>
6870                  *   Encoding UTF-16:
6871                  *
6872                  *   Encoding of a single character from an ISO 10646 character value to
6873                  *    UTF-16 proceeds as follows. Let U be the character number, no greater
6874                  *    than 0x10FFFF.
6875                  *
6876                  *    1) If U < 0x10000, encode U as a 16-bit unsigned integer and
6877                  *       terminate.
6878                  *
6879                  *    2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
6880                  *       U' must be less than or equal to 0xFFFFF. That is, U' can be
6881                  *       represented in 20 bits.
6882                  *
6883                  *    3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
6884                  *       0xDC00, respectively. These integers each have 10 bits free to
6885                  *       encode the character value, for a total of 20 bits.
6886                  *
6887                  *    4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
6888                  *       bits of W1 and the 10 low-order bits of U' to the 10 low-order
6889                  *       bits of W2. Terminate.
6890                  *
6891                  *    Graphically, steps 2 through 4 look like:
6892                  *    U' = yyyyyyyyyyxxxxxxxxxx
6893                  *    W1 = 110110yyyyyyyyyy
6894                  *    W2 = 110111xxxxxxxxxx
6895                  * </pre>
6896                  * @param array $unicode array containing UTF-8 unicode values
6897                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
6898                  * @return string
6899                  * @access protected
6900                  * @author Nicola Asuni
6901                  * @since 2.1.000 (2008-01-08)
6902                  * @see UTF8ToUTF16BE()
6903                  */
6904                 protected function arrUTF8ToUTF16BE($unicode, $setbom=true) {
6905                         $outstr = ''; // string to be returned
6906                         if ($setbom) {
6907                                 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
6908                         }
6909                         foreach ($unicode as $char) {
6910                                 if ($char == 0xFFFD) {
6911                                         $outstr .= "\xFF\xFD"; // replacement character
6912                                 } elseif ($char < 0x10000) {
6913                                         $outstr .= chr($char >> 0x08);
6914                                         $outstr .= chr($char & 0xFF);
6915                                 } else {
6916                                         $char -= 0x10000;
6917                                         $w1 = 0xD800 | ($char >> 0x10);
6918                                         $w2 = 0xDC00 | ($char & 0x3FF);
6919                                         $outstr .= chr($w1 >> 0x08);
6920                                         $outstr .= chr($w1 & 0xFF);
6921                                         $outstr .= chr($w2 >> 0x08);
6922                                         $outstr .= chr($w2 & 0xFF);
6923                                 }
6924                         }
6925                         return $outstr;
6926                 }
6927                 // ====================================================
6928
6929                 /**
6930                  * Set header font.
6931                  * @param array $font font
6932                  * @access public
6933                  * @since 1.1
6934                  */
6935                 public function setHeaderFont($font) {
6936                         $this->header_font = $font;
6937                 }
6938
6939                 /**
6940                  * Get header font.
6941                  * @return array()
6942                  * @access public
6943                  * @since 4.0.012 (2008-07-24)
6944                  */
6945                 public function getHeaderFont() {
6946                         return $this->header_font;
6947                 }
6948
6949                 /**
6950                  * Set footer font.
6951                  * @param array $font font
6952                  * @access public
6953                  * @since 1.1
6954                  */
6955                 public function setFooterFont($font) {
6956                         $this->footer_font = $font;
6957                 }
6958
6959                 /**
6960                  * Get Footer font.
6961                  * @return array()
6962                  * @access public
6963                  * @since 4.0.012 (2008-07-24)
6964                  */
6965                 public function getFooterFont() {
6966                         return $this->footer_font;
6967                 }
6968
6969                 /**
6970                  * Set language array.
6971                  * @param array $language
6972                  * @access public
6973                  * @since 1.1
6974                  */
6975                 public function setLanguageArray($language) {
6976                         $this->l = $language;
6977                         $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
6978                 }
6979
6980                 /**
6981                  * Returns the PDF data.
6982                  * @access public
6983                  */
6984                 public function getPDFData() {
6985                         if ($this->state < 3) {
6986                                 $this->Close();
6987                         }
6988                         return $this->buffer;
6989                 }
6990
6991                 /**
6992                  * Output anchor link.
6993                  * @param string $url link URL or internal link (i.e.: &lt;a href="#23"&gt;link to page 23&lt;/a&gt;)
6994                  * @param string $name link name
6995                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
6996                  * @param boolean $firstline if true prints only the first line and return the remaining string.
6997                  * @param array $color array of RGB text color
6998                  * @param string $style font style (U, D, B, I)
6999                  * @return the number of cells used or the remaining text if $firstline = true;
7000                  * @access public
7001                  */
7002                 public function addHtmlLink($url, $name, $fill=0, $firstline=false, $color='', $style=-1) {
7003                         if (!$this->empty_string($url) AND ($url{0} == '#')) {
7004                                 // convert url to internal link
7005                                 $page = intval(substr($url, 1));
7006                                 $url = $this->AddLink();
7007                                 $this->SetLink($url, 0, $page);
7008                         }
7009                         // store current settings
7010                         $prevcolor = $this->fgcolor;
7011                         $prevstyle = $this->FontStyle;
7012                         if (empty($color)) {
7013                                 $this->SetTextColorArray($this->htmlLinkColorArray);
7014                         } else {
7015                                 $this->SetTextColorArray($color);
7016                         }
7017                         if ($style == -1) {
7018                                 $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
7019                         } else {
7020                                 $this->SetFont('', $this->FontStyle.$style);
7021                         }
7022                         $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
7023                         // restore settings
7024                         $this->SetFont('', $prevstyle);
7025                         $this->SetTextColorArray($prevcolor);
7026                         return $ret;
7027                 }
7028
7029                 /**
7030                  * Returns an associative array (keys: R,G,B) from an html color name or a six-digit or three-digit hexadecimal color representation (i.e. #3FE5AA or #7FF).
7031                  * @param string $color html color
7032                  * @return array RGB color or false in case of error.
7033                  * @access public
7034                  */
7035                 public function convertHTMLColorToDec($color='#FFFFFF') {
7036                         global $webcolor;
7037                         $returncolor = false;
7038                         $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
7039                         $color = strtolower($color);
7040                         if (strlen($color) == 0) {
7041                                 return false;
7042                         }
7043                         if (substr($color, 0, 3) == 'rgb') {
7044                                 $codes = substr($color, 4);
7045                                 $codes = str_replace(')', '', $codes);
7046                                 $returncolor = explode(',', $codes, 3);
7047                                 return $returncolor;
7048                         }
7049                         if (substr($color, 0, 1) != '#') {
7050                                 // decode color name
7051                                 if (isset($webcolor[$color])) {
7052                                         $color_code = $webcolor[$color];
7053                                 } else {
7054                                         return false;
7055                                 }
7056                         } else {
7057                                 $color_code = substr($color, 1);
7058                         }
7059                         switch (strlen($color_code)) {
7060                                 case 3: {
7061                                         // three-digit hexadecimal representation
7062                                         $r = substr($color_code, 0, 1);
7063                                         $g = substr($color_code, 1, 1);
7064                                         $b = substr($color_code, 2, 1);
7065                                         $returncolor['R'] = hexdec($r.$r);
7066                                         $returncolor['G'] = hexdec($g.$g);
7067                                         $returncolor['B'] = hexdec($b.$b);
7068                                         break;
7069                                 }
7070                                 case 6: {
7071                                         // six-digit hexadecimal representation
7072                                         $returncolor['R'] = hexdec(substr($color_code, 0, 2));
7073                                         $returncolor['G'] = hexdec(substr($color_code, 2, 2));
7074                                         $returncolor['B'] = hexdec(substr($color_code, 4, 2));
7075                                         break;
7076                                 }
7077                         }
7078                         return $returncolor;
7079                 }
7080
7081                 /**
7082                  * Converts pixels to User's Units.
7083                  * @param int $px pixels
7084                  * @return float value in user's unit
7085                  * @access public
7086                  * @see setImageScale(), getImageScale()
7087                  */
7088                 public function pixelsToUnits($px) {
7089                         return ($px / ($this->imgscale * $this->k));
7090                 }
7091
7092                 /**
7093                  * Reverse function for htmlentities.
7094                  * Convert entities in UTF-8.
7095                  * @param $text_to_convert Text to convert.
7096                  * @return string converted
7097                  * @access public
7098                 */
7099                 public function unhtmlentities($text_to_convert) {
7100                         return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
7101                 }
7102
7103                 // ENCRYPTION METHODS ----------------------------------
7104                 // SINCE 2.0.000 (2008-01-02)
7105
7106                 /**
7107                 * Compute encryption key depending on object number where the encrypted data is stored
7108                 * @param int $n object number
7109                 * @access protected
7110                 * @since 2.0.000 (2008-01-02)
7111                 */
7112                 protected function _objectkey($n) {
7113                         return substr($this->_md5_16($this->encryption_key.pack('VXxx', $n)), 0, 10);
7114                 }
7115
7116                 /**
7117                  * Put encryption on PDF document.
7118                  * @access protected
7119                  * @since 2.0.000 (2008-01-02)
7120                  */
7121                 protected function _putencryption() {
7122                         $this->_out('/Filter /Standard');
7123                         $this->_out('/V 1');
7124                         $this->_out('/R 2');
7125                         $this->_out('/O ('.$this->_escape($this->Ovalue).')');
7126                         $this->_out('/U ('.$this->_escape($this->Uvalue).')');
7127                         $this->_out('/P '.$this->Pvalue);
7128                 }
7129
7130                 /**
7131                 * Returns the input text exrypted using RC4 algorithm and the specified key.
7132                 * RC4 is the standard encryption algorithm used in PDF format
7133                 * @param string $key encryption key
7134                 * @param String $text input text to be encrypted
7135                 * @return String encrypted text
7136                 * @access protected
7137                 * @since 2.0.000 (2008-01-02)
7138                 * @author Klemen Vodopivec
7139                 */
7140                 protected function _RC4($key, $text) {
7141                         if ($this->last_rc4_key != $key) {
7142                                 $k = str_repeat($key, ((256 / strlen($key)) + 1));
7143                                 $rc4 = range(0, 255);
7144                                 $j = 0;
7145                                 for ($i = 0; $i < 256; ++$i) {
7146                                         $t = $rc4[$i];
7147                                         $j = ($j + $t + ord($k{$i})) % 256;
7148                                         $rc4[$i] = $rc4[$j];
7149                                         $rc4[$j] = $t;
7150                                 }
7151                                 $this->last_rc4_key = $key;
7152                                 $this->last_rc4_key_c = $rc4;
7153                         } else {
7154                                 $rc4 = $this->last_rc4_key_c;
7155                         }
7156                         $len = strlen($text);
7157                         $a = 0;
7158                         $b = 0;
7159                         $out = '';
7160                         for ($i = 0; $i < $len; ++$i) {
7161                                 $a = ($a + 1) % 256;
7162                                 $t = $rc4[$a];
7163                                 $b = ($b + $t) % 256;
7164                                 $rc4[$a] = $rc4[$b];
7165                                 $rc4[$b] = $t;
7166                                 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
7167                                 $out .= chr(ord($text{$i}) ^ $k);
7168                         }
7169                         return $out;
7170                 }
7171
7172                 /**
7173                 * Encrypts a string using MD5 and returns it's value as a binary string.
7174                 * @param string $str input string
7175                 * @return String MD5 encrypted binary string
7176                 * @access protected
7177                 * @since 2.0.000 (2008-01-02)
7178                 * @author Klemen Vodopivec
7179                 */
7180                 protected function _md5_16($str) {
7181                         return pack('H*', md5($str));
7182                 }
7183
7184                 /**
7185                 * Compute O value (used for RC4 encryption)
7186                 * @param String $user_pass user password
7187                 * @param String $owner_pass user password
7188                 * @return String O value
7189                 * @access protected
7190                 * @since 2.0.000 (2008-01-02)
7191                 * @author Klemen Vodopivec
7192                 */
7193                 protected function _Ovalue($user_pass, $owner_pass) {
7194                         $tmp = $this->_md5_16($owner_pass);
7195                         $owner_RC4_key = substr($tmp, 0, 5);
7196                         return $this->_RC4($owner_RC4_key, $user_pass);
7197                 }
7198
7199                 /**
7200                 * Compute U value (used for RC4 encryption)
7201                 * @return String U value
7202                 * @access protected
7203                 * @since 2.0.000 (2008-01-02)
7204                 * @author Klemen Vodopivec
7205                 */
7206                 protected function _Uvalue() {
7207                         return $this->_RC4($this->encryption_key, $this->padding);
7208                 }
7209
7210                 /**
7211                 * Compute encryption key
7212                 * @param String $user_pass user password
7213                 * @param String $owner_pass user password
7214                 * @param String $protection protection type
7215                 * @access protected
7216                 * @since 2.0.000 (2008-01-02)
7217                 * @author Klemen Vodopivec
7218                 */
7219                 protected function _generateencryptionkey($user_pass, $owner_pass, $protection) {
7220                         // Pad passwords
7221                         $user_pass = substr($user_pass.$this->padding, 0, 32);
7222                         $owner_pass = substr($owner_pass.$this->padding, 0, 32);
7223                         // Compute O value
7224                         $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
7225                         // Compute encyption key
7226                         $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
7227                         $this->encryption_key = substr($tmp, 0, 5);
7228                         // Compute U value
7229                         $this->Uvalue = $this->_Uvalue();
7230                         // Compute P value
7231                         $this->Pvalue = -(($protection^255) + 1);
7232                 }
7233
7234                 /**
7235                 * Set document protection
7236                 * The permission array is composed of values taken from the following ones:
7237                 * - copy: copy text and images to the clipboard
7238                 * - print: print the document
7239                 * - modify: modify it (except for annotations and forms)
7240                 * - annot-forms: add annotations and forms
7241                 * Remark: the protection against modification is for people who have the full Acrobat product.
7242                 * If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access.
7243                 * Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts.
7244                 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
7245                 * @param String $user_pass user password. Empty by default.
7246                 * @param String $owner_pass owner password. If not specified, a random value is used.
7247                 * @access public
7248                 * @since 2.0.000 (2008-01-02)
7249                 * @author Klemen Vodopivec
7250                 */
7251                 public function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
7252                         $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
7253                         $protection = 192;
7254                         foreach ($permissions as $permission) {
7255                                 if (!isset($options[$permission])) {
7256                                         $this->Error('Incorrect permission: '.$permission);
7257                                 }
7258                                 $protection += $options[$permission];
7259                         }
7260                         if ($owner_pass === null) {
7261                                 $owner_pass = uniqid(rand());
7262                         }
7263                         $this->encrypted = true;
7264                         $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
7265                 }
7266
7267                 // END OF ENCRYPTION FUNCTIONS -------------------------
7268
7269                 // START TRANSFORMATIONS SECTION -----------------------
7270
7271                 /**
7272                 * Starts a 2D tranformation saving current graphic state.
7273                 * This function must be called before scaling, mirroring, translation, rotation and skewing.
7274                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
7275                 * @access public
7276                 * @since 2.1.000 (2008-01-07)
7277                 * @see StartTransform(), StopTransform()
7278                 */
7279                 public function StartTransform() {
7280                         $this->_out('q');
7281                         $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
7282                 }
7283
7284                 /**
7285                 * Stops a 2D tranformation restoring previous graphic state.
7286                 * This function must be called after scaling, mirroring, translation, rotation and skewing.
7287                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
7288                 * @access public
7289                 * @since 2.1.000 (2008-01-07)
7290                 * @see StartTransform(), StopTransform()
7291                 */
7292                 public function StopTransform() {
7293                         $this->_out('Q');
7294                         if (isset($this->transfmatrix)) {
7295                                 array_pop($this->transfmatrix);
7296                         }
7297                         array_pop($this->transfmrk[$this->page]);
7298                 }
7299                 /**
7300                 * Horizontal Scaling.
7301                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
7302                 * @param int $x abscissa of the scaling center. Default is current x position
7303                 * @param int $y ordinate of the scaling center. Default is current y position
7304                 * @access public
7305                 * @since 2.1.000 (2008-01-07)
7306                 * @see StartTransform(), StopTransform()
7307                 */
7308                 public function ScaleX($s_x, $x='', $y='') {
7309                         $this->Scale($s_x, 100, $x, $y);
7310                 }
7311
7312                 /**
7313                 * Vertical Scaling.
7314                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
7315                 * @param int $x abscissa of the scaling center. Default is current x position
7316                 * @param int $y ordinate of the scaling center. Default is current y position
7317                 * @access public
7318                 * @since 2.1.000 (2008-01-07)
7319                 * @see StartTransform(), StopTransform()
7320                 */
7321                 public function ScaleY($s_y, $x='', $y='') {
7322                         $this->Scale(100, $s_y, $x, $y);
7323                 }
7324
7325                 /**
7326                 * Vertical and horizontal proportional Scaling.
7327                 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
7328                 * @param int $x abscissa of the scaling center. Default is current x position
7329                 * @param int $y ordinate of the scaling center. Default is current y position
7330                 * @access public
7331                 * @since 2.1.000 (2008-01-07)
7332                 * @see StartTransform(), StopTransform()
7333                 */
7334                 public function ScaleXY($s, $x='', $y='') {
7335                         $this->Scale($s, $s, $x, $y);
7336                 }
7337
7338                 /**
7339                 * Vertical and horizontal non-proportional Scaling.
7340                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
7341                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
7342                 * @param int $x abscissa of the scaling center. Default is current x position
7343                 * @param int $y ordinate of the scaling center. Default is current y position
7344                 * @access public
7345                 * @since 2.1.000 (2008-01-07)
7346                 * @see StartTransform(), StopTransform()
7347                 */
7348                 public function Scale($s_x, $s_y, $x='', $y='') {
7349                         if ($x === '') {
7350                                 $x = $this->x;
7351                         }
7352                         if ($y === '') {
7353                                 $y = $this->y;
7354                         }
7355                         if ($this->rtl) {
7356                                 $x = $this->w - $x;
7357                         }
7358                         if (($s_x == 0) OR ($s_y == 0)) {
7359                                 $this->Error('Please do not use values equal to zero for scaling');
7360                         }
7361                         $y = ($this->h - $y) * $this->k;
7362                         $x *= $this->k;
7363                         //calculate elements of transformation matrix
7364                         $s_x /= 100;
7365                         $s_y /= 100;
7366                         $tm[0] = $s_x;
7367                         $tm[1] = 0;
7368                         $tm[2] = 0;
7369                         $tm[3] = $s_y;
7370                         $tm[4] = $x * (1 - $s_x);
7371                         $tm[5] = $y * (1 - $s_y);
7372                         //scale the coordinate system
7373                         $this->Transform($tm);
7374                 }
7375
7376                 /**
7377                 * Horizontal Mirroring.
7378                 * @param int $x abscissa of the point. Default is current x position
7379                 * @access public
7380                 * @since 2.1.000 (2008-01-07)
7381                 * @see StartTransform(), StopTransform()
7382                 */
7383                 public function MirrorH($x='') {
7384                         $this->Scale(-100, 100, $x);
7385                 }
7386
7387                 /**
7388                 * Verical Mirroring.
7389                 * @param int $y ordinate of the point. Default is current y position
7390                 * @access public
7391                 * @since 2.1.000 (2008-01-07)
7392                 * @see StartTransform(), StopTransform()
7393                 */
7394                 public function MirrorV($y='') {
7395                         $this->Scale(100, -100, '', $y);
7396                 }
7397
7398                 /**
7399                 * Point reflection mirroring.
7400                 * @param int $x abscissa of the point. Default is current x position
7401                 * @param int $y ordinate of the point. Default is current y position
7402                 * @access public
7403                 * @since 2.1.000 (2008-01-07)
7404                 * @see StartTransform(), StopTransform()
7405                 */
7406                 public function MirrorP($x='',$y='') {
7407                         $this->Scale(-100, -100, $x, $y);
7408                 }
7409
7410                 /**
7411                 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
7412                 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
7413                 * @param int $x abscissa of the point. Default is current x position
7414                 * @param int $y ordinate of the point. Default is current y position
7415                 * @access public
7416                 * @since 2.1.000 (2008-01-07)
7417                 * @see StartTransform(), StopTransform()
7418                 */
7419                 public function MirrorL($angle=0, $x='',$y='') {
7420                         $this->Scale(-100, 100, $x, $y);
7421                         $this->Rotate(-2*($angle-90), $x, $y);
7422                 }
7423
7424                 /**
7425                 * Translate graphic object horizontally.
7426                 * @param int $t_x movement to the right (or left for RTL)
7427                 * @access public
7428                 * @since 2.1.000 (2008-01-07)
7429                 * @see StartTransform(), StopTransform()
7430                 */
7431                 public function TranslateX($t_x) {
7432                         $this->Translate($t_x, 0);
7433                 }
7434
7435                 /**
7436                 * Translate graphic object vertically.
7437                 * @param int $t_y movement to the bottom
7438                 * @access public
7439                 * @since 2.1.000 (2008-01-07)
7440                 * @see StartTransform(), StopTransform()
7441                 */
7442                 public function TranslateY($t_y) {
7443                         $this->Translate(0, $t_y);
7444                 }
7445
7446                 /**
7447                 * Translate graphic object horizontally and vertically.
7448                 * @param int $t_x movement to the right
7449                 * @param int $t_y movement to the bottom
7450                 * @access public
7451                 * @since 2.1.000 (2008-01-07)
7452                 * @see StartTransform(), StopTransform()
7453                 */
7454                 public function Translate($t_x, $t_y) {
7455                         if ($this->rtl) {
7456                                 $t_x = -$t_x;
7457                         }
7458                         //calculate elements of transformation matrix
7459                         $tm[0] = 1;
7460                         $tm[1] = 0;
7461                         $tm[2] = 0;
7462                         $tm[3] = 1;
7463                         $tm[4] = $t_x * $this->k;
7464                         $tm[5] = -$t_y * $this->k;
7465                         //translate the coordinate system
7466                         $this->Transform($tm);
7467                 }
7468
7469                 /**
7470                 * Rotate object.
7471                 * @param float $angle angle in degrees for counter-clockwise rotation
7472                 * @param int $x abscissa of the rotation center. Default is current x position
7473                 * @param int $y ordinate of the rotation center. Default is current y position
7474                 * @access public
7475                 * @since 2.1.000 (2008-01-07)
7476                 * @see StartTransform(), StopTransform()
7477                 */
7478                 public function Rotate($angle, $x='', $y='') {
7479                         if ($x === '') {
7480                                 $x = $this->x;
7481                         }
7482                         if ($y === '') {
7483                                 $y = $this->y;
7484                         }
7485                         if ($this->rtl) {
7486                                 $x = $this->w - $x;
7487                                 $angle = -$angle;
7488                         }
7489                         $y = ($this->h - $y) * $this->k;
7490                         $x *= $this->k;
7491                         //calculate elements of transformation matrix
7492                         $tm[0] = cos(deg2rad($angle));
7493                         $tm[1] = sin(deg2rad($angle));
7494                         $tm[2] = -$tm[1];
7495                         $tm[3] = $tm[0];
7496                         $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
7497                         $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
7498                         //rotate the coordinate system around ($x,$y)
7499                         $this->Transform($tm);
7500                 }
7501
7502                 /**
7503                 * Skew horizontally.
7504                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
7505                 * @param int $x abscissa of the skewing center. default is current x position
7506                 * @param int $y ordinate of the skewing center. default is current y position
7507                 * @access public
7508                 * @since 2.1.000 (2008-01-07)
7509                 * @see StartTransform(), StopTransform()
7510                 */
7511                 public function SkewX($angle_x, $x='', $y='') {
7512                         $this->Skew($angle_x, 0, $x, $y);
7513                 }
7514
7515                 /**
7516                 * Skew vertically.
7517                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
7518                 * @param int $x abscissa of the skewing center. default is current x position
7519                 * @param int $y ordinate of the skewing center. default is current y position
7520                 * @access public
7521                 * @since 2.1.000 (2008-01-07)
7522                 * @see StartTransform(), StopTransform()
7523                 */
7524                 public function SkewY($angle_y, $x='', $y='') {
7525                         $this->Skew(0, $angle_y, $x, $y);
7526                 }
7527
7528                 /**
7529                 * Skew.
7530                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
7531                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
7532                 * @param int $x abscissa of the skewing center. default is current x position
7533                 * @param int $y ordinate of the skewing center. default is current y position
7534                 * @access public
7535                 * @since 2.1.000 (2008-01-07)
7536                 * @see StartTransform(), StopTransform()
7537                 */
7538                 public function Skew($angle_x, $angle_y, $x='', $y='') {
7539                         if ($x === '') {
7540                                 $x = $this->x;
7541                         }
7542                         if ($y === '') {
7543                                 $y = $this->y;
7544                         }
7545                         if ($this->rtl) {
7546                                 $x = $this->w - $x;
7547                                 $angle_x = -$angle_x;
7548                         }
7549                         if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
7550                                 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
7551                         }
7552                         $x *= $this->k;
7553                         $y = ($this->h - $y) * $this->k;
7554                         //calculate elements of transformation matrix
7555                         $tm[0] = 1;
7556                         $tm[1] = tan(deg2rad($angle_y));
7557                         $tm[2] = tan(deg2rad($angle_x));
7558                         $tm[3] = 1;
7559                         $tm[4] = -$tm[2] * $y;
7560                         $tm[5] = -$tm[1] * $x;
7561                         //skew the coordinate system
7562                         $this->Transform($tm);
7563                 }
7564
7565                 /**
7566                 * Apply graphic transformations.
7567                 * @access protected
7568                 * @since 2.1.000 (2008-01-07)
7569                 * @see StartTransform(), StopTransform()
7570                 */
7571                 protected function Transform($tm) {
7572                         $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
7573                         // store transformation matrix
7574                         $this->transfmatrix[] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
7575                         // update tranformation mark
7576                         if (end($this->transfmrk[$this->page]) !== false) {
7577                                 $key = key($this->transfmrk[$this->page]);
7578                                 $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
7579                         }
7580                 }
7581
7582                 // END TRANSFORMATIONS SECTION -------------------------
7583
7584
7585                 // START GRAPHIC FUNCTIONS SECTION ---------------------
7586                 // The following section is based on the code provided by David Hernandez Sanz
7587
7588                 /**
7589                 * Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page.
7590                 * @param float $width The width.
7591                 * @access public
7592                 * @since 1.0
7593                 * @see Line(), Rect(), Cell(), MultiCell()
7594                 */
7595                 public function SetLineWidth($width) {
7596                         //Set line width
7597                         $this->LineWidth = $width;
7598                         $this->linestyleWidth = sprintf('%.2F w', ($width * $this->k));
7599                         $this->_out($this->linestyleWidth);
7600                 }
7601
7602                 /**
7603                 * Returns the current the line width.
7604                 * @return int Line width
7605                 * @access public
7606                 * @since 2.1.000 (2008-01-07)
7607                 * @see Line(), SetLineWidth()
7608                 */
7609                 public function GetLineWidth() {
7610                         return $this->LineWidth;
7611                 }
7612
7613                 /**
7614                 * Set line style.
7615                 * @param array $style Line style. Array with keys among the following:
7616                 * <ul>
7617                 *        <li>width (float): Width of the line in user units.</li>
7618                 *        <li>cap (string): Type of cap to put on the line. Possible values are:
7619                 * butt, round, square. The difference between "square" and "butt" is that
7620                 * "square" projects a flat end past the end of the line.</li>
7621                 *        <li>join (string): Type of join. Possible values are: miter, round,
7622                 * bevel.</li>
7623                 *        <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
7624                 * series of length values, which are the lengths of the on and off dashes.
7625                 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
7626                 * 1 off, 2 on, 1 off, ...</li>
7627                 *        <li>phase (integer): Modifier on the dash pattern which is used to shift
7628                 * the point at which the pattern starts.</li>
7629                 *        <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
7630                 * </ul>
7631                 * @access public
7632                 * @since 2.1.000 (2008-01-08)
7633                 */
7634                 public function SetLineStyle($style) {
7635                         extract($style);
7636                         if (isset($width)) {
7637                                 $width_prev = $this->LineWidth;
7638                                 $this->SetLineWidth($width);
7639                                 $this->LineWidth = $width_prev;
7640                         }
7641                         if (isset($cap)) {
7642                                 $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
7643                                 if (isset($ca[$cap])) {
7644                                         $this->linestyleCap = $ca[$cap].' J';
7645                                         $this->_out($this->linestyleCap);
7646                                 }
7647                         }
7648                         if (isset($join)) {
7649                                 $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
7650                                 if (isset($ja[$join])) {
7651                                         $this->linestyleJoin = $ja[$join].' j';
7652                                         $this->_out($this->linestyleJoin);
7653                                 }
7654                         }
7655                         if (isset($dash)) {
7656                                 $dash_string = '';
7657                                 if ($dash) {
7658                                         if (preg_match('/^.+,/', $dash)) {
7659                                                 $tab = explode(',', $dash);
7660                                         } else {
7661                                                 $tab = array($dash);
7662                                         }
7663                                         $dash_string = '';
7664                                         foreach ($tab as $i => $v) {
7665                                                 if ($i) {
7666                                                         $dash_string .= ' ';
7667                                                 }
7668                                                 $dash_string .= sprintf("%.2F", $v);
7669                                         }
7670                                 }
7671                                 if (!isset($phase) OR !$dash) {
7672                                         $phase = 0;
7673                                 }
7674                                 $this->linestyleDash = sprintf("[%s] %.2F d", $dash_string, $phase);
7675                                 $this->_out($this->linestyleDash);
7676                         }
7677                         if (isset($color)) {
7678                                 $this->SetDrawColorArray($color);
7679                         }
7680                 }
7681
7682                 /*
7683                 * Set a draw point.
7684                 * @param float $x Abscissa of point.
7685                 * @param float $y Ordinate of point.
7686                 * @access protected
7687                 * @since 2.1.000 (2008-01-08)
7688                 */
7689                 protected function _outPoint($x, $y) {
7690                         if ($this->rtl) {
7691                                 $x = $this->w - $x;
7692                         }
7693                         $this->_out(sprintf("%.2F %.2F m", $x * $this->k, ($this->h - $y) * $this->k));
7694                 }
7695
7696                 /*
7697                 * Draws a line from last draw point.
7698                 * @param float $x Abscissa of end point.
7699                 * @param float $y Ordinate of end point.
7700                 * @access protected
7701                 * @since 2.1.000 (2008-01-08)
7702                 */
7703                 protected function _outLine($x, $y) {
7704                         if ($this->rtl) {
7705                                 $x = $this->w - $x;
7706                         }
7707                         $this->_out(sprintf("%.2F %.2F l", $x * $this->k, ($this->h - $y) * $this->k));
7708                 }
7709
7710                 /**
7711                 * Draws a rectangle.
7712                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
7713                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
7714                 * @param float $w Width.
7715                 * @param float $h Height.
7716                 * @param string $op options
7717                 * @access protected
7718                 * @since 2.1.000 (2008-01-08)
7719                 */
7720                 protected function _outRect($x, $y, $w, $h, $op) {
7721                         if ($this->rtl) {
7722                                 $x = $this->w - $x - $w;
7723                         }
7724                         $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
7725                 }
7726
7727                 /*
7728                 * Draws a Bezier curve from last draw point.
7729                 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
7730                 * @param float $x1 Abscissa of control point 1.
7731                 * @param float $y1 Ordinate of control point 1.
7732                 * @param float $x2 Abscissa of control point 2.
7733                 * @param float $y2 Ordinate of control point 2.
7734                 * @param float $x3 Abscissa of end point.
7735                 * @param float $y3 Ordinate of end point.
7736                 * @access protected
7737                 * @since 2.1.000 (2008-01-08)
7738                 */
7739                 protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
7740                         if ($this->rtl) {
7741                                 $x1 = $this->w - $x1;
7742                                 $x2 = $this->w - $x2;
7743                                 $x3 = $this->w - $x3;
7744                         }
7745                         $this->_out(sprintf("%.2F %.2F %.2F %.2F %.2F %.2F c", $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
7746                 }
7747
7748                 /**
7749                 * Draws a line between two points.
7750                 * @param float $x1 Abscissa of first point.
7751                 * @param float $y1 Ordinate of first point.
7752                 * @param float $x2 Abscissa of second point.
7753                 * @param float $y2 Ordinate of second point.
7754                 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7755                 * @access public
7756                 * @since 1.0
7757                 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
7758                 */
7759                 public function Line($x1, $y1, $x2, $y2, $style=array()) {
7760                         if ($style) {
7761                                 $this->SetLineStyle($style);
7762                         }
7763                         $this->_outPoint($x1, $y1);
7764                         $this->_outLine($x2, $y2);
7765                         $this->_out(' S');
7766                 }
7767
7768                 /**
7769                 * Draws a rectangle.
7770                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
7771                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
7772                 * @param float $w Width.
7773                 * @param float $h Height.
7774                 * @param string $style Style of rendering. Possible values are:
7775                 * <ul>
7776                 *        <li>D or empty string: Draw (default).</li>
7777                 *        <li>F: Fill.</li>
7778                 *        <li>DF or FD: Draw and fill.</li>
7779                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7780                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7781                 * </ul>
7782                 * @param array $border_style Border style of rectangle. Array with keys among the following:
7783                 * <ul>
7784                 *        <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
7785                 *        <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
7786                 * </ul>
7787                 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
7788                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7789                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
7790                 * @access public
7791                 * @since 1.0
7792                 * @see SetLineStyle()
7793                 */
7794                 public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
7795                         if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7796                                 $this->SetFillColorArray($fill_color);
7797                         }
7798                         switch ($style) {
7799                                 case 'F': {
7800                                         $op = 'f';
7801                                         $border_style = array();
7802                                         $this->_outRect($x, $y, $w, $h, $op);
7803                                         break;
7804                                 }
7805                                 case 'DF':
7806                                 case 'FD': {
7807                                         if ((!$border_style) OR (isset($border_style['all']))) {
7808                                                 $op = 'B';
7809                                                 if (isset($border_style['all'])) {
7810                                                         $this->SetLineStyle($border_style['all']);
7811                                                         $border_style = array();
7812                                                 }
7813                                         } else {
7814                                                 $op = 'f';
7815                                         }
7816                                         $this->_outRect($x, $y, $w, $h, $op);
7817                                         break;
7818                                 }
7819                                 case 'CNZ': {
7820                                         $op = 'W n';
7821                                         $this->_outRect($x, $y, $w, $h, $op);
7822                                         break;
7823                                 }
7824                                 case 'CEO': {
7825                                         $op = 'W* n';
7826                                         $this->_outRect($x, $y, $w, $h, $op);
7827                                         break;
7828                                 }
7829                                 default: {
7830                                         $op = 'S';
7831                                         if ((!$border_style) OR (isset($border_style['all']))) {
7832                                                 if (isset($border_style['all']) AND $border_style['all']) {
7833                                                         $this->SetLineStyle($border_style['all']);
7834                                                         $border_style = array();
7835                                                 }
7836                                                 $this->_outRect($x, $y, $w, $h, $op);
7837                                         }
7838                                         break;
7839                                 }
7840                         }
7841                         if ($border_style) {
7842                                 $border_style2 = array();
7843                                 foreach ($border_style as $line => $value) {
7844                                         $lenght = strlen($line);
7845                                         for ($i = 0; $i < $lenght; ++$i) {
7846                                                 $border_style2[$line[$i]] = $value;
7847                                         }
7848                                 }
7849                                 $border_style = $border_style2;
7850                                 if (isset($border_style['L']) AND $border_style['L']) {
7851                                         $this->Line($x, $y, $x, $y + $h, $border_style['L']);
7852                                 }
7853                                 if (isset($border_style['T']) AND $border_style['T']) {
7854                                         $this->Line($x, $y, $x + $w, $y, $border_style['T']);
7855                                 }
7856                                 if (isset($border_style['R']) AND $border_style['R']) {
7857                                         $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
7858                                 }
7859                                 if (isset($border_style['B']) AND $border_style['B']) {
7860                                         $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
7861                                 }
7862                         }
7863                 }
7864
7865
7866                 /**
7867                 * Draws a Bezier curve.
7868                 * The Bezier curve is a tangent to the line between the control points at
7869                 * either end of the curve.
7870                 * @param float $x0 Abscissa of start point.
7871                 * @param float $y0 Ordinate of start point.
7872                 * @param float $x1 Abscissa of control point 1.
7873                 * @param float $y1 Ordinate of control point 1.
7874                 * @param float $x2 Abscissa of control point 2.
7875                 * @param float $y2 Ordinate of control point 2.
7876                 * @param float $x3 Abscissa of end point.
7877                 * @param float $y3 Ordinate of end point.
7878                 * @param string $style Style of rendering. Possible values are:
7879                 * <ul>
7880                 *        <li>D or empty string: Draw (default).</li>
7881                 *        <li>F: Fill.</li>
7882                 *        <li>DF or FD: Draw and fill.</li>
7883                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7884                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7885                 * </ul>
7886                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7887                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
7888                 * @access public
7889                 * @see SetLineStyle()
7890                 * @since 2.1.000 (2008-01-08)
7891                 */
7892                 public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
7893                         if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7894                                 $this->SetFillColorArray($fill_color);
7895                         }
7896                         switch ($style) {
7897                                 case 'F': {
7898                                         $op = 'f';
7899                                         $line_style = array();
7900                                         break;
7901                                 }
7902                                 case 'FD':
7903                                 case 'DF': {
7904                                         $op = 'B';
7905                                         break;
7906                                 }
7907                                 case 'CNZ': {
7908                                         $op = 'W n';
7909                                         break;
7910                                 }
7911                                 case 'CEO': {
7912                                         $op = 'W* n';
7913                                         break;
7914                                 }
7915                                 default: {
7916                                         $op = 'S';
7917                                         break;
7918                                 }
7919                         }
7920                         if ($line_style) {
7921                                 $this->SetLineStyle($line_style);
7922                         }
7923                         $this->_outPoint($x0, $y0);
7924                         $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
7925                         $this->_out($op);
7926                 }
7927
7928                 /**
7929                 * Draws a poly-Bezier curve.
7930                 * Each Bezier curve segment is a tangent to the line between the control points at
7931                 * either end of the curve.
7932                 * @param float $x0 Abscissa of start point.
7933                 * @param float $y0 Ordinate of start point.
7934                 * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
7935                 * @param string $style Style of rendering. Possible values are:
7936                 * <ul>
7937                 *        <li>D or empty string: Draw (default).</li>
7938                 *        <li>F: Fill.</li>
7939                 *        <li>DF or FD: Draw and fill.</li>
7940                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7941                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7942                 * </ul>
7943                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7944                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
7945                 * @access public
7946                 * @see SetLineStyle()
7947                 * @since 3.0008 (2008-05-12)
7948                 */
7949                 public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
7950                         if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7951                                 $this->SetFillColorArray($fill_color);
7952                         }
7953                         switch ($style) {
7954                                 case 'F': {
7955                                         $op = 'f';
7956                                         $line_style = array();
7957                                         break;
7958                                 }
7959                                 case 'FD':
7960                                 case 'DF': {
7961                                         $op = 'B';
7962                                         break;
7963                                 }
7964                                 case 'CNZ': {
7965                                         $op = 'W n';
7966                                         break;
7967                                 }
7968                                 case 'CEO': {
7969                                         $op = 'W* n';
7970                                         break;
7971                                 }
7972                                 default: {
7973                                         $op = 'S';
7974                                         break;
7975                                 }
7976                         }
7977                         if ($line_style) {
7978                                 $this->SetLineStyle($line_style);
7979                         }
7980                         $this->_outPoint($x0, $y0);
7981                         foreach ($segments as $segment) {
7982                                 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
7983                                 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
7984                         }
7985                         $this->_out($op);
7986                 }
7987
7988                 /**
7989                 * Draws an ellipse.
7990                 * An ellipse is formed from n Bezier curves.
7991                 * @param float $x0 Abscissa of center point.
7992                 * @param float $y0 Ordinate of center point.
7993                 * @param float $rx Horizontal radius.
7994                 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
7995                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
7996                 * @param float $astart: Angle start of draw line. Default value: 0.
7997                 * @param float $afinish: Angle finish of draw line. Default value: 360.
7998                 * @param string $style Style of rendering. Possible values are:
7999                 * <ul>
8000                 *        <li>D or empty string: Draw (default).</li>
8001                 *        <li>F: Fill.</li>
8002                 *        <li>DF or FD: Draw and fill.</li>
8003                 *        <li>C: Draw close.</li>
8004                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8005                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8006                 * </ul>
8007                 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8008                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
8009                 * @param integer $nc Number of curves used in ellipse. Default value: 8.
8010                 * @access public
8011                 * @since 2.1.000 (2008-01-08)
8012                 */
8013                 public function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
8014                         if ($angle) {
8015                                 $this->StartTransform();
8016                                 $this->Rotate($angle, $x0, $y0);
8017                                 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
8018                                 $this->StopTransform();
8019                                 return;
8020                         }
8021                         if ($rx) {
8022                                 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8023                                         $this->SetFillColorArray($fill_color);
8024                                 }
8025                                 switch ($style) {
8026                                         case 'F': {
8027                                                 $op = 'f';
8028                                                 $line_style = array();
8029                                                 break;
8030                                         }
8031                                         case 'FD':
8032                                         case 'DF': {
8033                                                 $op = 'B';
8034                                                 break;
8035                                         }
8036                                         case 'C': {
8037                                                 $op = 's'; // Small 's' signifies closing the path as well
8038                                                 break;
8039                                         }
8040                                         case 'CNZ': {
8041                                                 $op = 'W n';
8042                                                 break;
8043                                         }
8044                                         case 'CEO': {
8045                                                 $op = 'W* n';
8046                                                 break;
8047                                         }
8048                                         default: {
8049                                                 $op = 'S';
8050                                                 break;
8051                                         }
8052                                 }
8053                                 if ($line_style) {
8054                                         $this->SetLineStyle($line_style);
8055                                 }
8056                                 if (!$ry) {
8057                                         $ry = $rx;
8058                                 }
8059                                 $rx *= $this->k;
8060                                 $ry *= $this->k;
8061                                 if ($nc < 2) {
8062                                         $nc = 2;
8063                                 }
8064                                 $astart = deg2rad((float) $astart);
8065                                 $afinish = deg2rad((float) $afinish);
8066                                 $total_angle = $afinish - $astart;
8067                                 $dt = $total_angle / $nc;
8068                                 $dtm = $dt / 3;
8069                                 $x0 *= $this->k;
8070                                 $y0 = ($this->h - $y0) * $this->k;
8071                                 $t1 = $astart;
8072                                 $a0 = $x0 + ($rx * cos($t1));
8073                                 $b0 = $y0 + ($ry * sin($t1));
8074                                 $c0 = -$rx * sin($t1);
8075                                 $d0 = $ry * cos($t1);
8076                                 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
8077                                 for ($i = 1; $i <= $nc; ++$i) {
8078                                         // Draw this bit of the total curve
8079                                         $t1 = ($i * $dt) + $astart;
8080                                         $a1 = $x0 + ($rx * cos($t1));
8081                                         $b1 = $y0 + ($ry * sin($t1));
8082                                         $c1 = -$rx * sin($t1);
8083                                         $d1 = $ry * cos($t1);
8084                                         $this->_outCurve(($a0 + ($c0 * $dtm)) / $this->k, $this->h - (($b0 + ($d0 * $dtm)) / $this->k), ($a1 - ($c1 * $dtm)) / $this->k, $this->h - (($b1 - ($d1 * $dtm)) / $this->k), $a1 / $this->k, $this->h - ($b1 / $this->k));
8085                                         $a0 = $a1;
8086                                         $b0 = $b1;
8087                                         $c0 = $c1;
8088                                         $d0 = $d1;
8089                                 }
8090                                 $this->_out($op);
8091                         }
8092                 }
8093
8094                 /**
8095                 * Draws a circle.
8096                 * A circle is formed from n Bezier curves.
8097                 * @param float $x0 Abscissa of center point.
8098                 * @param float $y0 Ordinate of center point.
8099                 * @param float $r Radius.
8100                 * @param float $astart: Angle start of draw line. Default value: 0.
8101                 * @param float $afinish: Angle finish of draw line. Default value: 360.
8102                 * @param string $style Style of rendering. Possible values are:
8103                 * <ul>
8104                 *        <li>D or empty string: Draw (default).</li>
8105                 *        <li>F: Fill.</li>
8106                 *        <li>DF or FD: Draw and fill.</li>
8107                 *        <li>C: Draw close.</li>
8108                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8109                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8110                 * </ul>
8111                 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8112                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8113                 * @param integer $nc Number of curves used in circle. Default value: 8.
8114                 * @access public
8115                 * @since 2.1.000 (2008-01-08)
8116                 */
8117                 public function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
8118                         $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
8119                 }
8120
8121                 /**
8122                 * Draws a polygon.
8123                 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
8124                 * @param string $style Style of rendering. Possible values are:
8125                 * <ul>
8126                 *        <li>D or empty string: Draw (default).</li>
8127                 *        <li>F: Fill.</li>
8128                 *        <li>DF or FD: Draw and fill.</li>
8129                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8130                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8131                 * </ul>
8132                 * @param array $line_style Line style of polygon. Array with keys among the following:
8133                 * <ul>
8134                 *        <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
8135                 *        <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
8136                 * </ul>
8137                 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
8138                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
8139                 * @access public
8140                 * @since 2.1.000 (2008-01-08)
8141                 */
8142                 public function Polygon($p, $style='', $line_style=array(), $fill_color=array()) {
8143                         $np = count($p) / 2;
8144                         if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8145                                 $this->SetFillColorArray($fill_color);
8146                         }
8147                         switch ($style) {
8148                                 case 'F': {
8149                                         $line_style = array();
8150                                         $op = 'f';
8151                                         break;
8152                                 }
8153                                 case 'FD':
8154                                 case 'DF': {
8155                                         $op = 'B';
8156                                         break;
8157                                 }
8158                                 case 'CNZ': {
8159                                         $op = 'W n';
8160                                         break;
8161                                 }
8162                                 case 'CEO': {
8163                                         $op = 'W* n';
8164                                         break;
8165                                 }
8166                                 default: {
8167                                         $op = 'S';
8168                                         break;
8169                                 }
8170                         }
8171                         $draw = true;
8172                         if ($line_style) {
8173                                 if (isset($line_style['all'])) {
8174                                         $this->SetLineStyle($line_style['all']);
8175                                 } else { // 0 .. (np - 1), op = {B, S}
8176                                         $draw = false;
8177                                         if ('B' == $op) {
8178                                                 $op = 'f';
8179                                                 $this->_outPoint($p[0], $p[1]);
8180                                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
8181                                                         $this->_outLine($p[$i], $p[$i + 1]);
8182                                                 }
8183                                                 $this->_outLine($p[0], $p[1]);
8184                                                 $this->_out($op);
8185                                         }
8186                                         $p[($np * 2)] = $p[0];
8187                                         $p[(($np * 2) + 1)] = $p[1];
8188                                         for ($i = 0; $i < $np; ++$i) {
8189                                                 if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
8190                                                         $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
8191                                                 }
8192                                         }
8193                                 }
8194                         }
8195                         if ($draw) {
8196                                 $this->_outPoint($p[0], $p[1]);
8197                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
8198                                         $this->_outLine($p[$i], $p[$i + 1]);
8199                                 }
8200                                 $this->_outLine($p[0], $p[1]);
8201                                 $this->_out($op);
8202                         }
8203                 }
8204
8205                 /**
8206                 * Draws a regular polygon.
8207                 * @param float $x0 Abscissa of center point.
8208                 * @param float $y0 Ordinate of center point.
8209                 * @param float $r: Radius of inscribed circle.
8210                 * @param integer $ns Number of sides.
8211                 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
8212                 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
8213                 * @param string $style Style of rendering. Possible values are:
8214                 * <ul>
8215                 *        <li>D or empty string: Draw (default).</li>
8216                 *        <li>F: Fill.</li>
8217                 *        <li>DF or FD: Draw and fill.</li>
8218                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8219                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8220                 * </ul>
8221                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
8222                 * <ul>
8223                 *        <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
8224                 *        <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
8225                 * </ul>
8226                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
8227                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8228                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
8229                 * <ul>
8230                 *        <li>D or empty string: Draw (default).</li>
8231                 *        <li>F: Fill.</li>
8232                 *        <li>DF or FD: Draw and fill.</li>
8233                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8234                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8235                 * </ul>
8236                 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8237                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
8238                 * @access public
8239                 * @since 2.1.000 (2008-01-08)
8240                 */
8241                 public function RegularPolygon($x0, $y0, $r, $ns, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {
8242                         if (3 > $ns) {
8243                                 $ns = 3;
8244                         }
8245                         if ($draw_circle) {
8246                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
8247                         }
8248                         $p = array();
8249                         for ($i = 0; $i < $ns; ++$i) {
8250                                 $a = $angle + ($i * 360 / $ns);
8251                                 $a_rad = deg2rad((float) $a);
8252                                 $p[] = $x0 + ($r * sin($a_rad));
8253                                 $p[] = $y0 + ($r * cos($a_rad));
8254                         }
8255                         $this->Polygon($p, $style, $line_style, $fill_color);
8256                 }
8257
8258                 /**
8259                 * Draws a star polygon
8260                 * @param float $x0 Abscissa of center point.
8261                 * @param float $y0 Ordinate of center point.
8262                 * @param float $r Radius of inscribed circle.
8263                 * @param integer $nv Number of vertices.
8264                 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
8265                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
8266                 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
8267                 * @param string $style Style of rendering. Possible values are:
8268                 * <ul>
8269                 *        <li>D or empty string: Draw (default).</li>
8270                 *        <li>F: Fill.</li>
8271                 *        <li>DF or FD: Draw and fill.</li>
8272                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8273                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8274                 * </ul>
8275                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
8276                 * <ul>
8277                 *        <li>all: Line style of all sides. Array like for
8278                 * {@link SetLineStyle SetLineStyle}.</li>
8279                 *        <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
8280                 * </ul>
8281                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
8282                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8283                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
8284                 * <ul>
8285                 *        <li>D or empty string: Draw (default).</li>
8286                 *        <li>F: Fill.</li>
8287                 *        <li>DF or FD: Draw and fill.</li>
8288                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8289                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8290                 * </ul>
8291                 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8292                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
8293                 * @access public
8294                 * @since 2.1.000 (2008-01-08)
8295                 */
8296                 public function StarPolygon($x0, $y0, $r, $nv, $ng, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {
8297                         if (2 > $nv) {
8298                                 $nv = 2;
8299                         }
8300                         if ($draw_circle) {
8301                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
8302                         }
8303                         $p2 = array();
8304                         $visited = array();
8305                         for ($i = 0; $i < $nv; ++$i) {
8306                                 $a = $angle + ($i * 360 / $nv);
8307                                 $a_rad = deg2rad((float) $a);
8308                                 $p2[] = $x0 + ($r * sin($a_rad));
8309                                 $p2[] = $y0 + ($r * cos($a_rad));
8310                                 $visited[] = false;
8311                         }
8312                         $p = array();
8313                         $i = 0;
8314                         do {
8315                                 $p[] = $p2[$i * 2];
8316                                 $p[] = $p2[($i * 2) + 1];
8317                                 $visited[$i] = true;
8318                                 $i += $ng;
8319                                 $i %= $nv;
8320                         } while (!$visited[$i]);
8321                         $this->Polygon($p, $style, $line_style, $fill_color);
8322                 }
8323
8324                 /**
8325                 * Draws a rounded rectangle.
8326                 * @param float $x Abscissa of upper-left corner.
8327                 * @param float $y Ordinate of upper-left corner.
8328                 * @param float $w Width.
8329                 * @param float $h Height.
8330                 * @param float $r Radius of the rounded corners.
8331                 * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111").
8332                 * @param string $style Style of rendering. Possible values are:
8333                 * <ul>
8334                 *        <li>D or empty string: Draw (default).</li>
8335                 *        <li>F: Fill.</li>
8336                 *        <li>DF or FD: Draw and fill.</li>
8337                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8338                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8339                 * </ul>
8340                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8341                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
8342                 * @access public
8343                 * @since 2.1.000 (2008-01-08)
8344                 */
8345                 public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
8346                         if ('0000' == $round_corner) { // Not rounded
8347                                 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
8348                         } else { // Rounded
8349                                 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8350                                         $this->SetFillColorArray($fill_color);
8351                                 }
8352                                 switch ($style) {
8353                                         case 'F': {
8354                                                 $border_style = array();
8355                                                 $op = 'f';
8356                                                 break;
8357                                         }
8358                                         case 'FD':
8359                                         case 'DF': {
8360                                                 $op = 'B';
8361                                                 break;
8362                                         }
8363                                         case 'CNZ': {
8364                                                 $op = 'W n';
8365                                                 break;
8366                                         }
8367                                         case 'CEO': {
8368                                                 $op = 'W* n';
8369                                                 break;
8370                                         }
8371                                         default: {
8372                                                 $op = 'S';
8373                                                 break;
8374                                         }
8375                                 }
8376                                 if ($border_style) {
8377                                         $this->SetLineStyle($border_style);
8378                                 }
8379                                 $MyArc = 4 / 3 * (sqrt(2) - 1);
8380                                 $this->_outPoint($x + $r, $y);
8381                                 $xc = $x + $w - $r;
8382                                 $yc = $y + $r;
8383                                 $this->_outLine($xc, $y);
8384                                 if ($round_corner[0]) {
8385                                         $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
8386                                 } else {
8387                                         $this->_outLine($x + $w, $y);
8388                                 }
8389                                 $xc = $x + $w - $r;
8390                                 $yc = $y + $h - $r;
8391                                 $this->_outLine($x + $w, $yc);
8392                                 if ($round_corner[1]) {
8393                                         $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
8394                                 } else {
8395                                         $this->_outLine($x + $w, $y + $h);
8396                                 }
8397                                 $xc = $x + $r;
8398                                 $yc = $y + $h - $r;
8399                                 $this->_outLine($xc, $y + $h);
8400                                 if ($round_corner[2]) {
8401                                         $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
8402                                 } else {
8403                                         $this->_outLine($x, $y + $h);
8404                                 }
8405                                 $xc = $x + $r;
8406                                 $yc = $y + $r;
8407                                 $this->_outLine($x, $yc);
8408                                 if ($round_corner[3]) {
8409                                         $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
8410                                 } else {
8411                                         $this->_outLine($x, $y);
8412                                         $this->_outLine($x + $r, $y);
8413                                 }
8414                                 $this->_out($op);
8415                         }
8416                 }
8417
8418                 // END GRAPHIC FUNCTIONS SECTION -----------------------
8419
8420                 // BIDIRECTIONAL TEXT SECTION --------------------------
8421                 /**
8422                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
8423                  * @param string $str string to manipulate.
8424                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
8425                  * @return string
8426                  * @access protected
8427                  * @author Nicola Asuni
8428                  * @since 2.1.000 (2008-01-08)
8429                 */
8430                 protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
8431                         return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $str, $forcertl), $setbom);
8432                 }
8433
8434                 /**
8435                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
8436                  * @param array $ta array of characters composing the string.
8437                  * @param string $str string to process
8438                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
8439                  * @return string
8440                  * @author Nicola Asuni
8441                  * @access protected
8442                  * @since 2.4.000 (2008-03-06)
8443                 */
8444                 protected function utf8Bidi($ta, $str='', $forcertl=false) {
8445                         global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
8446                         // paragraph embedding level
8447                         $pel = 0;
8448                         // max level
8449                         $maxlevel = 0;
8450                         if ($this->empty_string($str)) {
8451                                 // create string from array
8452                                 $str = $this->UTF8ArrSubString($ta);
8453                         }
8454                         // check if string contains arabic text
8455                         if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
8456                                 $arabic = true;
8457                         } else {
8458                                 $arabic = false;
8459                         }
8460                         // check if string contains RTL text
8461                         if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
8462                                 return $ta;
8463                         }
8464
8465                         // get number of chars
8466                         $numchars = count($ta);
8467
8468                         if ($forcertl == 'R') {
8469                                         $pel = 1;
8470                         } elseif ($forcertl == 'L') {
8471                                         $pel = 0;
8472                         } else {
8473                                 // P2. In each paragraph, find the first character of type L, AL, or R.
8474                                 // P3. If a character is found in P2 and it is of type AL or R, then set the paragraph embedding level to one; otherwise, set it to zero.
8475                                 for ($i=0; $i < $numchars; ++$i) {
8476                                         $type = $unicode[$ta[$i]];
8477                                         if ($type == 'L') {
8478                                                 $pel = 0;
8479                                                 break;
8480                                         } elseif (($type == 'AL') OR ($type == 'R')) {
8481                                                 $pel = 1;
8482                                                 break;
8483                                         }
8484                                 }
8485                         }
8486
8487                         // Current Embedding Level
8488                         $cel = $pel;
8489                         // directional override status
8490                         $dos = 'N';
8491                         $remember = array();
8492                         // start-of-level-run
8493                         $sor = $pel % 2 ? 'R' : 'L';
8494                         $eor = $sor;
8495
8496                         // Array of characters data
8497                         $chardata = Array();
8498
8499                         // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase.
8500                         //      In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
8501                         for ($i=0; $i < $numchars; ++$i) {
8502                                 if ($ta[$i] == K_RLE) {
8503                                         // X2. With each RLE, compute the least greater odd embedding level.
8504                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
8505                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8506                                         $next_level = $cel + ($cel % 2) + 1;
8507                                         if ($next_level < 62) {
8508                                                 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
8509                                                 $cel = $next_level;
8510                                                 $dos = 'N';
8511                                                 $sor = $eor;
8512                                                 $eor = $cel % 2 ? 'R' : 'L';
8513                                         }
8514                                 } elseif ($ta[$i] == K_LRE) {
8515                                         // X3. With each LRE, compute the least greater even embedding level.
8516                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
8517                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8518                                         $next_level = $cel + 2 - ($cel % 2);
8519                                         if ( $next_level < 62 ) {
8520                                                 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
8521                                                 $cel = $next_level;
8522                                                 $dos = 'N';
8523                                                 $sor = $eor;
8524                                                 $eor = $cel % 2 ? 'R' : 'L';
8525                                         }
8526                                 } elseif ($ta[$i] == K_RLO) {
8527                                         // X4. With each RLO, compute the least greater odd embedding level.
8528                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left.
8529                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8530                                         $next_level = $cel + ($cel % 2) + 1;
8531                                         if ($next_level < 62) {
8532                                                 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
8533                                                 $cel = $next_level;
8534                                                 $dos = 'R';
8535                                                 $sor = $eor;
8536                                                 $eor = $cel % 2 ? 'R' : 'L';
8537                                         }
8538                                 } elseif ($ta[$i] == K_LRO) {
8539                                         // X5. With each LRO, compute the least greater even embedding level.
8540                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right.
8541                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8542                                         $next_level = $cel + 2 - ($cel % 2);
8543                                         if ( $next_level < 62 ) {
8544                                                 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
8545                                                 $cel = $next_level;
8546                                                 $dos = 'L';
8547                                                 $sor = $eor;
8548                                                 $eor = $cel % 2 ? 'R' : 'L';
8549                                         }
8550                                 } elseif ($ta[$i] == K_PDF) {
8551                                         // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override.
8552                                         if (count($remember)) {
8553                                                 $last = count($remember ) - 1;
8554                                                 if (($remember[$last]['num'] == K_RLE) OR
8555                                                           ($remember[$last]['num'] == K_LRE) OR
8556                                                           ($remember[$last]['num'] == K_RLO) OR
8557                                                           ($remember[$last]['num'] == K_LRO)) {
8558                                                         $match = array_pop($remember);
8559                                                         $cel = $match['cel'];
8560                                                         $dos = $match['dos'];
8561                                                         $sor = $eor;
8562                                                         $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
8563                                                 }
8564                                         }
8565                                 } elseif (($ta[$i] != K_RLE) AND
8566                                                                  ($ta[$i] != K_LRE) AND
8567                                                                  ($ta[$i] != K_RLO) AND
8568                                                                  ($ta[$i] != K_LRO) AND
8569                                                                  ($ta[$i] != K_PDF)) {
8570                                         // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
8571                                         //      a. Set the level of the current character to the current embedding level.
8572                                         //      b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
8573                                         if ($dos != 'N') {
8574                                                 $chardir = $dos;
8575                                         } else {
8576                                                 $chardir = $unicode[$ta[$i]];
8577                                         }
8578                                         // stores string characters and other information
8579                                         $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
8580                                 }
8581                         } // end for each char
8582
8583                         // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
8584                         // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
8585                         // X10. The remaining rules are applied to each run of characters at the same level. For each run, determine the start-of-level-run (sor) and end-of-level-run (eor) type, either L or R. This depends on the higher of the two levels on either side of the boundary (at the start or end of the paragraph, the level of the 'other' run is the base embedding level). If the higher level is odd, the type is R; otherwise, it is L.
8586
8587                         // 3.3.3 Resolving Weak Types
8588                         // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used.
8589                         // Nonspacing marks are now resolved based on the previous characters.
8590                         $numchars = count($chardata);
8591
8592                         // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor.
8593                         $prevlevel = -1; // track level changes
8594                         $levcount = 0; // counts consecutive chars at the same level
8595                         for ($i=0; $i < $numchars; ++$i) {
8596                                 if ($chardata[$i]['type'] == 'NSM') {
8597                                         if ($levcount) {
8598                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
8599                                         } elseif ($i > 0) {
8600                                                 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
8601                                         }
8602                                 }
8603                                 if ($chardata[$i]['level'] != $prevlevel) {
8604                                         $levcount = 0;
8605                                 } else {
8606                                         ++$levcount;
8607                                 }
8608                                 $prevlevel = $chardata[$i]['level'];
8609                         }
8610
8611                         // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number.
8612                         $prevlevel = -1;
8613                         $levcount = 0;
8614                         for ($i=0; $i < $numchars; ++$i) {
8615                                 if ($chardata[$i]['char'] == 'EN') {
8616                                         for ($j=$levcount; $j >= 0; $j--) {
8617                                                 if ($chardata[$j]['type'] == 'AL') {
8618                                                         $chardata[$i]['type'] = 'AN';
8619                                                 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
8620                                                         break;
8621                                                 }
8622                                         }
8623                                 }
8624                                 if ($chardata[$i]['level'] != $prevlevel) {
8625                                         $levcount = 0;
8626                                 } else {
8627                                         ++$levcount;
8628                                 }
8629                                 $prevlevel = $chardata[$i]['level'];
8630                         }
8631
8632                         // W3. Change all ALs to R.
8633                         for ($i=0; $i < $numchars; ++$i) {
8634                                 if ($chardata[$i]['type'] == 'AL') {
8635                                         $chardata[$i]['type'] = 'R';
8636                                 }
8637                         }
8638
8639                         // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type.
8640                         $prevlevel = -1;
8641                         $levcount = 0;
8642                         for ($i=0; $i < $numchars; ++$i) {
8643                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8644                                         if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
8645                                                 $chardata[$i]['type'] = 'EN';
8646                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
8647                                                 $chardata[$i]['type'] = 'EN';
8648                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
8649                                                 $chardata[$i]['type'] = 'AN';
8650                                         }
8651                                 }
8652                                 if ($chardata[$i]['level'] != $prevlevel) {
8653                                         $levcount = 0;
8654                                 } else {
8655                                         ++$levcount;
8656                                 }
8657                                 $prevlevel = $chardata[$i]['level'];
8658                         }
8659
8660                         // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
8661                         $prevlevel = -1;
8662                         $levcount = 0;
8663                         for ($i=0; $i < $numchars; ++$i) {
8664                                 if ($chardata[$i]['type'] == 'ET') {
8665                                         if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
8666                                                 $chardata[$i]['type'] = 'EN';
8667                                         } else {
8668                                                 $j = $i+1;
8669                                                 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
8670                                                         if ($chardata[$j]['type'] == 'EN') {
8671                                                                 $chardata[$i]['type'] = 'EN';
8672                                                                 break;
8673                                                         } elseif ($chardata[$j]['type'] != 'ET') {
8674                                                                 break;
8675                                                         }
8676                                                         ++$j;
8677                                                 }
8678                                         }
8679                                 }
8680                                 if ($chardata[$i]['level'] != $prevlevel) {
8681                                         $levcount = 0;
8682                                 } else {
8683                                         ++$levcount;
8684                                 }
8685                                 $prevlevel = $chardata[$i]['level'];
8686                         }
8687
8688                         // W6. Otherwise, separators and terminators change to Other Neutral.
8689                         $prevlevel = -1;
8690                         $levcount = 0;
8691                         for ($i=0; $i < $numchars; ++$i) {
8692                                 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
8693                                         $chardata[$i]['type'] = 'ON';
8694                                 }
8695                                 if ($chardata[$i]['level'] != $prevlevel) {
8696                                         $levcount = 0;
8697                                 } else {
8698                                         ++$levcount;
8699                                 }
8700                                 $prevlevel = $chardata[$i]['level'];
8701                         }
8702
8703                         //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L.
8704                         $prevlevel = -1;
8705                         $levcount = 0;
8706                         for ($i=0; $i < $numchars; ++$i) {
8707                                 if ($chardata[$i]['char'] == 'EN') {
8708                                         for ($j=$levcount; $j >= 0; $j--) {
8709                                                 if ($chardata[$j]['type'] == 'L') {
8710                                                         $chardata[$i]['type'] = 'L';
8711                                                 } elseif ($chardata[$j]['type'] == 'R') {
8712                                                         break;
8713                                                 }
8714                                         }
8715                                 }
8716                                 if ($chardata[$i]['level'] != $prevlevel) {
8717                                         $levcount = 0;
8718                                 } else {
8719                                         ++$levcount;
8720                                 }
8721                                 $prevlevel = $chardata[$i]['level'];
8722                         }
8723
8724                         // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries.
8725                         $prevlevel = -1;
8726                         $levcount = 0;
8727                         for ($i=0; $i < $numchars; ++$i) {
8728                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8729                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
8730                                                 $chardata[$i]['type'] = 'L';
8731                                         } elseif (($chardata[$i]['type'] == 'N') AND
8732                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
8733                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
8734                                                 $chardata[$i]['type'] = 'R';
8735                                         } elseif ($chardata[$i]['type'] == 'N') {
8736                                                 // N2. Any remaining neutrals take the embedding direction
8737                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
8738                                         }
8739                                 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8740                                         // first char
8741                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
8742                                                 $chardata[$i]['type'] = 'L';
8743                                         } elseif (($chardata[$i]['type'] == 'N') AND
8744                                          (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
8745                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
8746                                                 $chardata[$i]['type'] = 'R';
8747                                         } elseif ($chardata[$i]['type'] == 'N') {
8748                                                 // N2. Any remaining neutrals take the embedding direction
8749                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
8750                                         }
8751                                 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
8752                                         //last char
8753                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
8754                                                 $chardata[$i]['type'] = 'L';
8755                                         } elseif (($chardata[$i]['type'] == 'N') AND
8756                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
8757                                          (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
8758                                                 $chardata[$i]['type'] = 'R';
8759                                         } elseif ($chardata[$i]['type'] == 'N') {
8760                                                 // N2. Any remaining neutrals take the embedding direction
8761                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
8762                                         }
8763                                 } elseif ($chardata[$i]['type'] == 'N') {
8764                                         // N2. Any remaining neutrals take the embedding direction
8765                                         $chardata[$i]['type'] = $chardata[$i]['sor'];
8766                                 }
8767                                 if ($chardata[$i]['level'] != $prevlevel) {
8768                                         $levcount = 0;
8769                                 } else {
8770                                         ++$levcount;
8771                                 }
8772                                 $prevlevel = $chardata[$i]['level'];
8773                         }
8774
8775                         // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels.
8776                         // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
8777                         for ($i=0; $i < $numchars; ++$i) {
8778                                 $odd = $chardata[$i]['level'] % 2;
8779                                 if ($odd) {
8780                                         if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
8781                                                 $chardata[$i]['level'] += 1;
8782                                         }
8783                                 } else {
8784                                         if ($chardata[$i]['type'] == 'R') {
8785                                                 $chardata[$i]['level'] += 1;
8786                                         } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
8787                                                 $chardata[$i]['level'] += 2;
8788                                         }
8789                                 }
8790                                 $maxlevel = max($chardata[$i]['level'],$maxlevel);
8791                         }
8792
8793                         // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
8794                         //      1. Segment separators,
8795                         //      2. Paragraph separators,
8796                         //      3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
8797                         //      4. Any sequence of white space characters at the end of the line.
8798                         for ($i=0; $i < $numchars; ++$i) {
8799                                 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
8800                                         $chardata[$i]['level'] = $pel;
8801                                 } elseif ($chardata[$i]['type'] == 'WS') {
8802                                         $j = $i+1;
8803                                         while ($j < $numchars) {
8804                                                 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
8805                                                         (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
8806                                                         $chardata[$i]['level'] = $pel;
8807                                                         break;
8808                                                 } elseif ($chardata[$j]['type'] != 'WS') {
8809                                                         break;
8810                                                 }
8811                                                 ++$j;
8812                                         }
8813                                 }
8814                         }
8815
8816                         // Arabic Shaping
8817                         // Cursively connected scripts, such as Arabic or Syriac, require the selection of positional character shapes that depend on adjacent characters. Shaping is logically applied after the Bidirectional Algorithm is used and is limited to characters within the same directional run.
8818                         if ($arabic) {
8819                                 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
8820                                 $alfletter = array(1570,1571,1573,1575);
8821                                 $chardata2 = $chardata;
8822                                 $laaletter = false;
8823                                 $charAL = array();
8824                                 $x = 0;
8825                                 for ($i=0; $i < $numchars; ++$i) {
8826                                         if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
8827                                                 $charAL[$x] = $chardata[$i];
8828                                                 $charAL[$x]['i'] = $i;
8829                                                 $chardata[$i]['x'] = $x;
8830                                                 ++$x;
8831                                         }
8832                                 }
8833                                 $numAL = $x;
8834                                 for ($i=0; $i < $numchars; ++$i) {
8835                                         $thischar = $chardata[$i];
8836                                         if ($i > 0) {
8837                                                 $prevchar = $chardata[($i-1)];
8838                                         } else {
8839                                                 $prevchar = false;
8840                                         }
8841                                         if (($i+1) < $numchars) {
8842                                                 $nextchar = $chardata[($i+1)];
8843                                         } else {
8844                                                 $nextchar = false;
8845                                         }
8846                                         if ($unicode[$thischar['char']] == 'AL') {
8847                                                 $x = $thischar['x'];
8848                                                 if ($x > 0) {
8849                                                         $prevchar = $charAL[($x-1)];
8850                                                 } else {
8851                                                         $prevchar = false;
8852                                                 }
8853                                                 if (($x+1) < $numAL) {
8854                                                         $nextchar = $charAL[($x+1)];
8855                                                 } else {
8856                                                         $nextchar = false;
8857                                                 }
8858                                                 // if laa letter
8859                                                 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
8860                                                         $arabicarr = $laa_array;
8861                                                         $laaletter = true;
8862                                                         if ($x > 1) {
8863                                                                 $prevchar = $charAL[($x-2)];
8864                                                         } else {
8865                                                                 $prevchar = false;
8866                                                         }
8867                                                 } else {
8868                                                         $arabicarr = $unicode_arlet;
8869                                                         $laaletter = false;
8870                                                 }
8871                                                 if (($prevchar !== false) AND ($nextchar !== false) AND
8872                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
8873                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
8874                                                         ($prevchar['type'] == $thischar['type']) AND
8875                                                         ($nextchar['type'] == $thischar['type']) AND
8876                                                         ($nextchar['char'] != 1567)) {
8877                                                         if (in_array($prevchar['char'], $endedletter)) {
8878                                                                 if (isset($arabicarr[$thischar['char']][2])) {
8879                                                                         // initial
8880                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
8881                                                                 }
8882                                                         } else {
8883                                                                 if (isset($arabicarr[$thischar['char']][3])) {
8884                                                                         // medial
8885                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
8886                                                                 }
8887                                                         }
8888                                                 } elseif (($nextchar !== false) AND
8889                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
8890                                                         ($nextchar['type'] == $thischar['type']) AND
8891                                                         ($nextchar['char'] != 1567)) {
8892                                                         if (isset($arabicarr[$chardata[$i]['char']][2])) {
8893                                                                 // initial
8894                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
8895                                                         }
8896                                                 } elseif ((($prevchar !== false) AND
8897                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
8898                                                         ($prevchar['type'] == $thischar['type'])) OR
8899                                                         (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
8900                                                         // final
8901                                                         if (($i > 1) AND ($thischar['char'] == 1607) AND
8902                                                                 ($chardata[$i-1]['char'] == 1604) AND
8903                                                                 ($chardata[$i-2]['char'] == 1604)) {
8904                                                                 //Allah Word
8905                                                                 // mark characters to delete with false
8906                                                                 $chardata2[$i-2]['char'] = false;
8907                                                                 $chardata2[$i-1]['char'] = false;
8908                                                                 $chardata2[$i]['char'] = 65010;
8909                                                         } else {
8910                                                                 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
8911                                                                         if (isset($arabicarr[$thischar['char']][0])) {
8912                                                                                 // isolated
8913                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
8914                                                                         }
8915                                                                 } else {
8916                                                                         if (isset($arabicarr[$thischar['char']][1])) {
8917                                                                                 // final
8918                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
8919                                                                         }
8920                                                                 }
8921                                                         }
8922                                                 } elseif (isset($arabicarr[$thischar['char']][0])) {
8923                                                         // isolated
8924                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
8925                                                 }
8926                                                 // if laa letter
8927                                                 if ($laaletter) {
8928                                                         // mark characters to delete with false
8929                                                         $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
8930                                                 }
8931                                         } // end if AL (Arabic Letter)
8932                                 } // end for each char
8933                                 /*
8934                                  * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
8935                                  * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
8936                                  */
8937                                 $cw = &$this->CurrentFont['cw'];
8938                                 for ($i = 0; $i < ($numchars-1); ++$i) {
8939                                         if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
8940                                                 // check if the subtitution font is defined on current font
8941                                                 if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
8942                                                         $chardata2[$i]['char'] = false;
8943                                                         $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
8944                                                 }
8945                                         }
8946                                 }
8947                                 // remove marked characters
8948                                 foreach ($chardata2 as $key => $value) {
8949                                         if ($value['char'] === false) {
8950                                                 unset($chardata2[$key]);
8951                                         }
8952                                 }
8953                                 $chardata = array_values($chardata2);
8954                                 $numchars = count($chardata);
8955                                 unset($chardata2);
8956                                 unset($arabicarr);
8957                                 unset($laaletter);
8958                                 unset($charAL);
8959                         }
8960
8961                         // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher.
8962                         for ($j=$maxlevel; $j > 0; $j--) {
8963                                 $ordarray = Array();
8964                                 $revarr = Array();
8965                                 $onlevel = false;
8966                                 for ($i=0; $i < $numchars; ++$i) {
8967                                         if ($chardata[$i]['level'] >= $j) {
8968                                                 $onlevel = true;
8969                                                 if (isset($unicode_mirror[$chardata[$i]['char']])) {
8970                                                         // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true.
8971                                                         $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
8972                                                 }
8973                                                 $revarr[] = $chardata[$i];
8974                                         } else {
8975                                                 if ($onlevel) {
8976                                                         $revarr = array_reverse($revarr);
8977                                                         $ordarray = array_merge($ordarray, $revarr);
8978                                                         $revarr = Array();
8979                                                         $onlevel = false;
8980                                                 }
8981                                                 $ordarray[] = $chardata[$i];
8982                                         }
8983                                 }
8984                                 if ($onlevel) {
8985                                         $revarr = array_reverse($revarr);
8986                                         $ordarray = array_merge($ordarray, $revarr);
8987                                 }
8988                                 $chardata = $ordarray;
8989                         }
8990
8991                         $ordarray = array();
8992                         for ($i=0; $i < $numchars; ++$i) {
8993                                 $ordarray[] = $chardata[$i]['char'];
8994                         }
8995
8996                         return $ordarray;
8997                 }
8998
8999                 // END OF BIDIRECTIONAL TEXT SECTION -------------------
9000
9001                 /*
9002                 * Adds a bookmark.
9003                 * @param string $txt bookmark description.
9004                 * @param int $level bookmark level (minimum value is 0).
9005                 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
9006                 * @param int $page target page number (leave empty for current page).
9007                 * @access public
9008                 * @author Olivier Plathey, Nicola Asuni
9009                 * @since 2.1.002 (2008-02-12)
9010                 */
9011                 public function Bookmark($txt, $level=0, $y=-1, $page='') {
9012                         if ($level < 0) {
9013                                 $level = 0;
9014                         }
9015                         if (isset($this->outlines[0])) {
9016                                 $lastoutline = end($this->outlines);
9017                                 $maxlevel = $lastoutline['l'] + 1;
9018                         } else {
9019                                 $maxlevel = 0;
9020                         }
9021                         if ($level > $maxlevel) {
9022                                 $level = $maxlevel;
9023                         }
9024                         if ($y == -1) {
9025                                 $y = $this->GetY();
9026                         }
9027                         if (empty($page)) {
9028                                 $page = $this->PageNo();
9029                         }
9030                         $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $page);
9031                 }
9032
9033                 /*
9034                 * Create a bookmark PDF string.
9035                 * @access protected
9036                 * @author Olivier Plathey, Nicola Asuni
9037                 * @since 2.1.002 (2008-02-12)
9038                 */
9039                 protected function _putbookmarks() {
9040                         $nb = count($this->outlines);
9041                         if ($nb == 0) {
9042                                 return;
9043                         }
9044                         $lru = array();
9045                         $level = 0;
9046                         foreach ($this->outlines as $i => $o) {
9047                                 if ($o['l'] > 0) {
9048                                         $parent = $lru[($o['l'] - 1)];
9049                                         //Set parent and last pointers
9050                                         $this->outlines[$i]['parent'] = $parent;
9051                                         $this->outlines[$parent]['last'] = $i;
9052                                         if ($o['l'] > $level) {
9053                                                 //Level increasing: set first pointer
9054                                                 $this->outlines[$parent]['first'] = $i;
9055                                         }
9056                                 } else {
9057                                         $this->outlines[$i]['parent'] = $nb;
9058                                 }
9059                                 if (($o['l'] <= $level) AND ($i > 0)) {
9060                                         //Set prev and next pointers
9061                                         $prev = $lru[$o['l']];
9062                                         $this->outlines[$prev]['next'] = $i;
9063                                         $this->outlines[$i]['prev'] = $prev;
9064                                 }
9065                                 $lru[$o['l']] = $i;
9066                                 $level = $o['l'];
9067                         }
9068                         //Outline items
9069                         $n = $this->n + 1;
9070                         foreach ($this->outlines as $i => $o) {
9071                                 $this->_newobj();
9072                                 $this->_out('<</Title '.$this->_textstring($o['t']));
9073                                 $this->_out('/Parent '.($n + $o['parent']).' 0 R');
9074                                 if (isset($o['prev']))
9075                                 $this->_out('/Prev '.($n + $o['prev']).' 0 R');
9076                                 if (isset($o['next']))
9077                                 $this->_out('/Next '.($n + $o['next']).' 0 R');
9078                                 if (isset($o['first']))
9079                                 $this->_out('/First '.($n + $o['first']).' 0 R');
9080                                 if (isset($o['last']))
9081                                 $this->_out('/Last '.($n + $o['last']).' 0 R');
9082                                 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $o['p'])), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k))));
9083                                 $this->_out('/Count 0>>');
9084                                 $this->_out('endobj');
9085                         }
9086                         //Outline root
9087                         $this->_newobj();
9088                         $this->OutlineRoot = $this->n;
9089                         $this->_out('<</Type /Outlines /First '.$n.' 0 R');
9090                         $this->_out('/Last '.($n + $lru[0]).' 0 R>>');
9091                         $this->_out('endobj');
9092                 }
9093
9094
9095                 // --- JAVASCRIPT - FORMS ------------------------------
9096
9097                 /*
9098                 * Adds a javascript
9099                 * @access public
9100                 * @author Johannes G�ntert, Nicola Asuni
9101                 * @since 2.1.002 (2008-02-12)
9102                 */
9103                 public function IncludeJS($script) {
9104                         $this->javascript .= $script;
9105                 }
9106
9107                 /*
9108                 * Create a javascript PDF string.
9109                 * @access protected
9110                 * @author Johannes G�ntert, Nicola Asuni
9111                 * @since 2.1.002 (2008-02-12)
9112                 */
9113                 protected function _putjavascript() {
9114                         if (empty($this->javascript)) {
9115                                 return;
9116                         }
9117                         // the following two lines are uded to avoid form fields duplication after saving
9118                         $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
9119                         $js2 = "getField('tcpdfdocsaved').value = 'saved';";
9120                         $this->_newobj();
9121                         $this->n_js = $this->n;
9122                         $this->_out('<<');
9123                         $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
9124                         $this->_out('>>');
9125                         $this->_out('endobj');
9126                         $this->_newobj();
9127                         $this->_out('<<');
9128                         $this->_out('/S /JavaScript');
9129                         $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
9130                         $this->_out('>>');
9131                         $this->_out('endobj');
9132                 }
9133
9134                 /*
9135                 * Convert color to javascript color.
9136                 * @param string $color color name or #RRGGBB
9137                 * @access protected
9138                 * @author Denis Van Nuffelen, Nicola Asuni
9139                 * @since 2.1.002 (2008-02-12)
9140                 */
9141                 protected function _JScolor($color) {
9142                         static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
9143                         if (substr($color,0,1) == '#') {
9144                                 return sprintf("['RGB',%.3F,%.3F,%.3F]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
9145                         }
9146                         if (!in_array($color,$aColors)) {
9147                                 $this->Error('Invalid color: '.$color);
9148                         }
9149                         return 'color.'.$color;
9150                 }
9151
9152                 /*
9153                 * Adds a javascript form field.
9154                 * @param string $type field type
9155                 * @param string $name field name
9156                 * @param int $x horizontal position
9157                 * @param int $y vertical position
9158                 * @param int $w width
9159                 * @param int $h height
9160                 * @param array $prop array of properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9161                 * @access protected
9162                 * @author Denis Van Nuffelen, Nicola Asuni
9163                 * @since 2.1.002 (2008-02-12)
9164                 */
9165                 protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
9166                         if ($this->rtl) {
9167                                 $x = $x - $w;
9168                         }
9169                         // the followind avoid fields duplication after saving the document
9170                         $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
9171                         $k = $this->k;
9172                         $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
9173                         $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
9174                         while (list($key, $val) = each($prop)) {
9175                                 if (strcmp(substr($key, -5), 'Color') == 0) {
9176                                         $val = $this->_JScolor($val);
9177                                 } else {
9178                                         $val = "'".$val."'";
9179                                 }
9180                                 $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
9181                         }
9182                         if ($this->rtl) {
9183                                 $this->x -= $w;
9184                         } else {
9185                                 $this->x += $w;
9186                         }
9187                         $this->javascript .= '}';
9188                 }
9189
9190                 /*
9191                 * Creates a text field
9192                 * @param string $name field name
9193                 * @param int $w width
9194                 * @param int $h height
9195                 * @param string $prop properties. The value property allows to set the initial value. The multiline property allows to define the field as multiline. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9196                 * @access public
9197                 * @author Denis Van Nuffelen, Nicola Asuni
9198                 * @since 2.1.002 (2008-02-12)
9199                 */
9200                 public function TextField($name, $w, $h, $prop=array()) {
9201                         $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
9202                 }
9203
9204                 /*
9205                 * Creates a RadioButton field
9206                 * @param string $name field name
9207                 * @param int $w width
9208                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9209                 * @access public
9210                 * @author Nicola Asuni
9211                 * @since 2.2.003 (2008-03-03)
9212                 */
9213                 public function RadioButton($name, $w, $prop=array()) {
9214                         if (!isset($prop['strokeColor'])) {
9215                                 $prop['strokeColor']='black';
9216                         }
9217                         $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
9218                 }
9219
9220                 /*
9221                 * Creates a List-box field
9222                 * @param string $name field name
9223                 * @param int $w width
9224                 * @param int $h height
9225                 * @param array $values array containing the list of values.
9226                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9227                 * @access public
9228                 * @author Nicola Asuni
9229                 * @since 2.2.003 (2008-03-03)
9230                 */
9231                 public function ListBox($name, $w, $h, $values, $prop=array()) {
9232                         if (!isset($prop['strokeColor'])) {
9233                                 $prop['strokeColor'] = 'ltGray';
9234                         }
9235                         $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
9236                         $s = '';
9237                         foreach ($values as $value) {
9238                                 $s .= "'".addslashes($value)."',";
9239                         }
9240                         $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
9241                 }
9242
9243                 /*
9244                 * Creates a Combo-box field
9245                 * @param string $name field name
9246                 * @param int $w width
9247                 * @param int $h height
9248                 * @param array $values array containing the list of values.
9249                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9250                 * @access public
9251                 * @author Denis Van Nuffelen, Nicola Asuni
9252                 * @since 2.1.002 (2008-02-12)
9253                 */
9254                 public function ComboBox($name, $w, $h, $values, $prop=array()) {
9255                         $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
9256                         $s = '';
9257                         foreach ($values as $value) {
9258                                 $s .= "'".addslashes($value)."',";
9259                         }
9260                         $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
9261                 }
9262
9263                 /*
9264                 * Creates a CheckBox field
9265                 * @param string $name field name
9266                 * @param int $w width
9267                 * @param boolean $checked define the initial state (default = false).
9268                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9269                 * @access public
9270                 * @author Denis Van Nuffelen, Nicola Asuni
9271                 * @since 2.1.002 (2008-02-12)
9272                 */
9273                 public function CheckBox($name, $w, $checked=false, $prop=array()) {
9274                         $prop['value'] = ($checked ? 'Yes' : 'Off');
9275                         if (!isset($prop['strokeColor'])) {
9276                                 $prop['strokeColor'] = 'black';
9277                         }
9278                         $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
9279                 }
9280
9281                 /*
9282                 * Creates a button field
9283                 * @param string $name field name
9284                 * @param int $w width
9285                 * @param int $h height
9286                 * @param string $caption caption.
9287                 * @param string $action action triggered by the button (JavaScript code).
9288                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9289                 * @access public
9290                 * @author Denis Van Nuffelen, Nicola Asuni
9291                 * @since 2.1.002 (2008-02-12)
9292                 */
9293                 public function Button($name, $w, $h, $caption, $action, $prop=array()) {
9294                         if (!isset($prop['strokeColor'])) {
9295                                 $prop['strokeColor'] = 'black';
9296                         }
9297                         if (!isset($prop['borderStyle'])) {
9298                                 $prop['borderStyle'] = 'beveled';
9299                         }
9300                         $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
9301                         $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
9302                         $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
9303                         $this->javascript .= 'f'.$name.".highlight='push';\n";
9304                         $this->javascript .= 'f'.$name.".print=false;\n";
9305                 }
9306
9307                 // END JAVASCRIPT - FORMS ------------------------------
9308
9309                 /*
9310                 * Enable Write permissions for PDF Reader.
9311                 * WARNING: This works only using the Adobe private key with the setSignature() method.
9312                 * @access protected
9313                 * @author Nicola Asuni
9314                 * @since 2.9.000 (2008-03-26)
9315                 */
9316                 protected function _putuserrights() {
9317                         if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] > 0))) {
9318                                 return;
9319                         }
9320                         $this->_out('/Perms');
9321                         $this->_out('<<');
9322                         $this->_out('/UR3');
9323                         $this->_out('<<');
9324                         $this->_out('/Type/Sig');
9325                         $this->_out('/Filter/Adobe.PPKLite');
9326                         $this->_out('/SubFilter/adbe.pkcs7.detached');
9327                         $this->_out('/ByteRange[0 ********** ********** **********]');
9328                         $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
9329                         if ($this->ur) {
9330                                 $this->_out('/Reference');
9331                                 $this->_out('[');
9332                                 $this->_out('<<');
9333                                 $this->_out('/Type/SigRef');
9334                                 $this->_out('/TransformMethod/UR3');
9335                                 $this->_out('/TransformParams');
9336                                 $this->_out('<<');
9337                                 $this->_out('/Type/TransformParams');
9338                                 $this->_out('/V/2.2');
9339                                 if (!$this->empty_string($this->ur_document)) {
9340                                         $this->_out('/Document['.$this->ur_document.']');
9341                                 }
9342                                 if (!$this->empty_string($this->ur_annots)) {
9343                                         $this->_out('/Annots['.$this->ur_annots.']');
9344                                 }
9345                                 if (!$this->empty_string($this->ur_form)) {
9346                                         $this->_out('/Form['.$this->ur_form.']');
9347                                 }
9348                                 if (!$this->empty_string($this->ur_signature)) {
9349                                         $this->_out('/Signature['.$this->ur_signature.']');
9350                                 }
9351                                 $this->_out('>>');
9352                                 $this->_out('>>');
9353                                 $this->_out(']');
9354                         }
9355                         $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
9356                         $this->_out('>>');
9357                         $this->_out('>>');
9358                 }
9359
9360                 /*
9361                 * Add certification signature (DocMDP)
9362                 * @access protected
9363                 * @author Nicola Asuni
9364                 * @since 4.6.008 (2009-05-07)
9365                 */
9366                 protected function _putcertification() {
9367                         if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] <= 0))) {
9368                                 return;
9369                         }
9370                         $this->_out('/Perms');
9371                         $this->_out('<<');
9372                         $this->_out('/DocMDP');
9373                         $this->_out('<<');
9374                         $this->_out('/Type/Sig');
9375                         $this->_out('/Filter/Adobe.PPKLite');
9376                         $this->_out('/SubFilter/adbe.pkcs7.detached');
9377                         $this->_out('/ByteRange[0 ********** ********** **********]');
9378                         $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
9379                         $this->_out('/Reference');
9380                         $this->_out('[');
9381                         $this->_out('<<');
9382                         $this->_out('/Type/SigRef');
9383                         $this->_out('/TransformMethod/DocMDP');
9384                         $this->_out('/TransformParams');
9385                         $this->_out('<<');
9386                         $this->_out('/Type/TransformParams');
9387                         $this->_out('/V/1.2');
9388                         $this->_out('/P '.$this->signature_data['cert_type'].'');
9389                         $this->_out('>>');
9390                         $this->_out('>>');
9391                         $this->_out(']');
9392                         $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
9393                         if (isset($this->signature_data['info']['Name']) AND !$this->empty_string($this->signature_data['info']['Name'])) {
9394                                 $this->_out('/Name '.$this->_textstring($this->signature_data['info']['Name']).'');
9395                         }
9396                         if (isset($this->signature_data['info']['Location']) AND !$this->empty_string($this->signature_data['info']['Location'])) {
9397                                 $this->_out('/Location '.$this->_textstring($this->signature_data['info']['Location']).'');
9398                         }
9399                         if (isset($this->signature_data['info']['Reason']) AND !$this->empty_string($this->signature_data['info']['Reason'])) {
9400                                 $this->_out('/Reason '.$this->_textstring($this->signature_data['info']['Reason']).'');
9401                         }
9402                         if (isset($this->signature_data['info']['ContactInfo']) AND !$this->empty_string($this->signature_data['info']['ContactInfo'])) {
9403                                 $this->_out('/ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo']).'');
9404                         }
9405                         $this->_out('>>');
9406                         $this->_out('>>');
9407                 }
9408
9409                 /*
9410                 * Set User's Rights for PDF Reader
9411                 * WARNING: This works only using the Adobe private key with the setSignature() method!.
9412                 * Check the PDF Reference 8.7.1 Transform Methods,
9413                 * Table 8.105 Entries in the UR transform parameters dictionary
9414                 * @param boolean $enable if true enable user's rights on PDF reader
9415                 * @param string $document Names specifying additional document-wide usage rights for the document. The only defined value is "/FullSave", which permits a user to save the document along with modified form and/or annotation data.
9416                 * @param string $annots Names specifying additional annotation-related usage rights for the document. Valid names in PDF 1.5 and later are /Create/Delete/Modify/Copy/Import/Export, which permit the user to perform the named operation on annotations.
9417                 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
9418                 * @param string $signature Names specifying additional signature-related usage rights for the document. The only defined value is /Modify, which permits a user to apply a digital signature to an existing signature form field or clear a signed signature form field.
9419                 * @access public
9420                 * @author Nicola Asuni
9421                 * @since 2.9.000 (2008-03-26)
9422                 */
9423                 public function setUserRights(
9424                                 $enable=true,
9425                                 $document='/FullSave',
9426                                 $annots='/Create/Delete/Modify/Copy/Import/Export',
9427                                 $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
9428                                 $signature='/Modify') {
9429                         $this->ur = $enable;
9430                         $this->ur_document = $document;
9431                         $this->ur_annots = $annots;
9432                         $this->ur_form = $form;
9433                         $this->ur_signature = $signature;
9434                 }
9435
9436                 /*
9437                 * Enable document signature (requires the OpenSSL Library).
9438                 * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
9439                 * @param mixed $signing_cert signing certificate (string or filename prefixed with 'file://')
9440                 * @param mixed $private_key private key (string or filename prefixed with 'file://')
9441                 * @param string $private_key_password password
9442                 * @param string $extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.
9443                 * @param int $cert_type The access permissions granted for this document. Valid values shall be: 1 = No changes to the document shall be permitted; any change to the document shall invalidate the signature; 2 = Permitted changes shall be filling in forms, instantiating page templates, and signing; other changes shall invalidate the signature; 3 = Permitted changes shall be the same as for 2, as well as annotation creation, deletion, and modification; other changes shall invalidate the signature.
9444                 * @parm array $info array of option information: Name, Location, Reason, ContactInfo.
9445                 * @access public
9446                 * @author Nicola Asuni
9447                 * @since 4.6.005 (2009-04-24)
9448                 */
9449                 public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array()) {
9450                         // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.pem -out tcpdf.pem
9451                         $this->sign = true;
9452                         $this->signature_data = array();
9453                         if (strlen($signing_cert) == 0) {
9454                                 $signing_cert = 'file://'.dirname(__FILE__).'/tcpdf.pem';
9455                         }
9456                         if (strlen($private_key) == 0) {
9457                                 $private_key = $signing_cert;
9458                         }
9459                         $this->signature_data['signcert'] = $signing_cert;
9460                         $this->signature_data['privkey'] = $private_key;
9461                         $this->signature_data['password'] = $private_key_password;
9462                         $this->signature_data['extracerts'] = $extracerts;
9463                         $this->signature_data['cert_type'] = $cert_type;
9464                         $this->signature_data['info'] = array();
9465                 }
9466
9467                 /*
9468                 * Create a new page group.
9469                 * NOTE: call this function before calling AddPage()
9470                 * @param int $page starting group page (leave empty for next page).
9471                 * @access public
9472                 * @since 3.0.000 (2008-03-27)
9473                 */
9474                 public function startPageGroup($page='') {
9475                         if (empty($page)) {
9476                                 $page = $this->page + 1;
9477                         }
9478                         $this->newpagegroup[$page] = true;
9479                 }
9480
9481                 /**
9482                 * Defines an alias for the total number of pages.
9483                 * It will be substituted as the document is closed.
9484                 * @param string $alias The alias.
9485                 * @access public
9486                 * @since 1.4
9487                 * @see getAliasNbPages(), PageNo(), Footer()
9488                 */
9489                 public function AliasNbPages($alias='{nb}') {
9490                         $this->AliasNbPages = $alias;
9491                 }
9492
9493                 /**
9494                  * Returns the string alias used for the total number of pages.
9495          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9496                  * @return string
9497                  * @access public
9498                  * @since 4.0.018 (2008-08-08)
9499                  * @see AliasNbPages(), PageNo(), Footer()
9500                 */
9501                 public function getAliasNbPages() {
9502                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9503                                 return '{'.$this->AliasNbPages.'}';
9504             }
9505                         return $this->AliasNbPages;
9506                 }
9507
9508                 /**
9509                 * Defines an alias for the page number.
9510                 * It will be substituted as the document is closed.
9511                 * @param string $alias The alias.
9512                 * @access public
9513                 * @since 4.5.000 (2009-01-02)
9514                 * @see getAliasNbPages(), PageNo(), Footer()
9515                 */
9516                 public function AliasNumPage($alias='{pnb}') {
9517                         //Define an alias for total number of pages
9518                         $this->AliasNumPage = $alias;
9519                 }
9520
9521                 /**
9522                  * Returns the string alias used for the page number.
9523          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9524                  * @return string
9525                  * @access public
9526                  * @since 4.5.000 (2009-01-02)
9527                  * @see AliasNbPages(), PageNo(), Footer()
9528                 */
9529                 public function getAliasNumPage() {
9530                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9531                                 return '{'.$this->AliasNumPage.'}';
9532             }
9533                         return $this->AliasNumPage;
9534                 }
9535
9536                 /*
9537                 * Return the current page in the group.
9538                 * @return current page in the group
9539                 * @access public
9540                 * @since 3.0.000 (2008-03-27)
9541                 */
9542                 public function getGroupPageNo() {
9543                         return $this->pagegroups[$this->currpagegroup];
9544                 }
9545
9546                 /**
9547                 * Returns the current group page number formatted as a string.
9548                 * @access public
9549                 * @since 4.3.003 (2008-11-18)
9550                 * @see PaneNo(), formatPageNumber()
9551                 */
9552                 public function getGroupPageNoFormatted() {
9553                         return $this->formatPageNumber($this->getGroupPageNo());
9554         }
9555
9556                 /*
9557                  * Return the alias of the current page group
9558          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9559                  * (will be replaced by the total number of pages in this group).
9560                  * @return alias of the current page group
9561                  * @access public
9562                  * @since 3.0.000 (2008-03-27)
9563                 */
9564                 public function getPageGroupAlias() {
9565                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9566                                 return '{'.$this->currpagegroup.'}';
9567             }
9568                         return $this->currpagegroup;
9569                 }
9570
9571                 /*
9572                  * Return the alias for the page number on the current page group
9573          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9574                  * (will be replaced by the total number of pages in this group).
9575                  * @return alias of the current page group
9576                  * @access public
9577                  * @since 4.5.000 (2009-01-02)
9578                 */
9579                 public function getPageNumGroupAlias() {
9580                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9581                                 return '{'.str_replace('{nb', '{pnb', $this->currpagegroup).'}';
9582             }
9583                         return str_replace('{nb', '{pnb', $this->currpagegroup);
9584                 }
9585
9586                 /**
9587                 * Format the page numbers.
9588                 * This method can be overriden for custom formats.
9589                 * @param int $num page number
9590                 * @access protected
9591                 * @since 4.2.005 (2008-11-06)
9592                 */
9593                 protected function formatPageNumber($num) {
9594                         return number_format((float)$num, 0, '', '.');
9595                 }
9596
9597                 /**
9598                 * Format the page numbers on the Table Of Content.
9599                 * This method can be overriden for custom formats.
9600                 * @param int $num page number
9601                 * @access protected
9602                 * @since 4.5.001 (2009-01-04)
9603                 * @see addTOC()
9604                 */
9605                 protected function formatTOCPageNumber($num) {
9606                         return number_format((float)$num, 0, '', '.');
9607                 }
9608
9609         /**
9610                 * Returns the current page number formatted as a string.
9611                 * @access public
9612                 * @since 4.2.005 (2008-11-06)
9613                 * @see PaneNo(), formatPageNumber()
9614                 */
9615                 public function PageNoFormatted() {
9616                         return $this->formatPageNumber($this->PageNo());
9617         }
9618
9619         /*
9620                 * Put visibility settings.
9621                 * @access protected
9622                 * @since 3.0.000 (2008-03-27)
9623                 */
9624                 protected function _putocg() {
9625                         $this->_newobj();
9626                         $this->n_ocg_print = $this->n;
9627                         $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
9628                         $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
9629                         $this->_out('endobj');
9630                         $this->_newobj();
9631                         $this->n_ocg_view=$this->n;
9632                         $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
9633                         $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
9634                         $this->_out('endobj');
9635                 }
9636
9637                 /*
9638                 * Set the visibility of the successive elements.
9639                 * This can be useful, for instance, to put a background
9640                 * image or color that will show on screen but won't print.
9641                 * @param string $v visibility mode. Legal values are: all, print, screen.
9642                 * @access public
9643                 * @since 3.0.000 (2008-03-27)
9644                 */
9645                 public function setVisibility($v) {
9646                         if ($this->openMarkedContent) {
9647                                 // close existing open marked-content
9648                                 $this->_out('EMC');
9649                                 $this->openMarkedContent = false;
9650                         }
9651                         switch($v) {
9652                                 case 'print': {
9653                                         $this->_out('/OC /OC1 BDC');
9654                                         $this->openMarkedContent = true;
9655                                         break;
9656                                 }
9657                                 case 'screen': {
9658                                         $this->_out('/OC /OC2 BDC');
9659                                         $this->openMarkedContent = true;
9660                                         break;
9661                                 }
9662                                 case 'all': {
9663                                         $this->_out('');
9664                                         break;
9665                                 }
9666                                 default: {
9667                                         $this->Error('Incorrect visibility: '.$v);
9668                                         break;
9669                                 }
9670                         }
9671                         $this->visibility = $v;
9672                 }
9673
9674                 /*
9675                 * Add transparency parameters to the current extgstate
9676                 * @param array $params parameters
9677                 * @return the number of extgstates
9678                 * @access protected
9679                 * @since 3.0.000 (2008-03-27)
9680                 */
9681                 protected function addExtGState($parms) {
9682                         $n = count($this->extgstates) + 1;
9683                         $this->extgstates[$n]['parms'] = $parms;
9684                         return $n;
9685                 }
9686
9687                 /*
9688                 * Add an extgstate
9689                 * @param array $gs extgstate
9690                 * @access protected
9691                 * @since 3.0.000 (2008-03-27)
9692                 */
9693                 protected function setExtGState($gs) {
9694                         $this->_out(sprintf('/GS%d gs', $gs));
9695                 }
9696
9697                 /*
9698                 * Put extgstates for object transparency
9699                 * @param array $gs extgstate
9700                 * @access protected
9701                 * @since 3.0.000 (2008-03-27)
9702                 */
9703                 protected function _putextgstates() {
9704                         $ne = count($this->extgstates);
9705                         for ($i = 1; $i <= $ne; ++$i) {
9706                                 $this->_newobj();
9707                                 $this->extgstates[$i]['n'] = $this->n;
9708                                 $this->_out('<</Type /ExtGState');
9709                                 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
9710                                         $this->_out('/'.$k.' '.$v);
9711                                 }
9712                                 $this->_out('>>');
9713                                 $this->_out('endobj');
9714                         }
9715                 }
9716
9717                 /*
9718                 * Set alpha for stroking (CA) and non-stroking (ca) operations.
9719                 * @param float $alpha real value from 0 (transparent) to 1 (opaque)
9720                 * @param string $bm blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
9721                 * @access public
9722                 * @since 3.0.000 (2008-03-27)
9723                 */
9724                 public function setAlpha($alpha, $bm='Normal') {
9725                         $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
9726                         $this->setExtGState($gs);
9727                 }
9728
9729                 /*
9730                 * Set the default JPEG compression quality (1-100)
9731                 * @param int $quality JPEG quality, integer between 1 and 100
9732                 * @access public
9733                 * @since 3.0.000 (2008-03-27)
9734                 */
9735                 public function setJPEGQuality($quality) {
9736                         if (($quality < 1) OR ($quality > 100)) {
9737                                 $quality = 75;
9738                         }
9739                         $this->jpeg_quality = intval($quality);
9740                 }
9741
9742                 /*
9743                 * Set the default number of columns in a row for HTML tables.
9744                 * @param int $cols number of columns
9745                 * @access public
9746                 * @since 3.0.014 (2008-06-04)
9747                 */
9748                 public function setDefaultTableColumns($cols=4) {
9749                         $this->default_table_columns = intval($cols);
9750                 }
9751
9752                 /*
9753                 * Set the height of cell repect font height.
9754                 * @param int $h cell proportion respect font height (typical value = 1.25).
9755                 * @access public
9756                 * @since 3.0.014 (2008-06-04)
9757                 */
9758                 public function setCellHeightRatio($h) {
9759                         $this->cell_height_ratio = $h;
9760                 }
9761
9762                 /*
9763                 * return the height of cell repect font height.
9764                 * @access public
9765                 * @since 4.0.012 (2008-07-24)
9766                 */
9767                 public function getCellHeightRatio() {
9768                         return $this->cell_height_ratio;
9769                 }
9770
9771                 /*
9772                 * Set the PDF version (check PDF reference for valid values).
9773                 * Default value is 1.t
9774                 * @access public
9775                 * @since 3.1.000 (2008-06-09)
9776                 */
9777                 public function setPDFVersion($version='1.7') {
9778                         $this->PDFVersion = $version;
9779                 }
9780
9781                 /*
9782                 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
9783                 * (see Section 8.1 of PDF reference, "Viewer Preferences").
9784                 * <ul>
9785                 * <li>HideToolbar boolean (Optional) A flag specifying whether to hide the viewer application's tool bars when the document is active. Default value: false.</li>
9786                 * <li>HideMenubar boolean (Optional) A flag specifying whether to hide the viewer application's menu bar when the document is active. Default value: false.</li>
9787                 * <li>HideWindowUI boolean (Optional) A flag specifying whether to hide user interface elements in the document's window (such as scroll bars and navigation controls), leaving only the document's contents displayed. Default value: false.</li>
9788                 * <li>FitWindow boolean (Optional) A flag specifying whether to resize the document's window to fit the size of the first displayed page. Default value: false.</li>
9789                 * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
9790                 * <li>DisplayDocTitle boolean (Optional; PDF 1.4) A flag specifying whether the window's title bar should display the document title taken from the Title entry of the document information dictionary (see Section 10.2.1, "Document Information Dictionary"). If false, the title bar should instead display the name of the PDF file containing the document. Default value: false.</li>
9791                 * <li>NonFullScreenPageMode name (Optional) The document's page mode, specifying how to display the document on exiting full-screen mode:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>UseOC Optional content group panel visible</li><ul>This entry is meaningful only if the value of the PageMode entry in the catalog dictionary (see Section 3.6.1, "Document Catalog") is FullScreen; it is ignored otherwise. Default value: UseNone.</li>
9792                 * <li>ViewArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be displayed when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9793                 * <li>ViewClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9794                 * <li>PrintArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be rendered when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9795                 * <li>PrintClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9796                 * <li>PrintScaling name (Optional; PDF 1.6) The page scaling option to be selected when a print dialog is displayed for this document. Valid values are: <ul><li>None, which indicates that the print dialog should reflect no page scaling</li><li>AppDefault (default), which indicates that applications should use the current print scaling</li><ul></li>
9797                 * <li>Duplex name (Optional; PDF 1.7) The paper handling option to use when printing the file from the print dialog. The following values are valid:<ul><li>Simplex - Print single-sided</li><li>DuplexFlipShortEdge - Duplex and flip on the short edge of the sheet</li><li>DuplexFlipLongEdge - Duplex and flip on the long edge of the sheet</li></ul>Default value: none</li>
9798                 * <li>PickTrayByPDFSize boolean (Optional; PDF 1.7) A flag specifying whether the PDF page size is used to select the input paper tray. This setting influences only the preset values used to populate the print dialog presented by a PDF viewer application. If PickTrayByPDFSize is true, the check box in the print dialog associated with input paper tray is checked. Note: This setting has no effect on Mac OS systems, which do not provide the ability to pick the input tray by size.</li>
9799                 * <li>PrintPageRange array (Optional; PDF 1.7) The page numbers used to initialize the print dialog box when the file is printed. The first page of the PDF file is denoted by 1. Each pair consists of the first and last pages in the sub-range. An odd number of integers causes this entry to be ignored. Negative numbers cause the entire array to be ignored. Default value: as defined by PDF viewer application</li>
9800                 * <li>NumCopies integer (Optional; PDF 1.7) The number of copies to be printed when the print dialog is opened for this file. Supported values are the integers 2 through 5. Values outside this range are ignored. Default value: as defined by PDF viewer application, but typically 1</li>
9801                 * </ul>
9802                 * @param array $preferences array of options.
9803                 * @author Nicola Asuni
9804                 * @access public
9805                 * @since 3.1.000 (2008-06-09)
9806                 */
9807                 public function setViewerPreferences($preferences) {
9808                         $this->viewer_preferences = $preferences;
9809                 }
9810
9811                 /**
9812                 * Paints a linear colour gradient.
9813                 * @param float $x abscissa of the top left corner of the rectangle.
9814                 * @param float $y ordinate of the top left corner of the rectangle.
9815                 * @param float $w width of the rectangle.
9816                 * @param float $h height of the rectangle.
9817                 * @param array $col1 first color (RGB components).
9818                 * @param array $col2 second color (RGB components).
9819                 * @param array $coords array of the form (x1, y1, x2, y2) which defines the gradient vector (see linear_gradient_coords.jpg). The default value is from left to right (x1=0, y1=0, x2=1, y2=0).
9820                 * @author Andreas W�rmser, Nicola Asuni
9821                 * @since 3.1.000 (2008-06-09)
9822                 * @access public
9823                 */
9824                 public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
9825                         $this->Clip($x, $y, $w, $h);
9826                         $this->Gradient(2, $col1, $col2, $coords);
9827                 }
9828
9829                 /**
9830                 * Paints a radial colour gradient.
9831                 * @param float $x abscissa of the top left corner of the rectangle.
9832                 * @param float $y ordinate of the top left corner of the rectangle.
9833                 * @param float $w width of the rectangle.
9834                 * @param float $h height of the rectangle.
9835                 * @param array $col1 first color (RGB components).
9836                 * @param array $col2 second color (RGB components).
9837                 * @param array $coords array of the form (fx, fy, cx, cy, r) where (fx, fy) is the starting point of the gradient with color1, (cx, cy) is the center of the circle with color2, and r is the radius of the circle (see radial_gradient_coords.jpg). (fx, fy) should be inside the circle, otherwise some areas will not be defined.
9838                 * @author Andreas W�rmser, Nicola Asuni
9839                 * @since 3.1.000 (2008-06-09)
9840                 * @access public
9841                 */
9842                 public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
9843                         $this->Clip($x, $y, $w, $h);
9844                         $this->Gradient(3, $col1, $col2, $coords);
9845                 }
9846
9847                 /**
9848                 * Paints a coons patch mesh.
9849                 * @param float $x abscissa of the top left corner of the rectangle.
9850                 * @param float $y ordinate of the top left corner of the rectangle.
9851                 * @param float $w width of the rectangle.
9852                 * @param float $h height of the rectangle.
9853                 * @param array $col1 first color (lower left corner) (RGB components).
9854                 * @param array $col2 second color (lower right corner) (RGB components).
9855                 * @param array $col3 third color (upper right corner) (RGB components).
9856                 * @param array $col4 fourth color (upper left corner) (RGB components).
9857                 * @param array $coords <ul><li>for one patch mesh: array(float x1, float y1, .... float x12, float y12): 12 pairs of coordinates (normally from 0 to 1) which specify the Bezier control points that define the patch. First pair is the lower left edge point, next is its right control point (control point 2). Then the other points are defined in the order: control point 1, edge point, control point 2 going counter-clockwise around the patch. Last (x12, y12) is the first edge point's left control point (control point 1).</li><li>for two or more patch meshes: array[number of patches]: arrays with the following keys for each patch: f: where to put that patch (0 = first patch, 1, 2, 3 = right, top and left of precedent patch - I didn't figure this out completely - just try and error ;-) points: 12 pairs of coordinates of the Bezier control points as above for the first patch, 8 pairs of coordinates for the following patches, ignoring the coordinates already defined by the precedent patch (I also didn't figure out the order of these - also: try and see what's happening) colors: must be 4 colors for the first patch, 2 colors for the following patches</li></ul>
9858                 * @param array $coords_min minimum value used by the coordinates. If a coordinate's value is smaller than this it will be cut to coords_min. default: 0
9859                 * @param array $coords_max maximum value used by the coordinates. If a coordinate's value is greater than this it will be cut to coords_max. default: 1
9860                 * @author Andreas W�rmser, Nicola Asuni
9861                 * @since 3.1.000 (2008-06-09)
9862                 * @access public
9863                 */
9864                 public function CoonsPatchMesh($x, $y, $w, $h, $col1=array(), $col2=array(), $col3=array(), $col4=array(), $coords=array(0.00,0.0,0.33,0.00,0.67,0.00,1.00,0.00,1.00,0.33,1.00,0.67,1.00,1.00,0.67,1.00,0.33,1.00,0.00,1.00,0.00,0.67,0.00,0.33), $coords_min=0, $coords_max=1) {
9865                         $this->Clip($x, $y, $w, $h);
9866                         $n = count($this->gradients) + 1;
9867                         $this->gradients[$n]['type'] = 6; //coons patch mesh
9868                         //check the coords array if it is the simple array or the multi patch array
9869                         if (!isset($coords[0]['f'])) {
9870                                 //simple array -> convert to multi patch array
9871                                 if (!isset($col1[1])) {
9872                                         $col1[1] = $col1[2] = $col1[0];
9873                                 }
9874                                 if (!isset($col2[1])) {
9875                                         $col2[1] = $col2[2] = $col2[0];
9876                                 }
9877                                 if (!isset($col3[1])) {
9878                                         $col3[1] = $col3[2] = $col3[0];
9879                                 }
9880                                 if (!isset($col4[1])) {
9881                                         $col4[1] = $col4[2] = $col4[0];
9882                                 }
9883                                 $patch_array[0]['f'] = 0;
9884                                 $patch_array[0]['points'] = $coords;
9885                                 $patch_array[0]['colors'][0]['r'] = $col1[0];
9886                                 $patch_array[0]['colors'][0]['g'] = $col1[1];
9887                                 $patch_array[0]['colors'][0]['b'] = $col1[2];
9888                                 $patch_array[0]['colors'][1]['r'] = $col2[0];
9889                                 $patch_array[0]['colors'][1]['g'] = $col2[1];
9890                                 $patch_array[0]['colors'][1]['b'] = $col2[2];
9891                                 $patch_array[0]['colors'][2]['r'] = $col3[0];
9892                                 $patch_array[0]['colors'][2]['g'] = $col3[1];
9893                                 $patch_array[0]['colors'][2]['b'] = $col3[2];
9894                                 $patch_array[0]['colors'][3]['r'] = $col4[0];
9895                                 $patch_array[0]['colors'][3]['g'] = $col4[1];
9896                                 $patch_array[0]['colors'][3]['b'] = $col4[2];
9897                         } else {
9898                                 //multi patch array
9899                                 $patch_array = $coords;
9900                         }
9901                         $bpcd = 65535; //16 BitsPerCoordinate
9902                         //build the data stream
9903                         $this->gradients[$n]['stream'] = '';
9904                         $count_patch = count($patch_array);
9905                         for ($i=0; $i < $count_patch; ++$i) {
9906                                 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
9907                                 $count_points = count($patch_array[$i]['points']);
9908                                 for ($j=0; $j < $count_points; ++$j) {
9909                                         //each point as 16 bit
9910                                         $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
9911                                         if ($patch_array[$i]['points'][$j] < 0) {
9912                                                 $patch_array[$i]['points'][$j] = 0;
9913                                         }
9914                                         if ($patch_array[$i]['points'][$j] > $bpcd) {
9915                                                 $patch_array[$i]['points'][$j] = $bpcd;
9916                                         }
9917                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
9918                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
9919                                 }
9920                                 $count_cols = count($patch_array[$i]['colors']);
9921                                 for ($j=0; $j < $count_cols; ++$j) {
9922                                         //each color component as 8 bit
9923                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
9924                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
9925                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
9926                                 }
9927                         }
9928                         //paint the gradient
9929                         $this->_out('/Sh'.$n.' sh');
9930                         //restore previous Graphic State
9931                         $this->_out('Q');
9932                 }
9933
9934                 /**
9935                 * Set a rectangular clipping area.
9936                 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
9937                 * @param float $y ordinate of the top left corner of the rectangle.
9938                 * @param float $w width of the rectangle.
9939                 * @param float $h height of the rectangle.
9940                 * @author Andreas W�rmser, Nicola Asuni
9941                 * @since 3.1.000 (2008-06-09)
9942                 * @access protected
9943                 */
9944                 protected function Clip($x, $y, $w, $h) {
9945                         if ($this->rtl) {
9946                                 $x = $this->w - $x - $w;
9947                         }
9948                         //save current Graphic State
9949                         $s = 'q';
9950                         //set clipping area
9951                         $s .= sprintf(' %.2F %.2F %.2F %.2F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
9952                         //set up transformation matrix for gradient
9953                         $s .= sprintf(' %.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
9954                         $this->_out($s);
9955                 }
9956
9957                 /**
9958                 * Output gradient.
9959                 * @param int $type type of gradient.
9960                 * @param array $col1 first color (RGB components).
9961                 * @param array $col2 second color (RGB components).
9962                 * @param array $coords array of coordinates.
9963                 * @author Andreas W�rmser, Nicola Asuni
9964                 * @since 3.1.000 (2008-06-09)
9965                 * @access protected
9966                 */
9967                 protected function Gradient($type, $col1, $col2, $coords) {
9968                         $n = count($this->gradients) + 1;
9969                         $this->gradients[$n]['type'] = $type;
9970                         if (!isset($col1[1])) {
9971                                 $col1[1]=$col1[2]=$col1[0];
9972                         }
9973                         $this->gradients[$n]['col1'] = sprintf('%.3F %.3F %.3F', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
9974                         if (!isset($col2[1])) {
9975                                 $col2[1] = $col2[2] = $col2[0];
9976                         }
9977                         $this->gradients[$n]['col2'] = sprintf('%.3F %.3F %.3F', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
9978                         $this->gradients[$n]['coords'] = $coords;
9979                         //paint the gradient
9980                         $this->_out('/Sh'.$n.' sh');
9981                         //restore previous Graphic State
9982                         $this->_out('Q');
9983                 }
9984
9985                 /**
9986                 * Output shaders.
9987                 * @author Andreas W�rmser, Nicola Asuni
9988                 * @since 3.1.000 (2008-06-09)
9989                 * @access protected
9990                 */
9991                 function _putshaders() {
9992                         foreach ($this->gradients as $id => $grad) {
9993                                 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
9994                                         $this->_newobj();
9995                                         $this->_out('<<');
9996                                         $this->_out('/FunctionType 2');
9997                                         $this->_out('/Domain [0.0 1.0]');
9998                                         $this->_out('/C0 ['.$grad['col1'].']');
9999                                         $this->_out('/C1 ['.$grad['col2'].']');
10000                                         $this->_out('/N 1');
10001                                         $this->_out('>>');
10002                                         $this->_out('endobj');
10003                                         $f1 = $this->n;
10004                                 }
10005                                 $this->_newobj();
10006                                 $this->_out('<<');
10007                                 $this->_out('/ShadingType '.$grad['type']);
10008                                 $this->_out('/ColorSpace /DeviceRGB');
10009                                 if ($grad['type'] == 2) {
10010                                         $this->_out(sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
10011                                         $this->_out('/Function '.$f1.' 0 R');
10012                                         $this->_out('/Extend [true true] ');
10013                                         $this->_out('>>');
10014                                 } elseif ($grad['type'] == 3) {
10015                                         //x0, y0, r0, x1, y1, r1
10016                                         //at this this time radius of inner circle is 0
10017                                         $this->_out(sprintf('/Coords [%.3F %.3F 0 %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]));
10018                                         $this->_out('/Function '.$f1.' 0 R');
10019                                         $this->_out('/Extend [true true] ');
10020                                         $this->_out('>>');
10021                                 } elseif ($grad['type'] == 6) {
10022                                         $this->_out('/BitsPerCoordinate 16');
10023                                         $this->_out('/BitsPerComponent 8');
10024                                         $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
10025                                         $this->_out('/BitsPerFlag 8');
10026                                         $this->_out('/Length '.strlen($grad['stream']));
10027                                         $this->_out('>>');
10028                                         $this->_putstream($grad['stream']);
10029                                 }
10030                                 $this->_out('endobj');
10031                                 $this->gradients[$id]['id'] = $this->n;
10032                         }
10033                 }
10034
10035                 /**
10036                 * Output an arc
10037                 * @author Maxime Delorme, Nicola Asuni
10038                 * @since 3.1.000 (2008-06-09)
10039                 * @access protected
10040                 */
10041                 protected function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
10042                         $h = $this->h;
10043                         $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c', $x1*$this->k, ($h-$y1)*$this->k, $x2*$this->k, ($h-$y2)*$this->k, $x3*$this->k, ($h-$y3)*$this->k));
10044                 }
10045
10046                 /**
10047                 * Draw the sector of a circle.
10048                 * It can be used for instance to render pie charts.
10049                 * @param float $xc abscissa of the center.
10050                 * @param float $yc ordinate of the center.
10051                 * @param float $r radius.
10052                 * @param float $a start angle (in degrees).
10053                 * @param float $b end angle (in degrees).
10054                 * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
10055                 * @param float $cw: indicates whether to go clockwise (default: true).
10056                 * @param float $o: origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). Default: 90.
10057                 * @author Maxime Delorme, Nicola Asuni
10058                 * @since 3.1.000 (2008-06-09)
10059                 * @access public
10060                 */
10061                 public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
10062                         if ($this->rtl) {
10063                                 $xc = $this->w - $xc;
10064                         }
10065                         if ($cw) {
10066                                 $d = $b;
10067                                 $b = $o - $a;
10068                                 $a = $o - $d;
10069                         } else {
10070                                 $b += $o;
10071                                 $a += $o;
10072                         }
10073                         $a = ($a % 360) + 360;
10074                         $b = ($b % 360) + 360;
10075                         if ($a > $b) {
10076                                 $b +=360;
10077                         }
10078                         $b = $b / 360 * 2 * M_PI;
10079                         $a = $a / 360 * 2 * M_PI;
10080                         $d = $b - $a;
10081                         if ($d == 0 ) {
10082                                 $d = 2 * M_PI;
10083                         }
10084                         $k = $this->k;
10085                         $hp = $this->h;
10086                         if ($style=='F') {
10087                                 $op = 'f';
10088                         } elseif ($style=='FD' or $style=='DF') {
10089                                 $op = 'b';
10090                         } else {
10091                                 $op = 's';
10092                         }
10093                         if (sin($d/2)) {
10094                                 $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
10095                         }
10096                         //first put the center
10097                         $this->_out(sprintf('%.2F %.2F m', ($xc)*$k, ($hp-$yc)*$k));
10098                         //put the first point
10099                         $this->_out(sprintf('%.2F %.2F l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
10100                         //draw the arc
10101                         if ($d < (M_PI/2)) {
10102                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10103                         } else {
10104                                 $b = $a + $d/4;
10105                                 $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
10106                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10107                                 $a = $b;
10108                                 $b = $a + $d/4;
10109                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10110                                 $a = $b;
10111                                 $b = $a + $d/4;
10112                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b) );
10113                                 $a = $b;
10114                                 $b = $a + $d/4;
10115                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10116                         }
10117                         //terminate drawing
10118                         $this->_out($op);
10119                 }
10120
10121                 /**
10122                 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
10123                 * Only vector drawing is supported, not text or bitmap.
10124                 * Although the script was successfully tested with various AI format versions, best results are probably achieved with files that were exported in the AI3 format (tested with Illustrator CS2, Freehand MX and Photoshop CS2).
10125                 * @param string $file Name of the file containing the image.
10126                 * @param float $x Abscissa of the upper-left corner.
10127                 * @param float $y Ordinate of the upper-left corner.
10128                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
10129                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
10130                 * @param mixed $link URL or identifier returned by AddLink().
10131                 * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
10132                 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
10133                 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
10134                 * @param mixed $border Indicates if borders must be drawn around the image. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
10135                 * @author Valentin Schmidt, Nicola Asuni
10136                 * @since 3.1.000 (2008-06-09)
10137                 * @access public
10138                 */
10139                 public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0) {
10140                         if ($x === '') {
10141                                 $x = $this->x;
10142                         }
10143                         if ($y === '') {
10144                                 $y = $this->y;
10145                         }
10146                         $k = $this->k;
10147                         $data = file_get_contents($file);
10148                         if ($data === false) {
10149                                 $this->Error('EPS file not found: '.$file);
10150                         }
10151                         $regs = array();
10152                         // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
10153                         preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
10154                         if (count($regs) > 1) {
10155                                 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
10156                                 if (strpos($version_str, 'Adobe Illustrator') !== false) {
10157                                         $versexp = explode(' ', $version_str);
10158                                         $version = (float)array_pop($versexp);
10159                                         if ($version >= 9) {
10160                                                 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
10161                                         }
10162                                 }
10163                         }
10164                         // strip binary bytes in front of PS-header
10165                         $start = strpos($data, '%!PS-Adobe');
10166                         if ($start > 0) {
10167                                 $data = substr($data, $start);
10168                         }
10169                         // find BoundingBox params
10170                         preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
10171                         if (count($regs) > 1) {
10172                                 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
10173                         } else {
10174                                 $this->Error('No BoundingBox found in EPS file: '.$file);
10175                         }
10176                         $start = strpos($data, '%%EndSetup');
10177                         if ($start === false) {
10178                                 $start = strpos($data, '%%EndProlog');
10179                         }
10180                         if ($start === false) {
10181                                 $start = strpos($data, '%%BoundingBox');
10182                         }
10183                         $data = substr($data, $start);
10184                         $end = strpos($data, '%%PageTrailer');
10185                         if ($end===false) {
10186                                 $end = strpos($data, 'showpage');
10187                         }
10188                         if ($end) {
10189                                 $data = substr($data, 0, $end);
10190                         }
10191                         if ($w > 0) {
10192                                 $scale_x = $w / (($x2 - $x1) / $k);
10193                                 if ($h > 0) {
10194                                         $scale_y = $h / (($y2 - $y1) / $k);
10195                                 } else {
10196                                         $scale_y = $scale_x;
10197                                         $h = ($y2 - $y1) / $k * $scale_y;
10198                                 }
10199                         } else {
10200                                 if ($h > 0) {
10201                                         $scale_y = $h / (($y2 - $y1) / $k);
10202                                         $scale_x = $scale_y;
10203                                         $w = ($x2-$x1) / $k * $scale_x;
10204                                 } else {
10205                                         $w = ($x2 - $x1) / $k;
10206                                         $h = ($y2 - $y1) / $k;
10207                                 }
10208                         }
10209                         // Check whether we need a new page first as this does not fit
10210                         if ($this->checkPageBreak($h, $y)) {
10211                                 $y = $this->GetY() + $this->cMargin;
10212                         }
10213                         // set bottomcoordinates
10214                         $this->img_rb_y = $y + $h;
10215                         // set alignment
10216                         if ($this->rtl) {
10217                                 if ($palign == 'L') {
10218                                         $ximg = $this->lMargin;
10219                                         // set right side coordinate
10220                                         $this->img_rb_x = $ximg + $w;
10221                                 } elseif ($palign == 'C') {
10222                                         $ximg = ($this->w - $x - $w) / 2;
10223                                         // set right side coordinate
10224                                         $this->img_rb_x = $ximg + $w;
10225                                 } else {
10226                                         $ximg = $this->w - $x - $w;
10227                                         // set left side coordinate
10228                                         $this->img_rb_x = $ximg;
10229                                 }
10230                         } else {
10231                                 if ($palign == 'R') {
10232                                         $ximg = $this->w - $this->rMargin - $w;
10233                                         // set left side coordinate
10234                                         $this->img_rb_x = $ximg;
10235                                 } elseif ($palign == 'C') {
10236                                         $ximg = ($this->w - $x - $w) / 2;
10237                                         // set right side coordinate
10238                                         $this->img_rb_x = $ximg + $w;
10239                                 } else {
10240                                         $ximg = $x;
10241                                         // set right side coordinate
10242                                         $this->img_rb_x = $ximg + $w;
10243                                 }
10244                         }
10245                         if ($useBoundingBox) {
10246                                 $dx = $ximg * $k - $x1;
10247                                 $dy = $y * $k - $y1;
10248                         } else {
10249                                 $dx = $ximg * $k;
10250                                 $dy = $y * $k;
10251                         }
10252                         // save the current graphic state
10253                         $this->_out('q'.$this->epsmarker);
10254                         // translate
10255                         $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
10256                         // scale
10257                         if (isset($scale_x)) {
10258                                 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
10259                         }
10260                         // handle pc/unix/mac line endings
10261                         preg_match('/[\r\n]+/s', $data, $regs);
10262                         $lines = explode($regs[0], $data);
10263                         $u=0;
10264                         $cnt = count($lines);
10265                         for ($i=0; $i < $cnt; ++$i) {
10266                                 $line = $lines[$i];
10267                                 if (($line == '') OR ($line{0} == '%')) {
10268                                         continue;
10269                                 }
10270                                 $len = strlen($line);
10271                                 $chunks = explode(' ', $line);
10272                                 $cmd = array_pop($chunks);
10273                                 // RGB
10274                                 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
10275                                         $b = array_pop($chunks);
10276                                         $g = array_pop($chunks);
10277                                         $r = array_pop($chunks);
10278                                         $this->_out(''.$r.' '.$g.' '.$b.' '.($cmd=='Xa'?'rg':'RG')); //substr($line, 0, -2).'rg' -> in EPS (AI8): c m y k r g b rg!
10279                                         continue;
10280                                 }
10281                                 switch ($cmd) {
10282                                         case 'm':
10283                                         case 'l':
10284                                         case 'v':
10285                                         case 'y':
10286                                         case 'c':
10287                                         case 'k':
10288                                         case 'K':
10289                                         case 'g':
10290                                         case 'G':
10291                                         case 's':
10292                                         case 'S':
10293                                         case 'J':
10294                                         case 'j':
10295                                         case 'w':
10296                                         case 'M':
10297                                         case 'd':
10298                                         case 'n':
10299                                         case 'v': {
10300                                                 $this->_out($line);
10301                                                 break;
10302                                         }
10303                                         case 'x': {// custom fill color
10304                                                 list($c,$m,$y,$k) = $chunks;
10305                                                 $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' k');
10306                                                 break;
10307                                         }
10308                                         case 'X': { // custom stroke color
10309                                                 list($c,$m,$y,$k) = $chunks;
10310                                                 $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' K');
10311                                                 break;
10312                                         }
10313                                         case 'Y':
10314                                         case 'N':
10315                                         case 'V':
10316                                         case 'L':
10317                                         case 'C': {
10318                                                 $line{$len-1} = strtolower($cmd);
10319                                                 $this->_out($line);
10320                                                 break;
10321                                         }
10322                                         case 'b':
10323                                         case 'B': {
10324                                                 $this->_out($cmd . '*');
10325                                                 break;
10326                                         }
10327                                         case 'f':
10328                                         case 'F': {
10329                                                 if ($u > 0) {
10330                                                         $isU = false;
10331                                                         $max = min($i+5, $cnt);
10332                                                         for ($j=$i+1; $j < $max; ++$j)
10333                                                           $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
10334                                                         if ($isU) {
10335                                                                 $this->_out('f*');
10336                                                         }
10337                                                 } else {
10338                                                         $this->_out('f*');
10339                                                 }
10340                                                 break;
10341                                         }
10342                                         case '*u': {
10343                                                 ++$u;
10344                                                 break;
10345                                         }
10346                                         case '*U': {
10347                                                 --$u;
10348                                                 break;
10349                                         }
10350                                 }
10351                         }
10352                         // restore previous graphic state
10353                         $this->_out($this->epsmarker.'Q');
10354                         if (!empty($border)) {
10355                                 $bx = $x;
10356                                 $by = $y;
10357                                 $this->x = $x;
10358                                 $this->y = $y;
10359                                 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
10360                                 $this->x = $bx;
10361                                 $this->y = $by;
10362                         }
10363                         if ($link) {
10364                                 $this->Link($ximg, $y, $w, $h, $link, 0);
10365                         }
10366                         // set pointer to align the successive text/objects
10367                         switch($align) {
10368                                 case 'T':{
10369                                         $this->y = $y;
10370                                         $this->x = $this->img_rb_x;
10371                                         break;
10372                                 }
10373                                 case 'M':{
10374                                         $this->y = $y + round($h/2);
10375                                         $this->x = $this->img_rb_x;
10376                                         break;
10377                                 }
10378                                 case 'B':{
10379                                         $this->y = $this->img_rb_y;
10380                                         $this->x = $this->img_rb_x;
10381                                         break;
10382                                 }
10383                                 case 'N':{
10384                                         $this->SetY($this->img_rb_y);
10385                                         break;
10386                                 }
10387                                 default:{
10388                                         break;
10389                                 }
10390                         }
10391                         $this->endlinex = $this->img_rb_x;
10392                 }
10393
10394                 /**
10395                  * Set document barcode.
10396                  * @param string $bc barcode
10397                  * @access public
10398                  */
10399                 public function setBarcode($bc='') {
10400                         $this->barcode = $bc;
10401                 }
10402
10403                 /**
10404                  * Get current barcode.
10405                  * @return string
10406                  * @access public
10407                  * @since 4.0.012 (2008-07-24)
10408                  */
10409                 public function getBarcode() {
10410                         return $this->barcode;
10411                 }
10412
10413                 /**
10414                  * Print a Linear Barcode.
10415                  * @param string $code code to print
10416                  * @param string $type type of barcode.
10417                  * @param int $x x position in user units
10418                  * @param int $y y position in user units
10419                  * @param int $w width in user units
10420                  * @param int $h height in user units
10421                  * @param float $xres width of the smallest bar in user units
10422                  * @param array $style array of options:<ul><li>string $style['position'] barcode position inside the specified width: L = left (default for LTR); C = center; R = right (default for RTL); S = stretch</li><li>boolean $style['border'] if true prints a border around the barcode</li><li>int $style['padding'] padding to leave around the barcode in user units</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background or false for transparent</li><li>boolean $style["text"] boolean if true prints text below the barcode</li><li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li><li>int $style['stretchtext']: 0 = disabled; 1 = horizontal scaling only if necessary; 2 = forced horizontal scaling; 3 = character spacing only if necessary; 4 = forced character spacing</li></ul>
10423                  * @param string $align Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
10424                  * @author Nicola Asuni
10425                  * @since 3.1.000 (2008-06-09)
10426                  * @access public
10427                  */
10428                 public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
10429                         if ($this->empty_string($code)) {
10430                                 return;
10431                         }
10432                         require_once(dirname(__FILE__).'/barcodes.php');
10433                         // save current graphic settings
10434                         $gvars = $this->getGraphicVars();
10435                         // create new barcode object
10436                         $barcodeobj = new TCPDFBarcode($code, $type);
10437                         $arrcode = $barcodeobj->getBarcodeArray();
10438                         if ($arrcode === false) {
10439                                 $this->Error('Error in 1D barcode string');
10440                         }
10441                         // set default values
10442                         if (!isset($style['position'])) {
10443                                 if ($this->rtl) {
10444                                         $style['position'] = 'R';
10445                                 } else {
10446                                         $style['position'] = 'L';
10447                                 }
10448                         }
10449                         if (!isset($style['padding'])) {
10450                                 $style['padding'] = 0;
10451                         }
10452                         if (!isset($style['fgcolor'])) {
10453                                 $style['fgcolor'] = array(0,0,0); // default black
10454                         }
10455                         if (!isset($style['bgcolor'])) {
10456                                 $style['bgcolor'] = false; // default transparent
10457                         }
10458                         if (!isset($style['border'])) {
10459                                 $style['border'] = false;
10460                         }
10461                         if (!isset($style['text'])) {
10462                                 $style['text'] = false;
10463                                 $fontsize = 0;
10464                         }
10465                         if ($style['text'] AND isset($style['font'])) {
10466                                 if (isset($style['fontsize'])) {
10467                                         $fontsize = $style['fontsize'];
10468                                 } else {
10469                                         $fontsize = 0;
10470                                 }
10471                                 $this->SetFont($style['font'], '', $fontsize);
10472                         }
10473                         if (!isset($style['stretchtext'])) {
10474                                 $style['stretchtext'] = 4;
10475                         }
10476                         // set foreground color
10477                         $this->SetDrawColorArray($style['fgcolor']);
10478                         $this->SetTextColorArray($style['fgcolor']);
10479                         if ($this->empty_string($w) OR ($w <= 0)) {
10480                                 if ($this->rtl) {
10481                                         $w = $this->x - $this->lMargin;
10482                                 } else {
10483                                         $w = $this->w - $this->rMargin - $this->x;
10484                                 }
10485                         }
10486                         if ($this->empty_string($x)) {
10487                                 $x = $this->GetX();
10488                         }
10489                         if ($this->rtl) {
10490                                 $x = $this->w - $x;
10491                         }
10492                         if ($this->empty_string($y)) {
10493                                 $y = $this->GetY();
10494                         }
10495                         if ($this->empty_string($xres)) {
10496                                 $xres = 0.4;
10497                         }
10498                         $fbw = ($arrcode['maxw'] * $xres) + (2 * $style['padding']);
10499                         $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style['padding']);
10500                         if ($this->empty_string($h) OR ($h <= 0)) {
10501                                 $h = 10 + $extraspace;
10502                         }
10503                         if ($this->checkPageBreak($h)) {
10504                                 $y = $this->y;
10505                         }
10506                         // maximum bar heigth
10507                         $barh = $h - $extraspace;
10508                         switch ($style['position']) {
10509                                 case 'L': { // left
10510                                         if ($this->rtl) {
10511                                                 $xpos = $x - $w;
10512                                         } else {
10513                                                 $xpos = $x;
10514                                         }
10515                                         break;
10516                                 }
10517                                 case 'C': { // center
10518                                         $xdiff = (($w - $fbw) / 2);
10519                                         if ($this->rtl) {
10520                                                 $xpos = $x - $w + $xdiff;
10521                                         } else {
10522                                                 $xpos = $x + $xdiff;
10523                                         }
10524                                         break;
10525                                 }
10526                                 case 'R': { // right
10527                                         if ($this->rtl) {
10528                                                 $xpos = $x - $fbw;
10529                                         } else {
10530                                                 $xpos = $x + $w - $fbw;
10531                                         }
10532                                         break;
10533                                 }
10534                                 case 'S': { // stretch
10535                                         $fbw = $w;
10536                                         $xres = ($w - (2 * $style['padding'])) / $arrcode['maxw'];
10537                                         if ($this->rtl) {
10538                                                 $xpos = $x - $w;
10539                                         } else {
10540                                                 $xpos = $x;
10541                                         }
10542                                         break;
10543                                 }
10544                         }
10545                         $xpos_rect = $xpos;
10546                         $xpos = $xpos_rect + $style['padding'];
10547                         $xpos_text = $xpos;
10548                         // barcode is always printed in LTR direction
10549                         $tempRTL = $this->rtl;
10550                         $this->rtl = false;
10551                         // print background color
10552                         if ($style['bgcolor']) {
10553                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style['bgcolor']);
10554                         } elseif ($style['border']) {
10555                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
10556                         }
10557                         // print bars
10558                         if ($arrcode !== false) {
10559                                 foreach ($arrcode['bcode'] as $k => $v) {
10560                                         $bw = ($v['w'] * $xres);
10561                                         if ($v['t']) {
10562                                                 // draw a vertical bar
10563                                                 $ypos = $y + $style['padding'] + ($v['p'] * $barh / $arrcode['maxh']);
10564                                                 $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh  / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
10565                                         }
10566                                         $xpos += $bw;
10567                                 }
10568                         }
10569                         // print text
10570                         if ($style['text']) {
10571                                 // print text
10572                                 $this->x = $xpos_text;
10573                                 $this->y = $y + $style['padding'] + $barh;
10574                                 $this->Cell(($arrcode['maxw'] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style['stretchtext']);
10575                         }
10576                         // restore original direction
10577                         $this->rtl = $tempRTL;
10578                         // restore previous settings
10579                         $this->setGraphicVars($gvars);
10580                         // set bottomcoordinates
10581                         $this->img_rb_y = $y + $h;
10582                         if ($this->rtl) {
10583                                 // set left side coordinate
10584                                 $this->img_rb_x = ($this->w - $x - $w);
10585                         } else {
10586                                 // set right side coordinate
10587                                 $this->img_rb_x = $x + $w;
10588                         }
10589                         // set pointer to align the successive text/objects
10590                         switch($align) {
10591                                 case 'T':{
10592                                         $this->y = $y;
10593                                         $this->x = $this->img_rb_x;
10594                                         break;
10595                                 }
10596                                 case 'M':{
10597                                         $this->y = $y + round($h/2);
10598                                         $this->x = $this->img_rb_x;
10599                                         break;
10600                                 }
10601                                 case 'B':{
10602                                         $this->y = $this->img_rb_y;
10603                                         $this->x = $this->img_rb_x;
10604                                         break;
10605                                 }
10606                                 case 'N':{
10607                                         $this->SetY($this->img_rb_y);
10608                                         break;
10609                                 }
10610                                 default:{
10611                                         break;
10612                                 }
10613                         }
10614                 }
10615
10616                 /**
10617                  * This function is DEPRECATED, please use the new write1DBarcode() function.
10618                  * @param int $x x position in user units
10619                  * @param int $y y position in user units
10620                  * @param int $w width in user units
10621                  * @param int $h height position in user units
10622                  * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
10623                  * @param string $style barcode style
10624                  * @param string $font font for text
10625                  * @param int $xres x resolution
10626                  * @param string $code code to print
10627                  * @deprecated deprecated since version 3.1.000 (2008-06-10)
10628                  * @access public
10629                  * @see write1DBarcode()
10630                  */
10631                 public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
10632                         // convert old settings for the new write1DBarcode() function.
10633                         $xres = 1 / $xres;
10634                         $newstyle = array(
10635                                 'position' => 'L',
10636                                 'border' => false,
10637                                 'padding' => 0,
10638                                 'fgcolor' => array(0,0,0),
10639                                 'bgcolor' => false,
10640                                 'text' => true,
10641                                 'font' => $font,
10642                                 'fontsize' => 8,
10643                                 'stretchtext' => 4
10644                         );
10645                         if ($style & 1) {
10646                                 $newstyle['border'] = true;
10647                         }
10648                         if ($style & 2) {
10649                                 $newstyle['bgcolor'] = false;
10650                         }
10651                         if ($style & 4) {
10652                                 $newstyle['position'] = 'C';
10653                         } elseif ($style & 8) {
10654                                 $newstyle['position'] = 'L';
10655                         } elseif ($style & 16) {
10656                                 $newstyle['position'] = 'R';
10657                         }
10658                         if ($style & 128) {
10659                                 $newstyle['text'] = true;
10660                         }
10661                         if ($style & 256) {
10662                                 $newstyle['stretchtext'] = 4;
10663                         }
10664                         $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
10665                 }
10666
10667                 /**
10668                  * Print 2D Barcode.
10669                  * @param string $code code to print
10670                  * @param string $type type of barcode.
10671                  * @param int $x x position in user units
10672                  * @param int $y y position in user units
10673                  * @param int $w width in user units
10674                  * @param int $h height in user units
10675                  * @param array $style array of options:<ul><li>boolean $style['border'] if true prints a border around the barcode</li><li>int $style['padding'] padding to leave around the barcode in user units</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background or false for transparent</li></ul>
10676                  * @param string $align Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
10677                  * @author Nicola Asuni
10678                  * @since 4.5.037 (2009-04-07)
10679                  * @access public
10680                  */
10681                 public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='') {
10682                         if ($this->empty_string($code)) {
10683                                 return;
10684                         }
10685                         require_once(dirname(__FILE__).'/2dbarcodes.php');
10686                         // save current graphic settings
10687                         $gvars = $this->getGraphicVars();
10688                         // create new barcode object
10689                         $barcodeobj = new TCPDF2DBarcode($code, $type);
10690                         $arrcode = $barcodeobj->getBarcodeArray();
10691                         if ($arrcode === false) {
10692                                 $this->Error('Error in 2D barcode string');
10693                         }
10694                         // set default values
10695                         if (!isset($style['padding'])) {
10696                                 $style['padding'] = 0;
10697                         }
10698                         if (!isset($style['fgcolor'])) {
10699                                 $style['fgcolor'] = array(0,0,0); // default black
10700                         }
10701                         if (!isset($style['bgcolor'])) {
10702                                 $style['bgcolor'] = false; // default transparent
10703                         }
10704                         if (!isset($style['border'])) {
10705                                 $style['border'] = false;
10706                         }
10707                         // set foreground color
10708                         $this->SetDrawColorArray($style['fgcolor']);
10709                         if ($this->empty_string($x)) {
10710                                 $x = $this->GetX();
10711                         }
10712                         if ($this->rtl) {
10713                                 $x = $this->w - $x;
10714                         }
10715                         if ($this->empty_string($y)) {
10716                                 $y = $this->GetY();
10717                         }
10718                         if ($this->empty_string($w) OR ($w <= 0)) {
10719                                 if ($this->rtl) {
10720                                         $w = $x - $this->lMargin;
10721                                 } else {
10722                                         $w = $this->w - $this->rMargin - $x;
10723                                 }
10724                         }
10725                         if ($this->empty_string($h) OR ($h <= 0)) {
10726                                 // 2d barcodes are square by default
10727                                 $h = $w;
10728                         }
10729                         if ($this->checkPageBreak($h)) {
10730                                 $y = $this->y;
10731                         }
10732                         // calculate barcode size (excluding padding)
10733                         $bw = $w - (2 * $style['padding']);
10734                         $bh = $h - (2 * $style['padding']);
10735                         // calculate starting coordinates
10736                         if ($this->rtl) {
10737                                 $xpos = $x - $w;
10738                         } else {
10739                                 $xpos = $x;
10740                         }
10741                         $xpos += $style['padding'];
10742                         $ypos = $y + $style['padding'];
10743                         // barcode is always printed in LTR direction
10744                         $tempRTL = $this->rtl;
10745                         $this->rtl = false;
10746                         // print background color
10747                         if ($style['bgcolor']) {
10748                                 $this->Rect($x, $y, $w, $h, 'DF', '', $style['bgcolor']);
10749                         } elseif ($style['border']) {
10750                                 $this->Rect($x, $y, $w, $h, 'D');
10751                         }
10752                         // print barcode cells
10753                         if ($arrcode !== false) {
10754                                 $rows = $arrcode['num_rows'];
10755                                 $cols = $arrcode['num_cols'];
10756                                 // calculate dimension of single barcode cell
10757                                 $cw = $bw / $cols;
10758                                 $ch = $bh / $rows;
10759                                 // for each row
10760                                 for ($r = 0; $r < $rows; ++$r) {
10761                                         $xr = $xpos;
10762                                         // for each column
10763                                         for ($c = 0; $c < $cols; ++$c) {
10764                                                 if ($arrcode['bcode'][$r][$c] == 1) {
10765                                                         // draw a single barcode cell
10766                                                         $this->Rect($xr, $ypos, $cw, $ch, 'F', array(), $style['fgcolor']);
10767                                                 }
10768                                                 $xr += $cw;
10769                                         }
10770                                         $ypos += $ch;
10771                                 }
10772                         }
10773                         // restore original direction
10774                         $this->rtl = $tempRTL;
10775                         // restore previous settings
10776                         $this->setGraphicVars($gvars);
10777                         // set bottomcoordinates
10778                         $this->img_rb_y = $y + $h;
10779                         if ($this->rtl) {
10780                                 // set left side coordinate
10781                                 $this->img_rb_x = ($this->w - $x - $w);
10782                         } else {
10783                                 // set right side coordinate
10784                                 $this->img_rb_x = $x + $w;
10785                         }
10786                         // set pointer to align the successive text/objects
10787                         switch($align) {
10788                                 case 'T':{
10789                                         $this->y = $y;
10790                                         $this->x = $this->img_rb_x;
10791                                         break;
10792                                 }
10793                                 case 'M':{
10794                                         $this->y = $y + round($h/2);
10795                                         $this->x = $this->img_rb_x;
10796                                         break;
10797                                 }
10798                                 case 'B':{
10799                                         $this->y = $this->img_rb_y;
10800                                         $this->x = $this->img_rb_x;
10801                                         break;
10802                                 }
10803                                 case 'N':{
10804                                         $this->SetY($this->img_rb_y);
10805                                         break;
10806                                 }
10807                                 default:{
10808                                         break;
10809                                 }
10810                         }
10811                 }
10812
10813                 /**
10814                  * Returns an array containing current margins:
10815                  * <ul>
10816                                 <li>$ret['left'] = left  margin</li>
10817                                 <li>$ret['right'] = right margin</li>
10818                                 <li>$ret['top'] = top margin</li>
10819                                 <li>$ret['bottom'] = bottom margin</li>
10820                                 <li>$ret['header'] = header margin</li>
10821                                 <li>$ret['footer'] = footer margin</li>
10822                                 <li>$ret['cell'] = cell margin</li>
10823                  * </ul>
10824                  * @return array containing all margins measures
10825                  * @access public
10826                  * @since 3.2.000 (2008-06-23)
10827                  */
10828                 public function getMargins() {
10829                         $ret = array(
10830                                 'left' => $this->lMargin,
10831                                 'right' => $this->rMargin,
10832                                 'top' => $this->tMargin,
10833                                 'bottom' => $this->bMargin,
10834                                 'header' => $this->header_margin,
10835                                 'footer' => $this->footer_margin,
10836                                 'cell' => $this->cMargin,
10837                         );
10838                         return $ret;
10839                 }
10840
10841                 /**
10842                  * Returns an array containing original margins:
10843                  * <ul>
10844                                 <li>$ret['left'] = left  margin</li>
10845                                 <li>$ret['right'] = right margin</li>
10846                  * </ul>
10847                  * @return array containing all margins measures
10848                  * @access public
10849                  * @since 4.0.012 (2008-07-24)
10850                  */
10851                 public function getOriginalMargins() {
10852                         $ret = array(
10853                                 'left' => $this->original_lMargin,
10854                                 'right' => $this->original_rMargin
10855                         );
10856                         return $ret;
10857                 }
10858
10859                 /**
10860                  * Returns the current font size.
10861                  * @return current font size
10862                  * @access public
10863                  * @since 3.2.000 (2008-06-23)
10864                  */
10865                 public function getFontSize() {
10866                         return $this->FontSize;
10867                 }
10868
10869                 /**
10870                  * Returns the current font size in points unit.
10871                  * @return current font size in points unit
10872                  * @access public
10873                  * @since 3.2.000 (2008-06-23)
10874                  */
10875                 public function getFontSizePt() {
10876                         return $this->FontSizePt;
10877                 }
10878
10879                 /**
10880                  * Returns the current font family name.
10881                  * @return string current font family name
10882                  * @access public
10883                  * @since 4.3.008 (2008-12-05)
10884                  */
10885                 public function getFontFamily() {
10886                         return $this->FontFamily;
10887                 }
10888
10889                 /**
10890                  * Returns the current font style.
10891                  * @return string current font style
10892                  * @access public
10893                  * @since 4.3.008 (2008-12-05)
10894                  */
10895                 public function getFontStyle() {
10896                         return $this->FontStyle;
10897                 }
10898
10899                 /**
10900                  * Prints a cell (rectangular area) with optional borders, background color and html text string.
10901                  * The upper-left corner of the cell corresponds to the current position. After the call, the current position moves to the right or to the next line.<br />
10902                  * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
10903                  * @param float $w Cell width. If 0, the cell extends up to the right margin.
10904                  * @param float $h Cell minimum height. The cell extends automatically if needed.
10905                  * @param float $x upper-left corner X coordinate
10906                  * @param float $y upper-left corner Y coordinate
10907                  * @param string $html html text to print. Default value: empty string.
10908                  * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
10909                  * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL language)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
10910         Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
10911                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
10912                  * @param boolean $reseth if true reset the last cell height (default true).
10913                  * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
10914                  * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
10915                  * @access public
10916                  * @uses MultiCell()
10917                  * @see Multicell(), writeHTML()
10918                  */
10919                 public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true) {
10920                         return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0);
10921                 }
10922
10923                 /**
10924                  * Returns the HTML DOM array.
10925                  * <ul><li>$dom[$key]['tag'] = true if tag, false otherwise;</li><li>$dom[$key]['value'] = tag name or text;</li><li>$dom[$key]['opening'] = true if opening tag, false otherwise;</li><li>$dom[$key]['attribute'] = array of attributes (attribute name is the key);</li><li>$dom[$key]['style'] = array of style attributes (attribute name is the key);</li><li>$dom[$key]['parent'] = id of parent element;</li><li>$dom[$key]['fontname'] = font family name;</li><li>$dom[$key]['fontstyle'] = font style;</li><li>$dom[$key]['fontsize'] = font size in points;</li><li>$dom[$key]['bgcolor'] = RGB array of background color;</li><li>$dom[$key]['fgcolor'] = RGB array of foreground color;</li><li>$dom[$key]['width'] = width in pixels;</li><li>$dom[$key]['height'] = height in pixels;</li><li>$dom[$key]['align'] = text alignment;</li><li>$dom[$key]['cols'] = number of colums in table;</li><li>$dom[$key]['rows'] = number of rows in table;</li></ul>
10926                  * @param string $html html code
10927                  * @return array
10928                  * @access protected
10929                  * @since 3.2.000 (2008-06-20)
10930                  */
10931                 protected function getHtmlDomArray($html) {
10932                         // remove all unsupported tags (the line below lists all supported tags)
10933                         $html = strip_tags($html, '<marker/><a><b><blockquote><br><br/><dd><del><div><dl><dt><em><font><h1><h2><h3><h4><h5><h6><hr><i><img><li><ol><p><pre><small><span><strong><sub><sup><table><tcpdf><td><th><thead><tr><tt><u><ul>');
10934                         //replace some blank characters
10935                         $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
10936                         $html = preg_replace('/<(table|tr|td|th|tcpdf|blockquote|dd|div|dt|h1|h2|h3|h4|h5|h6|br|hr|li|ol|ul|p)([^\>]*)>[\n\r\t]+/', '<\\1\\2>', $html);
10937                         $html = preg_replace('@(\r\n|\r)@', "\n", $html);
10938                         $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
10939                         $html = strtr($html, $repTable);
10940                         while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html)) {
10941                                 // preserve newlines on <pre> tag
10942                                 $html = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html);
10943                         }
10944                         $html = str_replace("\n", ' ', $html);
10945                         // remove extra spaces from code
10946                         $html = preg_replace('/[\s]+<\/(table|tr|td|th|ul|ol|li)>/', '</\\1>', $html);
10947                         $html = preg_replace('/[\s]+<(tr|td|th|ul|ol|li|br)/', '<\\1', $html);
10948                         $html = preg_replace('/<\/(table|tr|td|th|blockquote|dd|div|dt|h1|h2|h3|h4|h5|h6|hr|li|ol|ul|p)>[\s]+</', '</\\1><', $html);
10949                         $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
10950                         $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
10951                         $html = preg_replace('/<img/', ' <img', $html);
10952                         $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span></span>', $html);
10953                         $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
10954                         // trim string
10955                         $html = preg_replace('/^[\s]+/', '', $html);
10956                         $html = preg_replace('/[\s]+$/', '', $html);
10957                         // pattern for generic tag
10958                         $tagpattern = '/(<[^>]+>)/';
10959                         // explodes the string
10960                         $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
10961                         // count elements
10962                         $maxel = count($a);
10963                         $elkey = 0;
10964                         $key = 0;
10965                         // create an array of elements
10966                         $dom = array();
10967                         $dom[$key] = array();
10968                         // set first void element
10969                         $dom[$key]['tag'] = false;
10970                         $dom[$key]['value'] = '';
10971                         $dom[$key]['parent'] = 0;
10972                         $dom[$key]['fontname'] = $this->FontFamily;
10973                         $dom[$key]['fontstyle'] = $this->FontStyle;
10974                         $dom[$key]['fontsize'] = $this->FontSizePt;
10975                         $dom[$key]['bgcolor'] = false;
10976                         $dom[$key]['fgcolor'] = $this->fgcolor;
10977                         $dom[$key]['align'] = '';
10978                         $dom[$key]['listtype'] = '';
10979                         $thead = false; // true when we are inside the THEAD tag
10980                         ++$key;
10981                         $level = array();
10982                         array_push($level, 0); // root
10983                         while ($elkey < $maxel) {
10984                                 $dom[$key] = array();
10985                                 $element = $a[$elkey];
10986                                 $dom[$key]['elkey'] = $elkey;
10987                                 if (preg_match($tagpattern, $element)) {
10988                                         // html tag
10989                                         $element = substr($element, 1, -1);
10990                                         // get tag name
10991                                         preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
10992                                         $tagname = strtolower($tag[1]);
10993                                         // check if we are inside a table header
10994                                         if ($tagname == 'thead') {
10995                                                 if ($element{0} == '/') {
10996                                                         $thead = false;
10997                                                 } else {
10998                                                         $thead = true;
10999                                                 }
11000                                                 ++$elkey;
11001                                                 continue;
11002                                         }
11003                                         $dom[$key]['tag'] = true;
11004                                         $dom[$key]['value'] = $tagname;
11005                                         if ($element{0} == '/') {
11006                                                 // closing html tag
11007                                                 $dom[$key]['opening'] = false;
11008                                                 $dom[$key]['parent'] = end($level);
11009                                                 array_pop($level);
11010                                                 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
11011                                                 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
11012                                                 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
11013                                                 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
11014                                                 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
11015                                                 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
11016                                                 if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
11017                                                         $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
11018                                                 }
11019                                                 // set the number of columns in table tag
11020                                                 if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
11021                                                         $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
11022                                                 }
11023                                                 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
11024                                                         $dom[($dom[$key]['parent'])]['content'] = '';
11025                                                         for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
11026                                                                 $dom[($dom[$key]['parent'])]['content'] .= $a[$dom[$i]['elkey']];
11027                                                         }
11028                                                         $key = $i;
11029                                                 }
11030                                                 // store header rows on a new table
11031                                                 if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] == true)) {
11032                                                         if ($this->empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
11033                                                                 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
11034                                                         }
11035                                                         for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
11036                                                                 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
11037                                                         }
11038                                                 }
11039                                                 if (($dom[$key]['value'] == 'table') AND (!$this->empty_string($dom[($dom[$key]['parent'])]['thead']))) {
11040                                                         $dom[($dom[$key]['parent'])]['thead'] .= '</table>';
11041                                                 }
11042                                         } else {
11043                                                 // opening html tag
11044                                                 $dom[$key]['opening'] = true;
11045                                                 $dom[$key]['parent'] = end($level);
11046                                                 if (substr($element, -1, 1) != '/') {
11047                                                         // not self-closing tag
11048                                                         array_push($level, $key);
11049                                                         $dom[$key]['self'] = false;
11050                                                 } else {
11051                                                         $dom[$key]['self'] = true;
11052                                                 }
11053                                                 // copy some values from parent
11054                                                 $parentkey = 0;
11055                                                 if ($key > 0) {
11056                                                         $parentkey = $dom[$key]['parent'];
11057                                                         $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
11058                                                         $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
11059                                                         $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
11060                                                         $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
11061                                                         $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
11062                                                         $dom[$key]['align'] = $dom[$parentkey]['align'];
11063                                                         $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
11064                                                 }
11065                                                 // get attributes
11066                                                 preg_match_all('/([^=\s]*)=["]?([^"]*)["]?/', $element, $attr_array, PREG_PATTERN_ORDER);
11067                                                 $dom[$key]['attribute'] = array(); // reset attribute array
11068                                                 while (list($id, $name) = each($attr_array[1])) {
11069                                                         $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
11070                                                 }
11071                                                 // split style attributes
11072                                                 if (isset($dom[$key]['attribute']['style'])) {
11073                                                         // get style attributes
11074                                                         preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
11075                                                         $dom[$key]['style'] = array(); // reset style attribute array
11076                                                         while (list($id, $name) = each($style_array[1])) {
11077                                                                 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
11078                                                         }
11079                                                         // --- get some style attributes ---
11080                                                         if (isset($dom[$key]['style']['font-family'])) {
11081                                                                 // font family
11082                                                                 if (isset($dom[$key]['style']['font-family'])) {
11083                                                                         $fontslist = explode(',', strtolower($dom[$key]['style']['font-family']));
11084                                                                         foreach ($fontslist as $font) {
11085                                                                                 $font = trim(strtolower($font));
11086                                                                                 if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
11087                                                                                         $dom[$key]['fontname'] = $font;
11088                                                                                         break;
11089                                                                                 }
11090                                                                         }
11091                                                                 }
11092                                                         }
11093                                                         // list-style-type
11094                                                         if (isset($dom[$key]['style']['list-style-type'])) {
11095                                                                 $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
11096                                                                 if ($dom[$key]['listtype'] == 'inherit') {
11097                                                                         $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
11098                                                                 }
11099                                                         }
11100                                                         // font size
11101                                                         if (isset($dom[$key]['style']['font-size'])) {
11102                                                                 $fsize = trim($dom[$key]['style']['font-size']);
11103                                                                 switch ($fsize) {
11104                                                                         // absolute-size
11105                                                                         case 'xx-small': {
11106                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
11107                                                                                 break;
11108                                                                         }
11109                                                                         case 'x-small': {
11110                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
11111                                                                                 break;
11112                                                                         }
11113                                                                         case 'small': {
11114                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
11115                                                                                 break;
11116                                                                         }
11117                                                                         case 'medium': {
11118                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
11119                                                                                 break;
11120                                                                         }
11121                                                                         case 'large': {
11122                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
11123                                                                                 break;
11124                                                                         }
11125                                                                         case 'x-large': {
11126                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
11127                                                                                 break;
11128                                                                         }
11129                                                                         case 'xx-large': {
11130                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
11131                                                                                 break;
11132                                                                         }
11133                                                                         // relative-size
11134                                                                         case 'smaller': {
11135                                                                                 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] - 3;
11136                                                                                 break;
11137                                                                         }
11138                                                                         case 'larger': {
11139                                                                                 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] + 3;
11140                                                                                 break;
11141                                                                         }
11142                                                                         default: {
11143                                                                                 $dom[$key]['fontsize'] = $this->getHTMLUnitToUnits($fsize, $dom[$parentkey]['fontsize'], 'pt', true);
11144                                                                         }
11145                                                                 }
11146                                                         }
11147                                                         // font style
11148                                                         if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == 'b')) {
11149                                                                 $dom[$key]['fontstyle'] .= 'B';
11150                                                         }
11151                                                         if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == 'i')) {
11152                                                                 $dom[$key]['fontstyle'] .= '"I';
11153                                                         }
11154                                                         // font color
11155                                                         if (isset($dom[$key]['style']['color']) AND (!$this->empty_string($dom[$key]['style']['color']))) {
11156                                                                 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
11157                                                         }
11158                                                         // background color
11159                                                         if (isset($dom[$key]['style']['background-color']) AND (!$this->empty_string($dom[$key]['style']['background-color']))) {
11160                                                                 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
11161                                                         }
11162                                                         // text-decoration
11163                                                         if (isset($dom[$key]['style']['text-decoration'])) {
11164                                                                 $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
11165                                                                 foreach ($decors as $dec) {
11166                                                                         $dec = trim($dec);
11167                                                                         if (!$this->empty_string($dec)) {
11168                                                                                 if ($dec{0} == 'u') {
11169                                                                                         $dom[$key]['fontstyle'] .= 'U';
11170                                                                                 } elseif ($dec{0} == 'l') {
11171                                                                                         $dom[$key]['fontstyle'] .= 'D';
11172                                                                                 }
11173                                                                         }
11174                                                                 }
11175                                                         }
11176                                                         // check for width attribute
11177                                                         if (isset($dom[$key]['style']['width'])) {
11178                                                                 $dom[$key]['width'] = $dom[$key]['style']['width'];
11179                                                         }
11180                                                         // check for height attribute
11181                                                         if (isset($dom[$key]['style']['height'])) {
11182                                                                 $dom[$key]['height'] = $dom[$key]['style']['height'];
11183                                                         }
11184                                                         // check for text alignment
11185                                                         if (isset($dom[$key]['style']['text-align'])) {
11186                                                                 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
11187                                                         }
11188                                                         // check for border attribute
11189                                                         if (isset($dom[$key]['style']['border'])) {
11190                                                                 $dom[$key]['attribute']['border'] = $dom[$key]['style']['border'];
11191                                                         }
11192                                                 }
11193                                                 // check for font tag
11194                                                 if ($dom[$key]['value'] == 'font') {
11195                                                         // font family
11196                                                         if (isset($dom[$key]['attribute']['face'])) {
11197                                                                 $fontslist = explode(',', strtolower($dom[$key]['attribute']['face']));
11198                                                                 foreach ($fontslist as $font) {
11199                                                                         $font = trim(strtolower($font));
11200                                                                         if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
11201                                                                                 $dom[$key]['fontname'] = $font;
11202                                                                                 break;
11203                                                                         }
11204                                                                 }
11205                                                         }
11206                                                         // font size
11207                                                         if (isset($dom[$key]['attribute']['size'])) {
11208                                                                 if ($key > 0) {
11209                                                                         if ($dom[$key]['attribute']['size']{0} == '+') {
11210                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
11211                                                                         } elseif ($dom[$key]['attribute']['size']{0} == '-') {
11212                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
11213                                                                         } else {
11214                                                                                 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
11215                                                                         }
11216                                                                 } else {
11217                                                                         $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
11218                                                                 }
11219                                                         }
11220                                                 }
11221                                                 // force natural alignment for lists
11222                                                 if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
11223                                                         AND (!isset($dom[$key]['align']) OR $this->empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
11224                                                         if ($this->rtl) {
11225                                                                 $dom[$key]['align'] = 'R';
11226                                                         } else {
11227                                                                 $dom[$key]['align'] = 'L';
11228                                                         }
11229                                                 }
11230                                                 if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
11231                                                         $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
11232                                                 }
11233                                                 if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
11234                                                         $dom[$key]['fontstyle'] .= 'B';
11235                                                 }
11236                                                 if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
11237                                                         $dom[$key]['fontstyle'] .= 'I';
11238                                                 }
11239                                                 if ($dom[$key]['value'] == 'u') {
11240                                                         $dom[$key]['fontstyle'] .= 'U';
11241                                                 }
11242                                                 if ($dom[$key]['value'] == 'del') {
11243                                                         $dom[$key]['fontstyle'] .= 'D';
11244                                                 }
11245                                                 if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
11246                                                         $dom[$key]['fontname'] = $this->default_monospaced_font;
11247                                                 }
11248                                                 if (($dom[$key]['value']{0} == 'h') AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
11249                                                         $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
11250                                                         $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
11251                                                         $dom[$key]['fontstyle'] .= 'B';
11252                                                 }
11253                                                 if (($dom[$key]['value'] == 'table')) {
11254                                                         $dom[$key]['rows'] = 0; // number of rows
11255                                                         $dom[$key]['trids'] = array(); // IDs of TR elements
11256                                                         $dom[$key]['thead'] = ''; // table header rows
11257                                                 }
11258                                                 if (($dom[$key]['value'] == 'tr')) {
11259                                                         $dom[$key]['cols'] = 0;
11260                                                         // store the number of rows on table element
11261                                                         ++$dom[($dom[$key]['parent'])]['rows'];
11262                                                         // store the TR elements IDs on table element
11263                                                         array_push($dom[($dom[$key]['parent'])]['trids'], $key);
11264                                                         if ($thead) {
11265                                                                 $dom[$key]['thead'] = true;
11266                                                         } else {
11267                                                                 $dom[$key]['thead'] = false;
11268                                                         }
11269                                                 }
11270                                                 if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
11271                                                         if (isset($dom[$key]['attribute']['colspan'])) {
11272                                                                 $colspan = intval($dom[$key]['attribute']['colspan']);
11273                                                         } else {
11274                                                                 $colspan = 1;
11275                                                         }
11276                                                         $dom[$key]['attribute']['colspan'] = $colspan;
11277                                                         $dom[($dom[$key]['parent'])]['cols'] += $colspan;
11278                                                 }
11279                                                 // set foreground color attribute
11280                                                 if (isset($dom[$key]['attribute']['color']) AND (!$this->empty_string($dom[$key]['attribute']['color']))) {
11281                                                         $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
11282                                                 }
11283                                                 // set background color attribute
11284                                                 if (isset($dom[$key]['attribute']['bgcolor']) AND (!$this->empty_string($dom[$key]['attribute']['bgcolor']))) {
11285                                                         $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
11286                                                 }
11287                                                 // check for width attribute
11288                                                 if (isset($dom[$key]['attribute']['width'])) {
11289                                                         $dom[$key]['width'] = $dom[$key]['attribute']['width'];
11290                                                 }
11291                                                 // check for height attribute
11292                                                 if (isset($dom[$key]['attribute']['height'])) {
11293                                                         $dom[$key]['height'] = $dom[$key]['attribute']['height'];
11294                                                 }
11295                                                 // check for text alignment
11296                                                 if (isset($dom[$key]['attribute']['align']) AND (!$this->empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
11297                                                         $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
11298                                                 }
11299                                         } // end opening tag
11300                                 } else {
11301                                         // text
11302                                         $dom[$key]['tag'] = false;
11303                                         $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
11304                                         $dom[$key]['parent'] = end($level);
11305                                 }
11306                                 ++$elkey;
11307                                 ++$key;
11308                         }
11309                         return $dom;
11310                 }
11311
11312                 /**
11313                  * Allows to preserve some HTML formatting (limited support).<br />
11314                  * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
11315                  * Supported tags are: a, b, blockquote, br, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, li, ol, p, pre, small, span, strong, sub, sup, table, tcpdf, td, th, thead, tr, tt, u, ul
11316                  * @param string $html text to display
11317                  * @param boolean $ln if true add a new line after text (default = true)
11318                  * @param int $fill Indicates if the background must be painted (true) or transparent (false).
11319                  * @param boolean $reseth if true reset the last cell height (default false).
11320                  * @param boolean $cell if true add the default cMargin space to each Write (default false).
11321                  * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
11322                  * @access public
11323                  */
11324                 public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
11325                         $gvars = $this->getGraphicVars();
11326                         // store current values
11327                         $prevPage = $this->page;
11328                         $prevlMargin = $this->lMargin;
11329                         $prevrMargin = $this->rMargin;
11330                         $curfontname = $this->FontFamily;
11331                         $curfontstyle = $this->FontStyle;
11332                         $curfontsize = $this->FontSizePt;
11333                         $this->newline = true;
11334                         $minstartliney = $this->y;
11335                         $yshift = 0;
11336                         $startlinepage = $this->page;
11337                         $newline = true;
11338                         $loop = 0;
11339                         $curpos = 0;
11340                         $blocktags = array('blockquote','br','dd','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','ul','tcpdf');
11341                         $this->premode = false;
11342                         if (isset($this->PageAnnots[$this->page])) {
11343                                 $pask = count($this->PageAnnots[$this->page]);
11344                         } else {
11345                                 $pask = 0;
11346                         }
11347                         if (isset($this->footerlen[$this->page])) {
11348                                 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11349                         } else {
11350                                 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11351                         }
11352                         $startlinepos = $this->footerpos[$this->page];
11353                         $lalign = $align;
11354                         $plalign = $align;
11355                         if ($this->rtl) {
11356                                 $w = $this->x - $this->lMargin;
11357                         } else {
11358                                 $w = $this->w - $this->rMargin - $this->x;
11359                         }
11360                         $w -= (2 * $this->cMargin);
11361                         if ($cell) {
11362                                 if ($this->rtl) {
11363                                         $this->x -= $this->cMargin;
11364                                 } else {
11365                                         $this->x += $this->cMargin;
11366                                 }
11367                         }
11368                         if ($this->customlistindent >= 0) {
11369                                 $this->listindent = $this->customlistindent;
11370                         } else {
11371                                 $this->listindent = $this->GetStringWidth('0000');
11372                         }
11373                         $this->listnum = 0;
11374                         if (($this->empty_string($this->lasth)) OR ($reseth)) {
11375                                 //set row height
11376                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11377                         }
11378                         $dom = $this->getHtmlDomArray($html);
11379                         $maxel = count($dom);
11380                         $key = 0;
11381                         while ($key < $maxel) {
11382                                 if ($dom[$key]['tag'] OR ($key == 0)) {
11383                                         if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
11384                                                 $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
11385                                         }
11386                                         // vertically align image in line
11387                                         if ((!$this->newline)
11388                                                 AND ($dom[$key]['value'] == 'img')
11389                                                 AND (isset($dom[$key]['attribute']['height']))
11390                                                 AND ($dom[$key]['attribute']['height'] > 0)) {
11391                                                 // get image height
11392                                                 $imgh = $this->getHTMLUnitToUnits($dom[$key]['attribute']['height'], $this->lasth, 'px');
11393                                                 if (!$this->InFooter) {
11394                                                         // check for page break
11395                                                         $this->checkPageBreak($imgh);
11396                                                 }
11397                                                 if ($this->page > $startlinepage) {
11398                                                         // fix lines splitted over two pages
11399                                                         if (isset($this->footerlen[$startlinepage])) {
11400                                                                 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11401                                                         }
11402                                                         // line to be moved one page forward
11403                                                         $pagebuff = $this->getPageBuffer($startlinepage);
11404                                                         $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
11405                                                         $tstart = substr($pagebuff, 0, $startlinepos);
11406                                                         $tend = substr($this->getPageBuffer($startlinepage), $curpos);
11407                                                         // remove line start from previous page
11408                                                         $this->setPageBuffer($startlinepage, $tstart.''.$tend);
11409                                                         $pagebuff = $this->getPageBuffer($this->page);
11410                                                         $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
11411                                                         $tend = substr($pagebuff, $this->intmrk[$this->page]);
11412                                                         // add line start to current page
11413                                                         $yshift = $minstartliney - $this->y;
11414                                                         $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
11415                                                         $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
11416                                                         // shift the annotations and links
11417                                                         if (isset($this->PageAnnots[$startlinepage])) {
11418                                                                 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
11419                                                                         if ($pak >= $pask) {
11420                                                                                 $this->PageAnnots[$this->page][] = $pac;
11421                                                                                 unset($this->PageAnnots[$startlinepage][$pak]);
11422                                                                                 $npak = count($this->PageAnnots[$this->page]) - 1;
11423                                                                                 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
11424                                                                         }
11425                                                                 }
11426                                                         }
11427                                                         $startlinepos = $this->intmrk[$this->page];
11428                                                         $startlinepage = $this->page;
11429                                                         $startliney = $this->y;
11430                                                 }
11431
11432                                                 $this->y += (($curfontsize / $this->k) - $imgh);
11433                                                 $minstartliney = min($this->y, $minstartliney);
11434
11435                                         } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
11436                                                 // account for different font size
11437                                                 $pfontname = $curfontname;
11438                                                 $pfontstyle = $curfontstyle;
11439                                                 $pfontsize = $curfontsize;
11440                                                 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
11441                                                 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
11442                                                 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
11443                                                 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
11444                                                         $this->SetFont($fontname, $fontstyle, $fontsize);
11445                                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
11446                                                         if (is_numeric($fontsize) AND ($fontsize > 0)
11447                                                                 AND is_numeric($curfontsize) AND ($curfontsize > 0)
11448                                                                 AND ($fontsize != $curfontsize) AND (!$this->newline)
11449                                                                 AND ($key < ($maxel - 1))
11450                                                                 ) {
11451                                                                 if ((!$this->newline) AND ($this->page > $startlinepage)) {
11452                                                                         // fix lines splitted over two pages
11453                                                                         if (isset($this->footerlen[$startlinepage])) {
11454                                                                                 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11455                                                                         }
11456                                                                         // line to be moved one page forward
11457                                                                         $pagebuff = $this->getPageBuffer($startlinepage);
11458                                                                         $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
11459                                                                         $tstart = substr($pagebuff, 0, $startlinepos);
11460                                                                         $tend = substr($this->getPageBuffer($startlinepage), $curpos);
11461                                                                         // remove line start from previous page
11462                                                                         $this->setPageBuffer($startlinepage, $tstart.''.$tend);
11463                                                                         $pagebuff = $this->getPageBuffer($this->page);
11464                                                                         $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
11465                                                                         $tend = substr($pagebuff, $this->intmrk[$this->page]);
11466                                                                         // add line start to current page
11467                                                                         $yshift = $minstartliney - $this->y;
11468                                                                         $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
11469                                                                         $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
11470                                                                         // shift the annotations and links
11471                                                                         if (isset($this->PageAnnots[$startlinepage])) {
11472                                                                                 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
11473                                                                                         if ($pak >= $pask) {
11474                                                                                                 $this->PageAnnots[$this->page][] = $pac;
11475                                                                                                 unset($this->PageAnnots[$startlinepage][$pak]);
11476                                                                                                 $npak = count($this->PageAnnots[$this->page]) - 1;
11477                                                                                                 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
11478                                                                                         }
11479                                                                                 }
11480                                                                         }
11481                                                                 }
11482                                                                 $this->y += (($curfontsize - $fontsize) / $this->k);
11483                                                                 $minstartliney = min($this->y, $minstartliney);
11484                                                         }
11485                                                         $curfontname = $fontname;
11486                                                         $curfontstyle = $fontstyle;
11487                                                         $curfontsize = $fontsize;
11488                                                 }
11489                                         }
11490                                         if (($plalign == 'J') AND (in_array($dom[$key]['value'], $blocktags))) {
11491                                                 $plalign = '';
11492                                         }
11493                                         // get current position on page buffer
11494                                         $curpos = $this->pagelen[$startlinepage];
11495                                         if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
11496                                                 $this->SetFillColorArray($dom[$key]['bgcolor']);
11497                                                 $wfill = true;
11498                                         } else {
11499                                                 $wfill = $fill | false;
11500                                         }
11501                                         if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
11502                                                 $this->SetTextColorArray($dom[$key]['fgcolor']);
11503                                         }
11504                                         if (isset($dom[$key]['align'])) {
11505                                                 $lalign = $dom[$key]['align'];
11506                                         }
11507                                         if ($this->empty_string($lalign)) {
11508                                                 $lalign = $align;
11509                                         }
11510                                 }
11511                                 // align lines
11512                                 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
11513                                         $newline = true;
11514                                         // we are at the beginning of a new line
11515                                         if (isset($startlinex)) {
11516                                                 $yshift = $minstartliney - $startliney;
11517                                                 if (($yshift > 0) OR ($this->page > $startlinepage)) {
11518                                                         $yshift = 0;
11519                                                 }
11520                                                 if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
11521                                                         // the last line must be shifted to be aligned as requested
11522                                                         $linew = abs($this->endlinex - $startlinex);
11523                                                         $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
11524                                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
11525                                                                 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11526                                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
11527                                                         } elseif (isset($opentagpos)) {
11528                                                                 $midpos = $opentagpos;
11529                                                         } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
11530                                                                 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11531                                                                 $midpos = $this->footerpos[$startlinepage];
11532                                                         } else {
11533                                                                 $midpos = 0;
11534                                                         }
11535                                                         if ($midpos > 0) {
11536                                                                 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
11537                                                                 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
11538                                                         } else {
11539                                                                 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
11540                                                                 $pend = '';
11541                                                         }
11542                                                         // calculate shifting amount
11543                                                         $tw = $w;
11544                                                         if ($this->lMargin != $prevlMargin) {
11545                                                                 $tw += ($prevlMargin - $this->lMargin);
11546                                                         }
11547                                                         if ($this->rMargin != $prevrMargin) {
11548                                                                 $tw += ($prevrMargin - $this->rMargin);
11549                                                         }
11550                                                         $mdiff = abs($tw - $linew);
11551                                                         $t_x = 0;
11552                                                         if ($plalign == 'C') {
11553                                                                 if ($this->rtl) {
11554                                                                         $t_x = -($mdiff / 2);
11555                                                                 } else {
11556                                                                         $t_x = ($mdiff / 2);
11557                                                                 }
11558                                                         } elseif (($plalign == 'R') AND (!$this->rtl)) {
11559                                                                 // right alignment on LTR document
11560                                                                 $t_x = $mdiff;
11561                                                         } elseif (($plalign == 'L') AND ($this->rtl)) {
11562                                                                 // left alignment on RTL document
11563                                                                 $t_x = -$mdiff;
11564                                                         } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
11565                                                                 // Justification
11566                                                                 if ($this->rtl OR $this->tmprtl) {
11567                                                                         $t_x = $this->lMargin - $this->endlinex;
11568                                                                 }
11569                                                                 $no = 0;
11570                                                                 $ns = 0;
11571                                                                 $pmidtemp = $pmid;
11572                                                                 // escape special characters
11573                                                                 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
11574                                                                 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
11575                                                                 // search spaces
11576                                                                 if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
11577                                                                         $maxkk = count($lnstring[1]) - 1;
11578                                                                         for ($kk=0; $kk <= $maxkk; ++$kk) {
11579                                                                                 // restore special characters
11580                                                                                 $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
11581                                                                                 $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
11582                                                                                 if ($kk == $maxkk) {
11583                                                                                         if ($this->rtl OR $this->tmprtl) {
11584                                                                                                 $tvalue = ltrim($lnstring[1][$kk]);
11585                                                                                         } else {
11586                                                                                                 $tvalue = rtrim($lnstring[1][$kk]);
11587                                                                                         }
11588                                                                                 } else {
11589                                                                                         $tvalue = $lnstring[1][$kk];
11590                                                                                 }
11591                                                                                 // count spaces on line
11592                                                                                 $no += substr_count($lnstring[1][$kk], chr(32));
11593                                                                                 $ns += substr_count($tvalue, chr(32));
11594                                                                         }
11595                                                                         if ($this->rtl OR $this->tmprtl) {
11596                                                                                 $t_x = $this->lMargin - $this->endlinex - (($no - $ns - 1) * $this->GetStringWidth(chr(32)));
11597                                                                         }
11598                                                                         // calculate additional space to add to each space
11599                                                                         $spacewidth = (($tw - $linew + (($no - $ns) * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1)) * $this->k;
11600                                                                         $spacewidthu = ($tw - $linew + ($no * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1) / $this->FontSize / $this->k;
11601                                                                         $nsmax = $ns;
11602                                                                         $ns = 0;
11603                                                                         reset($lnstring);
11604                                                                         $offset = 0;
11605                                                                         $strcount = 0;
11606                                                                         $prev_epsposbeg = 0;
11607                                                                         global $spacew;
11608                                                                         while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
11609                                                                                 if ($this->rtl OR $this->tmprtl) {
11610                                                                                         $spacew = ($spacewidth * ($nsmax - $ns));
11611                                                                                 } else {
11612                                                                                         $spacew = ($spacewidth * $ns);
11613                                                                                 }
11614                                                                                 $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
11615                                                                                 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
11616                                                                                 $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset) + strlen($this->epsmarker.'Q');
11617                                                                                 if ((($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend))
11618                                                                                         OR (($epsposbeg === false) AND ($epsposend > 0) AND ($offset < $epsposend))) {
11619                                                                                         // shift EPS images
11620                                                                                         $trx = sprintf('1 0 0 1 %.3F 0 cm', $spacew);
11621                                                                                         $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
11622                                                                                         $pmid_b = substr($pmid, 0, $epsposbeg);
11623                                                                                         $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
11624                                                                                         $pmid_e = substr($pmid, $epsposend);
11625                                                                                         $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
11626                                                                                         $offset = $epsposend;
11627                                                                                         continue;
11628                                                                                 }
11629                                                                                 $prev_epsposbeg = $epsposbeg;
11630                                                                                 $currentxpos = 0;
11631                                                                                 // shift blocks of code
11632                                                                                 switch ($strpiece[2][0]) {
11633                                                                                         case 'Td':
11634                                                                                         case 'cm':
11635                                                                                         case 'm':
11636                                                                                         case 'l': {
11637                                                                                                 // get current X position
11638                                                                                                 preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11639                                                                                                 $currentxpos = $xmatches[1];
11640                                                                                                 if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
11641                                                                                                         if ($strcount == $maxkk) {
11642                                                                                                                 if ($this->rtl OR $this->tmprtl) {
11643                                                                                                                         $tvalue = $lnstring[1][$strcount];
11644                                                                                                                 } else {
11645                                                                                                                         $tvalue = rtrim($lnstring[1][$strcount]);
11646                                                                                                                 }
11647                                                                                                         } else {
11648                                                                                                                 $tvalue = $lnstring[1][$strcount];
11649                                                                                                         }
11650                                                                                                         $ns += substr_count($tvalue, chr(32));
11651                                                                                                         ++$strcount;
11652                                                                                                 }
11653                                                                                                 if ($this->rtl OR $this->tmprtl) {
11654                                                                                                         $spacew = ($spacewidth * ($nsmax - $ns));
11655                                                                                                 }
11656                                                                                                 // justify block
11657                                                                                                 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11658                                                                                                         create_function('$matches', 'global $spacew;
11659                                                                                                         $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
11660                                                                                                         return "".$newx." ".$matches[2]." x*#!#*x".$matches[3].$matches[4];'), $pmid, 1);
11661                                                                                                 break;
11662                                                                                         }
11663                                                                                         case 're': {
11664                                                                                                 // get current X position
11665                                                                                                 preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11666                                                                                                 $currentxpos = $xmatches[1];
11667                                                                                                 // justify block
11668                                                                                                 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11669                                                                                                         create_function('$matches', 'global $spacew;
11670                                                                                                         $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
11671                                                                                                         return "".$newx." ".$matches[2]." ".$matches[3]." ".$matches[4]." x*#!#*x".$matches[5].$matches[6];'), $pmid, 1);
11672                                                                                                 break;
11673                                                                                         }
11674                                                                                         case 'c': {
11675                                                                                                 // get current X position
11676                                                                                                 preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11677                                                                                                 $currentxpos = $xmatches[1];
11678                                                                                                 // justify block
11679                                                                                                 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11680                                                                                                         create_function('$matches', 'global $spacew;
11681                                                                                                         $newx1 = sprintf("%.3F",(floatval($matches[1]) + $spacew));
11682                                                                                                         $newx2 = sprintf("%.3F",(floatval($matches[3]) + $spacew));
11683                                                                                                         $newx3 = sprintf("%.3F",(floatval($matches[5]) + $spacew));
11684                                                                                                         return "".$newx1." ".$matches[2]." ".$newx2." ".$matches[4]." ".$newx3." ".$matches[6]." x*#!#*x".$matches[7].$matches[8];'), $pmid, 1);
11685                                                                                                 break;
11686                                                                                         }
11687                                                                                 }
11688                                                                                 // shift the annotations and links
11689                                                                                 if (isset($this->PageAnnots[$this->page])) {
11690                                                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
11691                                                                                                 if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
11692                                                                                                         $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
11693                                                                                                         $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
11694                                                                                                         break;
11695                                                                                                 }
11696                                                                                         }
11697                                                                                 }
11698                                                                         } // end of while
11699                                                                         // remove markers
11700                                                                         $pmid = str_replace('x*#!#*x', '', $pmid);
11701                                                                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
11702                                                                                 // multibyte characters
11703                                                                                 $spacew = $spacewidthu;
11704                                                                                 $pmidtemp = $pmid;
11705                                                                                 // escape special characters
11706                                                                                 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
11707                                                                                 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
11708                                                                                 $pmid = preg_replace_callback("/\[\(([^\)]*)\)\]/x",
11709                                                                                                         create_function('$matches', 'global $spacew;
11710                                                                                                         $matches[1] = str_replace("#!#OP#!#", "(", $matches[1]);
11711                                                                                                         $matches[1] = str_replace("#!#CP#!#", ")", $matches[1]);
11712                                                                                                         return "[(".str_replace(chr(0).chr(32), ") ".(-2830 * $spacew)." (", $matches[1]).")]";'), $pmidtemp);
11713                                                                                 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
11714                                                                                 $endlinepos = strlen($pstart."\n".$pmid."\n");
11715                                                                         } else {
11716                                                                                 // non-unicode (single-byte characters)
11717                                                                                 $rs = sprintf("%.3F Tw", $spacewidth);
11718                                                                                 $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
11719                                                                                 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
11720                                                                                 $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
11721                                                                         }
11722                                                                 }
11723                                                         } // end of J
11724                                                         if (($t_x != 0) OR ($yshift < 0)) {
11725                                                                 // shift the line
11726                                                                 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
11727                                                                 $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
11728                                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
11729                                                                 // shift the annotations and links
11730                                                                 if (isset($this->PageAnnots[$this->page])) {
11731                                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
11732                                                                                 if ($pak >= $pask) {
11733                                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
11734                                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
11735                                                                                 }
11736                                                                         }
11737                                                                 }
11738                                                                 $this->y -= $yshift;
11739                                                         }
11740                                                 }
11741                                         }
11742                                         $this->newline = false;
11743                                         $pbrk = $this->checkPageBreak($this->lasth);
11744                                         $this->SetFont($fontname, $fontstyle, $fontsize);
11745                                         if ($wfill) {
11746                                                 $this->SetFillColorArray($this->bgcolor);
11747                                         }
11748                                         $startlinex = $this->x;
11749                                         $startliney = $this->y;
11750                                         $minstartliney = $this->y;
11751                                         $startlinepage = $this->page;
11752                                         if (isset($endlinepos) AND (!$pbrk)) {
11753                                                 $startlinepos = $endlinepos;
11754                                                 unset($endlinepos);
11755                                         } else {
11756                                                 if (isset($this->footerlen[$this->page])) {
11757                                                         $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11758                                                 } else {
11759                                                         $this->footerpos[$this->page] = $this->pagelen[$this->page];
11760                                                 }
11761                                                 $startlinepos = $this->footerpos[$this->page];
11762                                         }
11763                                         $plalign = $lalign;
11764                                         if (isset($this->PageAnnots[$this->page])) {
11765                                                 $pask = count($this->PageAnnots[$this->page]);
11766                                         } else {
11767                                                 $pask = 0;
11768                                         }
11769                                 }
11770                                 if (isset($opentagpos)) {
11771                                         unset($opentagpos);
11772                                 }
11773                                 if ($dom[$key]['tag']) {
11774                                         if ($dom[$key]['opening']) {
11775                                                 if ($dom[$key]['value'] == 'table') {
11776                                                         if ($this->rtl) {
11777                                                                 $wtmp = $this->x - $this->lMargin;
11778                                                         } else {
11779                                                                 $wtmp = $this->w - $this->rMargin - $this->x;
11780                                                         }
11781                                                         $wtmp -= (2 * $this->cMargin);
11782                                                         // calculate cell width
11783                                                         if (isset($dom[$key]['width'])) {
11784                                                                 $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
11785                                                         } else {
11786                                                                 $table_width = $wtmp;
11787                                                         }
11788                                                 }
11789                                                 // table content is handled in a special way
11790                                                 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
11791                                                         $trid = $dom[$key]['parent'];
11792                                                         $table_el = $dom[$trid]['parent'];
11793                                                         if (!isset($dom[$table_el]['cols'])) {
11794                                                                 $dom[$table_el]['cols'] = $trid['cols'];
11795                                                         }
11796                                                         $oldmargin = $this->cMargin;
11797                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
11798                                                                 $currentcmargin = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
11799                                                         } else {
11800                                                                 $currentcmargin = 0;
11801                                                         }
11802                                                         $this->cMargin = $currentcmargin;
11803                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
11804                                                                 $cellspacing = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'], 1, 'px');
11805                                                         } else {
11806                                                                 $cellspacing = 0;
11807                                                         }
11808                                                         if ($this->rtl) {
11809                                                                 $cellspacingx = -$cellspacing;
11810                                                         } else {
11811                                                                 $cellspacingx = $cellspacing;
11812                                                         }
11813                                                         $colspan = $dom[$key]['attribute']['colspan'];
11814                                                         $wtmp = ($colspan * ($table_width / $dom[$table_el]['cols']));
11815                                                         if (isset($dom[$key]['width'])) {
11816                                                                 $cellw = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
11817                                                         } else {
11818                                                                 $cellw = $wtmp;
11819                                                         }
11820                                                         if (isset($dom[$key]['height'])) {
11821                                                                 // minimum cell height
11822                                                                 $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
11823                                                         } else {
11824                                                                 $cellh = 0;
11825                                                         }
11826                                                         $cellw -= $cellspacing;
11827                                                         if (isset($dom[$key]['content'])) {
11828                                                                 $cell_content = $dom[$key]['content'];
11829                                                         } else {
11830                                                                 $cell_content = '&nbsp;';
11831                                                         }
11832                                                         $tagtype = $dom[$key]['value'];
11833                                                         $parentid = $key;
11834                                                         while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
11835                                                                 // move $key index forward
11836                                                                 ++$key;
11837                                                         }
11838                                                         if (!isset($dom[$trid]['startpage'])) {
11839                                                                 $dom[$trid]['startpage'] = $this->page;
11840                                                         } else {
11841                                                                 $this->setPage($dom[$trid]['startpage']);
11842                                                         }
11843                                                         if (!isset($dom[$trid]['starty'])) {
11844                                                                 $dom[$trid]['starty'] = $this->y;
11845                                                         } else {
11846                                                                 $this->y = $dom[$trid]['starty'];
11847                                                         }
11848                                                         if (!isset($dom[$trid]['startx'])) {
11849                                                                 $dom[$trid]['startx'] = $this->x;
11850                                                         }
11851                                                         $this->x += ($cellspacingx / 2);
11852                                                         if (isset($dom[$parentid]['attribute']['rowspan'])) {
11853                                                                 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
11854                                                         } else {
11855                                                                 $rowspan = 1;
11856                                                         }
11857                                                         // skip row-spanned cells started on the previous rows
11858                                                         if (isset($dom[$table_el]['rowspans'])) {
11859                                                                 $rsk = 0;
11860                                                                 $rskmax = count($dom[$table_el]['rowspans']);
11861                                                                 while ($rsk < $rskmax) {
11862                                                                         $trwsp = $dom[$table_el]['rowspans'][$rsk];
11863                                                                         $rsstartx = $trwsp['startx'];
11864                                                                         $rsendx = $trwsp['endx'];
11865                                                                         // account for margin changes
11866                                                                         if ($trwsp['startpage'] < $this->page) {
11867                                                                                 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
11868                                                                                         $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
11869                                                                                         $rsstartx -= $dl;
11870                                                                                         $rsendx -= $dl;
11871                                                                                 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
11872                                                                                         $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
11873                                                                                         $rsstartx += $dl;
11874                                                                                         $rsendx += $dl;
11875                                                                                 }
11876                                                                         }
11877                                                                         if  (($trwsp['rowspan'] > 0)
11878                                                                                 AND ($rsstartx > ($this->x - $cellspacing - $currentcmargin - $this->feps))
11879                                                                                 AND ($rsstartx < ($this->x + $cellspacing + $currentcmargin + $this->feps))
11880                                                                                 AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page))) {
11881                                                                                 // set the starting X position of the current cell
11882                                                                                 $this->x = $rsendx + $cellspacingx;
11883                                                                                 if (($trwsp['rowspan'] == 1)
11884                                                                                         AND (isset($dom[$trid]['endy']))
11885                                                                                         AND (isset($dom[$trid]['endpage']))
11886                                                                                         AND ($trwsp['endpage'] == $dom[$trid]['endpage'])) {
11887                                                                                         // set ending Y position for row
11888                                                                                         $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
11889                                                                                         $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
11890                                                                                 }
11891                                                                                 $rsk = 0;
11892                                                                         } else {
11893                                                                                 ++$rsk;
11894                                                                         }
11895                                                                 }
11896                                                         }
11897                                                         // add rowspan information to table element
11898                                                         if ($rowspan > 1) {
11899                                                                 if (isset($this->footerlen[$this->page])) {
11900                                                                         $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11901                                                                 } else {
11902                                                                         $this->footerpos[$this->page] = $this->pagelen[$this->page];
11903                                                                 }
11904                                                                 $trintmrkpos = $this->footerpos[$this->page];
11905                                                                 $trsid = array_push($dom[$table_el]['rowspans'], array('trid' => $trid, 'rowspan' => $rowspan, 'mrowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startx' => $this->x, 'starty' => $this->y, 'intmrkpos' => $trintmrkpos));
11906                                                         }
11907                                                         $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
11908                                                         if ($rowspan > 1) {
11909                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
11910                                                         }
11911                                                         // push background colors
11912                                                         if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
11913                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
11914                                                         }
11915                                                         $prevLastH = $this->lasth;
11916                                                         // ****** write the cell content ******
11917                                                         $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
11918                                                         $this->lasth = $prevLastH;
11919                                                         $this->cMargin = $oldmargin;
11920                                                         $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
11921                                                         // update the end of row position
11922                                                         if ($rowspan <= 1) {
11923                                                                 if (isset($dom[$trid]['endy'])) {
11924                                                                         if ($this->page == $dom[$trid]['endpage']) {
11925                                                                                 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
11926                                                                         } elseif ($this->page > $dom[$trid]['endpage']) {
11927                                                                                 $dom[$trid]['endy'] = $this->y;
11928                                                                         }
11929                                                                 } else {
11930                                                                         $dom[$trid]['endy'] = $this->y;
11931                                                                 }
11932                                                                 if (isset($dom[$trid]['endpage'])) {
11933                                                                         $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
11934                                                                 } else {
11935                                                                         $dom[$trid]['endpage'] = $this->page;
11936                                                                 }
11937                                                         } else {
11938                                                                 // account for row-spanned cells
11939                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
11940                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
11941                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
11942                                                         }
11943                                                         if (isset($dom[$table_el]['rowspans'])) {
11944                                                                 // update endy and endpage on rowspanned cells
11945                                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
11946                                                                         if ($trwsp['rowspan'] > 0) {
11947                                                                                 if (isset($dom[$trid]['endpage'])) {
11948                                                                                         if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
11949                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
11950                                                                                         } elseif ($trwsp['endpage'] < $dom[$trid]['endpage']) {
11951                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
11952                                                                                                 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
11953                                                                                         } else {
11954                                                                                                 $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
11955                                                                                         }
11956                                                                                 }
11957                                                                         }
11958                                                                 }
11959                                                         }
11960                                                         $this->x += ($cellspacingx / 2);
11961                                                 } else {
11962                                                         // opening tag (or self-closing tag)
11963                                                         if (!isset($opentagpos)) {
11964                                                                 if (!$this->InFooter) {
11965                                                                         if (isset($this->footerlen[$this->page])) {
11966                                                                                 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11967                                                                         } else {
11968                                                                                 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11969                                                                         }
11970                                                                         $opentagpos = $this->footerpos[$this->page];
11971                                                                 }
11972                                                         }
11973                                                         $this->openHTMLTagHandler($dom, $key, $cell);
11974                                                 }
11975                                         } else {
11976                                                 // closing tag
11977                                                 $this->closeHTMLTagHandler($dom, $key, $cell);
11978                                         }
11979                                 } elseif (strlen($dom[$key]['value']) > 0) {
11980                                         // print list-item
11981                                         if (!$this->empty_string($this->lispacer)) {
11982                                                 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
11983                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11984                                                 $minstartliney = $this->y;
11985                                                 $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
11986                                                 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
11987                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11988                                                 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
11989                                                         $this->y += (($pfontsize - $curfontsize) / $this->k);
11990                                                         $minstartliney = min($this->y, $minstartliney);
11991                                                 }
11992                                         }
11993                                         // text
11994                                         $this->htmlvspace = 0;
11995                                         if ((!$this->premode) AND ($this->rtl OR $this->tmprtl)) {
11996                                                 // reverse spaces order
11997                                                 $len1 = strlen($dom[$key]['value']);
11998                                                 $lsp = $len1 - strlen(ltrim($dom[$key]['value']));
11999                                                 $rsp = $len1 - strlen(rtrim($dom[$key]['value']));
12000                                                 $tmpstr = '';
12001                                                 if ($rsp > 0) {
12002                                                         $tmpstr .= substr($dom[$key]['value'], -$rsp);
12003                                                 }
12004                                                 $tmpstr .= trim($dom[$key]['value']);
12005                                                 if ($lsp > 0) {
12006                                                         $tmpstr .= substr($dom[$key]['value'], 0, $lsp);
12007                                                 }
12008                                                 $dom[$key]['value'] = $tmpstr;
12009                                         }
12010                                         if ($newline) {
12011                                                 if (!$this->premode) {
12012                                                         if (($this->rtl OR $this->tmprtl)) {
12013                                                                 $dom[$key]['value'] = rtrim($dom[$key]['value']);
12014                                                         } else {
12015                                                                 $dom[$key]['value'] = ltrim($dom[$key]['value']);
12016                                                         }
12017                                                 }
12018                                                 $newline = false;
12019                                                 $firstblock = true;
12020                                         } else {
12021                                                 $firstblock = false;
12022                                         }
12023                                         $strrest = '';
12024                                         if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
12025                                                 // HTML <a> Link
12026                                                 $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $this->HREF['color'], $this->HREF['style']);
12027                                         } else {
12028                                                 $ctmpmargin = $this->cMargin;
12029                                                 $this->cMargin = 0;
12030                                                 // ****** write only until the end of the line and get the rest ******
12031                                                 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock);
12032                                                 $this->cMargin = $ctmpmargin;
12033                                         }
12034                                         if (strlen($strrest) > 0) {
12035                                                 // store the remaining string on the previous $key position
12036                                                 $this->newline = true;
12037                                                 if ($cell) {
12038                                                         if ($this->rtl) {
12039                                                                 $this->x -= $this->cMargin;
12040                                                         } else {
12041                                                                 $this->x += $this->cMargin;
12042                                                         }
12043                                                 }
12044                                                 if ($strrest == $dom[$key]['value']) {
12045                                                         // used to avoid infinite loop
12046                                                         ++$loop;
12047                                                 } else {
12048                                                         $loop = 0;
12049                                                 }
12050                                                 $dom[$key]['value'] = ltrim($strrest);
12051                                                 if ($loop < 3) {
12052                                                         --$key;
12053                                                 }
12054                                         } else {
12055                                                 $loop = 0;
12056                                         }
12057                                 }
12058                                 ++$key;
12059                         } // end for each $key
12060                         // align the last line
12061                         if (isset($startlinex)) {
12062                                 $yshift = $minstartliney - $startliney;
12063                                 if (($yshift > 0) OR ($this->page > $startlinepage)) {
12064                                         $yshift = 0;
12065                                 }
12066                                 if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
12067                                         // the last line must be shifted to be aligned as requested
12068                                         $linew = abs($this->endlinex - $startlinex);
12069                                         $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
12070                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
12071                                                 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
12072                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
12073                                         } elseif (isset($opentagpos)) {
12074                                                 $midpos = $opentagpos;
12075                                         } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
12076                                                 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
12077                                                 $midpos = $this->footerpos[$startlinepage];
12078                                         } else {
12079                                                 $midpos = 0;
12080                                         }
12081                                         if ($midpos > 0) {
12082                                                 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
12083                                                 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
12084                                         } else {
12085                                                 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
12086                                                 $pend = '';
12087                                         }
12088                                         // calculate shifting amount
12089                                         $tw = $w;
12090                                         if ($this->lMargin != $prevlMargin) {
12091                                                 $tw += ($prevlMargin - $this->lMargin);
12092                                         }
12093                                         if ($this->rMargin != $prevrMargin) {
12094                                                 $tw += ($prevrMargin - $this->rMargin);
12095                                         }
12096                                         $mdiff = abs($tw - $linew);
12097                                         if ($plalign == 'C') {
12098                                                 if ($this->rtl) {
12099                                                         $t_x = -($mdiff / 2);
12100                                                 } else {
12101                                                         $t_x = ($mdiff / 2);
12102                                                 }
12103                                         } elseif (($plalign == 'R') AND (!$this->rtl)) {
12104                                                 // right alignment on LTR document
12105                                                 $t_x = $mdiff;
12106                                         } elseif (($plalign == 'L') AND ($this->rtl)) {
12107                                                 // left alignment on RTL document
12108                                                 $t_x = -$mdiff;
12109                                         } else {
12110                                                 $t_x = 0;
12111                                         }
12112                                         if (($t_x != 0) OR ($yshift < 0)) {
12113                                                 // shift the line
12114                                                 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
12115                                                 $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
12116                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
12117                                                 // shift the annotations and links
12118                                                 if (isset($this->PageAnnots[$this->page])) {
12119                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
12120                                                                 if ($pak >= $pask) {
12121                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
12122                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
12123                                                                 }
12124                                                         }
12125                                                 }
12126                                                 $this->y -= $yshift;
12127                                         }
12128                                 }
12129                         }
12130                         if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
12131                                 $this->Ln($this->lasth);
12132                         }
12133                         // restore previous values
12134                         $this->setGraphicVars($gvars);
12135                         if ($this->page > $prevPage) {
12136                                 $this->lMargin = $this->pagedim[$this->page]['olm'];
12137                                 $this->rMargin = $this->pagedim[$this->page]['orm'];
12138                         }
12139                         unset($dom);
12140                 }
12141
12142                 /**
12143                  * Process opening tags.
12144                  * @param array $dom html dom array
12145                  * @param int $key current element id
12146                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
12147                  * @access protected
12148                  */
12149                 protected function openHTMLTagHandler(&$dom, $key, $cell=false) {
12150                         $tag = $dom[$key];
12151                         $parent = $dom[($dom[$key]['parent'])];
12152                         $firstorlast = ($key == 1);
12153                         // check for text direction attribute
12154                         if (isset($tag['attribute']['dir'])) {
12155                                 $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
12156                         } else {
12157                                 $this->tmprtl = false;
12158                         }
12159                         //Opening tag
12160                         switch($tag['value']) {
12161                                 case 'table': {
12162                                         $cp = 0;
12163                                         $cs = 0;
12164                                         $dom[$key]['rowspans'] = array();
12165                                         if (!$this->empty_string($dom[$key]['thead'])) {
12166                                                 // set table header
12167                                                 $this->thead = $dom[$key]['thead'];
12168                                         }
12169                                         if (isset($tag['attribute']['cellpadding'])) {
12170                                                 $cp = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
12171                                                 $this->oldcMargin = $this->cMargin;
12172                                                 $this->cMargin = $cp;
12173                                         }
12174                                         if (isset($tag['attribute']['cellspacing'])) {
12175                                                 $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
12176                                         }
12177                                         $this->checkPageBreak((2 * $cp) + (2 * $cs) + $this->lasth);
12178                                         break;
12179                                 }
12180                                 case 'tr': {
12181                                         // array of columns positions
12182                                         $dom[$key]['cellpos'] = array();
12183                                         break;
12184                                 }
12185                                 case 'hr': {
12186                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12187                                         $this->htmlvspace = 0;
12188                                         $wtmp = $this->w - $this->lMargin - $this->rMargin;
12189                                         if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
12190                                                 $hrWidth = $this->getHTMLUnitToUnits($tag['attribute']['width'], $wtmp, 'px');
12191                                         } else {
12192                                                 $hrWidth = $wtmp;
12193                                         }
12194                                         $x = $this->GetX();
12195                                         $y = $this->GetY();
12196                                         $prevlinewidth = $this->GetLineWidth();
12197                                         $this->Line($x, $y, $x + $hrWidth, $y);
12198                                         $this->SetLineWidth($prevlinewidth);
12199                                         $this->addHTMLVertSpace(1, $cell, '', !isset($dom[($key + 1)]), $tag['value'], false);
12200                                         break;
12201                                 }
12202                                 case 'a': {
12203                                         if (array_key_exists('href', $tag['attribute'])) {
12204                                                 $this->HREF['url'] = $tag['attribute']['href'];
12205                                         }
12206                                         $this->HREF['color'] = $this->htmlLinkColorArray;
12207                                         $this->HREF['style'] = $this->htmlLinkFontStyle;
12208                                         if (array_key_exists('style', $tag['attribute'])) {
12209                                                 // get style attributes
12210                                                 preg_match_all('/([^;:\s]*):([^;]*)/', $tag['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
12211                                                 $astyle = array();
12212                                                 while (list($id, $name) = each($style_array[1])) {
12213                                                         $name = strtolower($name);
12214                                                         $astyle[$name] = trim($style_array[2][$id]);
12215                                                 }
12216                                                 if (isset($astyle['color'])) {
12217                                                         $this->HREF['color'] = $this->convertHTMLColorToDec($astyle['color']);
12218                                                 }
12219                                                 if (isset($astyle['text-decoration'])) {
12220                                                         $this->HREF['style'] = '';
12221                                                         $decors = explode(' ', strtolower($astyle['text-decoration']));
12222                                                         foreach ($decors as $dec) {
12223                                                                 $dec = trim($dec);
12224                                                                 if (!$this->empty_string($dec)) {
12225                                                                         if ($dec{0} == 'u') {
12226                                                                                 $this->HREF['style'] .= 'U';
12227                                                                         } elseif ($dec{0} == 'l') {
12228                                                                                 $this->HREF['style'] .= 'D';
12229                                                                         }
12230                                                                 }
12231                                                         }
12232                                                 }
12233                                         }
12234                                         break;
12235                                 }
12236                                 case 'img': {
12237                                         if (isset($tag['attribute']['src'])) {
12238                                                 // replace relative path with real server path
12239                                                 if ($tag['attribute']['src'][0] == '/') {
12240                                                         $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
12241                                                 }
12242                                                 $tag['attribute']['src'] = urldecode($tag['attribute']['src']);
12243                                                 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
12244                                                 if (!isset($tag['attribute']['width'])) {
12245                                                         $tag['attribute']['width'] = 0;
12246                                                 }
12247                                                 if (!isset($tag['attribute']['height'])) {
12248                                                         $tag['attribute']['height'] = 0;
12249                                                 }
12250                                                 //if (!isset($tag['attribute']['align'])) {
12251                                                         // the only alignment supported is "bottom"
12252                                                         // further development is required for other modes.
12253                                                         $tag['attribute']['align'] = 'bottom';
12254                                                 //}
12255                                                 switch($tag['attribute']['align']) {
12256                                                         case 'top': {
12257                                                                 $align = 'T';
12258                                                                 break;
12259                                                         }
12260                                                         case 'middle': {
12261                                                                 $align = 'M';
12262                                                                 break;
12263                                                         }
12264                                                         case 'bottom': {
12265                                                                 $align = 'B';
12266                                                                 break;
12267                                                         }
12268                                                         default: {
12269                                                                 $align = 'B';
12270                                                                 break;
12271                                                         }
12272                                                 }
12273                                                 $fileinfo = pathinfo($tag['attribute']['src']);
12274                                                 if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
12275                                                         $type = strtolower($fileinfo['extension']);
12276                                                 }
12277                                                 $prevy = $this->y;
12278                                                 $xpos = $this->GetX();
12279                                                 if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == ' ')) {
12280                                                         if ($this->rtl) {
12281                                                                 $xpos += $this->GetStringWidth(' ');
12282                                                         } else {
12283                                                                 $xpos -= $this->GetStringWidth(' ');
12284                                                         }
12285                                                 }
12286                                                 $imglink = '';
12287                                                 if (isset($this->HREF['url']) AND !$this->empty_string($this->HREF['url'])) {
12288                                                         $imglink = $this->HREF['url'];
12289                                                         if ($imglink{0} == '#') {
12290                                                                 // convert url to internal link
12291                                                                 $page = intval(substr($imglink, 1));
12292                                                                 $imglink = $this->AddLink();
12293                                                                 $this->SetLink($imglink, 0, $page);
12294                                                         }
12295                                                 }
12296                                                 $border = 0;
12297                                                 if (isset($tag['attribute']['border']) AND !empty($tag['attribute']['border'])) {
12298                                                         // currently only support 1 (frame) or a combination of 'LTRB'
12299                                                         $border = $tag['attribute']['border'];
12300                                                 }
12301                                                 $iw = '';
12302                                                 if (isset($tag['attribute']['width'])) {
12303                                                         $iw = $this->getHTMLUnitToUnits($tag['attribute']['width'], 1, 'px', false);
12304                                                 }
12305                                                 $ih = '';
12306                                                 if (isset($tag['attribute']['height'])) {
12307                                                         $ih = $this->getHTMLUnitToUnits($tag['attribute']['height'], 1, 'px', false);
12308                                                 }
12309                                                 if (($type == 'eps') OR ($type == 'ai')) {
12310                                                         $this->ImageEps($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, $imglink, true, $align, '', $border);
12311                                                 } else {
12312                                                         $this->Image($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border);
12313                                                 }
12314                                                 switch($align) {
12315                                                         case 'T': {
12316                                                                 $this->y = $prevy;
12317                                                                 break;
12318                                                         }
12319                                                         case 'M': {
12320                                                                 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
12321                                                                 break;
12322                                                         }
12323                                                         case 'B': {
12324                                                                 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
12325                                                                 break;
12326                                                         }
12327                                                 }
12328                                         }
12329                                         break;
12330                                 }
12331                                 case 'dl': {
12332                                         ++$this->listnum;
12333                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12334                                         break;
12335                                 }
12336                                 case 'dt': {
12337                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12338                                         break;
12339                                 }
12340                                 case 'dd': {
12341                                         if ($this->rtl) {
12342                                                 $this->rMargin += $this->listindent;
12343                                         } else {
12344                                                 $this->lMargin += $this->listindent;
12345                                         }
12346                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12347                                         break;
12348                                 }
12349                                 case 'ul':
12350                                 case 'ol': {
12351                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12352                                         $this->htmlvspace = 0;
12353                                         ++$this->listnum;
12354                                         if ($tag['value'] == 'ol') {
12355                                                 $this->listordered[$this->listnum] = true;
12356                                         } else {
12357                                                 $this->listordered[$this->listnum] = false;
12358                                         }
12359                                         if (isset($tag['attribute']['start'])) {
12360                                                 $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
12361                                         } else {
12362                                                 $this->listcount[$this->listnum] = 0;
12363                                         }
12364                                         if ($this->rtl) {
12365                                                 $this->rMargin += $this->listindent;
12366                                         } else {
12367                                                 $this->lMargin += $this->listindent;
12368                                         }
12369                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12370                                         $this->htmlvspace = 0;
12371                                         break;
12372                                 }
12373                                 case 'li': {
12374                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12375                                         if ($this->listordered[$this->listnum]) {
12376                                                 // ordered item
12377                                                 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
12378                                                         $this->lispacer = $parent['attribute']['type'];
12379                                                 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
12380                                                         $this->lispacer = $parent['listtype'];
12381                                                 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
12382                                                         $this->lispacer = $this->lisymbol;
12383                                                 } else {
12384                                                         $this->lispacer = '#';
12385                                                 }
12386                                                 ++$this->listcount[$this->listnum];
12387                                                 if (isset($tag['attribute']['value'])) {
12388                                                         $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
12389                                                 }
12390                                         } else {
12391                                                 // unordered item
12392                                                 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
12393                                                         $this->lispacer = $parent['attribute']['type'];
12394                                                 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
12395                                                         $this->lispacer = $parent['listtype'];
12396                                                 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
12397                                                         $this->lispacer = $this->lisymbol;
12398                                                 } else {
12399                                                         $this->lispacer = '!';
12400                                                 }
12401                                         }
12402                                         break;
12403                                 }
12404                                 case 'blockquote': {
12405                                         if ($this->rtl) {
12406                                                 $this->rMargin += $this->listindent;
12407                                         } else {
12408                                                 $this->lMargin += $this->listindent;
12409                                         }
12410                                         $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
12411                                         break;
12412                                 }
12413                                 case 'br': {
12414                                         $this->Ln('', $cell);
12415                                         break;
12416                                 }
12417                                 case 'div': {
12418                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12419                                         break;
12420                                 }
12421                                 case 'p': {
12422                                         $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
12423                                         break;
12424                                 }
12425                                 case 'pre': {
12426                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12427                                         $this->premode = true;
12428                                         break;
12429                                 }
12430                                 case 'sup': {
12431                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
12432                                         break;
12433                                 }
12434                                 case 'sub': {
12435                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
12436                                         break;
12437                                 }
12438                                 case 'h1':
12439                                 case 'h2':
12440                                 case 'h3':
12441                                 case 'h4':
12442                                 case 'h5':
12443                                 case 'h6': {
12444                                         $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], false);
12445                                         break;
12446                                 }
12447                                 case 'tcpdf': {
12448                                         if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
12449                                                  // Special tag used to call TCPDF methods
12450                         if (isset($tag['attribute']['method'])) {
12451                             $tcpdf_method = $tag['attribute']['method'];
12452                             if (method_exists($this, $tcpdf_method)) {
12453                                 if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
12454                                     $params = unserialize(urldecode($tag['attribute']['params']));
12455                                     call_user_func_array(array($this, $tcpdf_method), $params);
12456                                 } else {
12457                                     $this->$tcpdf_method();
12458                                 }
12459                                 $this->newline = true;
12460                             }
12461                         }
12462                     }
12463                                 }
12464                                 default: {
12465                                         break;
12466                                 }
12467                         }
12468                 }
12469
12470                 /**
12471                  * Process closing tags.
12472                  * @param array $dom html dom array
12473                  * @param int $key current element id
12474                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
12475                  * @access protected
12476                  */
12477                 protected function closeHTMLTagHandler(&$dom, $key, $cell=false) {
12478                         $tag = $dom[$key];
12479                         $parent = $dom[($dom[$key]['parent'])];
12480                         $firstorlast = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
12481                         //Closing tag
12482                         switch($tag['value']) {
12483                                 case 'tr': {
12484                                         $table_el = $dom[($dom[$key]['parent'])]['parent'];
12485                                         if(!isset($parent['endy'])) {
12486                                                 $dom[($dom[$key]['parent'])]['endy'] = $this->y;
12487                                                 $parent['endy'] = $this->y;
12488                                         }
12489                                         if(!isset($parent['endpage'])) {
12490                                                 $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
12491                                                 $parent['endpage'] = $this->page;
12492                                         }
12493                                         // update row-spanned cells
12494                                         if (isset($dom[$table_el]['rowspans'])) {
12495                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12496                                                         $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
12497                                                         if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12498                                                                 if ($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) {
12499                                                                         $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
12500                                                                 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) {
12501                                                                         $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
12502                                                                         $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
12503                                                                 }
12504                                                         }
12505                                                 }
12506                                                 // report new endy and endpage to the rowspanned cells
12507                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12508                                                         if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12509                                                                 $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
12510                                                                 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
12511                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
12512                                                                 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
12513                                                         }
12514                                                 }
12515                                                 // update remaining rowspanned cells
12516                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12517                                                         if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12518                                                                 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
12519                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
12520                                                         }
12521                                                 }
12522                                         }
12523                                         $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
12524                                         $this->y = $dom[($dom[$key]['parent'])]['endy'];
12525                                         if (isset($dom[$table_el]['attribute']['cellspacing'])) {
12526                                                 $cellspacing = $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
12527                                                 $this->y += $cellspacing;
12528                                         }
12529                                         $this->Ln(0, $cell);
12530                                         $this->x = $parent['startx'];
12531                                         // account for booklet mode
12532                                         if ($this->page > $parent['startpage']) {
12533                                                 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
12534                                                         $this->x += ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
12535                                                 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
12536                                                         $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
12537                                                 }
12538                                         }
12539                                         break;
12540                                 }
12541                                 case 'table': {
12542                                         // draw borders
12543                                         $table_el = $parent;
12544                                         if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
12545                                                 OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
12546                                                         $border = 1;
12547                                         } else {
12548                                                 $border = 0;
12549                                         }
12550                                         // fix bottom line alignment of last line before page break
12551                                         foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
12552                                                 // update row-spanned cells
12553                                                 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
12554                                                         foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
12555                                                                 if ($trwsp['trid'] == $trkey) {
12556                                                                         $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
12557                                                                 }
12558                                                                 if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0)) {
12559                                                                         $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
12560                                                                 }
12561                                                         }
12562                                                 }
12563                                                 if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
12564                                                         $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
12565                                                         $dom[$prevtrkey]['endy'] = $pgendy;
12566                                                         // update row-spanned cells
12567                                                         if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
12568                                                                 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
12569                                                                         if (($trwsp['trid'] == $trkey) AND ($trwsp['mrowspan'] == 1) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
12570                                                                                 $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
12571                                                                                 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
12572                                                                         }
12573                                                                 }
12574                                                         }
12575                                                 }
12576                                                 $prevtrkey = $trkey;
12577                                                 $table_el = $dom[($dom[$key]['parent'])];
12578                                         }
12579                                         // for each row
12580                                         foreach ($table_el['trids'] as $j => $trkey) {
12581                                                 $parent = $dom[$trkey];
12582                                                 // for each cell on the row
12583                                                 foreach ($parent['cellpos'] as $k => $cellpos) {
12584                                                         if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
12585                                                                 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
12586                                                                 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
12587                                                                 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
12588                                                                 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
12589                                                                 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
12590                                                         } else {
12591                                                                 $endy = $parent['endy'];
12592                                                                 $startpage = $parent['startpage'];
12593                                                                 $endpage = $parent['endpage'];
12594                                                         }
12595                                                         if ($endpage > $startpage) {
12596                                                                 // design borders around HTML cells.
12597                                                                 for ($page=$startpage; $page <= $endpage; ++$page) {
12598                                                                         $this->setPage($page);
12599                                                                         if ($page == $startpage) {
12600                                                                                 $this->y = $parent['starty']; // put cursor at the beginning of row on the first page
12601                                                                                 $ch = $this->getPageHeight() - $parent['starty'] - $this->getBreakMargin();
12602                                                                                 $cborder = $this->getBorderMode($border, $position='start');
12603                                                                         } elseif ($page == $endpage) {
12604                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of last page
12605                                                                                 $ch = $endy - $this->tMargin;
12606                                                                                 $cborder = $this->getBorderMode($border, $position='end');
12607                                                                         } else {
12608                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of the current page
12609                                                                                 $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
12610                                                                                 $cborder = $this->getBorderMode($border, $position='middle');
12611                                                                         }
12612                                                                         if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
12613                                                                                 $this->SetFillColorArray($cellpos['bgcolor']);
12614                                                                                 $fill = true;
12615                                                                         } else {
12616                                                                                 $fill = false;
12617                                                                         }
12618                                                                         $cw = abs($cellpos['endx'] - $cellpos['startx']);
12619                                                                         $this->x = $cellpos['startx'];
12620                                                                         // account for margin changes
12621                                                                         if ($page > $startpage) {
12622                                                                                 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
12623                                                                                         $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
12624                                                                                 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['lm'] != $this->pagedim[$startpage]['olm'])) {
12625                                                                                         $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
12626                                                                                 }
12627                                                                         }
12628                                                                         // design a cell around the text
12629                                                                         $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $cborder, 1, '', $fill, '', 0, true);
12630                                                                         if ($cborder OR $fill) {
12631                                                                                 $pagebuff = $this->getPageBuffer($this->page);
12632                                                                                 $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
12633                                                                                 $pend = substr($pagebuff, $this->intmrk[$this->page]);
12634                                                                                 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
12635                                                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
12636                                                                         }
12637                                                                 }
12638                                                         } else {
12639                                                                 $this->setPage($startpage);
12640                                                                 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
12641                                                                         $this->SetFillColorArray($cellpos['bgcolor']);
12642                                                                         $fill = true;
12643                                                                 } else {
12644                                                                         $fill = false;
12645                                                                 }
12646                                                                 $this->x = $cellpos['startx'];
12647                                                                 $this->y = $parent['starty'];
12648                                                                 $cw = abs($cellpos['endx'] - $cellpos['startx']);
12649                                                                 $ch = $endy - $parent['starty'];
12650                                                                 // design a cell around the text
12651                                                                 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $border, 1, '', $fill, '', 0, true);
12652                                                                 if ($border OR $fill) {
12653                                                                         if (end($this->transfmrk[$this->page]) !== false) {
12654                                                                                 $pagemarkkey = key($this->transfmrk[$this->page]);
12655                                                                                 $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
12656                                                                         } elseif ($this->InFooter) {
12657                                                                                 $pagemark = &$this->footerpos[$this->page];
12658                                                                         } else {
12659                                                                                 $pagemark = &$this->intmrk[$this->page];
12660                                                                         }
12661                                                                         $pagebuff = $this->getPageBuffer($this->page);
12662                                                                         $pstart = substr($pagebuff, 0, $pagemark);
12663                                                                         $pend = substr($pagebuff, $pagemark);
12664                                                                         $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
12665                                                                         $pagemark += strlen($ccode."\n");
12666                                                                 }
12667                                                         }
12668                                                 }
12669                                                 if (isset($table_el['attribute']['cellspacing'])) {
12670                                                         $cellspacing = $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
12671                                                         $this->y += $cellspacing;
12672                                                 }
12673                                                 $this->Ln(0, $cell);
12674                                                 $this->x = $parent['startx'];
12675                                                 if ($endpage > $startpage) {
12676                                                         if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
12677                                                                 $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
12678                                                         } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
12679                                                                 $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
12680                                                         }
12681                                                 }
12682                                         }
12683                                         if (isset($parent['cellpadding'])) {
12684                                                 $this->cMargin = $this->oldcMargin;
12685                                         }
12686                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
12687                                         if (!$this->empty_string($this->theadMargin)) {
12688                                                 // restore top margin
12689                                                 $this->tMargin = $this->theadMargin;
12690                                                 $this->pagedim[$this->page]['tm'] = $this->theadMargin;
12691                                         }
12692                                         // reset table header
12693                                         $this->thead = '';
12694                                         $this->theadMargin = '';
12695                                         break;
12696                                 }
12697                                 case 'a': {
12698                                         $this->HREF = '';
12699                                         break;
12700                                 }
12701                                 case 'sup': {
12702                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
12703                                         break;
12704                                 }
12705                                 case 'sub': {
12706                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
12707                                         break;
12708                                 }
12709                                 case 'div': {
12710                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
12711                                         break;
12712                                 }
12713                                 case 'blockquote': {
12714                                         if ($this->rtl) {
12715                                                 $this->rMargin -= $this->listindent;
12716                                         } else {
12717                                                 $this->lMargin -= $this->listindent;
12718                                         }
12719                                         $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12720                                         break;
12721                                 }
12722                                 case 'p': {
12723                                         $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12724                                         break;
12725                                 }
12726                                 case 'pre': {
12727                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
12728                                         $this->premode = false;
12729                                         break;
12730                                 }
12731                                 case 'dl': {
12732                                         --$this->listnum;
12733                                         if ($this->listnum <= 0) {
12734                                                 $this->listnum = 0;
12735                                                 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12736                                         }
12737                                         break;
12738                                 }
12739                                 case 'dt': {
12740                                         $this->lispacer = '';
12741                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12742                                         break;
12743                                 }
12744                                 case 'dd': {
12745                                         $this->lispacer = '';
12746                                         if ($this->rtl) {
12747                                                 $this->rMargin -= $this->listindent;
12748                                         } else {
12749                                                 $this->lMargin -= $this->listindent;
12750                                         }
12751                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12752                                         break;
12753                                 }
12754                                 case 'ul':
12755                                 case 'ol': {
12756                                         --$this->listnum;
12757                                         $this->lispacer = '';
12758                                         if ($this->rtl) {
12759                                                 $this->rMargin -= $this->listindent;
12760                                         } else {
12761                                                 $this->lMargin -= $this->listindent;
12762                                         }
12763                                         if ($this->listnum <= 0) {
12764                                                 $this->listnum = 0;
12765                                                 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12766                                         }
12767                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
12768                                         break;
12769                                 }
12770                                 case 'li': {
12771                                         $this->lispacer = '';
12772                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12773                                         break;
12774                                 }
12775                                 case 'h1':
12776                                 case 'h2':
12777                                 case 'h3':
12778                                 case 'h4':
12779                                 case 'h5':
12780                                 case 'h6': {
12781                                         $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], true);
12782                                         break;
12783                                 }
12784                                 default : {
12785                                         break;
12786                                 }
12787                         }
12788                         $this->tmprtl = false;
12789                 }
12790
12791                 /**
12792                  * Add vertical spaces if needed.
12793                  * @param int $n number of spaces to add
12794                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
12795                  * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
12796                  * @param boolean $firstorlast if true do not print additional empty lines.
12797                  * @param string $tag HTML tag to which this space will be applied
12798                  * @param boolean $closing true if this space will be applied to a closing tag, false otherwise
12799                  * @access protected
12800                  */
12801                 protected function addHTMLVertSpace($n, $cell=false, $h='', $firstorlast=false, $tag='', $closing=false) {
12802                         if ($firstorlast) {
12803                                 $this->Ln(0, $cell);
12804                                 $this->htmlvspace = 0;
12805                                 return;
12806                         }
12807                         if (isset($this->tagvspaces[$tag][intval($closing)]['n'])) {
12808                                 $n = $this->tagvspaces[$tag][intval($closing)]['n'];
12809                         }
12810                         if (isset($this->tagvspaces[$tag][intval($closing)]['h'])) {
12811                                 $h = $this->tagvspaces[$tag][intval($closing)]['h'];
12812                         }
12813                         if (is_string($h)) {
12814                                 $vsize = $n * $this->lasth;
12815                         } else {
12816                                 $vsize = $n * $h;
12817                         }
12818                         if ($vsize > $this->htmlvspace) {
12819                                 $this->Ln(($vsize - $this->htmlvspace), $cell);
12820                                 $this->htmlvspace = $vsize;
12821                         }
12822                 }
12823
12824                 /**
12825                  * Set the default bullet to be used as LI bullet symbol
12826                  * @param string $symbol character or string to be used (legal values are: '' = automatic, '!' = auto bullet, '#' = auto numbering, 'disc', 'disc', 'circle', 'square', '1', 'decimal', 'decimal-leading-zero', 'i', 'lower-roman', 'I', 'upper-roman', 'a', 'lower-alpha', 'lower-latin', 'A', 'upper-alpha', 'upper-latin', 'lower-greek')
12827                  * @access public
12828                  * @since 4.0.028 (2008-09-26)
12829                  */
12830                 public function setLIsymbol($symbol='!') {
12831                         $symbol = strtolower($symbol);
12832                         switch ($symbol) {
12833                                 case '!' :
12834                                 case '#' :
12835                                 case 'disc' :
12836                                 case 'disc' :
12837                                 case 'circle' :
12838                                 case 'square' :
12839                                 case '1':
12840                                 case 'decimal':
12841                                 case 'decimal-leading-zero':
12842                                 case 'i':
12843                                 case 'lower-roman':
12844                                 case 'I':
12845                                 case 'upper-roman':
12846                                 case 'a':
12847                                 case 'lower-alpha':
12848                                 case 'lower-latin':
12849                                 case 'A':
12850                                 case 'upper-alpha':
12851                                 case 'upper-latin':
12852                                 case 'lower-greek': {
12853                                         $this->lisymbol = $symbol;
12854                                         break;
12855                                 }
12856                                 default : {
12857                                         $this->lisymbol = '';
12858                                 }
12859                         }
12860                 }
12861
12862                 /**
12863                 * Set the booklet mode for double-sided pages.
12864                 * @param boolean $booklet true set the booklet mode on, fals eotherwise.
12865                 * @param float $inner Inner page margin.
12866                 * @param float $outer Outer page margin.
12867                 * @access public
12868                 * @since 4.2.000 (2008-10-29)
12869                 */
12870                 public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
12871                         $this->booklet = $booklet;
12872                         if ($inner >= 0) {
12873                                 $this->lMargin = $inner;
12874                         }
12875                         if ($outer >= 0) {
12876                                 $this->rMargin = $outer;
12877                         }
12878                 }
12879
12880                 /**
12881                 * Swap the left and right margins.
12882                 * @param boolean $reverse if true swap left and right margins.
12883                 * @access protected
12884                 * @since 4.2.000 (2008-10-29)
12885                 */
12886                 protected function swapMargins($reverse=true) {
12887                         if ($reverse) {
12888                                 // swap left and right margins
12889                                 $mtemp = $this->original_lMargin;
12890                                 $this->original_lMargin = $this->original_rMargin;
12891                                 $this->original_rMargin = $mtemp;
12892                                 $deltam = $this->original_lMargin - $this->original_rMargin;
12893                                 $this->lMargin += $deltam;
12894                                 $this->rMargin -= $deltam;
12895                         }
12896                 }
12897
12898                 /**
12899                 * Set the vertical spaces for HTML tags.
12900                 * The array must have the following structure (example):
12901                 * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
12902                 * The first array level contains the tag names,
12903                 * the second level contains 0 for opening tags or 1 for closing tags,
12904                 * the third level contains the vertical space unit (h) and the number spaces to add (n).
12905                 * If the h parameter is not specified, default values are used.
12906                 * @param array $tagvs array of tags and relative vertical spaces.
12907                 * @access public
12908                 * @since 4.2.001 (2008-10-30)
12909                 */
12910                 public function setHtmlVSpace($tagvs) {
12911                         $this->tagvspaces = $tagvs;
12912                 }
12913
12914         /**
12915                 * Set custom width for list indentation.
12916                 * @param float $width width of the indentation. Use negative value to disable it.
12917                 * @access public
12918                 * @since 4.2.007 (2008-11-12)
12919                 */
12920                 public function setListIndentWidth($width) {
12921                         return $this->customlistindent = floatval($width);
12922         }
12923
12924         /**
12925                 * Set the top/bottom cell sides to be open or closed when the cell cross the page.
12926                 * @param boolean $isopen if true keeps the top/bottom border open for the cell sides that cross the page.
12927                 * @access public
12928                 * @since 4.2.010 (2008-11-14)
12929                 */
12930                 public function setOpenCell($isopen) {
12931                         $this->opencell = $isopen;
12932         }
12933
12934         /**
12935                 * Set the color and font style for HTML links.
12936                 * @param array $color RGB array of colors
12937                 * @param string $fontstyle additional font styles to add
12938                 * @access public
12939                 * @since 4.4.003 (2008-12-09)
12940                 */
12941                 public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
12942                         $this->htmlLinkColorArray = $color;
12943                         $this->htmlLinkFontStyle = $fontstyle;
12944         }
12945
12946         /**
12947                 * convert html string containing value and unit of measure to user's units or points.
12948                 * @param string $htmlval string containing values and unit
12949                 * @param string $refsize reference value in points
12950                 * @param string $defaultunit default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
12951                 * @param boolean $point if true returns points, otherwise returns value in user's units
12952                 * @return float value in user's unit or point if $points=true
12953                 * @access public
12954                 * @since 4.4.004 (2008-12-10)
12955                 */
12956         public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
12957                         $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
12958                         $retval = 0;
12959                         $value = 0;
12960                         $unit = 'px';
12961                         $k = $this->k;
12962                         if ($points) {
12963                                 $k = 1;
12964                         }
12965                         if (in_array($defaultunit, $supportedunits)) {
12966                                 $unit = $defaultunit;
12967                         }
12968                         if (is_numeric($htmlval)) {
12969                                 $value = floatval($htmlval);
12970                         } elseif (preg_match('/([0-9\.]+)/', $htmlval, $mnum)) {
12971                                 $value = floatval($mnum[1]);
12972                                 if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
12973                                         if (in_array($munit[1], $supportedunits)) {
12974                                                 $unit = $munit[1];
12975                                         }
12976                                 }
12977                         }
12978                         switch ($unit) {
12979                                 // percentage
12980                                 case '%': {
12981                                         $retval = (($value * $refsize) / 100);
12982                                         break;
12983                                 }
12984                                 // relative-size
12985                                 case 'em': {
12986                                         $retval = ($value * $refsize);
12987                                         break;
12988                                 }
12989                                 case 'ex': {
12990                                         $retval = $value * ($refsize / 2);
12991                                         break;
12992                                 }
12993                                 // absolute-size
12994                                 case 'in': {
12995                                         $retval = ($value * $this->dpi) / $k;
12996                                         break;
12997                                 }
12998                                 case 'cm': {
12999                                         $retval = ($value / 2.54 * $this->dpi) / $k;
13000                                         break;
13001                                 }
13002                                 case 'mm': {
13003                                         $retval = ($value / 25.4 * $this->dpi) / $k;
13004                                         break;
13005                                 }
13006                                 case 'pc': {
13007                                         // one pica is 12 points
13008                                         $retval = ($value * 12) / $k;
13009                                         break;
13010                                 }
13011                                 case 'pt': {
13012                                         $retval = $value / $k;
13013                                         break;
13014                                 }
13015                                 case 'px': {
13016                                         $retval = $this->pixelsToUnits($value);
13017                                         break;
13018                                 }
13019                         }
13020                         return $retval;
13021                 }
13022
13023                 /**
13024                 * Returns the Roman representation of an integer number
13025                 * @param int number to convert
13026                 * @return string roman representation of the specified number
13027                 * @access public
13028                 * @since 4.4.004 (2008-12-10)
13029                 */
13030                 public function intToRoman($number) {
13031                         $roman = '';
13032                         while ($number >= 1000) {
13033                                 $roman .= 'M';
13034                                 $number -= 1000;
13035                         }
13036                         while ($number >= 900) {
13037                                 $roman .= 'CM';
13038                                 $number -= 900;
13039                         }
13040                         while ($number >= 500) {
13041                                 $roman .= 'D';
13042                                 $number -= 500;
13043                         }
13044                         while ($number >= 400) {
13045                                 $roman .= 'CD';
13046                                 $number -= 400;
13047                         }
13048                         while ($number >= 100) {
13049                                 $roman .= 'C';
13050                                 $number -= 100;
13051                         }
13052                         while ($number >= 90) {
13053                         $roman .= 'XC';
13054                         $number -= 90;
13055                         }
13056                         while ($number >= 50) {
13057                                 $roman .= 'L';
13058                                 $number -= 50;
13059                         }
13060                         while ($number >= 40) {
13061                                 $roman .= 'XL';
13062                                 $number -= 40;
13063                         }
13064                         while ($number >= 10) {
13065                         $roman .= 'X';
13066                         $number -= 10;
13067                         }
13068                         while ($number >= 9) {
13069                                 $roman .= 'IX';
13070                                 $number -= 9;
13071                         }
13072                         while ($number >= 5) {
13073                                 $roman .= 'V';
13074                                 $number -= 5;
13075                         }
13076                         while ($number >= 4) {
13077                         $roman .= 'IV';
13078                         $number -= 4;
13079                         }
13080                         while ($number >= 1) {
13081                                 $roman .= 'I';
13082                                 --$number;
13083                         }
13084                         return $roman;
13085                 }
13086
13087                 /**
13088                 * Output an HTML list bullet or ordered item symbol
13089                 * @param int $listdepth list nesting level
13090                 * @param string $listtype type of list
13091                 * @param float $size current font size
13092                 * @access protected
13093                 * @since 4.4.004 (2008-12-10)
13094                 */
13095                 protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
13096                     $size /= $this->k;
13097                     $fill = '';
13098                     $color = $this->fgcolor;
13099                     $width = 0;
13100                     $textitem = '';
13101                     $tmpx = $this->x;
13102                         $lspace = $this->GetStringWidth('  ');
13103                         if ($listtype == '!') {
13104                                 // set default list type for unordered list
13105                                 $deftypes = array('disc', 'circle', 'square');
13106                                 $listtype = $deftypes[($listdepth - 1) % 3];
13107                         } elseif ($listtype == '#') {
13108                                 // set default list type for ordered list
13109                                 $listtype = 'decimal';
13110                         }
13111                 switch ($listtype) {
13112                         // unordered types
13113                                 case 'none': {
13114                                         break;
13115                                 }
13116                                 case 'disc': {
13117                                         $fill = 'F';
13118                                 }
13119                                 case 'circle': {
13120                                         $fill .= 'D';
13121                                         $r = $size / 6;
13122                                         $lspace += (2 * $r);
13123                                         if ($this->rtl) {
13124                                                 $this->x = $this->w - $this->x - $lspace;
13125                                         } else {
13126                                                 $this->x -= $lspace;
13127                                         }
13128                                         $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, $fill, array('color'=>$color), $color, 8);
13129                                         break;
13130                                 }
13131                                 case 'square': {
13132                                         $l = $size / 3;
13133                                         $lspace += $l;
13134                                         if ($this->rtl) {
13135                                                 $this->x = $this->w - $this->x - $lspace;
13136                                         } else {
13137                                                 $this->x -= $lspace;
13138                                         }
13139                                         $this->Rect($this->x, ($this->y + (($this->lasth - $l)/ 2)), $l, $l, 'F', array(), $color);
13140                                         break;
13141                                 }
13142                                 // ordered types
13143
13144                                 // $this->listcount[$this->listnum];
13145                                 // $textitem
13146                                 case '1':
13147                                 case 'decimal': {
13148                                         $textitem = $this->listcount[$this->listnum];
13149                                         break;
13150                                 }
13151                                 case 'decimal-leading-zero': {
13152                                         $textitem = sprintf("%02d", $this->listcount[$this->listnum]);
13153                                         break;
13154                                 }
13155                                 case 'i':
13156                                 case 'lower-roman': {
13157                                         $textitem = strtolower($this->intToRoman($this->listcount[$this->listnum]));
13158                                         break;
13159                                 }
13160                                 case 'I':
13161                                 case 'upper-roman': {
13162                                         $textitem = $this->intToRoman($this->listcount[$this->listnum]);
13163                                         break;
13164                                 }
13165                                 case 'a':
13166                                 case 'lower-alpha':
13167                                 case 'lower-latin': {
13168                                         $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
13169                                         break;
13170                                 }
13171                                 case 'A':
13172                                 case 'upper-alpha':
13173                                 case 'upper-latin': {
13174                                         $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
13175                                         break;
13176                                 }
13177                                 case 'lower-greek': {
13178                                         $textitem = $this->unichr(945 + $this->listcount[$this->listnum] - 1);
13179                                         break;
13180                                 }
13181                                 /*
13182                                 // Types to be implemented (special handling)
13183                                 case 'hebrew': {
13184                                         break;
13185                                 }
13186                                 case 'armenian': {
13187                                         break;
13188                                 }
13189                                 case 'georgian': {
13190                                         break;
13191                                 }
13192                                 case 'cjk-ideographic': {
13193                                         break;
13194                                 }
13195                                 case 'hiragana': {
13196                                         break;
13197                                 }
13198                                 case 'katakana': {
13199                                         break;
13200                                 }
13201                                 case 'hiragana-iroha': {
13202                                         break;
13203                                 }
13204                                 case 'katakana-iroha': {
13205                                         break;
13206                                 }
13207                                 */
13208                                 default: {
13209                                         $textitem = $this->listcount[$this->listnum];
13210                                 }
13211                         }
13212                         if (!$this->empty_string($textitem)) {
13213                                 // print ordered item
13214                                 if ($this->rtl) {
13215                                         $textitem = '.'.$textitem;
13216                                 } else {
13217                                         $textitem = $textitem.'.';
13218                                 }
13219                                 $lspace += $this->GetStringWidth($textitem);
13220                                 if ($this->rtl) {
13221                                         $this->x += $lspace;
13222                                 } else {
13223                                         $this->x -= $lspace;
13224                                 }
13225                                 $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
13226                         }
13227                         $this->x = $tmpx;
13228                         $this->lispacer = '';
13229                 }
13230
13231         /**
13232                 * Returns current graphic variables as array.
13233                 * @return array graphic variables
13234                 * @access protected
13235                 * @since 4.2.010 (2008-11-14)
13236                 */
13237                 protected function getGraphicVars() {
13238                         $grapvars = array(
13239                                 'FontFamily' => $this->FontFamily,
13240                                 'FontStyle' => $this->FontStyle,
13241                                 'FontSizePt' => $this->FontSizePt,
13242                                 'rMargin' => $this->rMargin,
13243                                 'lMargin' => $this->lMargin,
13244                                 'cMargin' => $this->cMargin,
13245                                 'LineWidth' => $this->LineWidth,
13246                                 'linestyleWidth' => $this->linestyleWidth,
13247                                 'linestyleCap' => $this->linestyleCap,
13248                                 'linestyleJoin' => $this->linestyleJoin,
13249                                 'linestyleDash' => $this->linestyleDash,
13250                                 'DrawColor' => $this->DrawColor,
13251                                 'FillColor' => $this->FillColor,
13252                                 'TextColor' => $this->TextColor,
13253                                 'ColorFlag' => $this->ColorFlag,
13254                                 'bgcolor' => $this->bgcolor,
13255                                 'fgcolor' => $this->fgcolor,
13256                                 'htmlvspace' => $this->htmlvspace,
13257                                 'lasth' => $this->lasth
13258                                 );
13259                         return $grapvars;
13260                 }
13261
13262         /**
13263                 * Set graphic variables.
13264                 * @param $gvars array graphic variables
13265                 * @access protected
13266                 * @since 4.2.010 (2008-11-14)
13267                 */
13268                 protected function setGraphicVars($gvars) {
13269                         $this->FontFamily = $gvars['FontFamily'];
13270                         $this->FontStyle = $gvars['FontStyle'];
13271                         $this->FontSizePt = $gvars['FontSizePt'];
13272                         $this->rMargin = $gvars['rMargin'];
13273                         $this->lMargin = $gvars['lMargin'];
13274                         $this->cMargin = $gvars['cMargin'];
13275                         $this->LineWidth = $gvars['LineWidth'];
13276                         $this->linestyleWidth = $gvars['linestyleWidth'];
13277                         $this->linestyleCap = $gvars['linestyleCap'];
13278                         $this->linestyleJoin = $gvars['linestyleJoin'];
13279                         $this->linestyleDash = $gvars['linestyleDash'];
13280                         $this->DrawColor = $gvars['DrawColor'];
13281                         $this->FillColor = $gvars['FillColor'];
13282                         $this->TextColor = $gvars['TextColor'];
13283                         $this->ColorFlag = $gvars['ColorFlag'];
13284                         $this->bgcolor = $gvars['bgcolor'];
13285                         $this->fgcolor = $gvars['fgcolor'];
13286                         $this->htmlvspace = $gvars['htmlvspace'];
13287                         //$this->lasth = $gvars['lasth'];
13288                         $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
13289                         if (!$this->empty_string($this->FontFamily)) {
13290                                 $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
13291                         }
13292                 }
13293
13294                 /**
13295                 * Returns a temporary filename for caching object on filesystem.
13296                 * @param string $prefix prefix to add to filename
13297                 * return string filename.
13298                 * @access protected
13299                 * @since 4.5.000 (2008-12-31)
13300                 */
13301                 protected function getObjFilename($name) {
13302                         return tempnam(K_PATH_CACHE, $name.'_');
13303                 }
13304
13305         /**
13306                 * Writes data to a temporary file on filesystem.
13307                 * @param string $file file name
13308                 * @param mixed $data data to write on file
13309                 * @param boolean $append if true append data, false replace.
13310                 * @access protected
13311                 * @since 4.5.000 (2008-12-31)
13312                 */
13313                 protected function writeDiskCache($filename, $data, $append=false) {
13314                         if ($append) {
13315                                 $fmode = 'ab+';
13316                         } else {
13317                                 $fmode = 'wb+';
13318                         }
13319                         $f = @fopen($filename, $fmode);
13320                         if (!$f) {
13321                                 $this->Error('Unable to write cache file: '.$filename);
13322                         } else {
13323                                 fwrite($f, $data);
13324                                 fclose($f);
13325                         }
13326                         // update file lenght (needed for transactions)
13327                         if (!isset($this->cache_file_lenght['_'.$filename])) {
13328                                 $this->cache_file_lenght['_'.$filename] = strlen($data);
13329                         } else {
13330                                 $this->cache_file_lenght['_'.$filename] += strlen($data);
13331                         }
13332                 }
13333
13334         /**
13335                 * Read data from a temporary file on filesystem.
13336                 * @param string $file file name
13337                 * @return mixed retrieved data
13338                 * @access protected
13339                 * @since 4.5.000 (2008-12-31)
13340                 */
13341                 protected function readDiskCache($filename) {
13342                         return file_get_contents($filename);
13343                 }
13344
13345                 /**
13346                 * Set buffer content (always append data).
13347                 * @param string $data data
13348                 * @access protected
13349                 * @since 4.5.000 (2009-01-02)
13350                 */
13351                 protected function setBuffer($data) {
13352                         $this->bufferlen += strlen($data);
13353                         if ($this->diskcache) {
13354                                 if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
13355                                         $this->buffer = $this->getObjFilename('buffer');
13356                                 }
13357                                 $this->writeDiskCache($this->buffer, $data, true);
13358                         } else {
13359                                 $this->buffer .= $data;
13360                         }
13361                 }
13362
13363         /**
13364                 * Get buffer content.
13365                 * @return string buffer content
13366                 * @access protected
13367                 * @since 4.5.000 (2009-01-02)
13368                 */
13369                 protected function getBuffer() {
13370                         if ($this->diskcache) {
13371                                 return $this->readDiskCache($this->buffer);
13372                         } else {
13373                                 return $this->buffer;
13374                         }
13375                 }
13376
13377         /**
13378                 * Set page buffer content.
13379                 * @param int $page page number
13380                 * @param string $data page data
13381                 * @param boolean $append if true append data, false replace.
13382                 * @access protected
13383                 * @since 4.5.000 (2008-12-31)
13384                 */
13385                 protected function setPageBuffer($page, $data, $append=false) {
13386                         if ($this->diskcache) {
13387                                 if (!isset($this->pages[$page])) {
13388                                         $this->pages[$page] = $this->getObjFilename('page'.$page);
13389                                 }
13390                                 $this->writeDiskCache($this->pages[$page], $data, $append);
13391                         } else {
13392                                 if ($append) {
13393                                         $this->pages[$page] .= $data;
13394                                 } else {
13395                                         $this->pages[$page] = $data;
13396                                 }
13397                         }
13398                         if ($append AND isset($this->pagelen[$page])) {
13399                                 $this->pagelen[$page] += strlen($data);
13400                         } else {
13401                                 $this->pagelen[$page] = strlen($data);
13402                         }
13403                 }
13404
13405         /**
13406                 * Get page buffer content.
13407                 * @param int $page page number
13408                 * @return string page buffer content or false in case of error
13409                 * @access protected
13410                 * @since 4.5.000 (2008-12-31)
13411                 */
13412                 protected function getPageBuffer($page) {
13413                         if ($this->diskcache) {
13414                                 return $this->readDiskCache($this->pages[$page]);
13415                         } elseif (isset($this->pages[$page])) {
13416                                 return $this->pages[$page];
13417                         }
13418                         return false;
13419                 }
13420
13421         /**
13422                 * Set image buffer content.
13423                 * @param string $image image key
13424                 * @param array $data image data
13425                 * @access protected
13426                 * @since 4.5.000 (2008-12-31)
13427                 */
13428                 protected function setImageBuffer($image, $data) {
13429                         if ($this->diskcache) {
13430                                 if (!isset($this->images[$image])) {
13431                                         $this->images[$image] = $this->getObjFilename('image'.$image);
13432                                 }
13433                                 $this->writeDiskCache($this->images[$image], serialize($data));
13434                         } else {
13435                                 $this->images[$image] = $data;
13436                         }
13437                         if (!in_array($image, $this->imagekeys)) {
13438                                 $this->imagekeys[] = $image;
13439                         }
13440                         ++$this->numimages;
13441                 }
13442
13443         /**
13444                 * Set image buffer content.
13445                 * @param string $image image key
13446                 * @param string $key image sub-key
13447                 * @param array $data image data
13448                 * @access protected
13449                 * @since 4.5.000 (2008-12-31)
13450                 */
13451                 protected function setImageSubBuffer($image, $key, $data) {
13452                         if (!isset($this->images[$image])) {
13453                                 $this->setImageBuffer($image, array());
13454                         }
13455                         if ($this->diskcache) {
13456                                 $tmpimg = $this->getImageBuffer($image);
13457                                 $tmpimg[$key] = $data;
13458                                 $this->writeDiskCache($this->images[$image], serialize($tmpimg));
13459                         } else {
13460                                 $this->images[$image][$key] = $data;
13461                         }
13462                 }
13463
13464         /**
13465                 * Get page buffer content.
13466                 * @param string $image image key
13467                 * @return string image buffer content or false in case of error
13468                 * @access protected
13469                 * @since 4.5.000 (2008-12-31)
13470                 */
13471                 protected function getImageBuffer($image) {
13472                         if ($this->diskcache AND isset($this->images[$image])) {
13473                                 return unserialize($this->readDiskCache($this->images[$image]));
13474                         } elseif (isset($this->images[$image])) {
13475                                 return $this->images[$image];
13476                         }
13477                         return false;
13478                 }
13479
13480                 /**
13481                 * Set font buffer content.
13482                 * @param string $font font key
13483                 * @param array $data font data
13484                 * @access protected
13485                 * @since 4.5.000 (2009-01-02)
13486                 */
13487                 protected function setFontBuffer($font, $data) {
13488                         if ($this->diskcache) {
13489                                 if (!isset($this->fonts[$font])) {
13490                                         $this->fonts[$font] = $this->getObjFilename('font');
13491                                 }
13492                                 $this->writeDiskCache($this->fonts[$font], serialize($data));
13493                         } else {
13494                                 $this->fonts[$font] = $data;
13495                         }
13496                         if (!in_array($font, $this->fontkeys)) {
13497                                 $this->fontkeys[] = $font;
13498                         }
13499                 }
13500
13501         /**
13502                 * Set font buffer content.
13503                 * @param string $font font key
13504                 * @param string $key font sub-key
13505                 * @param array $data font data
13506                 * @access protected
13507                 * @since 4.5.000 (2009-01-02)
13508                 */
13509                 protected function setFontSubBuffer($font, $key, $data) {
13510                         if (!isset($this->fonts[$font])) {
13511                                 $this->setFontBuffer($font, array());
13512                         }
13513                         if ($this->diskcache) {
13514                                 $tmpfont = $this->getFontBuffer($font);
13515                                 $tmpfont[$key] = $data;
13516                                 $this->writeDiskCache($this->fonts[$font], serialize($tmpfont));
13517                         } else {
13518                                 $this->fonts[$font][$key] = $data;
13519                         }
13520                 }
13521
13522         /**
13523                 * Get font buffer content.
13524                 * @param string $font font key
13525                 * @return string font buffer content or false in case of error
13526                 * @access protected
13527                 * @since 4.5.000 (2009-01-02)
13528                 */
13529                 protected function getFontBuffer($font) {
13530                         if ($this->diskcache AND isset($this->fonts[$font])) {
13531                                 return unserialize($this->readDiskCache($this->fonts[$font]));
13532                         } elseif (isset($this->fonts[$font])) {
13533                                 return $this->fonts[$font];
13534                         }
13535                         return false;
13536                 }
13537
13538         /**
13539                 * Move a page to a previous position.
13540                 * @param int $frompage number of the source page
13541                 * @param int $topage number of the destination page (must be less than $frompage)
13542                 * @return true in case of success, false in case of error.
13543                 * @access public
13544                 * @since 4.5.000 (2009-01-02)
13545                 */
13546                 public function movePage($frompage, $topage) {
13547                         if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
13548                                 return false;
13549                         }
13550                         if ($frompage == $this->page) {
13551                                 // close the page before moving it
13552                                 $this->endPage();
13553                         }
13554                         // move all page-related states
13555                         $tmppage = $this->pages[$frompage];
13556                         $tmppagedim = $this->pagedim[$frompage];
13557                         $tmppagelen = $this->pagelen[$frompage];
13558                         $tmpintmrk = $this->intmrk[$frompage];
13559                         if (isset($this->footerpos[$frompage])) {
13560                                 $tmpfooterpos = $this->footerpos[$frompage];
13561                         }
13562                         if (isset($this->footerlen[$frompage])) {
13563                                 $tmpfooterlen = $this->footerlen[$frompage];
13564                         }
13565                         if (isset($this->transfmrk[$frompage])) {
13566                                 $tmptransfmrk = $this->transfmrk[$frompage];
13567                         }
13568                         if (isset($this->PageAnnots[$frompage])) {
13569                                 $tmpannots = $this->PageAnnots[$frompage];
13570                         }
13571                         if (isset($this->newpagegroup[$frompage])) {
13572                                 $tmpnewpagegroup = $this->newpagegroup[$frompage];
13573                         }
13574                         for ($i = $frompage; $i > $topage; --$i) {
13575                                 $j = $i - 1;
13576                                 // shift pages down
13577                                 $this->pages[$i] = $this->pages[$j];
13578                                 $this->pagedim[$i] = $this->pagedim[$j];
13579                                 $this->pagelen[$i] = $this->pagelen[$j];
13580                                 $this->intmrk[$i] = $this->intmrk[$j];
13581                                 if (isset($this->footerpos[$j])) {
13582                                         $this->footerpos[$i] = $this->footerpos[$j];
13583                                 } elseif (isset($this->footerpos[$i])) {
13584                                         unset($this->footerpos[$i]);
13585                                 }
13586                                 if (isset($this->footerlen[$j])) {
13587                                         $this->footerlen[$i] = $this->footerlen[$j];
13588                                 } elseif (isset($this->footerlen[$i])) {
13589                                         unset($this->footerlen[$i]);
13590                                 }
13591                                 if (isset($this->transfmrk[$j])) {
13592                                         $this->transfmrk[$i] = $this->transfmrk[$j];
13593                                 } elseif (isset($this->transfmrk[$i])) {
13594                                         unset($this->transfmrk[$i]);
13595                                 }
13596                                 if (isset($this->PageAnnots[$j])) {
13597                                         $this->PageAnnots[$i] = $this->PageAnnots[$j];
13598                                 } elseif (isset($this->PageAnnots[$i])) {
13599                                         unset($this->PageAnnots[$i]);
13600                                 }
13601                                 if (isset($this->newpagegroup[$j])) {
13602                                         $this->newpagegroup[$i] = $this->newpagegroup[$j];
13603                                 } elseif (isset($this->newpagegroup[$i])) {
13604                                         unset($this->newpagegroup[$i]);
13605                                 }
13606                         }
13607                         $this->pages[$topage] = $tmppage;
13608                         $this->pagedim[$topage] = $tmppagedim;
13609                         $this->pagelen[$topage] = $tmppagelen;
13610                         $this->intmrk[$topage] = $tmpintmrk;
13611                         if (isset($tmpfooterpos)) {
13612                                 $this->footerpos[$topage] = $tmpfooterpos;
13613                         } elseif (isset($this->footerpos[$topage])) {
13614                                 unset($this->footerpos[$topage]);
13615                         }
13616                         if (isset($tmpfooterlen)) {
13617                                 $this->footerlen[$topage] = $tmpfooterlen;
13618                         } elseif (isset($this->footerlen[$topage])) {
13619                                 unset($this->footerlen[$topage]);
13620                         }
13621                         if (isset($tmptransfmrk)) {
13622                                 $this->transfmrk[$topage] = $tmptransfmrk;
13623                         } elseif (isset($this->transfmrk[$topage])) {
13624                                 unset($this->transfmrk[$topage]);
13625                         }
13626                         if (isset($tmpannots)) {
13627                                 $this->PageAnnots[$topage] = $tmpannots;
13628                         } elseif (isset($this->PageAnnots[$topage])) {
13629                                 unset($this->PageAnnots[$topage]);
13630                         }
13631                         if (isset($tmpnewpagegroup)) {
13632                                 $this->newpagegroup[$topage] = $tmpnewpagegroup;
13633                         } elseif (isset($this->newpagegroup[$topage])) {
13634                                 unset($this->newpagegroup[$topage]);
13635                         }
13636                         // adjust outlines
13637                         $tmpoutlines = $this->outlines;
13638                         foreach ($tmpoutlines as $key => $outline) {
13639                                 if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
13640                                         $this->outlines[$key]['p'] = $outline['p'] + 1;
13641                                 } elseif ($outline['p'] == $frompage) {
13642                                         $this->outlines[$key]['p'] = $topage;
13643                                 }
13644                         }
13645                         // adjust links
13646                         $tmplinks = $this->links;
13647                         foreach ($tmplinks as $key => $link) {
13648                                 if (($link[0] >= $topage) AND ($link[0] < $frompage)) {
13649                                         $this->links[$key][0] = $link[0] + 1;
13650                                 } elseif ($link[0] == $frompage) {
13651                                         $this->links[$key][0] = $topage;
13652                                 }
13653                         }
13654                         // adjust javascript
13655                         $tmpjavascript = $this->javascript;
13656                         global $jfrompage, $jtopage;
13657                         $jfrompage = $frompage;
13658                         $jtopage = $topage;
13659                         $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
13660                                 create_function('$matches', 'global $jfrompage, $jtopage;
13661                                 $pagenum = intval($matches[3]) + 1;
13662                                 if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
13663                                         $newpage = ($pagenum + 1);
13664                                 } elseif ($pagenum == $jfrompage) {
13665                                         $newpage = $jtopage;
13666                                 } else {
13667                                         $newpage = $pagenum;
13668                                 }
13669                                 --$newpage;
13670                                 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
13671                         // return to last page
13672                         $this->lastPage(true);
13673                         return true;
13674                 }
13675
13676         /**
13677                 * Remove the specified page.
13678                 * @param int $page page to remove
13679                 * @return true in case of success, false in case of error.
13680                 * @access public
13681                 * @since 4.6.004 (2009-04-23)
13682                 */
13683                 public function deletePage($page) {
13684                         if ($page > $this->numpages) {
13685                                 return false;
13686                         }
13687                         // delete current page
13688                         unset($this->pages[$page]);
13689                         unset($this->pagedim[$page]);
13690                         unset($this->pagelen[$page]);
13691                         unset($this->intmrk[$page]);
13692                         if (isset($this->footerpos[$page])) {
13693                                 unset($this->footerpos[$page]);
13694                         }
13695                         if (isset($this->footerlen[$page])) {
13696                                 unset($this->footerlen[$page]);
13697                         }
13698                         if (isset($this->transfmrk[$page])) {
13699                                 unset($this->transfmrk[$page]);
13700                         }
13701                         if (isset($this->PageAnnots[$page])) {
13702                                 unset($this->PageAnnots[$page]);
13703                         }
13704                         if (isset($this->newpagegroup[$page])) {
13705                                 unset($this->newpagegroup[$page]);
13706                         }
13707                         if (isset($this->pageopen[$page])) {
13708                                 unset($this->pageopen[$page]);
13709                         }
13710                         // update remaining pages
13711                         for ($i = $page; $i < $this->numpages; ++$i) {
13712                                 $j = $i + 1;
13713                                 // shift pages
13714                                 $this->pages[$i] = $this->pages[$j];
13715                                 $this->pagedim[$i] = $this->pagedim[$j];
13716                                 $this->pagelen[$i] = $this->pagelen[$j];
13717                                 $this->intmrk[$i] = $this->intmrk[$j];
13718                                 if (isset($this->footerpos[$j])) {
13719                                         $this->footerpos[$i] = $this->footerpos[$j];
13720                                 } elseif (isset($this->footerpos[$i])) {
13721                                         unset($this->footerpos[$i]);
13722                                 }
13723                                 if (isset($this->footerlen[$j])) {
13724                                         $this->footerlen[$i] = $this->footerlen[$j];
13725                                 } elseif (isset($this->footerlen[$i])) {
13726                                         unset($this->footerlen[$i]);
13727                                 }
13728                                 if (isset($this->transfmrk[$j])) {
13729                                         $this->transfmrk[$i] = $this->transfmrk[$j];
13730                                 } elseif (isset($this->transfmrk[$i])) {
13731                                         unset($this->transfmrk[$i]);
13732                                 }
13733                                 if (isset($this->PageAnnots[$j])) {
13734                                         $this->PageAnnots[$i] = $this->PageAnnots[$j];
13735                                 } elseif (isset($this->PageAnnots[$i])) {
13736                                         unset($this->PageAnnots[$i]);
13737                                 }
13738                                 if (isset($this->newpagegroup[$j])) {
13739                                         $this->newpagegroup[$i] = $this->newpagegroup[$j];
13740                                 } elseif (isset($this->newpagegroup[$i])) {
13741                                         unset($this->newpagegroup[$i]);
13742                                 }
13743                                 if (isset($this->pageopen[$j])) {
13744                                         $this->pageopen[$i] = $this->pageopen[$j];
13745                                 } elseif (isset($this->pageopen[$i])) {
13746                                         unset($this->pageopen[$i]);
13747                                 }
13748                         }
13749                         // remove last page
13750                         unset($this->pages[$this->numpages]);
13751                         unset($this->pagedim[$this->numpages]);
13752                         unset($this->pagelen[$this->numpages]);
13753                         unset($this->intmrk[$this->numpages]);
13754                         if (isset($this->footerpos[$this->numpages])) {
13755                                 unset($this->footerpos[$this->numpages]);
13756                         }
13757                         if (isset($this->footerlen[$this->numpages])) {
13758                                 unset($this->footerlen[$this->numpages]);
13759                         }
13760                         if (isset($this->transfmrk[$this->numpages])) {
13761                                 unset($this->transfmrk[$this->numpages]);
13762                         }
13763                         if (isset($this->PageAnnots[$this->numpages])) {
13764                                 unset($this->PageAnnots[$this->numpages]);
13765                         }
13766                         if (isset($this->newpagegroup[$this->numpages])) {
13767                                 unset($this->newpagegroup[$this->numpages]);
13768                         }
13769                         if (isset($this->pageopen[$this->numpages])) {
13770                                 unset($this->pageopen[$this->numpages]);
13771                         }
13772                         --$this->numpages;
13773                         $this->page = $this->numpages;
13774                         // adjust outlines
13775                         $tmpoutlines = $this->outlines;
13776                         foreach ($tmpoutlines as $key => $outline) {
13777                                 if ($outline['p'] > $page) {
13778                                         $this->outlines[$key]['p'] = $outline['p'] - 1;
13779                                 } elseif ($outline['p'] == $page) {
13780                                         unset($this->outlines[$key]);
13781                                 }
13782                         }
13783                         // adjust links
13784                         $tmplinks = $this->links;
13785                         foreach ($tmplinks as $key => $link) {
13786                                 if ($link[0] > $page) {
13787                                         $this->links[$key][0] = $link[0] - 1;
13788                                 } elseif ($link[0] == $page) {
13789                                         unset($this->links[$key]);
13790                                 }
13791                         }
13792                         // adjust javascript
13793                         $tmpjavascript = $this->javascript;
13794                         global $jpage;
13795                         $jpage = $page;
13796                         $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
13797                                 create_function('$matches', 'global $jpage;
13798                                 $pagenum = intval($matches[3]) + 1;
13799                                 if ($pagenum >= $jpage) {
13800                                         $newpage = ($pagenum - 1);
13801                                 } elseif ($pagenum == $jpage) {
13802                                         $newpage = 1;
13803                                 } else {
13804                                         $newpage = $pagenum;
13805                                 }
13806                                 --$newpage;
13807                                 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
13808                         // return to last page
13809                         $this->lastPage(true);
13810                         return true;
13811                 }
13812
13813                 /**
13814                 * Output a Table of Content Index (TOC).
13815                 * You can override this method to achieve different styles.
13816                 * @param int $page page number where this TOC should be inserted (leave empty for current page).
13817                 * @param string $numbersfont set the font for page numbers (please use monospaced font for better alignment).
13818                 * @param string $filler string used to fill the space between text and page number.
13819                 * @access public
13820                 * @author Nicola Asuni
13821                 * @since 4.5.000 (2009-01-02)
13822                 */
13823                 public function addTOC($page='', $numbersfont='', $filler='.') {
13824                         $fontsize = $this->FontSizePt;
13825                         $fontfamily = $this->FontFamily;
13826                         $fontstyle = $this->FontStyle;
13827                         $w = $this->w - $this->lMargin - $this->rMargin;
13828                         $spacer = $this->GetStringWidth(' ') * 4;
13829                         $page_first = $this->getPage();
13830                         $lmargin = $this->lMargin;
13831                         $rmargin = $this->rMargin;
13832                         $x_start = $this->GetX();
13833                         if ($this->empty_string($numbersfont)) {
13834                                 $numbersfont = $this->default_monospaced_font;
13835                         }
13836                         if ($this->empty_string($filler)) {
13837                                 $filler = ' ';
13838                         }
13839                         if ($this->empty_string($page)) {
13840                                 $gap = ' ';
13841                         } else {
13842                                 $gap = '';
13843                         }
13844                         foreach ($this->outlines as $key => $outline) {
13845                                 if ($this->rtl) {
13846                                         $aligntext = 'R';
13847                                         $alignnum = 'L';
13848                                 } else {
13849                                         $aligntext = 'L';
13850                                         $alignnum = 'R';
13851                                 }
13852                                 if ($outline['l'] == 0) {
13853                                         $this->SetFont($fontfamily, $fontstyle.'B', $fontsize);
13854                                 } else {
13855                                         $this->SetFont($fontfamily, $fontstyle, $fontsize - $outline['l']);
13856                                 }
13857                                 $indent = ($spacer * $outline['l']);
13858                                 if ($this->rtl) {
13859                                         $this->rMargin += $indent;
13860                                         $this->x -= $indent;
13861                                 } else {
13862                                         $this->lMargin += $indent;
13863                                         $this->x += $indent;
13864                                 }
13865                                 $link = $this->AddLink();
13866                                 $this->SetLink($link, 0, $outline['p']);
13867                                 // write the text
13868                                 $this->Write(0, $outline['t'], $link, 0, $aligntext, false, 0, false, false, 0);
13869                                 $this->SetFont($numbersfont, $fontstyle, $fontsize);
13870                                 if ($this->empty_string($page)) {
13871                                         $pagenum = $outline['p'];
13872                                 } else {
13873                                         // placemark to be replaced with the correct number
13874                                         $pagenum = '{#'.($outline['p']).'}';
13875                                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
13876                                                 $pagenum = '{'.$pagenum.'}';
13877                                     }
13878                                 }
13879                                 $numwidth = $this->GetStringWidth($pagenum);
13880                                 if ($this->rtl) {
13881                                         $tw = $this->x - $this->lMargin;
13882                                 } else {
13883                                         $tw = $this->w - $this->rMargin - $this->x;
13884                                 }
13885                                 $fw = $tw - $numwidth - $this->GetStringWidth(' ');
13886                                 $numfills = floor($fw / $this->GetStringWidth($filler));
13887                                 if ($numfills > 0) {
13888                                         $rowfill = str_repeat($filler, $numfills);
13889                                 } else {
13890                                         $rowfill = '';
13891                                 }
13892                                 if ($this->rtl) {
13893                                         $pagenum = $pagenum.$gap.$rowfill.' ';
13894                                 } else {
13895                                         $pagenum = ' '.$rowfill.$gap.$pagenum;
13896                                 }
13897                                 // write the number
13898                                 //$this->SetX($x_start);
13899                                 $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
13900                                 $this->SetX($x_start);
13901                                 $this->lMargin = $lmargin;
13902                                 $this->rMargin = $rmargin;
13903                         }
13904                         $page_last = $this->getPage();
13905                         $numpages = $page_last - $page_first + 1;
13906                         if (!$this->empty_string($page)) {
13907                                 for ($p = $page_first; $p <= $page_last; ++$p) {
13908                                         // get page data
13909                                         $temppage = $this->getPageBuffer($p);
13910                                         for ($n = 1; $n <= $this->numpages; ++$n) {
13911                                                 // update page numbers
13912                                                 $k = '{#'.$n.'}';
13913                                                 $ku = '{'.$k.'}';
13914                                                 $alias_a = $this->_escape($k);
13915                                                 $alias_au = $this->_escape('{'.$k.'}');
13916                                                 if ($this->isunicode) {
13917                                                         $alias_b = $this->_escape($this->UTF8ToLatin1($k));
13918                                                         $alias_bu = $this->_escape($this->UTF8ToLatin1($ku));
13919                                                         $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
13920                                                         $alias_cu = $this->_escape($this->utf8StrRev($ku, false, $this->tmprtl));
13921                                                 }
13922                                                 if ($n >= $page) {
13923                                                         $np = $n + $numpages;
13924                                                 } else {
13925                                                         $np = $n;
13926                                                 }
13927                                                 $ns = $this->formatTOCPageNumber($np);
13928                                                 $nu = $ns;
13929                                                 $sdiff = strlen($k) - strlen($ns) - 1;
13930                                                 $sdiffu = strlen($ku) - strlen($ns) - 1;
13931                                                 $sfill = str_repeat($filler, $sdiff);
13932                                                 $sfillu = str_repeat($filler, $sdiffu);
13933                                                 if ($this->rtl) {
13934                                                         $ns = $ns.' '.$sfill;
13935                                                         $nu = $nu.' '.$sfillu;
13936                                                 } else {
13937                                                         $ns = $sfill.' '.$ns;
13938                                                         $nu = $sfillu.' '.$nu;
13939                                                 }
13940                                                 $nu = $this->UTF8ToUTF16BE($nu, false);
13941                                                 $temppage = str_replace($alias_au, $nu, $temppage);
13942                                                 if ($this->isunicode) {
13943                                                         $temppage = str_replace($alias_bu, $nu, $temppage);
13944                                                         $temppage = str_replace($alias_cu, $nu, $temppage);
13945                                                         $temppage = str_replace($alias_b, $ns, $temppage);
13946                                                         $temppage = str_replace($alias_c, $ns, $temppage);
13947                                                 }
13948                                                 $temppage = str_replace($alias_a, $ns, $temppage);
13949                                         }
13950                                         // save changes
13951                                         $this->setPageBuffer($p, $temppage);
13952                                 }
13953                                 // move pages
13954                                 for ($i = 0; $i < $numpages; ++$i) {
13955                                         $this->movePage($page_last, $page);
13956                                 }
13957                         }
13958                         $this->SetFont($fontfamily, $fontstyle, $fontsize);
13959                 }
13960
13961                 /**
13962                 * Stores a copy of the current TCPDF object used for undo operation.
13963                 * @access public
13964                 * @since 4.5.029 (2009-03-19)
13965                 */
13966                 public function startTransaction() {
13967                         if (isset($this->objcopy)) {
13968                                 // remove previous copy
13969                                 $this->commitTransaction();
13970                         }
13971                         // clone current object
13972                         $this->objcopy = $this->objclone($this);
13973                 }
13974
13975                 /**
13976                 * Delete the copy of the current TCPDF object used for undo operation.
13977                 * @access public
13978                 * @since 4.5.029 (2009-03-19)
13979                 */
13980                 public function commitTransaction() {
13981                         if (isset($this->objcopy)) {
13982                                 $this->objcopy->_destroy(true, true);
13983                                 unset($this->objcopy);
13984                         }
13985                 }
13986
13987                 /**
13988                 * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
13989                 * @return TCPDF object.
13990                 * @access public
13991                 * @since 4.5.029 (2009-03-19)
13992                 */
13993                 public function rollbackTransaction() {
13994                         if (isset($this->objcopy)) {
13995                                 if (isset($this->objcopy->diskcache) AND $this->objcopy->diskcache) {
13996                                         // truncate files to previous values
13997                                         foreach ($this->objcopy->cache_file_lenght as $file => $lenght) {
13998                                                 $file = substr($file, 1);
13999                                                 $handle = fopen($file, 'r+');
14000                                                 ftruncate($handle, $lenght);
14001                                         }
14002                                 }
14003                                 $this->_destroy(true, true);
14004                                 return $this->objcopy;
14005                         }
14006                         return $this;
14007                 }
14008
14009                 /**
14010                 * Creates a copy of a class object
14011                 * @param object $object class object to be cloned
14012                 * @return cloned object
14013                 * @access public
14014                 * @since 4.5.029 (2009-03-19)
14015                 */
14016                 public function objclone($object) {
14017                         return @clone($object);
14018                 }
14019
14020                 /**
14021                 * Determine whether a string is empty.
14022                 * @param srting $str string to be checked
14023                 * @return boolean true if string is empty
14024                 * @access public
14025                 * @since 4.5.044 (2009-04-16)
14026                 */
14027                 public function empty_string($str) {
14028                         return (is_null($str) OR (is_string($str) AND (strlen($str) == 0)));
14029                 }
14030
14031         } // END OF TCPDF CLASS
14032 }
14033 //============================================================+
14034 // END OF FILE
14035 //============================================================+
14036 ?>