]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/tcpdf/tcpdf.php
Release 6.4.0
[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                                                 $cborder = $this->getBorderMode($border, $position='end');
3786                                         } else {
3787                                                 $this->y = $this->tMargin; // put cursor at the beginning of the current page
3788                                                 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
3789                                                 $cborder = $this->getBorderMode($border, $position='middle');
3790                                         }
3791                                         $nx = $x;
3792                                         // account for margin changes
3793                                         if ($page > $startpage) {
3794                                                 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
3795                                                         $nx = $x + ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
3796                                                 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
3797                                                         $nx = $x + ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
3798                                                 }
3799                                         }
3800                                         $this->SetX($nx);
3801                                         $ccode = $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, false);
3802                                         if ($cborder OR $fill) {
3803                                                 $pagebuff = $this->getPageBuffer($this->page);
3804                                                 $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
3805                                                 $pend = substr($pagebuff, $this->intmrk[$this->page]);
3806                                                 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
3807                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
3808                                         }
3809                                 }
3810                         } else {
3811                                 $h = max($h, ($currentY - $y));
3812                                 // put cursor at the beginning of text
3813                                 $this->SetY($y);
3814                                 $this->SetX($x);
3815                                 // design a cell around the text
3816                                 $ccode = $this->getCellCode($w, $h, '', $border, 1, '', $fill, '', 0, true);
3817                                 if ($border OR $fill) {
3818                                         if (end($this->transfmrk[$this->page]) !== false) {
3819                                                 $pagemarkkey = key($this->transfmrk[$this->page]);
3820                                                 $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
3821                                         } elseif ($this->InFooter) {
3822                                                 $pagemark = &$this->footerpos[$this->page];
3823                                         } else {
3824                                                 $pagemark = &$this->intmrk[$this->page];
3825                                         }
3826                                         $pagebuff = $this->getPageBuffer($this->page);
3827                                         $pstart = substr($pagebuff, 0, $pagemark);
3828                                         $pend = substr($pagebuff, $pagemark);
3829                                         $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
3830                                         $pagemark += strlen($ccode."\n");
3831                                 }
3832                         }
3833                         // Get end-of-cell Y position
3834                         $currentY = $this->GetY();
3835                         // restore original margin values
3836                         $this->SetLeftMargin($lMargin);
3837                         $this->SetRightMargin($rMargin);
3838                         if ($ln > 0) {
3839                                 //Go to the beginning of the next line
3840                                 $this->SetY($currentY);
3841                                 if ($ln == 2) {
3842                                         $this->SetX($x + $w);
3843                                 }
3844                         } else {
3845                                 // go left or right by case
3846                                 $this->setPage($startpage);
3847                                 $this->y = $y;
3848                                 $this->SetX($x + $w);
3849                         }
3850                         return $nl;
3851                 }
3852
3853                 /**
3854                 * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages)
3855                 * @param mixed $border Indicates if borders must be drawn around the cell block. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
3856                 * @param string multicell position: 'start', 'middle', 'end'
3857                 * @return border mode
3858                 * @access protected
3859                 * @since 4.4.002 (2008-12-09)
3860                 */
3861                 protected function getBorderMode($border, $position='start') {
3862                         if ((!$this->opencell) AND ($border == 1)) {
3863                                 return 1;
3864                         }
3865                         $cborder = '';
3866                         switch ($position) {
3867                                 case 'start': {
3868                                         if ($border == 1) {
3869                                                 $cborder = 'LTR';
3870                                         } else {
3871                                                 if (!(false === strpos($border, 'L'))) {
3872                                                         $cborder .= 'L';
3873                                                 }
3874                                                 if (!(false === strpos($border, 'T'))) {
3875                                                         $cborder .= 'T';
3876                                                 }
3877                                                 if (!(false === strpos($border, 'R'))) {
3878                                                         $cborder .= 'R';
3879                                                 }
3880                                                 if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
3881                                                         $cborder .= 'B';
3882                                                 }
3883                                         }
3884                                         break;
3885                                 }
3886                                 case 'middle': {
3887                                         if ($border == 1) {
3888                                                 $cborder = 'LR';
3889                                         } else {
3890                                                 if (!(false === strpos($border, 'L'))) {
3891                                                         $cborder .= 'L';
3892                                                 }
3893                                                 if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
3894                                                         $cborder .= 'T';
3895                                                 }
3896                                                 if (!(false === strpos($border, 'R'))) {
3897                                                         $cborder .= 'R';
3898                                                 }
3899                                                 if ((!$this->opencell) AND (!(false === strpos($border, 'B')))) {
3900                                                         $cborder .= 'B';
3901                                                 }
3902                                         }
3903                                         break;
3904                                 }
3905                                 case 'end': {
3906                                         if ($border == 1) {
3907                                                 $cborder = 'LRB';
3908                                         } else {
3909                                                 if (!(false === strpos($border, 'L'))) {
3910                                                         $cborder .= 'L';
3911                                                 }
3912                                                 if ((!$this->opencell) AND (!(false === strpos($border, 'T')))) {
3913                                                         $cborder .= 'T';
3914                                                 }
3915                                                 if (!(false === strpos($border, 'R'))) {
3916                                                         $cborder .= 'R';
3917                                                 }
3918                                                 if (!(false === strpos($border, 'B'))) {
3919                                                         $cborder .= 'B';
3920                                                 }
3921                                         }
3922                                         break;
3923                                 }
3924                                 default: {
3925                                         $cborder = $border;
3926                                         break;
3927                                 }
3928                         }
3929                         return $cborder;
3930                 }
3931
3932                 /**
3933                 * This method returns the estimated number of lines required to print the text.
3934                 * @param string $txt text to print
3935                 * @param float $w width of cell. If 0, they extend up to the right margin of the page.
3936                 * @return int Return the estimated number of lines.
3937                 * @access public
3938                 * @since 4.5.011
3939                 */
3940                 public function getNumLines($txt, $w=0) {
3941                         $lines = 0;
3942                         if ($this->empty_string($w) OR ($w <= 0)) {
3943                                 if ($this->rtl) {
3944                                         $w = $this->x - $this->lMargin;
3945                                 } else {
3946                                         $w = $this->w - $this->rMargin - $this->x;
3947                                 }
3948                         }
3949                         // max column width
3950                         $wmax = $w - (2 * $this->cMargin);
3951                         // remove carriage returns
3952                         $txt = str_replace("\r", '', $txt);
3953                         // remove last newline (if any)
3954                         if (substr($txt,-1) == "\n") {
3955                                 $txt = substr($txt, 0, -1);
3956                         }
3957                         // divide text in blocks
3958                         $txtblocks = explode("\n", $txt);
3959                         // for each block;
3960                         foreach ($txtblocks as $block) {
3961                                 // estimate the number of lines
3962                                 $lines += $this->empty_string($block) ? 1 : (ceil($this->GetStringWidth($block) / $wmax));
3963                         }
3964                         return $lines;
3965                 }
3966
3967                 /**
3968                 * This method prints text from the current position.<br />
3969                 * @param float $h Line height
3970                 * @param string $txt String to print
3971                 * @param mixed $link URL or identifier returned by AddLink()
3972                 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
3973                 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
3974                 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
3975                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
3976                 * @param boolean $firstline if true prints only the first line and return the remaining string.
3977                 * @param boolean $firstblock if true the string is the starting of a line.
3978                 * @param float $maxh maximum height. The remaining unprinted text will be returned. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
3979                 * @return mixed Return the number of cells or the remaining string if $firstline = true.
3980                 * @access public
3981                 * @since 1.5
3982                 */
3983                 public function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0) {
3984                         if (strlen($txt) == 0) {
3985                                 $txt = ' ';
3986                         }
3987                         // remove carriage returns
3988                         $s = str_replace("\r", '', $txt);
3989
3990                         // check if string contains arabic text
3991                         if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
3992                                 $arabic = true;
3993                         } else {
3994                                 $arabic = false;
3995                         }
3996                         // check if string contains RTL text
3997                         if ($arabic OR $this->tmprtl OR preg_match(K_RE_PATTERN_RTL, $txt)) {
3998                                 $rtlmode = true;
3999                         } else {
4000                                 $rtlmode = false;
4001                         }
4002                         // get a char width
4003                         $chrwidth = $this->GetCharWidth('.');
4004                         // get array of unicode values
4005                         $chars = $this->UTF8StringToArray($s);
4006                         // get array of chars
4007                         $uchars = $this->UTF8ArrayToUniArray($chars);
4008                         // get the number of characters
4009                         $nb = count($chars);
4010                         // replacement for SHY character (minus symbol)
4011                         $shy_replacement = 45;
4012                         $shy_replacement_char = $this->unichr($shy_replacement);
4013                         // widht for SHY replacement
4014                         $shy_replacement_width = $this->GetCharWidth($shy_replacement);
4015                         // store current position
4016                         $prevx = $this->x;
4017                         $prevy = $this->y;
4018                         // max Y
4019                         $maxy = $this->y + $maxh - $h - (2 * $this->cMargin);
4020                         // calculate remaining line width ($w)
4021                         if ($this->rtl) {
4022                                 $w = $this->x - $this->lMargin;
4023                         } else {
4024                                 $w = $this->w - $this->rMargin - $this->x;
4025                         }
4026                         // max column width
4027                         $wmax = $w - (2 * $this->cMargin);
4028                         if ($chrwidth > $wmax) {
4029                                 // a single character do not fit on column
4030                                 return '';
4031                         }
4032                         $i = 0; // character position
4033                         $j = 0; // current starting position
4034                         $sep = -1; // position of the last blank space
4035                         $shy = false; // true if the last blank is a soft hypen (SHY)
4036                         $l = 0; // current string lenght
4037                         $nl = 0; //number of lines
4038                         $linebreak = false;
4039                         // for each character
4040                         while ($i < $nb) {
4041                                 if (($maxh > 0) AND ($this->y >= $maxy) ) {
4042                                         $firstline = true;
4043                                 }
4044                                 //Get the current character
4045                                 $c = $chars[$i];
4046                                 if ($c == 10) { // 10 = "\n" = new line
4047                                         //Explicit line break
4048                                         if ($align == 'J') {
4049                                                 if ($this->rtl) {
4050                                                         $talign = 'R';
4051                                                 } else {
4052                                                         $talign = 'L';
4053                                                 }
4054                                         } else {
4055                                                 $talign = $align;
4056                                         }
4057                                         $tmpstr = $this->UniArrSubString($uchars, $j, $i);
4058                                         if ($firstline) {
4059                                                 $startx = $this->x;
4060                                                 $tmparr = array_slice($chars, $j, $i);
4061                                                 if ($rtlmode) {
4062                                                         $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4063                                                 }
4064                                                 $linew = $this->GetArrStringWidth($tmparr);
4065                                                 unset($tmparr);
4066                                                 if ($this->rtl) {
4067                                                         $this->endlinex = $startx - $linew;
4068                                                 } else {
4069                                                         $this->endlinex = $startx + $linew;
4070                                                 }
4071                                                 $w = $linew;
4072                                                 $tmpcmargin = $this->cMargin;
4073                                                 if ($maxh == 0) {
4074                                                         $this->cMargin = 0;
4075                                                 }
4076                                         }
4077                                         $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
4078                                         unset($tmpstr);
4079                                         if ($firstline) {
4080                                                 $this->cMargin = $tmpcmargin;
4081                                                 return ($this->UniArrSubString($uchars, $i));
4082                                         }
4083                                         ++$nl;
4084                                         $j = $i + 1;
4085                                         $l = 0;
4086                                         $sep = -1;
4087                                         $shy = false;
4088                                         // account for margin changes
4089                                         if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
4090                                                 // AcceptPageBreak() may be overriden on extended classed to include margin changes
4091                                                 $this->AcceptPageBreak();
4092                                         }
4093                                         $w = $this->getRemainingWidth();
4094                                         $wmax = $w - (2 * $this->cMargin);
4095                                 } else {
4096                                         // 160 is the non-breaking space.
4097                                         // 173 is SHY (Soft Hypen).
4098                                         // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
4099                                         // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
4100                                         // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
4101                                         if (($c != 160) AND (($c == 173) OR preg_match($this->re_spaces, $this->unichr($c)))) {
4102                                                 // update last blank space position
4103                                                 $sep = $i;
4104                                                 // check if is a SHY
4105                                                 if ($c == 173) {
4106                                                         $shy = true;
4107                                                 } else {
4108                                                         $shy = false;
4109                                                 }
4110                                         }
4111                                         // update string length
4112                                         if ((($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) AND ($arabic)) {
4113                                                 // with bidirectional algorithm some chars may be changed affecting the line length
4114                                                 // *** very slow ***
4115                                                 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), '', $this->tmprtl));
4116                                         } else {
4117                                                 $l += $this->GetCharWidth($c);
4118                                         }
4119                                         if (!$stretch && (($l > $wmax) OR ($shy AND (($l + $shy_replacement_width) > $wmax))) ) {
4120                                                 // we have reached the end of column
4121                                                 if ($sep == -1) {
4122                                                         // check if the line was already started
4123                                                         if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $chrwidth)))
4124                                                                 OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $chrwidth)))) {
4125                                                                 // print a void cell and go to next line
4126                                                                 $this->Cell($w, $h, '', 0, 1);
4127                                                                 $linebreak = true;
4128                                                                 if ($firstline) {
4129                                                                         return ($this->UniArrSubString($uchars, $j));
4130                                                                 }
4131                                                         } else {
4132                                                                 // truncate the word because do not fit on column
4133                                                                 $tmpstr = $this->UniArrSubString($uchars, $j, $i);
4134                                                                 if ($firstline) {
4135                                                                         $startx = $this->x;
4136                                                                         $tmparr = array_slice($chars, $j, $i);
4137                                                                         if ($rtlmode) {
4138                                                                                 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4139                                                                         }
4140                                                                         $linew = $this->GetArrStringWidth($tmparr);
4141                                                                         unset($tmparr);
4142                                                                         if ($this->rtl) {
4143                                                                                 $this->endlinex = $startx - $linew;
4144                                                                         } else {
4145                                                                                 $this->endlinex = $startx + $linew;
4146                                                                         }
4147                                                                         $w = $linew;
4148                                                                         $tmpcmargin = $this->cMargin;
4149                                                                         if ($maxh == 0) {
4150                                                                                 $this->cMargin = 0;
4151                                                                         }
4152                                                                 }
4153                                                                 $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
4154                                                                 unset($tmpstr);
4155                                                                 if ($firstline) {
4156                                                                         $this->cMargin = $tmpcmargin;
4157                                                                         return ($this->UniArrSubString($uchars, $i));
4158                                                                 }
4159                                                                 $j = $i;
4160                                                                 --$i;
4161                                                         }
4162                                                 } else {
4163                                                         // word wrapping
4164                                                         if ($this->rtl AND (!$firstblock)) {
4165                                                                 $endspace = 1;
4166                                                         } else {
4167                                                                 $endspace = 0;
4168                                                         }
4169                                                         if ($shy) {
4170                                                                 // add hypen (minus symbol) at the end of the line
4171                                                                 $shy_width = $shy_replacement_width;
4172                                                                 if ($this->rtl) {
4173                                                                         $shy_char_left = $shy_replacement_char;
4174                                                                         $shy_char_right = '';
4175                                                                 } else {
4176                                                                         $shy_char_left = '';
4177                                                                         $shy_char_right = $shy_replacement_char;
4178                                                                 }
4179                                                         } else {
4180                                                                 $shy_width = 0;
4181                                                                 $shy_char_left = '';
4182                                                                 $shy_char_right = '';
4183                                                         }
4184                                                         $tmpstr = $this->UniArrSubString($uchars, $j, ($sep + $endspace));
4185                                                         if ($firstline) {
4186                                                                 $startx = $this->x;
4187                                                                 $tmparr = array_slice($chars, $j, ($sep + $endspace));
4188                                                                 if ($rtlmode) {
4189                                                                         $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4190                                                                 }
4191                                                                 $linew = $this->GetArrStringWidth($tmparr);
4192                                                                 unset($tmparr);
4193                                                                 if ($this->rtl) {
4194                                                                         $this->endlinex = $startx - $linew - $shy_width;
4195                                                                 } else {
4196                                                                         $this->endlinex = $startx + $linew + $shy_width;
4197                                                                 }
4198                                                                 $w = $linew;
4199                                                                 $tmpcmargin = $this->cMargin;
4200                                                                 if ($maxh == 0) {
4201                                                                         $this->cMargin = 0;
4202                                                                 }
4203                                                         }
4204                                                         // print the line
4205                                                         $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
4206                                                         unset($tmpstr);
4207                                                         if ($firstline) {
4208                                                                 // return the remaining text
4209                                                                 $this->cMargin = $tmpcmargin;
4210                                                                 return ($this->UniArrSubString($uchars, ($sep + $endspace)));
4211                                                         }
4212                                                         $i = $sep;
4213                                                         $sep = -1;
4214                                                         $shy = false;
4215                                                         $j = ($i+1);
4216                                                 }
4217                                                 // account for margin changes
4218                                                 if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) {
4219                                                         // AcceptPageBreak() may be overriden on extended classed to include margin changes
4220                                                         $this->AcceptPageBreak();
4221                                                 }
4222                                                 $w = $this->getRemainingWidth();
4223                                                 $wmax = $w - (2 * $this->cMargin);
4224                                                 if ($linebreak) {
4225                                                         $linebreak = false;
4226                                                 } else {
4227                                                         ++$nl;
4228                                                         $l = 0;
4229                                                 }
4230                                         }
4231                                 }
4232                                 ++$i;
4233                         } // end while i < nb
4234                         // print last substring (if any)
4235                         if ($l > 0) {
4236                             if (!$stretch)
4237                             {
4238                                 switch ($align) {
4239                                         case 'J':
4240                                         case 'C': {
4241                                                 $w = $w;
4242                                                 break;
4243                                         }
4244                                         case 'L': {
4245                                                 if ($this->rtl) {
4246                                                         $w = $w;
4247                                                 } else {
4248                                                         $w = $l;
4249                                                 }
4250                                                 break;
4251                                         }
4252                                         case 'R': {
4253                                                 if ($this->rtl) {
4254                                                         $w = $l;
4255                                                 } else {
4256                                                         $w = $w;
4257                                                 }
4258                                                 break;
4259                                         }
4260                                         default: {
4261                                                 $w = $l;
4262                                                 break;
4263                                         }
4264                                 }
4265                             }
4266                                 $tmpstr = $this->UniArrSubString($uchars, $j, $nb);
4267                                 if ($firstline) {
4268                                         $startx = $this->x;
4269                                         $tmparr = array_slice($chars, $j, $nb);
4270                                         if ($rtlmode) {
4271                                                 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
4272                                         }
4273                                         $linew = $this->GetArrStringWidth($tmparr);
4274                                         unset($tmparr);
4275                                         if ($this->rtl) {
4276                                                 $this->endlinex = $startx - $linew;
4277                                         } else {
4278                                                 $this->endlinex = $startx + $linew;
4279                                         }
4280                                         if (!$stretch)
4281                                             $w = $linew;
4282                                         $tmpcmargin = $this->cMargin;
4283                                         if ($maxh == 0) {
4284                                                 $this->cMargin = 0;
4285                                         }
4286                                 }
4287                                 $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
4288                                 unset($tmpstr);
4289                                 if ($firstline) {
4290                                         $this->cMargin = $tmpcmargin;
4291                                         return ($this->UniArrSubString($uchars, $nb));
4292                                 }
4293                                 ++$nl;
4294                         }
4295                         if ($firstline) {
4296                                 return '';
4297                         }
4298                         return $nl;
4299                 }
4300
4301                 /**
4302                 * Returns the remaining width between the current position and margins.
4303                 * @return int Return the remaining width
4304                 * @access protected
4305                 */
4306                 protected function getRemainingWidth() {
4307                         if ($this->rtl) {
4308                                 return ($this->x - $this->lMargin);
4309                         } else {
4310                                 return ($this->w - $this->rMargin - $this->x);
4311                         }
4312                 }
4313
4314                 /**
4315                 * Extract a slice of the $strarr array and return it as string.
4316                 * @param string $strarr The input array of characters.
4317                 * @param int $start the starting element of $strarr.
4318                 * @param int $end first element that will not be returned.
4319                 * @return Return part of a string
4320                 * @access public
4321                 */
4322                 public function UTF8ArrSubString($strarr, $start='', $end='') {
4323                         if (strlen($start) == 0) {
4324                                 $start = 0;
4325                         }
4326                         if (strlen($end) == 0) {
4327                                 $end = count($strarr);
4328                         }
4329                         $string = '';
4330                         for ($i=$start; $i < $end; ++$i) {
4331                                 $string .= $this->unichr($strarr[$i]);
4332                         }
4333                         return $string;
4334                 }
4335
4336                 /**
4337                 * Extract a slice of the $uniarr array and return it as string.
4338                 * @param string $uniarr The input array of characters.
4339                 * @param int $start the starting element of $strarr.
4340                 * @param int $end first element that will not be returned.
4341                 * @return Return part of a string
4342                 * @access public
4343                 * @since 4.5.037 (2009-04-07)
4344                 */
4345                 public function UniArrSubString($uniarr, $start='', $end='') {
4346                         if (strlen($start) == 0) {
4347                                 $start = 0;
4348                         }
4349                         if (strlen($end) == 0) {
4350                                 $end = count($uniarr);
4351                         }
4352                         $string = '';
4353                         for ($i=$start; $i < $end; ++$i) {
4354                                 $string .= $uniarr[$i];
4355                         }
4356                         return $string;
4357                 }
4358
4359                 /**
4360                 * Convert an array of UTF8 values to array of unicode characters
4361                 * @param string $ta The input array of UTF8 values.
4362                 * @return Return array of unicode characters
4363                 * @access public
4364                 * @since 4.5.037 (2009-04-07)
4365                 */
4366                 public function UTF8ArrayToUniArray($ta) {
4367                         return array_map(array($this, 'unichr'), $ta);
4368                 }
4369
4370                 /**
4371                 * Returns the unicode caracter specified by UTF-8 code
4372                 * @param int $c UTF-8 code
4373                 * @return Returns the specified character.
4374                 * @author Miguel Perez, Nicola Asuni
4375                 * @access public
4376                 * @since 2.3.000 (2008-03-05)
4377                 */
4378                 public function unichr($c) {
4379                         if (!$this->isunicode) {
4380                                 return chr($c);
4381                         } elseif ($c <= 0x7F) {
4382                                 // one byte
4383                                 return chr($c);
4384                         } elseif ($c <= 0x7FF) {
4385                                 // two bytes
4386                                 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
4387                         } elseif ($c <= 0xFFFF) {
4388                                 // three bytes
4389                                 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
4390                         } elseif ($c <= 0x10FFFF) {
4391                                 // four bytes
4392                                 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
4393                         } else {
4394                                 return '';
4395                         }
4396                 }
4397
4398                 /**
4399                 * Puts an image in the page.
4400                 * The upper-left corner must be given.
4401                 * The dimensions can be specified in different ways:<ul>
4402                 * <li>explicit width and height (expressed in user unit)</li>
4403                 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
4404                 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
4405                 * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
4406                 * The format can be specified explicitly or inferred from the file extension.<br />
4407                 * It is possible to put a link on the image.<br />
4408                 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
4409                 * @param string $file Name of the file containing the image.
4410                 * @param float $x Abscissa of the upper-left corner.
4411                 * @param float $y Ordinate of the upper-left corner.
4412                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
4413                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
4414                 * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
4415                 * @param mixed $link URL or identifier returned by AddLink().
4416                 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
4417                 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
4418                 * @param int $dpi dot-per-inch resolution used on resize
4419                 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
4420                 * @param boolean $ismask true if this image is a mask, false otherwise
4421                 * @param mixed $imgmask image object returned by this function or false
4422                 * @param mixed $border Indicates if borders must be drawn around the image. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
4423                 * @param boolean $fitbox If true scale image dimensions proportionally to fit within the ($w, $h) box.
4424                 * @return image information
4425                 * @access public
4426                 * @since 1.1
4427         *
4428         * peter d: Upgrading tcpdf to the latest version causes the whole thing to blow up since we have modifications to the original source as well as sugarpdf which
4429         * also extend from this. The only option is to add a workaround for some of the bugs in this function.
4430                 */
4431                 public function Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false) {
4432                         if ($x === '') {
4433                                 $x = $this->x;
4434                         }
4435                         if ($y === '') {
4436                                 $y = $this->y;
4437                         }
4438                         // get image dimensions
4439                         $imsize = @getimagesize($file);
4440                         if ($imsize === FALSE) {
4441                                 // encode spaces on filename
4442                                 $file = str_replace(' ', '%20', $file);
4443                                 $imsize = @getimagesize($file);
4444                                 if ($imsize === FALSE) {
4445                                         $this->Error('[Image] No such file or directory in '.$file);
4446                                 }
4447                         }
4448                         // get original image width and height in pixels
4449                         list($pixw, $pixh) = $imsize;
4450                         // calculate image width and height on document
4451                         if (($w <= 0) AND ($h <= 0)) {
4452                                 // convert image size to document unit
4453                                 $w = $this->pixelsToUnits($pixw);
4454                                 $h = $this->pixelsToUnits($pixh);
4455                         } elseif ($w <= 0) {
4456                                 $w = $h * $pixw / $pixh;
4457                         } elseif ($h <= 0) {
4458                                 $h = $w * $pixh / $pixw;
4459                         } elseif ($fitbox AND ($w > 0) AND ($h > 0)) {
4460                                 // scale image dimensions proportionally to fit within the ($w, $h) box
4461                 // NOTE: This section doesn't actually work very well, use the resize = true case I added.
4462                                 if ((($w * $pixh) / ($h * $pixw)) < 1) {
4463                                         $h = $w * $pixh / $pixw;
4464                                 } else {
4465                                         $w = $h * $pixw / $pixh;
4466                                 }
4467                         } else if ($resize) { // Added resize case
4468                 // Note: The issue here is that $w and $h represent abstract sizes, we pass it in as pixels,
4469                 // but tcpdf treats it as document units.
4470                 $wratio = $pixw / $w;
4471                 $hratio = $pixh / $h;
4472
4473                 // Check if our image exceeds the boundaries of $w and $h
4474                 if ($wratio > 1 AND $hratio > 1) {
4475                     $favoredRatio = ($wratio > $hratio) ? $wratio : $hratio;
4476                 } else if ($wratio > 1) {
4477                     $favoredRatio = $wratio;
4478                 } else if ($hratio > 1) {
4479                     $favoredRatio = $hratio;
4480                 } else {
4481                     $favoredRatio = 1;
4482                     $resize = false;
4483                 }
4484
4485                 // Calculate the new boundaries that also happen to fit the box..
4486                 // Dividing by the unit conversion $this->k seems to make the size not blow up
4487                 // later down in the code.
4488                 $w = $pixw / $favoredRatio / $this->k;
4489                 $h = $pixh / $favoredRatio / $this->k;
4490             }
4491                         // calculate new minimum dimensions in pixels
4492                         $neww = round($w * $this->k * $dpi / $this->dpi);
4493                         $newh = round($h * $this->k * $dpi / $this->dpi);
4494
4495                         // check if resize is necessary (resize is used only to reduce the image)
4496
4497             // - commmented out by pete d.
4498             // this is not a good way of checking for resize. and it might overwrite resize if the flag is enabled.
4499                         // if (($neww * $newh) >= ($pixw * $pixh)) {
4500                         //      $resize = false;
4501                         // }
4502
4503                         // check if image has been already added on document
4504                         if (!in_array($file, $this->imagekeys)) {
4505                                 //First use of image, get info
4506                                 if ($type == '') {
4507                                         $fileinfo = pathinfo($file);
4508                                         if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
4509                                                 $type = $fileinfo['extension'];
4510                                         } else {
4511                                                 $this->Error('Image file has no extension and no type was specified: '.$file);
4512                                         }
4513                                 }
4514                                 $type = strtolower($type);
4515                                 if ($type == 'jpg') {
4516                                         $type = 'jpeg';
4517                                 }
4518                                 $mqr = get_magic_quotes_runtime();
4519                                 //set_magic_quotes_runtime(0);
4520                                 // Specific image handlers
4521                                 $mtd = '_parse'.$type;
4522                                 // GD image handler function
4523                                 $gdfunction = 'imagecreatefrom'.$type;
4524                                 $info = false;
4525                                 if ((method_exists($this, $mtd)) AND (!($resize AND function_exists($gdfunction)))) {
4526                                         // TCPDF image functions
4527                                         $info = $this->$mtd($file);
4528                                         if ($info == 'pngalpha') {
4529                                                 return $this->ImagePngAlpha($file, $x, $y, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign);
4530                                         }
4531                                 }
4532                                 if (!$info) {
4533                                         if (function_exists($gdfunction)) {
4534                                                 // GD library
4535                                                 $img = $gdfunction($file);
4536                                                 if ($resize) {
4537                                                         $imgr = imagecreatetruecolor($neww, $newh);
4538                                                         imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
4539                                                         $info = $this->_toJPEG($imgr);
4540                                                 } else {
4541                                                         $info = $this->_toJPEG($img);
4542                                                 }
4543                                         } elseif (extension_loaded('imagick')) {
4544                                                 // ImageMagick library
4545                                                 $img = new Imagick();
4546                                                 $img->readImage($file);
4547                                                 if ($resize) {
4548                                                         $img->resizeImage($neww, $newh, 10, 1, false);
4549                                                 }
4550                                                 $img->setCompressionQuality($this->jpeg_quality);
4551                                                 $img->setImageFormat('jpeg');
4552                                                 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
4553                                                 $img->writeImage($tempname);
4554                                                 $info = $this->_parsejpeg($tempname);
4555                                                 unlink($tempname);
4556                                                 $img->destroy();
4557                                         }
4558                                         else if ($type == 'jpeg') {
4559                                                 $info = $this->_parsejpeg($file);
4560                                         }
4561                                         else {
4562                                                 return;
4563                                         }
4564                                 }
4565                                 if ($info === false) {
4566                                         //If false, we cannot process image
4567                                         return;
4568                                 }
4569                                 //set_magic_quotes_runtime($mqr);
4570                                 if ($ismask) {
4571                                         // force grayscale
4572                                         $info['cs'] = 'DeviceGray';
4573                                 }
4574                                 $info['i'] = $this->numimages + 1;
4575                                 if ($imgmask !== false) {
4576                                         $info['masked'] = $imgmask;
4577                                 }
4578                                 // add image to document
4579                                 $this->setImageBuffer($file, $info);
4580                         } else {
4581                                 $info = $this->getImageBuffer($file);
4582                         }
4583                         // Check whether we need a new page first as this does not fit
4584                         if ($this->checkPageBreak($h, $y)) {
4585                                 $y = $this->GetY() + $this->cMargin;
4586                         }
4587                         // set bottomcoordinates
4588                         $this->img_rb_y = $y + $h;
4589                         // set alignment
4590                         if ($this->rtl) {
4591                                 if ($palign == 'L') {
4592                                         $ximg = $this->lMargin;
4593                                         // set right side coordinate
4594                                         $this->img_rb_x = $ximg + $w;
4595                                 } elseif ($palign == 'C') {
4596                                         $ximg = ($this->w - $x - $w) / 2;
4597                                         // set right side coordinate
4598                                         $this->img_rb_x = $ximg + $w;
4599                                 } else {
4600                                         $ximg = $this->w - $x - $w;
4601                                         // set left side coordinate
4602                                         $this->img_rb_x = $ximg;
4603                                 }
4604                         } else {
4605                                 if ($palign == 'R') {
4606                                         $ximg = $this->w - $this->rMargin - $w;
4607                                         // set left side coordinate
4608                                         $this->img_rb_x = $ximg;
4609                                 } elseif ($palign == 'C') {
4610                                         $ximg = ($this->w - $x - $w) / 2;
4611                                         // set right side coordinate
4612                                         $this->img_rb_x = $ximg + $w;
4613                                 } else {
4614                                         $ximg = $x;
4615                                         // set right side coordinate
4616                                         $this->img_rb_x = $ximg + $w;
4617                                 }
4618                         }
4619                         if ($ismask) {
4620                                 // embed hidden, ouside the canvas
4621                                 $xkimg = ($this->pagedim[$this->page]['w'] + 10);
4622                         } else {
4623                                 $xkimg = $ximg * $this->k;
4624                         }
4625                         $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%d Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
4626                         if (!empty($border)) {
4627                                 $bx = $x;
4628                                 $by = $y;
4629                                 $this->x = $ximg;
4630                                 $this->y = $y;
4631                                 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
4632                                 $this->x = $bx;
4633                                 $this->y = $by;
4634                         }
4635                         if ($link) {
4636                                 $this->Link($ximg, $y, $w, $h, $link, 0);
4637                         }
4638                         // set pointer to align the successive text/objects
4639                         switch($align) {
4640                                 case 'T': {
4641                                         $this->y = $y;
4642                                         $this->x = $this->img_rb_x;
4643                                         break;
4644                                 }
4645                                 case 'M': {
4646                                         $this->y = $y + round($h/2);
4647                                         $this->x = $this->img_rb_x;
4648                                         break;
4649                                 }
4650                                 case 'B': {
4651                                         $this->y = $this->img_rb_y;
4652                                         $this->x = $this->img_rb_x;
4653                                         break;
4654                                 }
4655                                 case 'N': {
4656                                         $this->SetY($this->img_rb_y);
4657                                         break;
4658                                 }
4659                                 default:{
4660                                         break;
4661                                 }
4662                         }
4663                         $this->endlinex = $this->img_rb_x;
4664                         return $info['i'];
4665                 }
4666
4667                 /**
4668                 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
4669                 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
4670                 * @param string $file Image file name.
4671                 * @param image $image Image object.
4672                 * return image JPEG image object.
4673                 * @access protected
4674                 */
4675                 protected function _toJPEG($image) {
4676                         $tempname = tempnam(K_PATH_CACHE, 'jpg_');
4677                         imagejpeg($image, $tempname, $this->jpeg_quality);
4678                         imagedestroy($image);
4679                         $retvars = $this->_parsejpeg($tempname);
4680                         // tidy up by removing temporary image
4681                         unlink($tempname);
4682                         return $retvars;
4683                 }
4684
4685                 /**
4686                 * Extract info from a JPEG file without using the GD library.
4687                 * @param string $file image file to parse
4688                 * @return array structure containing the image data
4689                 * @access protected
4690                 */
4691                 protected function _parsejpeg($file) {
4692                         $a = getimagesize($file);
4693                         if (empty($a)) {
4694                                 $this->Error('Missing or incorrect image file: '.$file);
4695                         }
4696                         if ($a[2] != 2) {
4697                                 $this->Error('Not a JPEG file: '.$file);
4698                         }
4699                         if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
4700                                 $colspace = 'DeviceRGB';
4701                         } elseif ($a['channels'] == 4) {
4702                                 $colspace = 'DeviceCMYK';
4703                         } else {
4704                                 $colspace = 'DeviceGray';
4705                         }
4706                         $bpc = isset($a['bits']) ? $a['bits'] : 8;
4707                         $data = file_get_contents($file);
4708                         return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
4709                 }
4710
4711                 /**
4712                 * Extract info from a PNG file without using the GD library.
4713                 * @param string $file image file to parse
4714                 * @return array structure containing the image data
4715                 * @access protected
4716                 */
4717                 protected function _parsepng($file) {
4718                         $f = fopen($file, 'rb');
4719                         if ($f === false) {
4720                                 $this->Error('Can\'t open image file: '.$file);
4721                         }
4722                         //Check signature
4723                         if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
4724                                 $this->Error('Not a PNG file: '.$file);
4725                         }
4726                         //Read header chunk
4727                         fread($f, 4);
4728                         if (fread($f, 4) != 'IHDR') {
4729                                 $this->Error('Incorrect PNG file: '.$file);
4730                         }
4731                         $w = $this->_freadint($f);
4732                         $h = $this->_freadint($f);
4733                         $bpc = ord(fread($f, 1));
4734                         if ($bpc > 8) {
4735                                 //$this->Error('16-bit depth not supported: '.$file);
4736                                 fclose($f);
4737                                 return false;
4738                         }
4739                         $ct = ord(fread($f, 1));
4740                         if ($ct == 0) {
4741                                 $colspace = 'DeviceGray';
4742                         } elseif ($ct == 2) {
4743                                 $colspace = 'DeviceRGB';
4744                         } elseif ($ct == 3) {
4745                                 $colspace = 'Indexed';
4746                         } else {
4747                                 // alpha channel
4748                                 fclose($f);
4749                                 return 'pngalpha';
4750                         }
4751                         if (ord(fread($f, 1)) != 0) {
4752                                 //$this->Error('Unknown compression method: '.$file);
4753                                 fclose($f);
4754                                 return false;
4755                         }
4756                         if (ord(fread($f, 1)) != 0) {
4757                                 //$this->Error('Unknown filter method: '.$file);
4758                                 fclose($f);
4759                                 return false;
4760                         }
4761                         if (ord(fread($f, 1)) != 0) {
4762                                 //$this->Error('Interlacing not supported: '.$file);
4763                                 fclose($f);
4764                                 return false;
4765                         }
4766                         fread($f, 4);
4767                         $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
4768                         //Scan chunks looking for palette, transparency and image data
4769                         $pal = '';
4770                         $trns = '';
4771                         $data = '';
4772                         do {
4773                                 $n = $this->_freadint($f);
4774                                 $type = fread($f, 4);
4775                                 if ($type == 'PLTE') {
4776                                         //Read palette
4777                                         $pal = $this->rfread($f, $n);
4778                                         fread($f, 4);
4779                                 } elseif ($type == 'tRNS') {
4780                                         //Read transparency info
4781                                         $t = $this->rfread($f, $n);
4782                                         if ($ct == 0) {
4783                                                 $trns = array(ord(substr($t, 1, 1)));
4784                                         } elseif ($ct == 2) {
4785                                                 $trns = array(ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1)));
4786                                         } else {
4787                                                 $pos = strpos($t, chr(0));
4788                                                 if ($pos !== false) {
4789                                                         $trns = array($pos);
4790                                                 }
4791                                         }
4792                                         fread($f, 4);
4793                                 } elseif ($type == 'IDAT') {
4794                                         //Read image data block
4795                                         $data .= $this->rfread($f, $n);
4796                                         fread($f, 4);
4797                                 } elseif ($type == 'IEND') {
4798                                         break;
4799                                 } else {
4800                                         $this->rfread($f, $n + 4);
4801                                 }
4802                         } while ($n);
4803                         if (($colspace == 'Indexed') AND (empty($pal))) {
4804                                 //$this->Error('Missing palette in '.$file);
4805                                 fclose($f);
4806                                 return false;
4807                         }
4808                         fclose($f);
4809                         return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
4810                 }
4811
4812                 /**
4813                 * Binary-safe and URL-safe file read.
4814                 * Reads up to length  bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met: length bytes have been read; EOF (end of file) is reached.
4815                 * @param resource $handle
4816                 * @param int $length
4817                 * @return Returns the read string or FALSE in case of error.
4818                 * @author Nicola Asuni
4819                 * @access protected
4820                 * @since 4.5.027 (2009-03-16)
4821                 */
4822                 protected function rfread($handle, $length) {
4823                         $data = fread($handle, $length);
4824                         if ($data === false) {
4825                                 return false;
4826                         }
4827                         $rest = $length - strlen($data);
4828                         if ($rest > 0) {
4829                                 $data .= $this->rfread($handle, $rest);
4830                         }
4831                         return $data;
4832                 }
4833
4834                 /**
4835                 * Extract info from a PNG image with alpha channel using the GD library.
4836                 * @param string $file Name of the file containing the image.
4837                 * @param float $x Abscissa of the upper-left corner.
4838                 * @param float $y Ordinate of the upper-left corner.
4839                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
4840                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
4841                 * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
4842                 * @param mixed $link URL or identifier returned by AddLink().
4843                 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
4844                 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
4845                 * @param int $dpi dot-per-inch resolution used on resize
4846                 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
4847                 * @author Valentin Schmidt, Nicola Asuni
4848                 * @access protected
4849                 * @since 4.3.007 (2008-12-04)
4850                 * @see Image()
4851                 */
4852                 protected function ImagePngAlpha($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
4853                         // get image size
4854                         list($wpx, $hpx) = getimagesize($file);
4855                         // generate images
4856                         $img = imagecreatefrompng($file);
4857                         $imgalpha = imagecreate($wpx, $hpx);
4858                         // generate gray scale pallete
4859                         for ($c = 0; $c < 256; ++$c) {
4860                                 ImageColorAllocate($imgalpha, $c, $c, $c);
4861                         }
4862                         // extract alpha channel
4863                         for ($xpx = 0; $xpx < $wpx; ++$xpx) {
4864                                 for ($ypx = 0; $ypx < $hpx; ++$ypx) {
4865                                         $colorindex = imagecolorat($img, $xpx, $ypx);
4866                                         $col = imagecolorsforindex($img, $colorindex);
4867                                         imagesetpixel($imgalpha, $xpx, $ypx, $this->getGDgamma((127 - $col['alpha']) * 255 / 127));
4868                                 }
4869                         }
4870                         // create temp alpha file
4871                         $tempfile_alpha = tempnam(K_PATH_CACHE, 'mska_');
4872                         imagepng($imgalpha, $tempfile_alpha);
4873                         imagedestroy($imgalpha);
4874                         // extract image without alpha channel
4875                         $imgplain = imagecreatetruecolor($wpx, $hpx);
4876                         imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
4877                         // create temp image file
4878                         $tempfile_plain = tempnam(K_PATH_CACHE, 'mskp_');
4879                         imagepng($imgplain, $tempfile_plain);
4880                         imagedestroy($imgplain);
4881                         // embed mask image
4882                         $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
4883                         // embed image, masked with previously embedded mask
4884                         $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
4885                         // remove temp files
4886                         unlink($tempfile_alpha);
4887                         unlink($tempfile_plain);
4888                 }
4889
4890                 /**
4891                 * Correct the gamma value to be used with GD library
4892                 * @param float $v the gamma value to be corrected
4893                 * @access protected
4894                 * @since 4.3.007 (2008-12-04)
4895                 */
4896                 protected function getGDgamma($v) {
4897                         return (pow(($v / 255), 2.2) * 255);
4898                 }
4899
4900                 /**
4901                 * Performs a line break.
4902                 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
4903                 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
4904                 * @param boolean $cell if true add a cMargin to the x coordinate
4905                 * @access public
4906                 * @since 1.0
4907                 * @see Cell()
4908                 */
4909                 public function Ln($h='', $cell=false) {
4910                         //Line feed; default value is last cell height
4911                         if ($cell) {
4912                                 $cellmargin = $this->cMargin;
4913                         } else {
4914                                 $cellmargin = 0;
4915                         }
4916                         if ($this->rtl) {
4917                                 $this->x = $this->w - $this->rMargin - $cellmargin;
4918                         } else {
4919                                 $this->x = $this->lMargin + $cellmargin;
4920                         }
4921                         if (is_string($h)) {
4922                                 $this->y += $this->lasth;
4923                         } else {
4924                                 $this->y += $h;
4925                         }
4926                         $this->newline = true;
4927                 }
4928
4929                 /**
4930                 * Returns the relative X value of current position.
4931                 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
4932                 * @return float
4933                 * @access public
4934                 * @since 1.2
4935                 * @see SetX(), GetY(), SetY()
4936                 */
4937                 public function GetX() {
4938                         //Get x position
4939                         if ($this->rtl) {
4940                                 return ($this->w - $this->x);
4941                         } else {
4942                                 return $this->x;
4943                         }
4944                 }
4945
4946                 /**
4947                 * Returns the absolute X value of current position.
4948                 * @return float
4949                 * @access public
4950                 * @since 1.2
4951                 * @see SetX(), GetY(), SetY()
4952                 */
4953                 public function GetAbsX() {
4954                         return $this->x;
4955                 }
4956
4957                 /**
4958                 * Returns the ordinate of the current position.
4959                 * @return float
4960                 * @access public
4961                 * @since 1.0
4962                 * @see SetY(), GetX(), SetX()
4963                 */
4964                 public function GetY() {
4965                         //Get y position
4966                         return $this->y;
4967                 }
4968
4969                 /**
4970                 * Defines the abscissa of the current position.
4971                 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
4972                 * @param float $x The value of the abscissa.
4973                 * @access public
4974                 * @since 1.2
4975                 * @see GetX(), GetY(), SetY(), SetXY()
4976                 */
4977                 public function SetX($x) {
4978                         //Set x position
4979                         if ($this->rtl) {
4980                                 if ($x >= 0) {
4981                                         $this->x = $this->w - $x;
4982                                 } else {
4983                                         $this->x = abs($x);
4984                                 }
4985                         } else {
4986                                 if ($x >= 0) {
4987                                         $this->x = $x;
4988                                 } else {
4989                                         $this->x = $this->w + $x;
4990                                 }
4991                         }
4992                         if ($this->x < 0) {
4993                                 $this->x = 0;
4994                         }
4995                         if ($this->x > $this->w) {
4996                                 $this->x = $this->w;
4997                         }
4998                 }
4999
5000                 /**
5001                 * Moves the current abscissa back to the left margin and sets the ordinate.
5002                 * If the passed value is negative, it is relative to the bottom of the page.
5003                 * @param float $y The value of the ordinate.
5004                 * @param bool $resetx if true (default) reset the X position.
5005                 * @access public
5006                 * @since 1.0
5007                 * @see GetX(), GetY(), SetY(), SetXY()
5008                 */
5009                 public function SetY($y, $resetx=true) {
5010                         if ($resetx) {
5011                                 //reset x
5012                                 if ($this->rtl) {
5013                                         $this->x = $this->w - $this->rMargin;
5014                                 } else {
5015                                         $this->x = $this->lMargin;
5016                                 }
5017                         }
5018                         if ($y >= 0) {
5019                                 $this->y = $y;
5020                         } else {
5021                                 $this->y = $this->h + $y;
5022                         }
5023                         if ($this->y < 0) {
5024                                 $this->y = 0;
5025                         }
5026                         if ($this->y > $this->h) {
5027                                 $this->y = $this->h;
5028                         }
5029                 }
5030
5031                 /**
5032                 * Defines the abscissa and ordinate of the current position.
5033                 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
5034                 * @param float $x The value of the abscissa
5035                 * @param float $y The value of the ordinate
5036                 * @access public
5037                 * @since 1.2
5038                 * @see SetX(), SetY()
5039                 */
5040                 public function SetXY($x, $y) {
5041                         //Set x and y positions
5042                         $this->SetY($y);
5043                         $this->SetX($x);
5044                 }
5045
5046                 /**
5047                 * Send the document to a given destination: string, local file or browser.
5048                 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
5049                 * The method first calls Close() if necessary to terminate the document.
5050                 * @param string $name The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
5051                 * @param string $dest Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local file with the name given by name.</li><li>S: return the document as a string. name is ignored.</li></ul>
5052                 * @access public
5053                 * @since 1.0
5054                 * @see Close()
5055                 */
5056                 public function Output($name='doc.pdf', $dest='I') {
5057                         //Output PDF to some destination
5058                         //Finish document if necessary
5059                         if ($this->state < 3) {
5060                                 $this->Close();
5061                         }
5062                         //Normalize parameters
5063                         if (is_bool($dest)) {
5064                                 $dest = $dest ? 'D' : 'F';
5065                         }
5066                         $dest = strtoupper($dest);
5067                         if ($dest != 'F') {
5068                                 $name = preg_replace('/[\s]+/', '_', $name);
5069                                 $name = preg_replace('/[^a-zA-Z0-9\._-\x{4e00}-\x{9fa5}]/u', '', $name);
5070                         }
5071                         if ($this->sign) {
5072                                 // *** apply digital signature to the document ***
5073                                 // get the document content
5074                                 $pdfdoc = $this->getBuffer();
5075                                 // remove last newline
5076                                 $pdfdoc = substr($pdfdoc, 0, -1);
5077                                 // Remove the original buffer
5078                                 if (isset($this->diskcache) AND $this->diskcache) {
5079                                         // remove buffer file from cache
5080                                         unlink($this->buffer);
5081                                 }
5082                                 unset($this->buffer);
5083                                 // remove filler space
5084                                 $tmppos = strpos($pdfdoc, '/ByteRange[0 ********** ********** **********]') + 58;
5085                                 $pdfdoc = substr($pdfdoc, 0, $tmppos).substr($pdfdoc, $tmppos + $this->signature_max_lenght);
5086                                 // define the ByteRange
5087                                 $byte_range = array();
5088                                 $byte_range[0] = 0;
5089                                 $byte_range[1] = $tmppos - 1;
5090                                 $byte_range[2] = $byte_range[1] + $this->signature_max_lenght;
5091                                 $byte_range[3] = strlen($pdfdoc) - $byte_range[1];
5092                                 // replace the ByteRange
5093                                 $byterange = sprintf('/ByteRange[0 %010u %010u %010u]', $byte_range[1], $byte_range[2], $byte_range[3]);
5094                                 $pdfdoc = str_replace('/ByteRange[0 ********** ********** **********]', $byterange, $pdfdoc);
5095                                 // write the document to a temporary folder
5096                                 $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_');
5097                                 $f = fopen($tempdoc, 'wb');
5098                                 if (!$f) {
5099                                         $this->Error('Unable to create temporary file: '.$tempdoc);
5100                                 }
5101                                 $pdfdoc_lenght = strlen($pdfdoc);
5102                                 fwrite($f, $pdfdoc, $pdfdoc_lenght);
5103                                 fclose($f);
5104                                 // get digital signature.
5105                                 // IS THE FOLLOWING PROCEDURE CORRECT? THE SIGNED DOCUMENTS ARE NOT VALID!
5106                                 $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_');
5107                                 if (empty($this->signature_data['extracerts'])) {
5108                                         openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
5109                                 } else {
5110                                         openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED, $this->signature_data['extracerts']);
5111                                 }
5112                                 unlink($tempdoc);
5113                                 // read signature
5114                                 $signature = file_get_contents($tempsign, false, null, $pdfdoc_lenght);
5115                                 unlink($tempsign);
5116                                 // extract signature
5117                                 $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
5118                                 $tmparr = explode("\n\n", $signature);
5119                                 $signature = $tmparr[1];
5120                                 unset($tmparr);
5121                                 // decode signature
5122                                 $signature = base64_decode(trim($signature));
5123                                 // convert signature to hex
5124                                 $signature = current(unpack('H*', $signature));
5125                                 $signature = str_pad($signature, $this->signature_max_lenght, '0');
5126                                 // Add signature to the document
5127                                 $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).$signature.substr($pdfdoc, (0 - $byte_range[3]));
5128                                 $this->diskcache = false;
5129                                 $this->buffer = &$pdfdoc;
5130                                 $this->bufferlen = strlen($pdfdoc);
5131                         }
5132                         switch($dest) {
5133                                 case 'I': {
5134                                         // Send PDF to the standard output
5135                                         if (ob_get_contents()) {
5136                                                 $this->Error('Some data has already been output, can\'t send PDF file');
5137                                         }
5138                                         if (php_sapi_name() != 'cli') {
5139                                                 //We send to a browser
5140                                                 header('Content-Type: application/pdf');
5141                                                 if (headers_sent()) {
5142                                                         $this->Error('Some data has already been output to browser, can\'t send PDF file');
5143                                                 }
5144                                                 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
5145                                                 header('Pragma: public');
5146                                                 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
5147                                                 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
5148                                                 header('Content-Length: '.$this->bufferlen);
5149                                                 header('Content-Disposition: inline; filename="'.basename($name).'";');
5150                                         }
5151                                         echo $this->getBuffer();
5152                                         break;
5153                                 }
5154                                 case 'D': {
5155                                         // Download PDF as file
5156                                         if (ob_get_contents()) {
5157                                                 $this->Error('Some data has already been output, can\'t send PDF file');
5158                                         }
5159                                         header('Content-Description: File Transfer');
5160                                         if (headers_sent()) {
5161                                                 $this->Error('Some data has already been output to browser, can\'t send PDF file');
5162                                         }
5163                                         header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
5164                                         header('Pragma: public');
5165                                         header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
5166                                         header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
5167                                         // force download dialog
5168                                         header('Content-Type: application/force-download');
5169                                         header('Content-Type: application/octet-stream', false);
5170                                         header('Content-Type: application/download', false);
5171                                         header('Content-Type: application/pdf', false);
5172                                         // use the Content-Disposition header to supply a recommended filename
5173                                         header('Content-Disposition: attachment; filename="'.basename($name).'";');
5174                                         header('Content-Transfer-Encoding: binary');
5175                                         header('Content-Length: '.$this->bufferlen);
5176                                         echo $this->getBuffer();
5177                                         break;
5178                                 }
5179                                 case 'F': {
5180                                         // Save PDF to a local file
5181                                         if ($this->diskcache) {
5182                                                 copy($this->buffer, $name);
5183                                         } else {
5184                                                 $f = fopen($name, 'wb');
5185                                                 if (!$f) {
5186                                                         $this->Error('Unable to create output file: '.$name);
5187                                                 }
5188                                                 fwrite($f, $this->getBuffer(), $this->bufferlen);
5189                                                 fclose($f);
5190                                         }
5191                                         break;
5192                                 }
5193                                 case 'S': {
5194                                         // Returns PDF as a string
5195                                         return $this->getBuffer();
5196                                 }
5197                                 default: {
5198                                         $this->Error('Incorrect output destination: '.$dest);
5199                                 }
5200                         }
5201                         return '';
5202                 }
5203
5204                 /**
5205                  * Unset all class variables except the following critical variables: internal_encoding, state, bufferlen, buffer and diskcache.
5206                  * @param boolean $destroyall if true destroys all class variables, otherwise preserves critical variables.
5207                  * @param boolean $preserve_objcopy if true preserves the objcopy variable
5208                  * @access public
5209                  * @since 4.5.016 (2009-02-24)
5210                  */
5211                 public function _destroy($destroyall=false, $preserve_objcopy=false) {
5212                         if ($destroyall AND isset($this->diskcache) AND $this->diskcache AND (!$preserve_objcopy) AND (!$this->empty_string($this->buffer))) {
5213                                 // remove buffer file from cache
5214                                 unlink($this->buffer);
5215                         }
5216                         foreach (array_keys(get_object_vars($this)) as $val) {
5217                                 if ($destroyall OR (
5218                                         ($val != 'internal_encoding')
5219                                         AND ($val != 'state')
5220                                         AND ($val != 'bufferlen')
5221                                         AND ($val != 'buffer')
5222                                         AND ($val != 'diskcache')
5223                                         AND ($val != 'sign')
5224                                         AND ($val != 'signature_data')
5225                                         AND ($val != 'signature_max_lenght')
5226                                         )) {
5227                                         if (!$preserve_objcopy OR ($val != 'objcopy')) {
5228                                                 unset($this->$val);
5229                                         }
5230                                 }
5231                         }
5232                 }
5233
5234                 /**
5235                 * Check for locale-related bug
5236                 * @access protected
5237                 */
5238                 protected function _dochecks() {
5239                         //Check for locale-related bug
5240                         if (1.1 == 1) {
5241                                 $this->Error('Don\'t alter the locale before including class file');
5242                         }
5243                         //Check for decimal separator
5244                         if (sprintf('%.1F', 1.0) != '1.0') {
5245                                 setlocale(LC_NUMERIC, 'C');
5246                         }
5247                 }
5248
5249                 /**
5250                 * Return fonts path
5251                 * @return string
5252                 * @access protected
5253                 */
5254                 protected function _getfontpath() {
5255                         if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
5256                                 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
5257                         }
5258                         return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
5259                 }
5260
5261                 /**
5262                 * Output pages.
5263                 * @access protected
5264                 */
5265                 protected function _putpages() {
5266                         $nb = $this->numpages;
5267                         if (!empty($this->AliasNbPages)) {
5268                                 $nbs = $this->formatPageNumber($nb);
5269                                 $nbu = $this->UTF8ToUTF16BE($nbs, false); // replacement for unicode font
5270                                 $alias_a = $this->_escape($this->AliasNbPages);
5271                                 $alias_au = $this->_escape('{'.$this->AliasNbPages.'}');
5272                                 if ($this->isunicode) {
5273                                         $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
5274                                         $alias_bu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNbPages.'}'));
5275                                         $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
5276                                         $alias_cu = $this->_escape($this->utf8StrRev('{'.$this->AliasNbPages.'}', false, $this->tmprtl));
5277                                 }
5278                         }
5279                         if (!empty($this->AliasNumPage)) {
5280                                 $alias_pa = $this->_escape($this->AliasNumPage);
5281                                 $alias_pau = $this->_escape('{'.$this->AliasNumPage.'}');
5282                                 if ($this->isunicode) {
5283                                         $alias_pb = $this->_escape($this->UTF8ToLatin1($this->AliasNumPage));
5284                                         $alias_pbu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNumPage.'}'));
5285                                         $alias_pc = $this->_escape($this->utf8StrRev($this->AliasNumPage, false, $this->tmprtl));
5286                                         $alias_pcu = $this->_escape($this->utf8StrRev('{'.$this->AliasNumPage.'}', false, $this->tmprtl));
5287                                 }
5288                         }
5289                         $pagegroupnum = 0;
5290                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
5291                         for ($n=1; $n <= $nb; ++$n) {
5292                                 $temppage = $this->getPageBuffer($n);
5293                                 if (!empty($this->pagegroups)) {
5294                                         if(isset($this->newpagegroup[$n])) {
5295                                                 $pagegroupnum = 0;
5296                                         }
5297                                         ++$pagegroupnum;
5298                                         foreach ($this->pagegroups as $k => $v) {
5299                                                 // replace total pages group numbers
5300                                                 $vs = $this->formatPageNumber($v);
5301                                                 $vu = $this->UTF8ToUTF16BE($vs, false);
5302                                                 $alias_ga = $this->_escape($k);
5303                                                 $alias_gau = $this->_escape('{'.$k.'}');
5304                                                 if ($this->isunicode) {
5305                                                         $alias_gb = $this->_escape($this->UTF8ToLatin1($k));
5306                                                         $alias_gbu = $this->_escape($this->UTF8ToLatin1('{'.$k.'}'));
5307                                                         $alias_gc = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
5308                                                         $alias_gcu = $this->_escape($this->utf8StrRev('{'.$k.'}', false, $this->tmprtl));
5309                                                 }
5310                                                 $temppage = str_replace($alias_gau, $vu, $temppage);
5311                                                 if ($this->isunicode) {
5312                                                         $temppage = str_replace($alias_gbu, $vu, $temppage);
5313                                                         $temppage = str_replace($alias_gcu, $vu, $temppage);
5314                                                         $temppage = str_replace($alias_gb, $vs, $temppage);
5315                                                         $temppage = str_replace($alias_gc, $vs, $temppage);
5316                                                 }
5317                                                 $temppage = str_replace($alias_ga, $vs, $temppage);
5318                                                 // replace page group numbers
5319                                                 $pvs = $this->formatPageNumber($pagegroupnum);
5320                                                 $pvu = $this->UTF8ToUTF16BE($pvs, false);
5321                                                 $pk = str_replace('{nb', '{pnb', $k);
5322                                                 $alias_pga = $this->_escape($pk);
5323                                                 $alias_pgau = $this->_escape('{'.$pk.'}');
5324                                                 if ($this->isunicode) {
5325                                                         $alias_pgb = $this->_escape($this->UTF8ToLatin1($pk));
5326                                                         $alias_pgbu = $this->_escape($this->UTF8ToLatin1('{'.$pk.'}'));
5327                                                         $alias_pgc = $this->_escape($this->utf8StrRev($pk, false, $this->tmprtl));
5328                                                         $alias_pgcu = $this->_escape($this->utf8StrRev('{'.$pk.'}', false, $this->tmprtl));
5329                                                 }
5330                                                 $temppage = str_replace($alias_pgau, $pvu, $temppage);
5331                                                 if ($this->isunicode) {
5332                                                         $temppage = str_replace($alias_pgbu, $pvu, $temppage);
5333                                                         $temppage = str_replace($alias_pgcu, $pvu, $temppage);
5334                                                         $temppage = str_replace($alias_pgb, $pvs, $temppage);
5335                                                         $temppage = str_replace($alias_pgc, $pvs, $temppage);
5336                                                 }
5337                                                 $temppage = str_replace($alias_pga, $pvs, $temppage);
5338                                         }
5339                                 }
5340                                 if (!empty($this->AliasNbPages)) {
5341                                         // replace total pages number
5342                                         $temppage = str_replace($alias_au, $nbu, $temppage);
5343                                         if ($this->isunicode) {
5344                                                 $temppage = str_replace($alias_bu, $nbu, $temppage);
5345                                                 $temppage = str_replace($alias_cu, $nbu, $temppage);
5346                                                 $temppage = str_replace($alias_b, $nbs, $temppage);
5347                                                 $temppage = str_replace($alias_c, $nbs, $temppage);
5348                                         }
5349                                         $temppage = str_replace($alias_a, $nbs, $temppage);
5350                                 }
5351                                 if (!empty($this->AliasNumPage)) {
5352                                         // replace page number
5353                                         $pnbs = $this->formatPageNumber($n);
5354                                         $pnbu = $this->UTF8ToUTF16BE($pnbs, false); // replacement for unicode font
5355                                         $temppage = str_replace($alias_pau, $pnbu, $temppage);
5356                                         if ($this->isunicode) {
5357                                                 $temppage = str_replace($alias_pbu, $pnbu, $temppage);
5358                                                 $temppage = str_replace($alias_pcu, $pnbu, $temppage);
5359                                                 $temppage = str_replace($alias_pb, $pnbs, $temppage);
5360                                                 $temppage = str_replace($alias_pc, $pnbs, $temppage);
5361                                         }
5362                                         $temppage = str_replace($alias_pa, $pnbs, $temppage);
5363                                 }
5364                                 $temppage = str_replace($this->epsmarker, '', $temppage);
5365                                 //$this->setPageBuffer($n, $temppage);
5366                                 //Page
5367                                 $this->_newobj();
5368                                 $this->_out('<</Type /Page');
5369                                 $this->_out('/Parent 1 0 R');
5370                                 $this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
5371                                 $this->_out('/Resources 2 0 R');
5372                                 $this->_putannots($n);
5373                                 $this->_out('/Contents '.($this->n + 1).' 0 R>>');
5374                                 $this->_out('endobj');
5375                                 //Page content
5376                                 $p = ($this->compress) ? gzcompress($temppage) : $temppage;
5377                                 $this->_newobj();
5378                                 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
5379                                 $this->_putstream($p);
5380                                 $this->_out('endobj');
5381                                 if ($this->diskcache) {
5382                                         // remove temporary files
5383                                         unlink($this->pages[$n]);
5384                                 }
5385                         }
5386                         //Pages root
5387                         $this->offsets[1] = $this->bufferlen;
5388                         $this->_out('1 0 obj');
5389                         $this->_out('<</Type /Pages');
5390                         $kids='/Kids [';
5391                         for ($i=0; $i < $nb; ++$i) {
5392                                 $kids .= (3 + (2 * $i)).' 0 R ';
5393                         }
5394                         $this->_out($kids.']');
5395                         $this->_out('/Count '.$nb);
5396                         //$this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
5397                         $this->_out('>>');
5398                         $this->_out('endobj');
5399                 }
5400
5401                 /**
5402                 * Output Page Annotations.
5403                 * !!! THIS FUNCTION IS NOT YET COMPLETED !!!
5404                 * See section 8.4 of PDF reference.
5405                 * @param int $n page number
5406                 * @access protected
5407                 * @author Nicola Asuni
5408                 * @since 4.0.018 (2008-08-06)
5409                 */
5410                 protected function _putannots($n) {
5411                         if (isset($this->PageAnnots[$n])) {
5412                                 $annots = '/Annots [';
5413                                 foreach ($this->PageAnnots[$n] as $key => $pl) {
5414                                         $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
5415                                         $a = $pl['x'] * $this->k;
5416                                         $b = $this->pagedim[$n]['h'] - ($pl['y']  * $this->k);
5417                                         $c = $pl['w'] * $this->k;
5418                                         $d = $pl['h'] * $this->k;
5419                                         $rect = sprintf('%.2F %.2F %.2F %.2F', $a, $b, $a+$c, $b-$d);
5420                                         $annots .= "\n";
5421                                         $annots .= '<</Type /Annot';
5422                                         $annots .= ' /Subtype /'.$pl['opt']['subtype'];
5423                                         $annots .= ' /Rect ['.$rect.']';
5424                                         $annots .= ' /Contents '.$this->_textstring($pl['txt']);
5425                                         //$annots .= ' /P ';
5426                                         $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
5427                                         $annots .= ' /M '.$this->_datastring('D:'.date('YmdHis'));
5428                                         if (isset($pl['opt']['f'])) {
5429                                                 $val = 0;
5430                                                 if (is_array($pl['opt']['f'])) {
5431                                                         foreach ($pl['opt']['f'] as $f) {
5432                                                                 switch (strtolower($f)) {
5433                                                                         case 'invisible': {
5434                                                                                 $val += 1 << 0;
5435                                                                                 break;
5436                                                                         }
5437                                                                         case 'hidden': {
5438                                                                                 $val += 1 << 1;
5439                                                                                 break;
5440                                                                         }
5441                                                                         case 'print': {
5442                                                                                 $val += 1 << 2;
5443                                                                                 break;
5444                                                                         }
5445                                                                         case 'nozoom': {
5446                                                                                 $val += 1 << 3;
5447                                                                                 break;
5448                                                                         }
5449                                                                         case 'norotate': {
5450                                                                                 $val += 1 << 4;
5451                                                                                 break;
5452                                                                         }
5453                                                                         case 'noview': {
5454                                                                                 $val += 1 << 5;
5455                                                                                 break;
5456                                                                         }
5457                                                                         case 'readonly': {
5458                                                                                 $val += 1 << 6;
5459                                                                                 break;
5460                                                                         }
5461                                                                         case 'locked': {
5462                                                                                 $val += 1 << 8;
5463                                                                                 break;
5464                                                                         }
5465                                                                         case 'togglenoview': {
5466                                                                                 $val += 1 << 9;
5467                                                                                 break;
5468                                                                         }
5469                                                                         case 'lockedcontents': {
5470                                                                                 $val += 1 << 10;
5471                                                                                 break;
5472                                                                         }
5473                                                                         default: {
5474                                                                                 break;
5475                                                                         }
5476                                                                 }
5477                                                         }
5478                                                 }
5479                                                 $annots .= ' /F '.intval($val);
5480                                         }
5481                                         //$annots .= ' /AP ';
5482                                         //$annots .= ' /AS ';
5483                                         $annots .= ' /Border [';
5484                                         if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
5485                                                 $annots .= intval($pl['opt']['border'][0]).' ';
5486                                                 $annots .= intval($pl['opt']['border'][1]).' ';
5487                                                 $annots .= intval($pl['opt']['border'][2]);
5488                                                 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
5489                                                         $annots .= ' [';
5490                                                         foreach ($pl['opt']['border'][3] as $dash) {
5491                                                                 $annots .= intval($dash).' ';
5492                                                         }
5493                                                         $annots .= ']';
5494                                                 }
5495                                         } else {
5496                                                 $annots .= '0 0 0';
5497                                         }
5498                                         $annots .= ']';
5499                                         if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
5500                                                 $annots .= ' /BS <<Type /Border';
5501                                                 if (isset($pl['opt']['bs']['w'])) {
5502                                                         $annots .= ' /W '.sprintf("%.4F", floatval($pl['opt']['bs']['w']));
5503                                                 }
5504                                                 $bstyles = array('S', 'D', 'B', 'I', 'U');
5505                                                 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
5506                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
5507                                                 }
5508                                                 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
5509                                                         $annots .= ' /D [';
5510                                                         foreach ($pl['opt']['bs']['d'] as $cord) {
5511                                                                 $cord = floatval($cord);
5512                                                                 $annots .= sprintf(" %.4F", $cord);
5513                                                         }
5514                                                         $annots .= ']';
5515                                                 }
5516                                                 $annots .= '>> ';
5517                                         }
5518                                         if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
5519                                                 $annots .= ' /BE <<';
5520                                                 $bstyles = array('S', 'C');
5521                                                 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
5522                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
5523                                                 } else {
5524                                                         $annots .= ' /S /S';
5525                                                 }
5526                                                 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
5527                                                         $annots .= ' /I '.sprintf(" %.4F", $pl['opt']['be']['i']);
5528                                                 }
5529                                                 $annots .= '>>';
5530                                         }
5531                                         $annots .= ' /C [';
5532                                         if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
5533                                                 foreach ($pl['opt']['c'] as $col) {
5534                                                         $col = intval($col);
5535                                                         $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
5536                                                         $annots .= sprintf(" %.4F", $color);
5537                                                 }
5538                                         }
5539                                         $annots .= ']';
5540                                         //$annots .= ' /StructParent ';
5541                                         //$annots .= ' /OC ';
5542                                         $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight',  'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
5543                                         if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
5544                                                 // this is a markup type
5545                                                 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
5546                                                         $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
5547                                                 }
5548                                                 //$annots .= ' /Popup ';
5549                                                 if (isset($pl['opt']['ca'])) {
5550                                                         $annots .= ' /CA '.sprintf("%.4F", floatval($pl['opt']['ca']));
5551                                                 }
5552                                                 if (isset($pl['opt']['rc'])) {
5553                                                         $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
5554                                                 }
5555                                                 $annots .= ' /CreationDate '.$this->_datastring('D:'.date('YmdHis'));
5556                                                 //$annots .= ' /IRT ';
5557                                                 if (isset($pl['opt']['subj'])) {
5558                                                         $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
5559                                                 }
5560                                                 //$annots .= ' /RT ';
5561                                                 //$annots .= ' /IT ';
5562                                                 //$annots .= ' /ExData ';
5563                                         }
5564                                         switch (strtolower($pl['opt']['subtype'])) {
5565                                                 case 'text': {
5566                                                         if (isset($pl['opt']['open'])) {
5567                                                                 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
5568                                                         }
5569                                                         $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
5570                                                         if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5571                                                                 $annots .= ' /Name /'.$pl['opt']['name'];
5572                                                         } else {
5573                                                                 $annots .= ' /Name /Note';
5574                                                         }
5575                                                         $statemodels = array('Marked', 'Review');
5576                                                         if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
5577                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
5578                                                         } else {
5579                                                                 $pl['opt']['statemodel'] = 'Marked';
5580                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
5581                                                         }
5582                                                         if ($pl['opt']['statemodel'] == 'Marked') {
5583                                                                 $states = array('Accepted', 'Unmarked');
5584                                                         } else {
5585                                                                 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
5586                                                         }
5587                                                         if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
5588                                                                 $annots .= ' /State /'.$pl['opt']['state'];
5589                                                         } else {
5590                                                                 if ($pl['opt']['statemodel'] == 'Marked') {
5591                                                                         $annots .= ' /State /Unmarked';
5592                                                                 } else {
5593                                                                         $annots .= ' /State /None';
5594                                                                 }
5595                                                         }
5596                                                         break;
5597                                                 }
5598                                                 case 'link': {
5599                                                         if(is_string($pl['txt'])) {
5600                                                                 // external URI link
5601                                                                 $annots .= ' /A <</S /URI /URI '.$this->_datastring($pl['txt']).'>>';
5602                                                         } else {
5603                                                                 // internal link
5604                                                                 $l = $this->links[$pl['txt']];
5605                                                                 $annots .= sprintf(' /Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $l[0])), ($this->pagedim[$l[0]]['h'] - ($l[1] * $this->k)));
5606                                                         }
5607                                                         $hmodes = array('N', 'I', 'O', 'P');
5608                                                         if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
5609                                                                 $annots .= ' /H /'.$pl['opt']['h'];
5610                                                         } else {
5611                                                                 $annots .= ' /H /I';
5612                                                         }
5613                                                         //$annots .= ' /PA ';
5614                                                         //$annots .= ' /Quadpoints ';
5615                                                         break;
5616                                                 }
5617                                                 case 'freetext': {
5618                                                         $annots .= ' /DA '.$this->_textstring($pl['txt']);
5619                                                         if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
5620                                                                 $annots .= ' /Q '.intval($pl['opt']['q']);
5621                                                         }
5622                                                         if (isset($pl['opt']['rc'])) {
5623                                                                 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
5624                                                         }
5625                                                         if (isset($pl['opt']['ds'])) {
5626                                                                 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
5627                                                         }
5628                                                         if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
5629                                                                 $annots .= ' /CL [';
5630                                                                 foreach ($pl['opt']['cl'] as $cl) {
5631                                                                         $annots .= sprintf("%.4F ", $cl * $this->k);
5632                                                                 }
5633                                                                 $annots .= ']';
5634                                                         }
5635                                                         $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
5636                                                         if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
5637                                                                 $annots .= ' /IT '.$pl['opt']['it'];
5638                                                         }
5639                                                         if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
5640                                                                 $l = $pl['opt']['rd'][0] * $this->k;
5641                                                                 $r = $pl['opt']['rd'][1] * $this->k;
5642                                                                 $t = $pl['opt']['rd'][2] * $this->k;
5643                                                                 $b = $pl['opt']['rd'][3] * $this->k;
5644                                                                 $annots .= ' /RD ['.sprintf('%.2F %.2F %.2F %.2F', $l, $r, $t, $b).']';
5645                                                         }
5646                                                         //$annots .= ' /LE ';
5647                                                         break;
5648                                                 }
5649                                                 // ... to be completed ...
5650                                                 case 'line': {
5651                                                         break;
5652                                                 }
5653                                                 case 'square': {
5654                                                         break;
5655                                                 }
5656                                                 case 'circle': {
5657                                                         break;
5658                                                 }
5659                                                 case 'polygon': {
5660                                                         break;
5661                                                 }
5662                                                 case 'polyline': {
5663                                                         break;
5664                                                 }
5665                                                 case 'highlight': {
5666                                                         break;
5667                                                 }
5668                                                 case 'underline': {
5669                                                         break;
5670                                                 }
5671                                                 case 'squiggly': {
5672                                                         break;
5673                                                 }
5674                                                 case 'strikeout': {
5675                                                         break;
5676                                                 }
5677                                                 case 'stamp': {
5678                                                         break;
5679                                                 }
5680                                                 case 'caret': {
5681                                                         break;
5682                                                 }
5683                                                 case 'ink': {
5684                                                         break;
5685                                                 }
5686                                                 case 'popup': {
5687                                                         break;
5688                                                 }
5689                                                 case 'fileattachment': {
5690                                                         if (!isset($pl['opt']['fs'])) {
5691                                                                 break;
5692                                                         }
5693                                                         $filename = basename($pl['opt']['fs']);
5694                                                         if (isset($this->embeddedfiles[$filename]['n'])) {
5695                                                                 $annots .= ' /FS <</Type /Filespec /F '.$this->_datastring($filename).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
5696                                                                 $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
5697                                                                 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5698                                                                         $annots .= ' /Name /'.$pl['opt']['name'];
5699                                                                 } else {
5700                                                                         $annots .= ' /Name /PushPin';
5701                                                                 }
5702                                                         }
5703                                                         break;
5704                                                 }
5705                                                 case 'sound': {
5706                                                         if (!isset($pl['opt']['sound'])) {
5707                                                                 break;
5708                                                         }
5709                                                         $filename = basename($pl['opt']['sound']);
5710                                                         if (isset($this->embeddedfiles[$filename]['n'])) {
5711                                                                 // ... TO BE COMPLETED ...
5712                                                                 $iconsapp = array('Speaker', 'Mic');
5713                                                                 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
5714                                                                         $annots .= ' /Name /'.$pl['opt']['name'];
5715                                                                 } else {
5716                                                                         $annots .= ' /Name /Speaker';
5717                                                                 }
5718                                                         }
5719                                                         break;
5720                                                 }
5721                                                 case 'movie': {
5722                                                         break;
5723                                                 }
5724                                                 case 'widget': {
5725                                                         if (isset($pl['opt']['h'])) {
5726                                                                 $annots .= ' /H '.intval($pl['opt']['h']);
5727                                                         }
5728                                                         if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk']))) {
5729                                                                 $annots .= ' /MK <<';
5730                                                                 // ... TO BE COMPLETED ...
5731                                                                 $annots .= '>>';
5732                                                         }
5733                                                         break;
5734                                                 }
5735                                                 case 'screen': {
5736                                                         break;
5737                                                 }
5738                                                 case 'printermark': {
5739                                                         break;
5740                                                 }
5741                                                 case 'trapnet': {
5742                                                         break;
5743                                                 }
5744                                                 case 'watermark': {
5745                                                         break;
5746                                                 }
5747                                                 case '3d': {
5748                                                         break;
5749                                                 }
5750                                                 default: {
5751                                                         break;
5752                                                 }
5753                                         }
5754
5755                                 $annots .= '>>';
5756                                 }
5757                                 $annots .= "\n]";
5758                                 $this->_out($annots);
5759                         }
5760                 }
5761
5762                 /**
5763                 * Output fonts.
5764                 * @access protected
5765                 */
5766                 protected function _putfonts() {
5767                         $nf = $this->n;
5768                         foreach ($this->diffs as $diff) {
5769                                 //Encodings
5770                                 $this->_newobj();
5771                                 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
5772                                 $this->_out('endobj');
5773                         }
5774                         $mqr = get_magic_quotes_runtime();
5775                         //set_magic_quotes_runtime(0);
5776                         foreach ($this->FontFiles as $file => $info) {
5777                                 // search and get font file to embedd
5778                                 $fontdir = $info['fontdir'];
5779                                 $file = strtolower($file);
5780                                 $fontfile = '';
5781                                 // search files on various directories
5782                                 if (file_exists($fontdir.$file)) {
5783                                         $fontfile = $fontdir.$file;
5784                                 } elseif (file_exists($this->_getfontpath().$file)) {
5785                                         $fontfile = $this->_getfontpath().$file;
5786                                 } elseif (file_exists($file)) {
5787                                         $fontfile = $file;
5788                                 }
5789                                 if (!$this->empty_string($fontfile)) {
5790                                         $font = file_get_contents($fontfile);
5791                                         $compressed = (substr($file, -2) == '.z');
5792                                         if ((!$compressed) AND (isset($info['length2']))) {
5793                                                 $header = (ord($font{0}) == 128);
5794                                                 if ($header) {
5795                                                         //Strip first binary header
5796                                                         $font = substr($font, 6);
5797                                                 }
5798                                                 if ($header AND (ord($font{$info['length1']}) == 128)) {
5799                                                         //Strip second binary header
5800                                                         $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
5801                                                 }
5802                                         }
5803                                         $this->_newobj();
5804                                         $this->FontFiles[$file]['n'] = $this->n;
5805                                         $this->_out('<</Length '.strlen($font));
5806                                         if ($compressed) {
5807                                                 $this->_out('/Filter /FlateDecode');
5808                                         }
5809                                         $this->_out('/Length1 '.$info['length1']);
5810                                         if (isset($info['length2'])) {
5811                                                 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
5812                                         }
5813                                         $this->_out('>>');
5814                                         $this->_putstream($font);
5815                                         $this->_out('endobj');
5816                                 }
5817                         }
5818                         //set_magic_quotes_runtime($mqr);
5819                         foreach ($this->fontkeys as $k) {
5820                                 //Font objects
5821                                 $this->setFontSubBuffer($k, 'n', $this->n + 1);
5822                                 $font = $this->getFontBuffer($k);
5823                                 $type = $font['type'];
5824                                 $name = $font['name'];
5825                                 if ($type == 'core') {
5826                                         //Standard font
5827                                         $this->_newobj();
5828                                         $this->_out('<</Type /Font');
5829                                         $this->_out('/BaseFont /'.$name);
5830                                         $this->_out('/Subtype /Type1');
5831                                         if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
5832                                                 $this->_out('/Encoding /WinAnsiEncoding');
5833                                         }
5834                                         $this->_out('>>');
5835                                         $this->_out('endobj');
5836                                 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
5837                                         //Additional Type1 or TrueType font
5838                                         $this->_newobj();
5839                                         $this->_out('<</Type /Font');
5840                                         $this->_out('/BaseFont /'.$name);
5841                                         $this->_out('/Subtype /'.$type);
5842                                         $this->_out('/FirstChar 32 /LastChar 255');
5843                                         $this->_out('/Widths '.($this->n + 1).' 0 R');
5844                                         $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
5845                                         if ($font['enc']) {
5846                                                 if (isset($font['diff'])) {
5847                                                         $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
5848                                                 } else {
5849                                                         $this->_out('/Encoding /WinAnsiEncoding');
5850                                                 }
5851                                         }
5852                                         $this->_out('>>');
5853                                         $this->_out('endobj');
5854                                         // Widths
5855                                         $this->_newobj();
5856                                         $cw = &$font['cw'];
5857                                         $s = '[';
5858                                         for ($i = 32; $i < 256; ++$i) {
5859                                                 $s .= $cw[$i].' ';
5860                                         }
5861                                         $this->_out($s.']');
5862                                         $this->_out('endobj');
5863                                         //Descriptor
5864                                         $this->_newobj();
5865                                         $s = '<</Type /FontDescriptor /FontName /'.$name;
5866                                         foreach ($font['desc'] as $k => $v) {
5867                                                 $s .= ' /'.$k.' '.$v.'';
5868                                         }
5869                                         if (!$this->empty_string($font['file'])) {
5870                                                 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
5871                                         }
5872                                         $this->_out($s.'>>');
5873                                         $this->_out('endobj');
5874                                 } else {
5875                                         //Allow for additional types
5876                                         $mtd = '_put'.strtolower($type);
5877                                         if (!method_exists($this, $mtd)) {
5878                                                 $this->Error('Unsupported font type: '.$type);
5879                                         }
5880                                         $this->$mtd($font);
5881                                 }
5882                         }
5883                 }
5884
5885                 /**
5886                 * Outputs font widths
5887                 * @parameter array $font font data
5888                 * @parameter int $cidoffset offset for CID values
5889                 * @author Nicola Asuni
5890                 * @access protected
5891                 * @since 4.4.000 (2008-12-07)
5892                 */
5893                 protected function _putfontwidths($font, $cidoffset=0) {
5894                         ksort($font['cw']);
5895                         $rangeid = 0;
5896                         $range = array();
5897                         $prevcid = -2;
5898                         $prevwidth = -1;
5899                         $interval = false;
5900                         // for each character
5901                         foreach ($font['cw'] as $cid => $width) {
5902                                 $cid -= $cidoffset;
5903                                 if ($width != $font['dw']) {
5904                                         if ($cid == ($prevcid + 1)) {
5905                                                 // consecutive CID
5906                                                 if ($width == $prevwidth) {
5907                                                         if ($width == $range[$rangeid][0]) {
5908                                                                 $range[$rangeid][] = $width;
5909                                                         } else {
5910                                                                 array_pop($range[$rangeid]);
5911                                                                 // new range
5912                                                                 $rangeid = $prevcid;
5913                                                                 $range[$rangeid] = array();
5914                                                                 $range[$rangeid][] = $prevwidth;
5915                                                                 $range[$rangeid][] = $width;
5916                                                         }
5917                                                         $interval = true;
5918                                                         $range[$rangeid]['interval'] = true;
5919                                                 } else {
5920                                                         if ($interval) {
5921                                                                 // new range
5922                                                                 $rangeid = $cid;
5923                                                                 $range[$rangeid] = array();
5924                                                                 $range[$rangeid][] = $width;
5925                                                         } else {
5926                                                                 $range[$rangeid][] = $width;
5927                                                         }
5928                                                         $interval = false;
5929                                                 }
5930                                         } else {
5931                                                 // new range
5932                                                 $rangeid = $cid;
5933                                                 $range[$rangeid] = array();
5934                                                 $range[$rangeid][] = $width;
5935                                                 $interval = false;
5936                                         }
5937                                         $prevcid = $cid;
5938                                         $prevwidth = $width;
5939                                 }
5940                         }
5941                         // optimize ranges
5942                         $prevk = -1;
5943                         $nextk = -1;
5944                         $prevint = false;
5945                         foreach ($range as $k => $ws) {
5946                                 $cws = count($ws);
5947                                 if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) {
5948                                         if (isset($range[$k]['interval'])) {
5949                                                 unset($range[$k]['interval']);
5950                                         }
5951                                         $range[$prevk] = array_merge($range[$prevk], $range[$k]);
5952                                         unset($range[$k]);
5953                                 } else {
5954                                         $prevk = $k;
5955                                 }
5956                                 $nextk = $k + $cws;
5957                                 if (isset($ws['interval'])) {
5958                                         if ($cws > 3) {
5959                                                 $prevint = true;
5960                                         } else {
5961                                                 $prevint = false;
5962                                         }
5963                                         unset($range[$k]['interval']);
5964                                         --$nextk;
5965                                 } else {
5966                                         $prevint = false;
5967                                 }
5968                         }
5969                         // output data
5970                         $w = '';
5971                         foreach ($range as $k => $ws) {
5972                                 if (count(array_count_values($ws)) == 1) {
5973                                         // interval mode is more compact
5974                                         $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0];
5975                                 } else {
5976                                         // range mode
5977                                         $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
5978                                 }
5979                         }
5980                         $this->_out('/W ['.$w.' ]');
5981                 }
5982
5983                 /**
5984                 * Adds unicode fonts.<br>
5985                 * Based on PDF Reference 1.3 (section 5)
5986                 * @parameter array $font font data
5987                 * @access protected
5988                 * @author Nicola Asuni
5989                 * @since 1.52.0.TC005 (2005-01-05)
5990                 */
5991                 protected function _puttruetypeunicode($font) {
5992                         // Type0 Font
5993                         // A composite font composed of other fonts, organized hierarchically
5994                         $this->_newobj();
5995                         $this->_out('<</Type /Font');
5996                         $this->_out('/Subtype /Type0');
5997                         $this->_out('/BaseFont /'.$font['name'].'');
5998                         $this->_out('/Encoding /Identity-H'); //The horizontal identity mapping for 2-byte CIDs; may be used with CIDFonts using any Registry, Ordering, and Supplement values.
5999                         $this->_out('/ToUnicode /Identity-H');
6000                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
6001                         $this->_out('>>');
6002                         $this->_out('endobj');
6003                         // CIDFontType2
6004                         // A CIDFont whose glyph descriptions are based on TrueType font technology
6005                         $this->_newobj();
6006                         $this->_out('<</Type /Font');
6007                         $this->_out('/Subtype /CIDFontType2');
6008                         $this->_out('/BaseFont /'.$font['name'].'');
6009                         // A dictionary containing entries that define the character collection of the CIDFont.
6010                         $cidinfo = '/Registry '.$this->_datastring('Adobe');
6011                         $cidinfo .= ' /Ordering '.$this->_datastring('Identity');
6012                         $cidinfo .= ' /Supplement 0';
6013                         $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
6014                         $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
6015                         $this->_out('/DW '.$font['dw'].''); // default width
6016                         $this->_putfontwidths($font, 0);
6017                         $this->_out('/CIDToGIDMap '.($this->n + 2).' 0 R');
6018                         $this->_out('>>');
6019                         $this->_out('endobj');
6020                         // Font descriptor
6021                         // A font descriptor describing the CIDFont default metrics other than its glyph widths
6022                         $this->_newobj();
6023                         $this->_out('<</Type /FontDescriptor');
6024                         $this->_out('/FontName /'.$font['name']);
6025                         foreach ($font['desc'] as $key => $value) {
6026                                 $this->_out('/'.$key.' '.$value);
6027                         }
6028                         $fontdir = '';
6029                         if (!$this->empty_string($font['file'])) {
6030                                 // A stream containing a TrueType font
6031                                 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
6032                                 $fontdir = $this->FontFiles[$font['file']]['fontdir'];
6033                         }
6034                         $this->_out('>>');
6035                         $this->_out('endobj');
6036                         $this->_newobj();
6037                         if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
6038                                 // Embed CIDToGIDMap
6039                                 // A specification of the mapping from CIDs to glyph indices
6040                                 // search and get CTG font file to embedd
6041                                 $ctgfile = strtolower($font['ctg']);
6042                                 // search and get ctg font file to embedd
6043                                 $fontfile = '';
6044                                 // search files on various directories
6045                                 if (file_exists($fontdir.$ctgfile)) {
6046                                         $fontfile = $fontdir.$ctgfile;
6047                                 } elseif (file_exists($this->_getfontpath().$ctgfile)) {
6048                                         $fontfile = $this->_getfontpath().$ctgfile;
6049                                 } elseif (file_exists($ctgfile)) {
6050                                         $fontfile = $ctgfile;
6051                                 }
6052                                 if ($this->empty_string($fontfile)) {
6053                                         $this->Error('Font file not found: '.$ctgfile);
6054                                 }
6055                                 $size = filesize($fontfile);
6056                                 $this->_out('<</Length '.$size.'');
6057                                 if (substr($fontfile, -2) == '.z') { // check file extension
6058                                         // Decompresses data encoded using the public-domain
6059                                         // zlib/deflate compression method, reproducing the
6060                                         // original text or binary data
6061                                         $this->_out('/Filter /FlateDecode');
6062                                 }
6063                                 $this->_out('>>');
6064                                 $this->_putstream(file_get_contents($fontfile));
6065                         }
6066                         $this->_out('endobj');
6067                 }
6068
6069                 /**
6070                  * Output CID-0 fonts.
6071                  * @param array $font font data
6072                  * @access protected
6073                  * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
6074                  * @since 3.2.000 (2008-06-23)
6075                  */
6076                 protected function _putcidfont0($font) {
6077                         $cidoffset = 31;
6078                         if (isset($font['cidinfo']['uni2cid'])) {
6079                                 // convert unicode to cid.
6080                                 $uni2cid = $font['cidinfo']['uni2cid'];
6081                                 $cw = array();
6082                                 foreach ($font['cw'] as $uni => $width) {
6083                                         if (isset($uni2cid[$uni])) {
6084                                                 $cw[($uni2cid[$uni] + $cidoffset)] = $width;
6085                                         } elseif ($uni < 256) {
6086                                                 $cw[$uni] = $width;
6087                                         } // else unknown character
6088                                 }
6089                                 $font = array_merge($font, array('cw' => $cw));
6090                         }
6091                         $name = $font['name'];
6092                         $enc = $font['enc'];
6093                         if ($enc) {
6094                                 $longname = $name.'-'.$enc;
6095                         } else {
6096                                 $longname = $name;
6097                         }
6098                         $this->_newobj();
6099                         $this->_out('<</Type /Font');
6100                         $this->_out('/BaseFont /'.$longname);
6101                         $this->_out('/Subtype /Type0');
6102                         if ($enc) {
6103                                 $this->_out('/Encoding /'.$enc);
6104                         }
6105                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
6106                         $this->_out('>>');
6107                         $this->_out('endobj');
6108                         $this->_newobj();
6109                         $this->_out('<</Type /Font');
6110                         $this->_out('/BaseFont /'.$name);
6111                         $this->_out('/Subtype /CIDFontType0');
6112                         $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry']);
6113                         $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering']);
6114                         $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
6115                         $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
6116                         $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
6117                         $this->_out('/DW '.$font['dw']);
6118                         $this->_putfontwidths($font, $cidoffset);
6119                         $this->_out('>>');
6120                         $this->_out('endobj');
6121                         $this->_newobj();
6122                         $s = '<</Type /FontDescriptor /FontName /'.$name;
6123                         foreach ($font['desc'] as $k => $v) {
6124                                 if ($k != 'Style') {
6125                                         $s .= ' /'.$k.' '.$v.'';
6126                                 }
6127                         }
6128                         $this->_out($s.'>>');
6129                         $this->_out('endobj');
6130                 }
6131
6132                 /**
6133                  * Output images.
6134                  * @access protected
6135                  */
6136                 protected function _putimages() {
6137                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
6138                         foreach ($this->imagekeys as $file) {
6139                                 $info = $this->getImageBuffer($file);
6140                                 $this->_newobj();
6141                                 $this->setImageSubBuffer($file, 'n', $this->n);
6142                                 $this->_out('<</Type /XObject');
6143                                 $this->_out('/Subtype /Image');
6144                                 $this->_out('/Width '.$info['w']);
6145                                 $this->_out('/Height '.$info['h']);
6146                                 if (isset($info['masked'])) {
6147                                         $this->_out('/SMask '.($this->n - 1).' 0 R');
6148                                 }
6149                                 if ($info['cs'] == 'Indexed') {
6150                                         $this->_out('/ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]');
6151                                 } else {
6152                                         $this->_out('/ColorSpace /'.$info['cs']);
6153                                         if ($info['cs'] == 'DeviceCMYK') {
6154                                                 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
6155                                         }
6156                                 }
6157                                 $this->_out('/BitsPerComponent '.$info['bpc']);
6158                                 if (isset($info['f'])) {
6159                                         $this->_out('/Filter /'.$info['f']);
6160                                 }
6161                                 if (isset($info['parms'])) {
6162                                         $this->_out($info['parms']);
6163                                 }
6164                                 if (isset($info['trns']) AND is_array($info['trns'])) {
6165                                         $trns='';
6166                                         $count_info = count($info['trns']);
6167                                         for ($i=0; $i < $count_info; ++$i) {
6168                                                 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
6169                                         }
6170                                         $this->_out('/Mask ['.$trns.']');
6171                                 }
6172                                 $this->_out('/Length '.strlen($info['data']).'>>');
6173                                 $this->_putstream($info['data']);
6174                                 $this->_out('endobj');
6175                                 //Palette
6176                                 if ($info['cs'] == 'Indexed') {
6177                                         $this->_newobj();
6178                                         $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
6179                                         $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
6180                                         $this->_putstream($pal);
6181                                         $this->_out('endobj');
6182                                 }
6183                         }
6184                 }
6185
6186                 /**
6187                 * Output Spot Colors Resources.
6188                 * @access protected
6189                 * @since 4.0.024 (2008-09-12)
6190                 */
6191                 protected function _putspotcolors() {
6192                         foreach ($this->spot_colors as $name => $color) {
6193                                 $this->_newobj();
6194                                 $this->spot_colors[$name]['n'] = $this->n;
6195                                 $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
6196                                 $this->_out('/DeviceCMYK <<');
6197                                 $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
6198                                 $this->_out(sprintf('/C1 [%.4F %.4F %.4F %.4F] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
6199                                 $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
6200                                 $this->_out('endobj');
6201                         }
6202                 }
6203
6204                 /**
6205                 * Output object dictionary for images.
6206                 * @access protected
6207                 */
6208                 protected function _putxobjectdict() {
6209                         foreach ($this->imagekeys as $file) {
6210                                 $info = $this->getImageBuffer($file);
6211                                 $this->_out('/I'.$info['i'].' '.$info['n'].' 0 R');
6212                         }
6213                 }
6214
6215                 /**
6216                 * Output Resources Dictionary.
6217                 * @access protected
6218                 */
6219                 protected function _putresourcedict() {
6220                         $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
6221                         $this->_out('/Font <<');
6222                         foreach ($this->fontkeys as $fontkey) {
6223                                 $font = $this->getFontBuffer($fontkey);
6224                                 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
6225                         }
6226                         $this->_out('>>');
6227                         $this->_out('/XObject <<');
6228                         $this->_putxobjectdict();
6229                         $this->_out('>>');
6230                         // visibility
6231                         $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
6232                         // transparency
6233                         $this->_out('/ExtGState <<');
6234                         foreach ($this->extgstates as $k => $extgstate) {
6235                                 $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
6236                         }
6237                         $this->_out('>>');
6238                         // gradients
6239                         if (isset($this->gradients) AND (count($this->gradients) > 0)) {
6240                                 $this->_out('/Shading <<');
6241                                 foreach ($this->gradients as $id => $grad) {
6242                                         $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
6243                                 }
6244                                 $this->_out('>>');
6245                         }
6246                         // spot colors
6247                         if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
6248                                 $this->_out('/ColorSpace <<');
6249                                 foreach ($this->spot_colors as $color) {
6250                                         $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
6251                                 }
6252                                 $this->_out('>>');
6253                         }
6254                 }
6255
6256                 /**
6257                 * Output Resources.
6258                 * @access protected
6259                 */
6260                 protected function _putresources() {
6261                         $this->_putextgstates();
6262                         $this->_putocg();
6263                         $this->_putfonts();
6264                         $this->_putimages();
6265                         $this->_putspotcolors();
6266                         $this->_putshaders();
6267                         //Resource dictionary
6268                         $this->offsets[2] = $this->bufferlen;
6269                         $this->_out('2 0 obj');
6270                         $this->_out('<<');
6271                         $this->_putresourcedict();
6272                         $this->_out('>>');
6273                         $this->_out('endobj');
6274                         $this->_putjavascript();
6275                         $this->_putbookmarks();
6276                         $this->_putEmbeddedFiles();
6277                         // encryption
6278                         if ($this->encrypted) {
6279                                 $this->_newobj();
6280                                 $this->enc_obj_id = $this->n;
6281                                 $this->_out('<<');
6282                                 $this->_putencryption();
6283                                 $this->_out('>>');
6284                                 $this->_out('endobj');
6285                         }
6286                 }
6287
6288                 /**
6289                 * Adds some Metadata information
6290                 * (see Chapter 10.2 of PDF Reference)
6291                 * @access protected
6292                 */
6293                 protected function _putinfo() {
6294                         if (!$this->empty_string($this->title)) {
6295                                 $this->_out('/Title '.$this->_textstring($this->title));
6296                         }
6297                         if (!$this->empty_string($this->author)) {
6298                                 $this->_out('/Author '.$this->_textstring($this->author));
6299                         }
6300                         if (!$this->empty_string($this->subject)) {
6301                                 $this->_out('/Subject '.$this->_textstring($this->subject));
6302                         }
6303                         if (!$this->empty_string($this->keywords)) {
6304                                 $this->_out('/Keywords '.$this->_textstring($this->keywords));
6305                         }
6306                         if (!$this->empty_string($this->creator)) {
6307                                 $this->_out('/Creator '.$this->_textstring($this->creator));
6308                         }
6309                         if (defined('PDF_PRODUCER')) {
6310                                 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
6311                         }
6312                         $this->_out('/CreationDate '.$this->_datastring('D:'.date('YmdHis')));
6313                         $this->_out('/ModDate '.$this->_datastring('D:'.date('YmdHis')));
6314                 }
6315
6316                 /**
6317                 * Output Catalog.
6318                 * @access protected
6319                 */
6320                 protected function _putcatalog() {
6321                         $this->_out('/Type /Catalog');
6322                         $this->_out('/Pages 1 0 R');
6323                         if ($this->ZoomMode == 'fullpage') {
6324                                 $this->_out('/OpenAction [3 0 R /Fit]');
6325                         } elseif ($this->ZoomMode == 'fullwidth') {
6326                                 $this->_out('/OpenAction [3 0 R /FitH null]');
6327                         } elseif ($this->ZoomMode == 'real') {
6328                                 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
6329                         } elseif (!is_string($this->ZoomMode)) {
6330                                 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
6331                         }
6332                         if (isset($this->LayoutMode) AND (!$this->empty_string($this->LayoutMode))) {
6333                                 $this->_out('/PageLayout /'.$this->LayoutMode.'');
6334                         }
6335                         if (isset($this->PageMode) AND (!$this->empty_string($this->PageMode))) {
6336                                 $this->_out('/PageMode /'.$this->PageMode);
6337                         }
6338                         if (isset($this->l['a_meta_language'])) {
6339                                 $this->_out('/Lang /'.$this->l['a_meta_language']);
6340                         }
6341                         $this->_out('/Names <<');
6342                         if (!$this->empty_string($this->javascript)) {
6343                                 $this->_out('/JavaScript '.($this->n_js).' 0 R');
6344                         }
6345                         $this->_out('>>');
6346                         if (count($this->outlines) > 0) {
6347                                 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
6348                                 $this->_out('/PageMode /UseOutlines');
6349                         }
6350                         $this->_putviewerpreferences();
6351                         $p = $this->n_ocg_print.' 0 R';
6352                         $v = $this->n_ocg_view.' 0 R';
6353                         $as = '<</Event /Print /OCGs ['.$p.' '.$v.'] /Category [/Print]>> <</Event /View /OCGs ['.$p.' '.$v.'] /Category [/View]>>';
6354                         $this->_out('/OCProperties <</OCGs ['.$p.' '.$v.'] /D <</ON ['.$p.'] /OFF ['.$v.'] /AS ['.$as.']>>>>');
6355                 }
6356
6357                 /**
6358                 * Output viewer preferences.
6359                 * @author Nicola asuni
6360                 * @since 3.1.000 (2008-06-09)
6361                 * @access protected
6362                 */
6363                 protected function _putviewerpreferences() {
6364                         $this->_out('/ViewerPreferences<<');
6365                         if ($this->rtl) {
6366                                 $this->_out('/Direction /R2L');
6367                         } else {
6368                                 $this->_out('/Direction /L2R');
6369                         }
6370                         if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
6371                                 $this->_out('/HideToolbar true');
6372                         }
6373                         if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
6374                                 $this->_out('/HideMenubar true');
6375                         }
6376                         if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
6377                                 $this->_out('/HideWindowUI true');
6378                         }
6379                         if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
6380                                 $this->_out('/FitWindow true');
6381                         }
6382                         if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
6383                                 $this->_out('/CenterWindow true');
6384                         }
6385                         if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
6386                                 $this->_out('/DisplayDocTitle true');
6387                         }
6388                         if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
6389                                 $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
6390                         }
6391                         if (isset($this->viewer_preferences['ViewArea'])) {
6392                                 $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
6393                         }
6394                         if (isset($this->viewer_preferences['ViewClip'])) {
6395                                 $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
6396                         }
6397                         if (isset($this->viewer_preferences['PrintArea'])) {
6398                                 $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
6399                         }
6400                         if (isset($this->viewer_preferences['PrintClip'])) {
6401                                 $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
6402                         }
6403                         if (isset($this->viewer_preferences['PrintScaling'])) {
6404                                 $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
6405                         }
6406                         if (isset($this->viewer_preferences['Duplex']) AND (!$this->empty_string($this->viewer_preferences['Duplex']))) {
6407                                 $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
6408                         }
6409                         if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
6410                                 if ($this->viewer_preferences['PickTrayByPDFSize']) {
6411                                         $this->_out('/PickTrayByPDFSize true');
6412                                 } else {
6413                                         $this->_out('/PickTrayByPDFSize false');
6414                                 }
6415                         }
6416                         if (isset($this->viewer_preferences['PrintPageRange'])) {
6417                                 $PrintPageRangeNum = '';
6418                                 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
6419                                         $PrintPageRangeNum .= ' '.($v - 1).'';
6420                                 }
6421                                 $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
6422                         }
6423                         if (isset($this->viewer_preferences['NumCopies'])) {
6424                                 $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
6425                         }
6426                         $this->_out('>>');
6427                 }
6428
6429                 /**
6430                 * Output trailer.
6431                 * @access protected
6432                 */
6433                 protected function _puttrailer() {
6434                         $this->_out('/Size '.($this->n + 1));
6435                         $this->_out('/Root '.$this->n.' 0 R');
6436                         $this->_out('/Info '.($this->n - 1).' 0 R');
6437                         if ($this->encrypted) {
6438                                 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
6439                                 $this->_out('/ID [()()]');
6440                         }
6441                 }
6442
6443                 /**
6444                 * Output PDF header.
6445                 * @access protected
6446                 */
6447                 protected function _putheader() {
6448                         $this->_out('%PDF-'.$this->PDFVersion);
6449                 }
6450
6451                 /**
6452                 * Output end of document (EOF).
6453                 * @access protected
6454                 */
6455                 protected function _enddoc() {
6456                         $this->state = 1;
6457                         $this->_putheader();
6458                         $this->_putpages();
6459                         $this->_putresources();
6460                         //Info
6461                         $this->_newobj();
6462                         $this->_out('<<');
6463                         $this->_putinfo();
6464                         $this->_out('>>');
6465                         $this->_out('endobj');
6466                         //Catalog
6467                         $this->_newobj();
6468                         $this->_out('<<');
6469                         $this->_putcatalog();
6470                         $this->_putcertification();
6471                         $this->_putuserrights();
6472                         $this->_out('>>');
6473                         $this->_out('endobj');
6474                         //Cross-ref
6475                         $o = $this->bufferlen;
6476                         $this->_out('xref');
6477                         $this->_out('0 '.($this->n + 1));
6478                         $this->_out('0000000000 65535 f ');
6479                         for ($i=1; $i <= $this->n; ++$i) {
6480                                 $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
6481                         }
6482                         if (isset($this->embeddedfiles) AND count($this->embeddedfiles) > 0) {
6483                                 $this->_out('100000 '.count($this->embeddedfiles));
6484                                 foreach ($this->embeddedfiles as $filename => $filedata) {
6485                                         $this->_out(sprintf('%010d 00000 n ', $this->offsets[$filedata['n']]));
6486                                 }
6487                         }
6488                         //Trailer
6489                         $this->_out('trailer');
6490                         $this->_out('<<');
6491                         $this->_puttrailer();
6492                         $this->_out('>>');
6493                         $this->_out('startxref');
6494                         $this->_out($o);
6495                         $this->_out('%%EOF');
6496                         $this->state = 3; // end-of-doc
6497                         if ($this->diskcache) {
6498                                 // remove temporary files used for images
6499                                 foreach ($this->imagekeys as $key) {
6500                                         // remove temporary files
6501                                         unlink($this->images[$key]);
6502                                 }
6503                                 foreach ($this->fontkeys as $key) {
6504                                         // remove temporary files
6505                                         unlink($this->fonts[$key]);
6506                                 }
6507                         }
6508                 }
6509
6510                 /**
6511                 * Initialize a new page.
6512                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
6513                 * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
6514                 * @access protected
6515                 */
6516                 protected function _beginpage($orientation='', $format='') {
6517                         ++$this->page;
6518                         $this->setPageBuffer($this->page, '');
6519                         // initialize array for graphics tranformation positions inside a page buffer
6520                         $this->transfmrk[$this->page] = array();
6521                         $this->state = 2;
6522                         if ($this->empty_string($orientation)) {
6523                                 if (isset($this->CurOrientation)) {
6524                                         $orientation = $this->CurOrientation;
6525                                 } else {
6526                                         $orientation = 'P';
6527                                 }
6528                         }
6529                         if ($this->empty_string($format)) {
6530                                 $this->setPageOrientation($orientation);
6531                         } else {
6532                                 $this->setPageFormat($format, $orientation);
6533                         }
6534                         if ($this->rtl) {
6535                                 $this->x = $this->w - $this->rMargin;
6536                         } else {
6537                                 $this->x = $this->lMargin;
6538                         }
6539                         $this->y = $this->tMargin;
6540                         if (isset($this->newpagegroup[$this->page])) {
6541                                 // start a new group
6542                                 $n = sizeof($this->pagegroups) + 1;
6543                                 $alias = '{nb'.$n.'}';
6544                                 $this->pagegroups[$alias] = 1;
6545                                 $this->currpagegroup = $alias;
6546                         } elseif ($this->currpagegroup) {
6547                                 ++$this->pagegroups[$this->currpagegroup];
6548                         }
6549                 }
6550
6551                 /**
6552                 * Mark end of page.
6553                 * @access protected
6554                 */
6555                 protected function _endpage() {
6556                         $this->setVisibility('all');
6557                         $this->state = 1;
6558                 }
6559
6560                 /**
6561                 * Begin a new object.
6562                 * @access protected
6563                 */
6564                 protected function _newobj() {
6565                         ++$this->n;
6566                         $this->offsets[$this->n] = $this->bufferlen;
6567                         $this->_out($this->n.' 0 obj');
6568                 }
6569
6570                 /**
6571                 * Underline text.
6572                 * @param int $x X coordinate
6573                 * @param int $y Y coordinate
6574                 * @param string $txt text to underline
6575                 * @access protected
6576                 */
6577                 protected function _dounderline($x, $y, $txt) {
6578                         $up = $this->CurrentFont['up'];
6579                         $ut = $this->CurrentFont['ut'];
6580                         $w = $this->GetStringWidth($txt);
6581                         return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ($this->h - ($y - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
6582                 }
6583
6584                 /**
6585                 * Line through text.
6586                 * @param int $x X coordinate
6587                 * @param int $y Y coordinate
6588                 * @param string $txt text to linethrough
6589                 * @access protected
6590                 */
6591                 protected function _dolinethrough($x, $y, $txt) {
6592                         $up = $this->CurrentFont['up'];
6593                         $ut = $this->CurrentFont['ut'];
6594                         $w = $this->GetStringWidth($txt);
6595                         return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ($this->h - ($y - ($this->FontSize/2) - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
6596                 }
6597
6598                 /**
6599                 * Read a 4-byte integer from file.
6600                 * @param string $f file name.
6601                 * @return 4-byte integer
6602                 * @access protected
6603                 */
6604                 protected function _freadint($f) {
6605                         $a = unpack('Ni', fread($f, 4));
6606                         return $a['i'];
6607                 }
6608
6609                 /**
6610                 * Add "\" before "\", "(" and ")"
6611                 * @param string $s string to escape.
6612                 * @return string escaped string.
6613                 * @access protected
6614                 */
6615                 protected function _escape($s) {
6616                         // the chr(13) substitution fixes the Bugs item #1421290.
6617                         return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
6618                 }
6619
6620                 /**
6621                 * Format a date string for meta information
6622                 * @param string $s date string to escape.
6623                 * @return string escaped string.
6624                 * @access protected
6625                 */
6626                 protected function _datastring($s) {
6627                         if ($this->encrypted) {
6628                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
6629                         }
6630                         return '('. $this->_escape($s).')';
6631                 }
6632
6633                 /**
6634                 * Format a text string for meta information
6635                 * @param string $s string to escape.
6636                 * @return string escaped string.
6637                 * @access protected
6638                 */
6639                 protected function _textstring($s) {
6640                         if ($this->isunicode) {
6641                                 //Convert string to UTF-16BE
6642                                 $s = $this->UTF8ToUTF16BE($s, true);
6643                         }
6644                         return $this->_datastring($s);
6645                 }
6646
6647                 /**
6648                 * Format a text string
6649                 * @param string $s string to escape.
6650                 * @return string escaped string.
6651                 * @access protected
6652                 */
6653                 protected function _escapetext($s) {
6654                         if ($this->isunicode) {
6655                                 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
6656                                         $s = $this->UTF8ToLatin1($s);
6657                                 } else {
6658                                         //Convert string to UTF-16BE and reverse RTL language
6659                                         $s = $this->utf8StrRev($s, false, $this->tmprtl);
6660                                 }
6661                         }
6662                         return $this->_escape($s);
6663                 }
6664
6665                 /**
6666                 * Output a stream.
6667                 * @param string $s string to output.
6668                 * @access protected
6669                 */
6670                 protected function _putstream($s) {
6671                         if ($this->encrypted) {
6672                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
6673                         }
6674                         $this->_out('stream');
6675                         $this->_out($s);
6676                         $this->_out('endstream');
6677                 }
6678
6679                 /**
6680                 * Output a string to the document.
6681                 * @param string $s string to output.
6682                 * @access protected
6683                 */
6684                 protected function _out($s) {
6685                         if ($this->state == 2) {
6686                                 if ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
6687                                         // puts data before page footer
6688                                         $pagebuff = $this->getPageBuffer($this->page);
6689                                         $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
6690                                         $footer = substr($pagebuff, -$this->footerlen[$this->page]);
6691                                         $this->setPageBuffer($this->page, $page.$s."\n".$footer);
6692                                         // update footer position
6693                                         $this->footerpos[$this->page] += strlen($s."\n");
6694                                 } else {
6695                                         $this->setPageBuffer($this->page, $s."\n", true);
6696                                 }
6697                         } else {
6698                                 $this->setBuffer($s."\n");
6699                         }
6700                 }
6701
6702                  /**
6703                  * Converts UTF-8 strings to codepoints array.<br>
6704                  * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
6705                  * Based on: http://www.faqs.org/rfcs/rfc3629.html
6706                  * <pre>
6707                  *        Char. number range  |        UTF-8 octet sequence
6708                  *       (hexadecimal)    |              (binary)
6709                  *    --------------------+-----------------------------------------------
6710                  *    0000 0000-0000 007F | 0xxxxxxx
6711                  *    0000 0080-0000 07FF | 110xxxxx 10xxxxxx
6712                  *    0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
6713                  *    0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
6714                  *    ---------------------------------------------------------------------
6715                  *
6716                  *   ABFN notation:
6717                  *   ---------------------------------------------------------------------
6718                  *   UTF8-octets = *( UTF8-char )
6719                  *   UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
6720                  *   UTF8-1      = %x00-7F
6721                  *   UTF8-2      = %xC2-DF UTF8-tail
6722                  *
6723                  *   UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
6724                  *                 %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
6725                  *   UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
6726                  *                 %xF4 %x80-8F 2( UTF8-tail )
6727                  *   UTF8-tail   = %x80-BF
6728                  *   ---------------------------------------------------------------------
6729                  * </pre>
6730                  * @param string $str string to process.
6731                  * @return array containing codepoints (UTF-8 characters values)
6732                  * @access protected
6733                  * @author Nicola Asuni
6734                  * @since 1.53.0.TC005 (2005-01-05)
6735                  */
6736                 protected function UTF8StringToArray($str) {
6737                         if (isset($this->cache_UTF8StringToArray['_'.$str])) {
6738                                 // return cached value
6739                                 return($this->cache_UTF8StringToArray['_'.$str]);
6740                         }
6741                         // check cache size
6742                         if ($this->cache_size_UTF8StringToArray >= $this->cache_maxsize_UTF8StringToArray) {
6743                                 // remove first element
6744                                 array_shift($this->cache_UTF8StringToArray);
6745                         }
6746                         ++$this->cache_size_UTF8StringToArray;
6747                         if (!$this->isunicode) {
6748                                 // split string into array of equivalent codes
6749                                 $strarr = array();
6750                                 $strlen = strlen($str);
6751                                 for ($i=0; $i < $strlen; ++$i) {
6752                                         $strarr[] = ord($str{$i});
6753                                 }
6754                                 // insert new value on cache
6755                                 $this->cache_UTF8StringToArray['_'.$str] = $strarr;
6756                                 return $strarr;
6757                         }
6758                         $unicode = array(); // array containing unicode values
6759                         $bytes  = array(); // array containing single character byte sequences
6760                         $numbytes  = 1; // number of octetc needed to represent the UTF-8 character
6761                         $str .= ''; // force $str to be a string
6762                         $length = strlen($str);
6763                         for ($i = 0; $i < $length; ++$i) {
6764                                 $char = ord($str{$i}); // get one string character at time
6765                                 if (count($bytes) == 0) { // get starting octect
6766                                         if ($char <= 0x7F) {
6767                                                 $unicode[] = $char; // use the character "as is" because is ASCII
6768                                                 $numbytes = 1;
6769                                         } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
6770                                                 $bytes[] = ($char - 0xC0) << 0x06;
6771                                                 $numbytes = 2;
6772                                         } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
6773                                                 $bytes[] = ($char - 0xE0) << 0x0C;
6774                                                 $numbytes = 3;
6775                                         } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
6776                                                 $bytes[] = ($char - 0xF0) << 0x12;
6777                                                 $numbytes = 4;
6778                                         } else {
6779                                                 // use replacement character for other invalid sequences
6780                                                 $unicode[] = 0xFFFD;
6781                                                 $bytes = array();
6782                                                 $numbytes = 1;
6783                                         }
6784                                 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
6785                                         $bytes[] = $char - 0x80;
6786                                         if (count($bytes) == $numbytes) {
6787                                                 // compose UTF-8 bytes to a single unicode value
6788                                                 $char = $bytes[0];
6789                                                 for ($j = 1; $j < $numbytes; ++$j) {
6790                                                         $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
6791                                                 }
6792                                                 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
6793                                                         /* The definition of UTF-8 prohibits encoding character numbers between
6794                                                         U+D800 and U+DFFF, which are reserved for use with the UTF-16
6795                                                         encoding form (as surrogate pairs) and do not directly represent
6796                                                         characters. */
6797                                                         $unicode[] = 0xFFFD; // use replacement character
6798                                                 } else {
6799                                                         $unicode[] = $char; // add char to array
6800                                                 }
6801                                                 // reset data for next char
6802                                                 $bytes = array();
6803                                                 $numbytes = 1;
6804                                         }
6805                                 } else {
6806                                         // use replacement character for other invalid sequences
6807                                         $unicode[] = 0xFFFD;
6808                                         $bytes = array();
6809                                         $numbytes = 1;
6810                                 }
6811                         }
6812                         // insert new value on cache
6813                         $this->cache_UTF8StringToArray['_'.$str] = $unicode;
6814                         return $unicode;
6815                 }
6816
6817                 /**
6818                  * Converts UTF-8 strings to UTF16-BE.<br>
6819                  * @param string $str string to process.
6820                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
6821                  * @return string
6822                  * @access protected
6823                  * @author Nicola Asuni
6824                  * @since 1.53.0.TC005 (2005-01-05)
6825                  * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
6826                  */
6827                 protected function UTF8ToUTF16BE($str, $setbom=true) {
6828                         if (!$this->isunicode) {
6829                                 return $str; // string is not in unicode
6830                         }
6831                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
6832                         return $this->arrUTF8ToUTF16BE($unicode, $setbom);
6833                 }
6834
6835                 /**
6836                  * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
6837                  * @param string $str string to process.
6838                  * @return string
6839                  * @author Andrew Whitehead, Nicola Asuni
6840                  * @access protected
6841                  * @since 3.2.000 (2008-06-23)
6842                  */
6843                 protected function UTF8ToLatin1($str) {
6844                         global $utf8tolatin;
6845                         if (!$this->isunicode) {
6846                                 return $str; // string is not in unicode
6847                         }
6848                         $outstr = ''; // string to be returned
6849                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
6850                         foreach ($unicode as $char) {
6851                                 if ($char < 256) {
6852                                         $outstr .= chr($char);
6853                                 } elseif (array_key_exists($char, $utf8tolatin)) {
6854                                         // map from UTF-8
6855                                         $outstr .= chr($utf8tolatin[$char]);
6856                                 } elseif ($char == 0xFFFD) {
6857                                         // skip
6858                                 } else {
6859                                         $outstr .= '?';
6860                                 }
6861                         }
6862                         return $outstr;
6863                 }
6864
6865                 /**
6866                  * Converts array of UTF-8 characters to UTF16-BE string.<br>
6867                  * Based on: http://www.faqs.org/rfcs/rfc2781.html
6868                  * <pre>
6869                  *   Encoding UTF-16:
6870                  *
6871                  *   Encoding of a single character from an ISO 10646 character value to
6872                  *    UTF-16 proceeds as follows. Let U be the character number, no greater
6873                  *    than 0x10FFFF.
6874                  *
6875                  *    1) If U < 0x10000, encode U as a 16-bit unsigned integer and
6876                  *       terminate.
6877                  *
6878                  *    2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
6879                  *       U' must be less than or equal to 0xFFFFF. That is, U' can be
6880                  *       represented in 20 bits.
6881                  *
6882                  *    3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
6883                  *       0xDC00, respectively. These integers each have 10 bits free to
6884                  *       encode the character value, for a total of 20 bits.
6885                  *
6886                  *    4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
6887                  *       bits of W1 and the 10 low-order bits of U' to the 10 low-order
6888                  *       bits of W2. Terminate.
6889                  *
6890                  *    Graphically, steps 2 through 4 look like:
6891                  *    U' = yyyyyyyyyyxxxxxxxxxx
6892                  *    W1 = 110110yyyyyyyyyy
6893                  *    W2 = 110111xxxxxxxxxx
6894                  * </pre>
6895                  * @param array $unicode array containing UTF-8 unicode values
6896                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
6897                  * @return string
6898                  * @access protected
6899                  * @author Nicola Asuni
6900                  * @since 2.1.000 (2008-01-08)
6901                  * @see UTF8ToUTF16BE()
6902                  */
6903                 protected function arrUTF8ToUTF16BE($unicode, $setbom=true) {
6904                         $outstr = ''; // string to be returned
6905                         if ($setbom) {
6906                                 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
6907                         }
6908                         foreach ($unicode as $char) {
6909                                 if ($char == 0xFFFD) {
6910                                         $outstr .= "\xFF\xFD"; // replacement character
6911                                 } elseif ($char < 0x10000) {
6912                                         $outstr .= chr($char >> 0x08);
6913                                         $outstr .= chr($char & 0xFF);
6914                                 } else {
6915                                         $char -= 0x10000;
6916                                         $w1 = 0xD800 | ($char >> 0x10);
6917                                         $w2 = 0xDC00 | ($char & 0x3FF);
6918                                         $outstr .= chr($w1 >> 0x08);
6919                                         $outstr .= chr($w1 & 0xFF);
6920                                         $outstr .= chr($w2 >> 0x08);
6921                                         $outstr .= chr($w2 & 0xFF);
6922                                 }
6923                         }
6924                         return $outstr;
6925                 }
6926                 // ====================================================
6927
6928                 /**
6929                  * Set header font.
6930                  * @param array $font font
6931                  * @access public
6932                  * @since 1.1
6933                  */
6934                 public function setHeaderFont($font) {
6935                         $this->header_font = $font;
6936                 }
6937
6938                 /**
6939                  * Get header font.
6940                  * @return array()
6941                  * @access public
6942                  * @since 4.0.012 (2008-07-24)
6943                  */
6944                 public function getHeaderFont() {
6945                         return $this->header_font;
6946                 }
6947
6948                 /**
6949                  * Set footer font.
6950                  * @param array $font font
6951                  * @access public
6952                  * @since 1.1
6953                  */
6954                 public function setFooterFont($font) {
6955                         $this->footer_font = $font;
6956                 }
6957
6958                 /**
6959                  * Get Footer font.
6960                  * @return array()
6961                  * @access public
6962                  * @since 4.0.012 (2008-07-24)
6963                  */
6964                 public function getFooterFont() {
6965                         return $this->footer_font;
6966                 }
6967
6968                 /**
6969                  * Set language array.
6970                  * @param array $language
6971                  * @access public
6972                  * @since 1.1
6973                  */
6974                 public function setLanguageArray($language) {
6975                         $this->l = $language;
6976                         $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
6977                 }
6978
6979                 /**
6980                  * Returns the PDF data.
6981                  * @access public
6982                  */
6983                 public function getPDFData() {
6984                         if ($this->state < 3) {
6985                                 $this->Close();
6986                         }
6987                         return $this->buffer;
6988                 }
6989
6990                 /**
6991                  * Output anchor link.
6992                  * @param string $url link URL or internal link (i.e.: &lt;a href="#23"&gt;link to page 23&lt;/a&gt;)
6993                  * @param string $name link name
6994                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
6995                  * @param boolean $firstline if true prints only the first line and return the remaining string.
6996                  * @param array $color array of RGB text color
6997                  * @param string $style font style (U, D, B, I)
6998                  * @return the number of cells used or the remaining text if $firstline = true;
6999                  * @access public
7000                  */
7001                 public function addHtmlLink($url, $name, $fill=0, $firstline=false, $color='', $style=-1) {
7002                         if (!$this->empty_string($url) AND ($url{0} == '#')) {
7003                                 // convert url to internal link
7004                                 $page = intval(substr($url, 1));
7005                                 $url = $this->AddLink();
7006                                 $this->SetLink($url, 0, $page);
7007                         }
7008                         // store current settings
7009                         $prevcolor = $this->fgcolor;
7010                         $prevstyle = $this->FontStyle;
7011                         if (empty($color)) {
7012                                 $this->SetTextColorArray($this->htmlLinkColorArray);
7013                         } else {
7014                                 $this->SetTextColorArray($color);
7015                         }
7016                         if ($style == -1) {
7017                                 $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
7018                         } else {
7019                                 $this->SetFont('', $this->FontStyle.$style);
7020                         }
7021                         $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
7022                         // restore settings
7023                         $this->SetFont('', $prevstyle);
7024                         $this->SetTextColorArray($prevcolor);
7025                         return $ret;
7026                 }
7027
7028                 /**
7029                  * Returns an associative array (keys: R,G,B) from an html color name or a six-digit or three-digit hexadecimal color representation (i.e. #3FE5AA or #7FF).
7030                  * @param string $color html color
7031                  * @return array RGB color or false in case of error.
7032                  * @access public
7033                  */
7034                 public function convertHTMLColorToDec($color='#FFFFFF') {
7035                         global $webcolor;
7036                         $returncolor = false;
7037                         $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
7038                         $color = strtolower($color);
7039                         if (strlen($color) == 0) {
7040                                 return false;
7041                         }
7042                         if (substr($color, 0, 3) == 'rgb') {
7043                                 $codes = substr($color, 4);
7044                                 $codes = str_replace(')', '', $codes);
7045                                 $returncolor = explode(',', $codes, 3);
7046                                 return $returncolor;
7047                         }
7048                         if (substr($color, 0, 1) != '#') {
7049                                 // decode color name
7050                                 if (isset($webcolor[$color])) {
7051                                         $color_code = $webcolor[$color];
7052                                 } else {
7053                                         return false;
7054                                 }
7055                         } else {
7056                                 $color_code = substr($color, 1);
7057                         }
7058                         switch (strlen($color_code)) {
7059                                 case 3: {
7060                                         // three-digit hexadecimal representation
7061                                         $r = substr($color_code, 0, 1);
7062                                         $g = substr($color_code, 1, 1);
7063                                         $b = substr($color_code, 2, 1);
7064                                         $returncolor['R'] = hexdec($r.$r);
7065                                         $returncolor['G'] = hexdec($g.$g);
7066                                         $returncolor['B'] = hexdec($b.$b);
7067                                         break;
7068                                 }
7069                                 case 6: {
7070                                         // six-digit hexadecimal representation
7071                                         $returncolor['R'] = hexdec(substr($color_code, 0, 2));
7072                                         $returncolor['G'] = hexdec(substr($color_code, 2, 2));
7073                                         $returncolor['B'] = hexdec(substr($color_code, 4, 2));
7074                                         break;
7075                                 }
7076                         }
7077                         return $returncolor;
7078                 }
7079
7080                 /**
7081                  * Converts pixels to User's Units.
7082                  * @param int $px pixels
7083                  * @return float value in user's unit
7084                  * @access public
7085                  * @see setImageScale(), getImageScale()
7086                  */
7087                 public function pixelsToUnits($px) {
7088                         return ($px / ($this->imgscale * $this->k));
7089                 }
7090
7091                 /**
7092                  * Reverse function for htmlentities.
7093                  * Convert entities in UTF-8.
7094                  * @param $text_to_convert Text to convert.
7095                  * @return string converted
7096                  * @access public
7097                 */
7098                 public function unhtmlentities($text_to_convert) {
7099                         return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
7100                 }
7101
7102                 // ENCRYPTION METHODS ----------------------------------
7103                 // SINCE 2.0.000 (2008-01-02)
7104
7105                 /**
7106                 * Compute encryption key depending on object number where the encrypted data is stored
7107                 * @param int $n object number
7108                 * @access protected
7109                 * @since 2.0.000 (2008-01-02)
7110                 */
7111                 protected function _objectkey($n) {
7112                         return substr($this->_md5_16($this->encryption_key.pack('VXxx', $n)), 0, 10);
7113                 }
7114
7115                 /**
7116                  * Put encryption on PDF document.
7117                  * @access protected
7118                  * @since 2.0.000 (2008-01-02)
7119                  */
7120                 protected function _putencryption() {
7121                         $this->_out('/Filter /Standard');
7122                         $this->_out('/V 1');
7123                         $this->_out('/R 2');
7124                         $this->_out('/O ('.$this->_escape($this->Ovalue).')');
7125                         $this->_out('/U ('.$this->_escape($this->Uvalue).')');
7126                         $this->_out('/P '.$this->Pvalue);
7127                 }
7128
7129                 /**
7130                 * Returns the input text exrypted using RC4 algorithm and the specified key.
7131                 * RC4 is the standard encryption algorithm used in PDF format
7132                 * @param string $key encryption key
7133                 * @param String $text input text to be encrypted
7134                 * @return String encrypted text
7135                 * @access protected
7136                 * @since 2.0.000 (2008-01-02)
7137                 * @author Klemen Vodopivec
7138                 */
7139                 protected function _RC4($key, $text) {
7140                         if ($this->last_rc4_key != $key) {
7141                                 $k = str_repeat($key, ((256 / strlen($key)) + 1));
7142                                 $rc4 = range(0, 255);
7143                                 $j = 0;
7144                                 for ($i = 0; $i < 256; ++$i) {
7145                                         $t = $rc4[$i];
7146                                         $j = ($j + $t + ord($k{$i})) % 256;
7147                                         $rc4[$i] = $rc4[$j];
7148                                         $rc4[$j] = $t;
7149                                 }
7150                                 $this->last_rc4_key = $key;
7151                                 $this->last_rc4_key_c = $rc4;
7152                         } else {
7153                                 $rc4 = $this->last_rc4_key_c;
7154                         }
7155                         $len = strlen($text);
7156                         $a = 0;
7157                         $b = 0;
7158                         $out = '';
7159                         for ($i = 0; $i < $len; ++$i) {
7160                                 $a = ($a + 1) % 256;
7161                                 $t = $rc4[$a];
7162                                 $b = ($b + $t) % 256;
7163                                 $rc4[$a] = $rc4[$b];
7164                                 $rc4[$b] = $t;
7165                                 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
7166                                 $out .= chr(ord($text{$i}) ^ $k);
7167                         }
7168                         return $out;
7169                 }
7170
7171                 /**
7172                 * Encrypts a string using MD5 and returns it's value as a binary string.
7173                 * @param string $str input string
7174                 * @return String MD5 encrypted binary string
7175                 * @access protected
7176                 * @since 2.0.000 (2008-01-02)
7177                 * @author Klemen Vodopivec
7178                 */
7179                 protected function _md5_16($str) {
7180                         return pack('H*', md5($str));
7181                 }
7182
7183                 /**
7184                 * Compute O value (used for RC4 encryption)
7185                 * @param String $user_pass user password
7186                 * @param String $owner_pass user password
7187                 * @return String O value
7188                 * @access protected
7189                 * @since 2.0.000 (2008-01-02)
7190                 * @author Klemen Vodopivec
7191                 */
7192                 protected function _Ovalue($user_pass, $owner_pass) {
7193                         $tmp = $this->_md5_16($owner_pass);
7194                         $owner_RC4_key = substr($tmp, 0, 5);
7195                         return $this->_RC4($owner_RC4_key, $user_pass);
7196                 }
7197
7198                 /**
7199                 * Compute U value (used for RC4 encryption)
7200                 * @return String U value
7201                 * @access protected
7202                 * @since 2.0.000 (2008-01-02)
7203                 * @author Klemen Vodopivec
7204                 */
7205                 protected function _Uvalue() {
7206                         return $this->_RC4($this->encryption_key, $this->padding);
7207                 }
7208
7209                 /**
7210                 * Compute encryption key
7211                 * @param String $user_pass user password
7212                 * @param String $owner_pass user password
7213                 * @param String $protection protection type
7214                 * @access protected
7215                 * @since 2.0.000 (2008-01-02)
7216                 * @author Klemen Vodopivec
7217                 */
7218                 protected function _generateencryptionkey($user_pass, $owner_pass, $protection) {
7219                         // Pad passwords
7220                         $user_pass = substr($user_pass.$this->padding, 0, 32);
7221                         $owner_pass = substr($owner_pass.$this->padding, 0, 32);
7222                         // Compute O value
7223                         $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
7224                         // Compute encyption key
7225                         $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
7226                         $this->encryption_key = substr($tmp, 0, 5);
7227                         // Compute U value
7228                         $this->Uvalue = $this->_Uvalue();
7229                         // Compute P value
7230                         $this->Pvalue = -(($protection^255) + 1);
7231                 }
7232
7233                 /**
7234                 * Set document protection
7235                 * The permission array is composed of values taken from the following ones:
7236                 * - copy: copy text and images to the clipboard
7237                 * - print: print the document
7238                 * - modify: modify it (except for annotations and forms)
7239                 * - annot-forms: add annotations and forms
7240                 * Remark: the protection against modification is for people who have the full Acrobat product.
7241                 * If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access.
7242                 * Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts.
7243                 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
7244                 * @param String $user_pass user password. Empty by default.
7245                 * @param String $owner_pass owner password. If not specified, a random value is used.
7246                 * @access public
7247                 * @since 2.0.000 (2008-01-02)
7248                 * @author Klemen Vodopivec
7249                 */
7250                 public function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
7251                         $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
7252                         $protection = 192;
7253                         foreach ($permissions as $permission) {
7254                                 if (!isset($options[$permission])) {
7255                                         $this->Error('Incorrect permission: '.$permission);
7256                                 }
7257                                 $protection += $options[$permission];
7258                         }
7259                         if ($owner_pass === null) {
7260                                 $owner_pass = uniqid(rand());
7261                         }
7262                         $this->encrypted = true;
7263                         $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
7264                 }
7265
7266                 // END OF ENCRYPTION FUNCTIONS -------------------------
7267
7268                 // START TRANSFORMATIONS SECTION -----------------------
7269
7270                 /**
7271                 * Starts a 2D tranformation saving current graphic state.
7272                 * This function must be called before scaling, mirroring, translation, rotation and skewing.
7273                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
7274                 * @access public
7275                 * @since 2.1.000 (2008-01-07)
7276                 * @see StartTransform(), StopTransform()
7277                 */
7278                 public function StartTransform() {
7279                         $this->_out('q');
7280                         $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
7281                 }
7282
7283                 /**
7284                 * Stops a 2D tranformation restoring previous graphic state.
7285                 * This function must be called after scaling, mirroring, translation, rotation and skewing.
7286                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
7287                 * @access public
7288                 * @since 2.1.000 (2008-01-07)
7289                 * @see StartTransform(), StopTransform()
7290                 */
7291                 public function StopTransform() {
7292                         $this->_out('Q');
7293                         if (isset($this->transfmatrix)) {
7294                                 array_pop($this->transfmatrix);
7295                         }
7296                         array_pop($this->transfmrk[$this->page]);
7297                 }
7298                 /**
7299                 * Horizontal Scaling.
7300                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
7301                 * @param int $x abscissa of the scaling center. Default is current x position
7302                 * @param int $y ordinate of the scaling center. Default is current y position
7303                 * @access public
7304                 * @since 2.1.000 (2008-01-07)
7305                 * @see StartTransform(), StopTransform()
7306                 */
7307                 public function ScaleX($s_x, $x='', $y='') {
7308                         $this->Scale($s_x, 100, $x, $y);
7309                 }
7310
7311                 /**
7312                 * Vertical Scaling.
7313                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
7314                 * @param int $x abscissa of the scaling center. Default is current x position
7315                 * @param int $y ordinate of the scaling center. Default is current y position
7316                 * @access public
7317                 * @since 2.1.000 (2008-01-07)
7318                 * @see StartTransform(), StopTransform()
7319                 */
7320                 public function ScaleY($s_y, $x='', $y='') {
7321                         $this->Scale(100, $s_y, $x, $y);
7322                 }
7323
7324                 /**
7325                 * Vertical and horizontal proportional Scaling.
7326                 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
7327                 * @param int $x abscissa of the scaling center. Default is current x position
7328                 * @param int $y ordinate of the scaling center. Default is current y position
7329                 * @access public
7330                 * @since 2.1.000 (2008-01-07)
7331                 * @see StartTransform(), StopTransform()
7332                 */
7333                 public function ScaleXY($s, $x='', $y='') {
7334                         $this->Scale($s, $s, $x, $y);
7335                 }
7336
7337                 /**
7338                 * Vertical and horizontal non-proportional Scaling.
7339                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
7340                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
7341                 * @param int $x abscissa of the scaling center. Default is current x position
7342                 * @param int $y ordinate of the scaling center. Default is current y position
7343                 * @access public
7344                 * @since 2.1.000 (2008-01-07)
7345                 * @see StartTransform(), StopTransform()
7346                 */
7347                 public function Scale($s_x, $s_y, $x='', $y='') {
7348                         if ($x === '') {
7349                                 $x = $this->x;
7350                         }
7351                         if ($y === '') {
7352                                 $y = $this->y;
7353                         }
7354                         if ($this->rtl) {
7355                                 $x = $this->w - $x;
7356                         }
7357                         if (($s_x == 0) OR ($s_y == 0)) {
7358                                 $this->Error('Please do not use values equal to zero for scaling');
7359                         }
7360                         $y = ($this->h - $y) * $this->k;
7361                         $x *= $this->k;
7362                         //calculate elements of transformation matrix
7363                         $s_x /= 100;
7364                         $s_y /= 100;
7365                         $tm[0] = $s_x;
7366                         $tm[1] = 0;
7367                         $tm[2] = 0;
7368                         $tm[3] = $s_y;
7369                         $tm[4] = $x * (1 - $s_x);
7370                         $tm[5] = $y * (1 - $s_y);
7371                         //scale the coordinate system
7372                         $this->Transform($tm);
7373                 }
7374
7375                 /**
7376                 * Horizontal Mirroring.
7377                 * @param int $x abscissa of the point. Default is current x position
7378                 * @access public
7379                 * @since 2.1.000 (2008-01-07)
7380                 * @see StartTransform(), StopTransform()
7381                 */
7382                 public function MirrorH($x='') {
7383                         $this->Scale(-100, 100, $x);
7384                 }
7385
7386                 /**
7387                 * Verical Mirroring.
7388                 * @param int $y ordinate of the point. Default is current y position
7389                 * @access public
7390                 * @since 2.1.000 (2008-01-07)
7391                 * @see StartTransform(), StopTransform()
7392                 */
7393                 public function MirrorV($y='') {
7394                         $this->Scale(100, -100, '', $y);
7395                 }
7396
7397                 /**
7398                 * Point reflection mirroring.
7399                 * @param int $x abscissa of the point. Default is current x position
7400                 * @param int $y ordinate of the point. Default is current y position
7401                 * @access public
7402                 * @since 2.1.000 (2008-01-07)
7403                 * @see StartTransform(), StopTransform()
7404                 */
7405                 public function MirrorP($x='',$y='') {
7406                         $this->Scale(-100, -100, $x, $y);
7407                 }
7408
7409                 /**
7410                 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
7411                 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
7412                 * @param int $x abscissa of the point. Default is current x position
7413                 * @param int $y ordinate of the point. Default is current y position
7414                 * @access public
7415                 * @since 2.1.000 (2008-01-07)
7416                 * @see StartTransform(), StopTransform()
7417                 */
7418                 public function MirrorL($angle=0, $x='',$y='') {
7419                         $this->Scale(-100, 100, $x, $y);
7420                         $this->Rotate(-2*($angle-90), $x, $y);
7421                 }
7422
7423                 /**
7424                 * Translate graphic object horizontally.
7425                 * @param int $t_x movement to the right (or left for RTL)
7426                 * @access public
7427                 * @since 2.1.000 (2008-01-07)
7428                 * @see StartTransform(), StopTransform()
7429                 */
7430                 public function TranslateX($t_x) {
7431                         $this->Translate($t_x, 0);
7432                 }
7433
7434                 /**
7435                 * Translate graphic object vertically.
7436                 * @param int $t_y movement to the bottom
7437                 * @access public
7438                 * @since 2.1.000 (2008-01-07)
7439                 * @see StartTransform(), StopTransform()
7440                 */
7441                 public function TranslateY($t_y) {
7442                         $this->Translate(0, $t_y);
7443                 }
7444
7445                 /**
7446                 * Translate graphic object horizontally and vertically.
7447                 * @param int $t_x movement to the right
7448                 * @param int $t_y movement to the bottom
7449                 * @access public
7450                 * @since 2.1.000 (2008-01-07)
7451                 * @see StartTransform(), StopTransform()
7452                 */
7453                 public function Translate($t_x, $t_y) {
7454                         if ($this->rtl) {
7455                                 $t_x = -$t_x;
7456                         }
7457                         //calculate elements of transformation matrix
7458                         $tm[0] = 1;
7459                         $tm[1] = 0;
7460                         $tm[2] = 0;
7461                         $tm[3] = 1;
7462                         $tm[4] = $t_x * $this->k;
7463                         $tm[5] = -$t_y * $this->k;
7464                         //translate the coordinate system
7465                         $this->Transform($tm);
7466                 }
7467
7468                 /**
7469                 * Rotate object.
7470                 * @param float $angle angle in degrees for counter-clockwise rotation
7471                 * @param int $x abscissa of the rotation center. Default is current x position
7472                 * @param int $y ordinate of the rotation center. Default is current y position
7473                 * @access public
7474                 * @since 2.1.000 (2008-01-07)
7475                 * @see StartTransform(), StopTransform()
7476                 */
7477                 public function Rotate($angle, $x='', $y='') {
7478                         if ($x === '') {
7479                                 $x = $this->x;
7480                         }
7481                         if ($y === '') {
7482                                 $y = $this->y;
7483                         }
7484                         if ($this->rtl) {
7485                                 $x = $this->w - $x;
7486                                 $angle = -$angle;
7487                         }
7488                         $y = ($this->h - $y) * $this->k;
7489                         $x *= $this->k;
7490                         //calculate elements of transformation matrix
7491                         $tm[0] = cos(deg2rad($angle));
7492                         $tm[1] = sin(deg2rad($angle));
7493                         $tm[2] = -$tm[1];
7494                         $tm[3] = $tm[0];
7495                         $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
7496                         $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
7497                         //rotate the coordinate system around ($x,$y)
7498                         $this->Transform($tm);
7499                 }
7500
7501                 /**
7502                 * Skew horizontally.
7503                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
7504                 * @param int $x abscissa of the skewing center. default is current x position
7505                 * @param int $y ordinate of the skewing center. default is current y position
7506                 * @access public
7507                 * @since 2.1.000 (2008-01-07)
7508                 * @see StartTransform(), StopTransform()
7509                 */
7510                 public function SkewX($angle_x, $x='', $y='') {
7511                         $this->Skew($angle_x, 0, $x, $y);
7512                 }
7513
7514                 /**
7515                 * Skew vertically.
7516                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
7517                 * @param int $x abscissa of the skewing center. default is current x position
7518                 * @param int $y ordinate of the skewing center. default is current y position
7519                 * @access public
7520                 * @since 2.1.000 (2008-01-07)
7521                 * @see StartTransform(), StopTransform()
7522                 */
7523                 public function SkewY($angle_y, $x='', $y='') {
7524                         $this->Skew(0, $angle_y, $x, $y);
7525                 }
7526
7527                 /**
7528                 * Skew.
7529                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
7530                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
7531                 * @param int $x abscissa of the skewing center. default is current x position
7532                 * @param int $y ordinate of the skewing center. default is current y position
7533                 * @access public
7534                 * @since 2.1.000 (2008-01-07)
7535                 * @see StartTransform(), StopTransform()
7536                 */
7537                 public function Skew($angle_x, $angle_y, $x='', $y='') {
7538                         if ($x === '') {
7539                                 $x = $this->x;
7540                         }
7541                         if ($y === '') {
7542                                 $y = $this->y;
7543                         }
7544                         if ($this->rtl) {
7545                                 $x = $this->w - $x;
7546                                 $angle_x = -$angle_x;
7547                         }
7548                         if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
7549                                 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
7550                         }
7551                         $x *= $this->k;
7552                         $y = ($this->h - $y) * $this->k;
7553                         //calculate elements of transformation matrix
7554                         $tm[0] = 1;
7555                         $tm[1] = tan(deg2rad($angle_y));
7556                         $tm[2] = tan(deg2rad($angle_x));
7557                         $tm[3] = 1;
7558                         $tm[4] = -$tm[2] * $y;
7559                         $tm[5] = -$tm[1] * $x;
7560                         //skew the coordinate system
7561                         $this->Transform($tm);
7562                 }
7563
7564                 /**
7565                 * Apply graphic transformations.
7566                 * @access protected
7567                 * @since 2.1.000 (2008-01-07)
7568                 * @see StartTransform(), StopTransform()
7569                 */
7570                 protected function Transform($tm) {
7571                         $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
7572                         // store transformation matrix
7573                         $this->transfmatrix[] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
7574                         // update tranformation mark
7575                         if (end($this->transfmrk[$this->page]) !== false) {
7576                                 $key = key($this->transfmrk[$this->page]);
7577                                 $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
7578                         }
7579                 }
7580
7581                 // END TRANSFORMATIONS SECTION -------------------------
7582
7583
7584                 // START GRAPHIC FUNCTIONS SECTION ---------------------
7585                 // The following section is based on the code provided by David Hernandez Sanz
7586
7587                 /**
7588                 * Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page.
7589                 * @param float $width The width.
7590                 * @access public
7591                 * @since 1.0
7592                 * @see Line(), Rect(), Cell(), MultiCell()
7593                 */
7594                 public function SetLineWidth($width) {
7595                         //Set line width
7596                         $this->LineWidth = $width;
7597                         $this->linestyleWidth = sprintf('%.2F w', ($width * $this->k));
7598                         $this->_out($this->linestyleWidth);
7599                 }
7600
7601                 /**
7602                 * Returns the current the line width.
7603                 * @return int Line width
7604                 * @access public
7605                 * @since 2.1.000 (2008-01-07)
7606                 * @see Line(), SetLineWidth()
7607                 */
7608                 public function GetLineWidth() {
7609                         return $this->LineWidth;
7610                 }
7611
7612                 /**
7613                 * Set line style.
7614                 * @param array $style Line style. Array with keys among the following:
7615                 * <ul>
7616                 *        <li>width (float): Width of the line in user units.</li>
7617                 *        <li>cap (string): Type of cap to put on the line. Possible values are:
7618                 * butt, round, square. The difference between "square" and "butt" is that
7619                 * "square" projects a flat end past the end of the line.</li>
7620                 *        <li>join (string): Type of join. Possible values are: miter, round,
7621                 * bevel.</li>
7622                 *        <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
7623                 * series of length values, which are the lengths of the on and off dashes.
7624                 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
7625                 * 1 off, 2 on, 1 off, ...</li>
7626                 *        <li>phase (integer): Modifier on the dash pattern which is used to shift
7627                 * the point at which the pattern starts.</li>
7628                 *        <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
7629                 * </ul>
7630                 * @access public
7631                 * @since 2.1.000 (2008-01-08)
7632                 */
7633                 public function SetLineStyle($style) {
7634                         extract($style);
7635                         if (isset($width)) {
7636                                 $width_prev = $this->LineWidth;
7637                                 $this->SetLineWidth($width);
7638                                 $this->LineWidth = $width_prev;
7639                         }
7640                         if (isset($cap)) {
7641                                 $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
7642                                 if (isset($ca[$cap])) {
7643                                         $this->linestyleCap = $ca[$cap].' J';
7644                                         $this->_out($this->linestyleCap);
7645                                 }
7646                         }
7647                         if (isset($join)) {
7648                                 $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
7649                                 if (isset($ja[$join])) {
7650                                         $this->linestyleJoin = $ja[$join].' j';
7651                                         $this->_out($this->linestyleJoin);
7652                                 }
7653                         }
7654                         if (isset($dash)) {
7655                                 $dash_string = '';
7656                                 if ($dash) {
7657                                         if (preg_match('/^.+,/', $dash)) {
7658                                                 $tab = explode(',', $dash);
7659                                         } else {
7660                                                 $tab = array($dash);
7661                                         }
7662                                         $dash_string = '';
7663                                         foreach ($tab as $i => $v) {
7664                                                 if ($i) {
7665                                                         $dash_string .= ' ';
7666                                                 }
7667                                                 $dash_string .= sprintf("%.2F", $v);
7668                                         }
7669                                 }
7670                                 if (!isset($phase) OR !$dash) {
7671                                         $phase = 0;
7672                                 }
7673                                 $this->linestyleDash = sprintf("[%s] %.2F d", $dash_string, $phase);
7674                                 $this->_out($this->linestyleDash);
7675                         }
7676                         if (isset($color)) {
7677                                 $this->SetDrawColorArray($color);
7678                         }
7679                 }
7680
7681                 /*
7682                 * Set a draw point.
7683                 * @param float $x Abscissa of point.
7684                 * @param float $y Ordinate of point.
7685                 * @access protected
7686                 * @since 2.1.000 (2008-01-08)
7687                 */
7688                 protected function _outPoint($x, $y) {
7689                         if ($this->rtl) {
7690                                 $x = $this->w - $x;
7691                         }
7692                         $this->_out(sprintf("%.2F %.2F m", $x * $this->k, ($this->h - $y) * $this->k));
7693                 }
7694
7695                 /*
7696                 * Draws a line from last draw point.
7697                 * @param float $x Abscissa of end point.
7698                 * @param float $y Ordinate of end point.
7699                 * @access protected
7700                 * @since 2.1.000 (2008-01-08)
7701                 */
7702                 protected function _outLine($x, $y) {
7703                         if ($this->rtl) {
7704                                 $x = $this->w - $x;
7705                         }
7706                         $this->_out(sprintf("%.2F %.2F l", $x * $this->k, ($this->h - $y) * $this->k));
7707                 }
7708
7709                 /**
7710                 * Draws a rectangle.
7711                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
7712                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
7713                 * @param float $w Width.
7714                 * @param float $h Height.
7715                 * @param string $op options
7716                 * @access protected
7717                 * @since 2.1.000 (2008-01-08)
7718                 */
7719                 protected function _outRect($x, $y, $w, $h, $op) {
7720                         if ($this->rtl) {
7721                                 $x = $this->w - $x - $w;
7722                         }
7723                         $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
7724                 }
7725
7726                 /*
7727                 * Draws a Bezier curve from last draw point.
7728                 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
7729                 * @param float $x1 Abscissa of control point 1.
7730                 * @param float $y1 Ordinate of control point 1.
7731                 * @param float $x2 Abscissa of control point 2.
7732                 * @param float $y2 Ordinate of control point 2.
7733                 * @param float $x3 Abscissa of end point.
7734                 * @param float $y3 Ordinate of end point.
7735                 * @access protected
7736                 * @since 2.1.000 (2008-01-08)
7737                 */
7738                 protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
7739                         if ($this->rtl) {
7740                                 $x1 = $this->w - $x1;
7741                                 $x2 = $this->w - $x2;
7742                                 $x3 = $this->w - $x3;
7743                         }
7744                         $this->_out(sprintf("%.2F %.2F %.2F %.2F %.2F %.2F c", $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
7745                 }
7746
7747                 /**
7748                 * Draws a line between two points.
7749                 * @param float $x1 Abscissa of first point.
7750                 * @param float $y1 Ordinate of first point.
7751                 * @param float $x2 Abscissa of second point.
7752                 * @param float $y2 Ordinate of second point.
7753                 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7754                 * @access public
7755                 * @since 1.0
7756                 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
7757                 */
7758                 public function Line($x1, $y1, $x2, $y2, $style=array()) {
7759                         if ($style) {
7760                                 $this->SetLineStyle($style);
7761                         }
7762                         $this->_outPoint($x1, $y1);
7763                         $this->_outLine($x2, $y2);
7764                         $this->_out(' S');
7765                 }
7766
7767                 /**
7768                 * Draws a rectangle.
7769                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
7770                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
7771                 * @param float $w Width.
7772                 * @param float $h Height.
7773                 * @param string $style Style of rendering. Possible values are:
7774                 * <ul>
7775                 *        <li>D or empty string: Draw (default).</li>
7776                 *        <li>F: Fill.</li>
7777                 *        <li>DF or FD: Draw and fill.</li>
7778                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7779                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7780                 * </ul>
7781                 * @param array $border_style Border style of rectangle. Array with keys among the following:
7782                 * <ul>
7783                 *        <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
7784                 *        <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
7785                 * </ul>
7786                 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
7787                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7788                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
7789                 * @access public
7790                 * @since 1.0
7791                 * @see SetLineStyle()
7792                 */
7793                 public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
7794                         if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7795                                 $this->SetFillColorArray($fill_color);
7796                         }
7797                         switch ($style) {
7798                                 case 'F': {
7799                                         $op = 'f';
7800                                         $border_style = array();
7801                                         $this->_outRect($x, $y, $w, $h, $op);
7802                                         break;
7803                                 }
7804                                 case 'DF':
7805                                 case 'FD': {
7806                                         if ((!$border_style) OR (isset($border_style['all']))) {
7807                                                 $op = 'B';
7808                                                 if (isset($border_style['all'])) {
7809                                                         $this->SetLineStyle($border_style['all']);
7810                                                         $border_style = array();
7811                                                 }
7812                                         } else {
7813                                                 $op = 'f';
7814                                         }
7815                                         $this->_outRect($x, $y, $w, $h, $op);
7816                                         break;
7817                                 }
7818                                 case 'CNZ': {
7819                                         $op = 'W n';
7820                                         $this->_outRect($x, $y, $w, $h, $op);
7821                                         break;
7822                                 }
7823                                 case 'CEO': {
7824                                         $op = 'W* n';
7825                                         $this->_outRect($x, $y, $w, $h, $op);
7826                                         break;
7827                                 }
7828                                 default: {
7829                                         $op = 'S';
7830                                         if ((!$border_style) OR (isset($border_style['all']))) {
7831                                                 if (isset($border_style['all']) AND $border_style['all']) {
7832                                                         $this->SetLineStyle($border_style['all']);
7833                                                         $border_style = array();
7834                                                 }
7835                                                 $this->_outRect($x, $y, $w, $h, $op);
7836                                         }
7837                                         break;
7838                                 }
7839                         }
7840                         if ($border_style) {
7841                                 $border_style2 = array();
7842                                 foreach ($border_style as $line => $value) {
7843                                         $lenght = strlen($line);
7844                                         for ($i = 0; $i < $lenght; ++$i) {
7845                                                 $border_style2[$line[$i]] = $value;
7846                                         }
7847                                 }
7848                                 $border_style = $border_style2;
7849                                 if (isset($border_style['L']) AND $border_style['L']) {
7850                                         $this->Line($x, $y, $x, $y + $h, $border_style['L']);
7851                                 }
7852                                 if (isset($border_style['T']) AND $border_style['T']) {
7853                                         $this->Line($x, $y, $x + $w, $y, $border_style['T']);
7854                                 }
7855                                 if (isset($border_style['R']) AND $border_style['R']) {
7856                                         $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
7857                                 }
7858                                 if (isset($border_style['B']) AND $border_style['B']) {
7859                                         $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
7860                                 }
7861                         }
7862                 }
7863
7864
7865                 /**
7866                 * Draws a Bezier curve.
7867                 * The Bezier curve is a tangent to the line between the control points at
7868                 * either end of the curve.
7869                 * @param float $x0 Abscissa of start point.
7870                 * @param float $y0 Ordinate of start point.
7871                 * @param float $x1 Abscissa of control point 1.
7872                 * @param float $y1 Ordinate of control point 1.
7873                 * @param float $x2 Abscissa of control point 2.
7874                 * @param float $y2 Ordinate of control point 2.
7875                 * @param float $x3 Abscissa of end point.
7876                 * @param float $y3 Ordinate of end point.
7877                 * @param string $style Style of rendering. Possible values are:
7878                 * <ul>
7879                 *        <li>D or empty string: Draw (default).</li>
7880                 *        <li>F: Fill.</li>
7881                 *        <li>DF or FD: Draw and fill.</li>
7882                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7883                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7884                 * </ul>
7885                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7886                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
7887                 * @access public
7888                 * @see SetLineStyle()
7889                 * @since 2.1.000 (2008-01-08)
7890                 */
7891                 public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
7892                         if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7893                                 $this->SetFillColorArray($fill_color);
7894                         }
7895                         switch ($style) {
7896                                 case 'F': {
7897                                         $op = 'f';
7898                                         $line_style = array();
7899                                         break;
7900                                 }
7901                                 case 'FD':
7902                                 case 'DF': {
7903                                         $op = 'B';
7904                                         break;
7905                                 }
7906                                 case 'CNZ': {
7907                                         $op = 'W n';
7908                                         break;
7909                                 }
7910                                 case 'CEO': {
7911                                         $op = 'W* n';
7912                                         break;
7913                                 }
7914                                 default: {
7915                                         $op = 'S';
7916                                         break;
7917                                 }
7918                         }
7919                         if ($line_style) {
7920                                 $this->SetLineStyle($line_style);
7921                         }
7922                         $this->_outPoint($x0, $y0);
7923                         $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
7924                         $this->_out($op);
7925                 }
7926
7927                 /**
7928                 * Draws a poly-Bezier curve.
7929                 * Each Bezier curve segment is a tangent to the line between the control points at
7930                 * either end of the curve.
7931                 * @param float $x0 Abscissa of start point.
7932                 * @param float $y0 Ordinate of start point.
7933                 * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
7934                 * @param string $style Style of rendering. Possible values are:
7935                 * <ul>
7936                 *        <li>D or empty string: Draw (default).</li>
7937                 *        <li>F: Fill.</li>
7938                 *        <li>DF or FD: Draw and fill.</li>
7939                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
7940                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
7941                 * </ul>
7942                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
7943                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
7944                 * @access public
7945                 * @see SetLineStyle()
7946                 * @since 3.0008 (2008-05-12)
7947                 */
7948                 public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
7949                         if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
7950                                 $this->SetFillColorArray($fill_color);
7951                         }
7952                         switch ($style) {
7953                                 case 'F': {
7954                                         $op = 'f';
7955                                         $line_style = array();
7956                                         break;
7957                                 }
7958                                 case 'FD':
7959                                 case 'DF': {
7960                                         $op = 'B';
7961                                         break;
7962                                 }
7963                                 case 'CNZ': {
7964                                         $op = 'W n';
7965                                         break;
7966                                 }
7967                                 case 'CEO': {
7968                                         $op = 'W* n';
7969                                         break;
7970                                 }
7971                                 default: {
7972                                         $op = 'S';
7973                                         break;
7974                                 }
7975                         }
7976                         if ($line_style) {
7977                                 $this->SetLineStyle($line_style);
7978                         }
7979                         $this->_outPoint($x0, $y0);
7980                         foreach ($segments as $segment) {
7981                                 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
7982                                 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
7983                         }
7984                         $this->_out($op);
7985                 }
7986
7987                 /**
7988                 * Draws an ellipse.
7989                 * An ellipse is formed from n Bezier curves.
7990                 * @param float $x0 Abscissa of center point.
7991                 * @param float $y0 Ordinate of center point.
7992                 * @param float $rx Horizontal radius.
7993                 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
7994                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
7995                 * @param float $astart: Angle start of draw line. Default value: 0.
7996                 * @param float $afinish: Angle finish of draw line. Default value: 360.
7997                 * @param string $style Style of rendering. Possible values are:
7998                 * <ul>
7999                 *        <li>D or empty string: Draw (default).</li>
8000                 *        <li>F: Fill.</li>
8001                 *        <li>DF or FD: Draw and fill.</li>
8002                 *        <li>C: Draw close.</li>
8003                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8004                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8005                 * </ul>
8006                 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8007                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
8008                 * @param integer $nc Number of curves used in ellipse. Default value: 8.
8009                 * @access public
8010                 * @since 2.1.000 (2008-01-08)
8011                 */
8012                 public function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
8013                         if ($angle) {
8014                                 $this->StartTransform();
8015                                 $this->Rotate($angle, $x0, $y0);
8016                                 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
8017                                 $this->StopTransform();
8018                                 return;
8019                         }
8020                         if ($rx) {
8021                                 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8022                                         $this->SetFillColorArray($fill_color);
8023                                 }
8024                                 switch ($style) {
8025                                         case 'F': {
8026                                                 $op = 'f';
8027                                                 $line_style = array();
8028                                                 break;
8029                                         }
8030                                         case 'FD':
8031                                         case 'DF': {
8032                                                 $op = 'B';
8033                                                 break;
8034                                         }
8035                                         case 'C': {
8036                                                 $op = 's'; // Small 's' signifies closing the path as well
8037                                                 break;
8038                                         }
8039                                         case 'CNZ': {
8040                                                 $op = 'W n';
8041                                                 break;
8042                                         }
8043                                         case 'CEO': {
8044                                                 $op = 'W* n';
8045                                                 break;
8046                                         }
8047                                         default: {
8048                                                 $op = 'S';
8049                                                 break;
8050                                         }
8051                                 }
8052                                 if ($line_style) {
8053                                         $this->SetLineStyle($line_style);
8054                                 }
8055                                 if (!$ry) {
8056                                         $ry = $rx;
8057                                 }
8058                                 $rx *= $this->k;
8059                                 $ry *= $this->k;
8060                                 if ($nc < 2) {
8061                                         $nc = 2;
8062                                 }
8063                                 $astart = deg2rad((float) $astart);
8064                                 $afinish = deg2rad((float) $afinish);
8065                                 $total_angle = $afinish - $astart;
8066                                 $dt = $total_angle / $nc;
8067                                 $dtm = $dt / 3;
8068                                 $x0 *= $this->k;
8069                                 $y0 = ($this->h - $y0) * $this->k;
8070                                 $t1 = $astart;
8071                                 $a0 = $x0 + ($rx * cos($t1));
8072                                 $b0 = $y0 + ($ry * sin($t1));
8073                                 $c0 = -$rx * sin($t1);
8074                                 $d0 = $ry * cos($t1);
8075                                 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
8076                                 for ($i = 1; $i <= $nc; ++$i) {
8077                                         // Draw this bit of the total curve
8078                                         $t1 = ($i * $dt) + $astart;
8079                                         $a1 = $x0 + ($rx * cos($t1));
8080                                         $b1 = $y0 + ($ry * sin($t1));
8081                                         $c1 = -$rx * sin($t1);
8082                                         $d1 = $ry * cos($t1);
8083                                         $this->_outCurve(($a0 + ($c0 * $dtm)) / $this->k, $this->h - (($b0 + ($d0 * $dtm)) / $this->k), ($a1 - ($c1 * $dtm)) / $this->k, $this->h - (($b1 - ($d1 * $dtm)) / $this->k), $a1 / $this->k, $this->h - ($b1 / $this->k));
8084                                         $a0 = $a1;
8085                                         $b0 = $b1;
8086                                         $c0 = $c1;
8087                                         $d0 = $d1;
8088                                 }
8089                                 $this->_out($op);
8090                         }
8091                 }
8092
8093                 /**
8094                 * Draws a circle.
8095                 * A circle is formed from n Bezier curves.
8096                 * @param float $x0 Abscissa of center point.
8097                 * @param float $y0 Ordinate of center point.
8098                 * @param float $r Radius.
8099                 * @param float $astart: Angle start of draw line. Default value: 0.
8100                 * @param float $afinish: Angle finish of draw line. Default value: 360.
8101                 * @param string $style Style of rendering. Possible values are:
8102                 * <ul>
8103                 *        <li>D or empty string: Draw (default).</li>
8104                 *        <li>F: Fill.</li>
8105                 *        <li>DF or FD: Draw and fill.</li>
8106                 *        <li>C: Draw close.</li>
8107                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8108                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8109                 * </ul>
8110                 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8111                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8112                 * @param integer $nc Number of curves used in circle. Default value: 8.
8113                 * @access public
8114                 * @since 2.1.000 (2008-01-08)
8115                 */
8116                 public function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=8) {
8117                         $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
8118                 }
8119
8120                 /**
8121                 * Draws a polygon.
8122                 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
8123                 * @param string $style Style of rendering. Possible values are:
8124                 * <ul>
8125                 *        <li>D or empty string: Draw (default).</li>
8126                 *        <li>F: Fill.</li>
8127                 *        <li>DF or FD: Draw and fill.</li>
8128                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8129                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8130                 * </ul>
8131                 * @param array $line_style Line style of polygon. Array with keys among the following:
8132                 * <ul>
8133                 *        <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
8134                 *        <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
8135                 * </ul>
8136                 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
8137                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
8138                 * @access public
8139                 * @since 2.1.000 (2008-01-08)
8140                 */
8141                 public function Polygon($p, $style='', $line_style=array(), $fill_color=array()) {
8142                         $np = count($p) / 2;
8143                         if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8144                                 $this->SetFillColorArray($fill_color);
8145                         }
8146                         switch ($style) {
8147                                 case 'F': {
8148                                         $line_style = array();
8149                                         $op = 'f';
8150                                         break;
8151                                 }
8152                                 case 'FD':
8153                                 case 'DF': {
8154                                         $op = 'B';
8155                                         break;
8156                                 }
8157                                 case 'CNZ': {
8158                                         $op = 'W n';
8159                                         break;
8160                                 }
8161                                 case 'CEO': {
8162                                         $op = 'W* n';
8163                                         break;
8164                                 }
8165                                 default: {
8166                                         $op = 'S';
8167                                         break;
8168                                 }
8169                         }
8170                         $draw = true;
8171                         if ($line_style) {
8172                                 if (isset($line_style['all'])) {
8173                                         $this->SetLineStyle($line_style['all']);
8174                                 } else { // 0 .. (np - 1), op = {B, S}
8175                                         $draw = false;
8176                                         if ('B' == $op) {
8177                                                 $op = 'f';
8178                                                 $this->_outPoint($p[0], $p[1]);
8179                                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
8180                                                         $this->_outLine($p[$i], $p[$i + 1]);
8181                                                 }
8182                                                 $this->_outLine($p[0], $p[1]);
8183                                                 $this->_out($op);
8184                                         }
8185                                         $p[($np * 2)] = $p[0];
8186                                         $p[(($np * 2) + 1)] = $p[1];
8187                                         for ($i = 0; $i < $np; ++$i) {
8188                                                 if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
8189                                                         $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
8190                                                 }
8191                                         }
8192                                 }
8193                         }
8194                         if ($draw) {
8195                                 $this->_outPoint($p[0], $p[1]);
8196                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
8197                                         $this->_outLine($p[$i], $p[$i + 1]);
8198                                 }
8199                                 $this->_outLine($p[0], $p[1]);
8200                                 $this->_out($op);
8201                         }
8202                 }
8203
8204                 /**
8205                 * Draws a regular polygon.
8206                 * @param float $x0 Abscissa of center point.
8207                 * @param float $y0 Ordinate of center point.
8208                 * @param float $r: Radius of inscribed circle.
8209                 * @param integer $ns Number of sides.
8210                 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
8211                 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
8212                 * @param string $style Style of rendering. Possible values are:
8213                 * <ul>
8214                 *        <li>D or empty string: Draw (default).</li>
8215                 *        <li>F: Fill.</li>
8216                 *        <li>DF or FD: Draw and fill.</li>
8217                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8218                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8219                 * </ul>
8220                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
8221                 * <ul>
8222                 *        <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
8223                 *        <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
8224                 * </ul>
8225                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
8226                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8227                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
8228                 * <ul>
8229                 *        <li>D or empty string: Draw (default).</li>
8230                 *        <li>F: Fill.</li>
8231                 *        <li>DF or FD: Draw and fill.</li>
8232                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8233                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8234                 * </ul>
8235                 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8236                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
8237                 * @access public
8238                 * @since 2.1.000 (2008-01-08)
8239                 */
8240                 public function RegularPolygon($x0, $y0, $r, $ns, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {
8241                         if (3 > $ns) {
8242                                 $ns = 3;
8243                         }
8244                         if ($draw_circle) {
8245                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
8246                         }
8247                         $p = array();
8248                         for ($i = 0; $i < $ns; ++$i) {
8249                                 $a = $angle + ($i * 360 / $ns);
8250                                 $a_rad = deg2rad((float) $a);
8251                                 $p[] = $x0 + ($r * sin($a_rad));
8252                                 $p[] = $y0 + ($r * cos($a_rad));
8253                         }
8254                         $this->Polygon($p, $style, $line_style, $fill_color);
8255                 }
8256
8257                 /**
8258                 * Draws a star polygon
8259                 * @param float $x0 Abscissa of center point.
8260                 * @param float $y0 Ordinate of center point.
8261                 * @param float $r Radius of inscribed circle.
8262                 * @param integer $nv Number of vertices.
8263                 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
8264                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
8265                 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
8266                 * @param string $style Style of rendering. Possible values are:
8267                 * <ul>
8268                 *        <li>D or empty string: Draw (default).</li>
8269                 *        <li>F: Fill.</li>
8270                 *        <li>DF or FD: Draw and fill.</li>
8271                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8272                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8273                 * </ul>
8274                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
8275                 * <ul>
8276                 *        <li>all: Line style of all sides. Array like for
8277                 * {@link SetLineStyle SetLineStyle}.</li>
8278                 *        <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
8279                 * </ul>
8280                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
8281                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
8282                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
8283                 * <ul>
8284                 *        <li>D or empty string: Draw (default).</li>
8285                 *        <li>F: Fill.</li>
8286                 *        <li>DF or FD: Draw and fill.</li>
8287                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8288                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8289                 * </ul>
8290                 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8291                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
8292                 * @access public
8293                 * @since 2.1.000 (2008-01-08)
8294                 */
8295                 public function StarPolygon($x0, $y0, $r, $nv, $ng, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {
8296                         if (2 > $nv) {
8297                                 $nv = 2;
8298                         }
8299                         if ($draw_circle) {
8300                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
8301                         }
8302                         $p2 = array();
8303                         $visited = array();
8304                         for ($i = 0; $i < $nv; ++$i) {
8305                                 $a = $angle + ($i * 360 / $nv);
8306                                 $a_rad = deg2rad((float) $a);
8307                                 $p2[] = $x0 + ($r * sin($a_rad));
8308                                 $p2[] = $y0 + ($r * cos($a_rad));
8309                                 $visited[] = false;
8310                         }
8311                         $p = array();
8312                         $i = 0;
8313                         do {
8314                                 $p[] = $p2[$i * 2];
8315                                 $p[] = $p2[($i * 2) + 1];
8316                                 $visited[$i] = true;
8317                                 $i += $ng;
8318                                 $i %= $nv;
8319                         } while (!$visited[$i]);
8320                         $this->Polygon($p, $style, $line_style, $fill_color);
8321                 }
8322
8323                 /**
8324                 * Draws a rounded rectangle.
8325                 * @param float $x Abscissa of upper-left corner.
8326                 * @param float $y Ordinate of upper-left corner.
8327                 * @param float $w Width.
8328                 * @param float $h Height.
8329                 * @param float $r Radius of the rounded corners.
8330                 * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111").
8331                 * @param string $style Style of rendering. Possible values are:
8332                 * <ul>
8333                 *        <li>D or empty string: Draw (default).</li>
8334                 *        <li>F: Fill.</li>
8335                 *        <li>DF or FD: Draw and fill.</li>
8336                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
8337                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
8338                 * </ul>
8339                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
8340                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
8341                 * @access public
8342                 * @since 2.1.000 (2008-01-08)
8343                 */
8344                 public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
8345                         if ('0000' == $round_corner) { // Not rounded
8346                                 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
8347                         } else { // Rounded
8348                                 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
8349                                         $this->SetFillColorArray($fill_color);
8350                                 }
8351                                 switch ($style) {
8352                                         case 'F': {
8353                                                 $border_style = array();
8354                                                 $op = 'f';
8355                                                 break;
8356                                         }
8357                                         case 'FD':
8358                                         case 'DF': {
8359                                                 $op = 'B';
8360                                                 break;
8361                                         }
8362                                         case 'CNZ': {
8363                                                 $op = 'W n';
8364                                                 break;
8365                                         }
8366                                         case 'CEO': {
8367                                                 $op = 'W* n';
8368                                                 break;
8369                                         }
8370                                         default: {
8371                                                 $op = 'S';
8372                                                 break;
8373                                         }
8374                                 }
8375                                 if ($border_style) {
8376                                         $this->SetLineStyle($border_style);
8377                                 }
8378                                 $MyArc = 4 / 3 * (sqrt(2) - 1);
8379                                 $this->_outPoint($x + $r, $y);
8380                                 $xc = $x + $w - $r;
8381                                 $yc = $y + $r;
8382                                 $this->_outLine($xc, $y);
8383                                 if ($round_corner[0]) {
8384                                         $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
8385                                 } else {
8386                                         $this->_outLine($x + $w, $y);
8387                                 }
8388                                 $xc = $x + $w - $r;
8389                                 $yc = $y + $h - $r;
8390                                 $this->_outLine($x + $w, $yc);
8391                                 if ($round_corner[1]) {
8392                                         $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
8393                                 } else {
8394                                         $this->_outLine($x + $w, $y + $h);
8395                                 }
8396                                 $xc = $x + $r;
8397                                 $yc = $y + $h - $r;
8398                                 $this->_outLine($xc, $y + $h);
8399                                 if ($round_corner[2]) {
8400                                         $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
8401                                 } else {
8402                                         $this->_outLine($x, $y + $h);
8403                                 }
8404                                 $xc = $x + $r;
8405                                 $yc = $y + $r;
8406                                 $this->_outLine($x, $yc);
8407                                 if ($round_corner[3]) {
8408                                         $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
8409                                 } else {
8410                                         $this->_outLine($x, $y);
8411                                         $this->_outLine($x + $r, $y);
8412                                 }
8413                                 $this->_out($op);
8414                         }
8415                 }
8416
8417                 // END GRAPHIC FUNCTIONS SECTION -----------------------
8418
8419                 // BIDIRECTIONAL TEXT SECTION --------------------------
8420                 /**
8421                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
8422                  * @param string $str string to manipulate.
8423                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
8424                  * @return string
8425                  * @access protected
8426                  * @author Nicola Asuni
8427                  * @since 2.1.000 (2008-01-08)
8428                 */
8429                 protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
8430                         return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $str, $forcertl), $setbom);
8431                 }
8432
8433                 /**
8434                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
8435                  * @param array $ta array of characters composing the string.
8436                  * @param string $str string to process
8437                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
8438                  * @return string
8439                  * @author Nicola Asuni
8440                  * @access protected
8441                  * @since 2.4.000 (2008-03-06)
8442                 */
8443                 protected function utf8Bidi($ta, $str='', $forcertl=false) {
8444                         global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
8445                         // paragraph embedding level
8446                         $pel = 0;
8447                         // max level
8448                         $maxlevel = 0;
8449                         if ($this->empty_string($str)) {
8450                                 // create string from array
8451                                 $str = $this->UTF8ArrSubString($ta);
8452                         }
8453                         // check if string contains arabic text
8454                         if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
8455                                 $arabic = true;
8456                         } else {
8457                                 $arabic = false;
8458                         }
8459                         // check if string contains RTL text
8460                         if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
8461                                 return $ta;
8462                         }
8463
8464                         // get number of chars
8465                         $numchars = count($ta);
8466
8467                         if ($forcertl == 'R') {
8468                                         $pel = 1;
8469                         } elseif ($forcertl == 'L') {
8470                                         $pel = 0;
8471                         } else {
8472                                 // P2. In each paragraph, find the first character of type L, AL, or R.
8473                                 // P3. If a character is found in P2 and it is of type AL or R, then set the paragraph embedding level to one; otherwise, set it to zero.
8474                                 for ($i=0; $i < $numchars; ++$i) {
8475                                         $type = $unicode[$ta[$i]];
8476                                         if ($type == 'L') {
8477                                                 $pel = 0;
8478                                                 break;
8479                                         } elseif (($type == 'AL') OR ($type == 'R')) {
8480                                                 $pel = 1;
8481                                                 break;
8482                                         }
8483                                 }
8484                         }
8485
8486                         // Current Embedding Level
8487                         $cel = $pel;
8488                         // directional override status
8489                         $dos = 'N';
8490                         $remember = array();
8491                         // start-of-level-run
8492                         $sor = $pel % 2 ? 'R' : 'L';
8493                         $eor = $sor;
8494
8495                         // Array of characters data
8496                         $chardata = Array();
8497
8498                         // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase.
8499                         //      In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
8500                         for ($i=0; $i < $numchars; ++$i) {
8501                                 if ($ta[$i] == K_RLE) {
8502                                         // X2. With each RLE, compute the least greater odd embedding level.
8503                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
8504                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8505                                         $next_level = $cel + ($cel % 2) + 1;
8506                                         if ($next_level < 62) {
8507                                                 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
8508                                                 $cel = $next_level;
8509                                                 $dos = 'N';
8510                                                 $sor = $eor;
8511                                                 $eor = $cel % 2 ? 'R' : 'L';
8512                                         }
8513                                 } elseif ($ta[$i] == K_LRE) {
8514                                         // X3. With each LRE, compute the least greater even embedding level.
8515                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
8516                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8517                                         $next_level = $cel + 2 - ($cel % 2);
8518                                         if ( $next_level < 62 ) {
8519                                                 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
8520                                                 $cel = $next_level;
8521                                                 $dos = 'N';
8522                                                 $sor = $eor;
8523                                                 $eor = $cel % 2 ? 'R' : 'L';
8524                                         }
8525                                 } elseif ($ta[$i] == K_RLO) {
8526                                         // X4. With each RLO, compute the least greater odd embedding level.
8527                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left.
8528                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8529                                         $next_level = $cel + ($cel % 2) + 1;
8530                                         if ($next_level < 62) {
8531                                                 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
8532                                                 $cel = $next_level;
8533                                                 $dos = 'R';
8534                                                 $sor = $eor;
8535                                                 $eor = $cel % 2 ? 'R' : 'L';
8536                                         }
8537                                 } elseif ($ta[$i] == K_LRO) {
8538                                         // X5. With each LRO, compute the least greater even embedding level.
8539                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right.
8540                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
8541                                         $next_level = $cel + 2 - ($cel % 2);
8542                                         if ( $next_level < 62 ) {
8543                                                 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
8544                                                 $cel = $next_level;
8545                                                 $dos = 'L';
8546                                                 $sor = $eor;
8547                                                 $eor = $cel % 2 ? 'R' : 'L';
8548                                         }
8549                                 } elseif ($ta[$i] == K_PDF) {
8550                                         // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override.
8551                                         if (count($remember)) {
8552                                                 $last = count($remember ) - 1;
8553                                                 if (($remember[$last]['num'] == K_RLE) OR
8554                                                           ($remember[$last]['num'] == K_LRE) OR
8555                                                           ($remember[$last]['num'] == K_RLO) OR
8556                                                           ($remember[$last]['num'] == K_LRO)) {
8557                                                         $match = array_pop($remember);
8558                                                         $cel = $match['cel'];
8559                                                         $dos = $match['dos'];
8560                                                         $sor = $eor;
8561                                                         $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
8562                                                 }
8563                                         }
8564                                 } elseif (($ta[$i] != K_RLE) AND
8565                                                                  ($ta[$i] != K_LRE) AND
8566                                                                  ($ta[$i] != K_RLO) AND
8567                                                                  ($ta[$i] != K_LRO) AND
8568                                                                  ($ta[$i] != K_PDF)) {
8569                                         // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
8570                                         //      a. Set the level of the current character to the current embedding level.
8571                                         //      b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
8572                                         if ($dos != 'N') {
8573                                                 $chardir = $dos;
8574                                         } else {
8575                                                 $chardir = $unicode[$ta[$i]];
8576                                         }
8577                                         // stores string characters and other information
8578                                         $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
8579                                 }
8580                         } // end for each char
8581
8582                         // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
8583                         // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
8584                         // X10. The remaining rules are applied to each run of characters at the same level. For each run, determine the start-of-level-run (sor) and end-of-level-run (eor) type, either L or R. This depends on the higher of the two levels on either side of the boundary (at the start or end of the paragraph, the level of the 'other' run is the base embedding level). If the higher level is odd, the type is R; otherwise, it is L.
8585
8586                         // 3.3.3 Resolving Weak Types
8587                         // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used.
8588                         // Nonspacing marks are now resolved based on the previous characters.
8589                         $numchars = count($chardata);
8590
8591                         // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor.
8592                         $prevlevel = -1; // track level changes
8593                         $levcount = 0; // counts consecutive chars at the same level
8594                         for ($i=0; $i < $numchars; ++$i) {
8595                                 if ($chardata[$i]['type'] == 'NSM') {
8596                                         if ($levcount) {
8597                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
8598                                         } elseif ($i > 0) {
8599                                                 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
8600                                         }
8601                                 }
8602                                 if ($chardata[$i]['level'] != $prevlevel) {
8603                                         $levcount = 0;
8604                                 } else {
8605                                         ++$levcount;
8606                                 }
8607                                 $prevlevel = $chardata[$i]['level'];
8608                         }
8609
8610                         // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number.
8611                         $prevlevel = -1;
8612                         $levcount = 0;
8613                         for ($i=0; $i < $numchars; ++$i) {
8614                                 if ($chardata[$i]['char'] == 'EN') {
8615                                         for ($j=$levcount; $j >= 0; $j--) {
8616                                                 if ($chardata[$j]['type'] == 'AL') {
8617                                                         $chardata[$i]['type'] = 'AN';
8618                                                 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
8619                                                         break;
8620                                                 }
8621                                         }
8622                                 }
8623                                 if ($chardata[$i]['level'] != $prevlevel) {
8624                                         $levcount = 0;
8625                                 } else {
8626                                         ++$levcount;
8627                                 }
8628                                 $prevlevel = $chardata[$i]['level'];
8629                         }
8630
8631                         // W3. Change all ALs to R.
8632                         for ($i=0; $i < $numchars; ++$i) {
8633                                 if ($chardata[$i]['type'] == 'AL') {
8634                                         $chardata[$i]['type'] = 'R';
8635                                 }
8636                         }
8637
8638                         // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type.
8639                         $prevlevel = -1;
8640                         $levcount = 0;
8641                         for ($i=0; $i < $numchars; ++$i) {
8642                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8643                                         if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
8644                                                 $chardata[$i]['type'] = 'EN';
8645                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
8646                                                 $chardata[$i]['type'] = 'EN';
8647                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
8648                                                 $chardata[$i]['type'] = 'AN';
8649                                         }
8650                                 }
8651                                 if ($chardata[$i]['level'] != $prevlevel) {
8652                                         $levcount = 0;
8653                                 } else {
8654                                         ++$levcount;
8655                                 }
8656                                 $prevlevel = $chardata[$i]['level'];
8657                         }
8658
8659                         // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
8660                         $prevlevel = -1;
8661                         $levcount = 0;
8662                         for ($i=0; $i < $numchars; ++$i) {
8663                                 if ($chardata[$i]['type'] == 'ET') {
8664                                         if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
8665                                                 $chardata[$i]['type'] = 'EN';
8666                                         } else {
8667                                                 $j = $i+1;
8668                                                 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
8669                                                         if ($chardata[$j]['type'] == 'EN') {
8670                                                                 $chardata[$i]['type'] = 'EN';
8671                                                                 break;
8672                                                         } elseif ($chardata[$j]['type'] != 'ET') {
8673                                                                 break;
8674                                                         }
8675                                                         ++$j;
8676                                                 }
8677                                         }
8678                                 }
8679                                 if ($chardata[$i]['level'] != $prevlevel) {
8680                                         $levcount = 0;
8681                                 } else {
8682                                         ++$levcount;
8683                                 }
8684                                 $prevlevel = $chardata[$i]['level'];
8685                         }
8686
8687                         // W6. Otherwise, separators and terminators change to Other Neutral.
8688                         $prevlevel = -1;
8689                         $levcount = 0;
8690                         for ($i=0; $i < $numchars; ++$i) {
8691                                 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
8692                                         $chardata[$i]['type'] = 'ON';
8693                                 }
8694                                 if ($chardata[$i]['level'] != $prevlevel) {
8695                                         $levcount = 0;
8696                                 } else {
8697                                         ++$levcount;
8698                                 }
8699                                 $prevlevel = $chardata[$i]['level'];
8700                         }
8701
8702                         //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L.
8703                         $prevlevel = -1;
8704                         $levcount = 0;
8705                         for ($i=0; $i < $numchars; ++$i) {
8706                                 if ($chardata[$i]['char'] == 'EN') {
8707                                         for ($j=$levcount; $j >= 0; $j--) {
8708                                                 if ($chardata[$j]['type'] == 'L') {
8709                                                         $chardata[$i]['type'] = 'L';
8710                                                 } elseif ($chardata[$j]['type'] == 'R') {
8711                                                         break;
8712                                                 }
8713                                         }
8714                                 }
8715                                 if ($chardata[$i]['level'] != $prevlevel) {
8716                                         $levcount = 0;
8717                                 } else {
8718                                         ++$levcount;
8719                                 }
8720                                 $prevlevel = $chardata[$i]['level'];
8721                         }
8722
8723                         // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries.
8724                         $prevlevel = -1;
8725                         $levcount = 0;
8726                         for ($i=0; $i < $numchars; ++$i) {
8727                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8728                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
8729                                                 $chardata[$i]['type'] = 'L';
8730                                         } elseif (($chardata[$i]['type'] == 'N') AND
8731                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
8732                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
8733                                                 $chardata[$i]['type'] = 'R';
8734                                         } elseif ($chardata[$i]['type'] == 'N') {
8735                                                 // N2. Any remaining neutrals take the embedding direction
8736                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
8737                                         }
8738                                 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
8739                                         // first char
8740                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
8741                                                 $chardata[$i]['type'] = 'L';
8742                                         } elseif (($chardata[$i]['type'] == 'N') AND
8743                                          (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
8744                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
8745                                                 $chardata[$i]['type'] = 'R';
8746                                         } elseif ($chardata[$i]['type'] == 'N') {
8747                                                 // N2. Any remaining neutrals take the embedding direction
8748                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
8749                                         }
8750                                 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
8751                                         //last char
8752                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
8753                                                 $chardata[$i]['type'] = 'L';
8754                                         } elseif (($chardata[$i]['type'] == 'N') AND
8755                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
8756                                          (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
8757                                                 $chardata[$i]['type'] = 'R';
8758                                         } elseif ($chardata[$i]['type'] == 'N') {
8759                                                 // N2. Any remaining neutrals take the embedding direction
8760                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
8761                                         }
8762                                 } elseif ($chardata[$i]['type'] == 'N') {
8763                                         // N2. Any remaining neutrals take the embedding direction
8764                                         $chardata[$i]['type'] = $chardata[$i]['sor'];
8765                                 }
8766                                 if ($chardata[$i]['level'] != $prevlevel) {
8767                                         $levcount = 0;
8768                                 } else {
8769                                         ++$levcount;
8770                                 }
8771                                 $prevlevel = $chardata[$i]['level'];
8772                         }
8773
8774                         // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels.
8775                         // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
8776                         for ($i=0; $i < $numchars; ++$i) {
8777                                 $odd = $chardata[$i]['level'] % 2;
8778                                 if ($odd) {
8779                                         if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
8780                                                 $chardata[$i]['level'] += 1;
8781                                         }
8782                                 } else {
8783                                         if ($chardata[$i]['type'] == 'R') {
8784                                                 $chardata[$i]['level'] += 1;
8785                                         } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
8786                                                 $chardata[$i]['level'] += 2;
8787                                         }
8788                                 }
8789                                 $maxlevel = max($chardata[$i]['level'],$maxlevel);
8790                         }
8791
8792                         // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
8793                         //      1. Segment separators,
8794                         //      2. Paragraph separators,
8795                         //      3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
8796                         //      4. Any sequence of white space characters at the end of the line.
8797                         for ($i=0; $i < $numchars; ++$i) {
8798                                 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
8799                                         $chardata[$i]['level'] = $pel;
8800                                 } elseif ($chardata[$i]['type'] == 'WS') {
8801                                         $j = $i+1;
8802                                         while ($j < $numchars) {
8803                                                 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
8804                                                         (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
8805                                                         $chardata[$i]['level'] = $pel;
8806                                                         break;
8807                                                 } elseif ($chardata[$j]['type'] != 'WS') {
8808                                                         break;
8809                                                 }
8810                                                 ++$j;
8811                                         }
8812                                 }
8813                         }
8814
8815                         // Arabic Shaping
8816                         // Cursively connected scripts, such as Arabic or Syriac, require the selection of positional character shapes that depend on adjacent characters. Shaping is logically applied after the Bidirectional Algorithm is used and is limited to characters within the same directional run.
8817                         if ($arabic) {
8818                                 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
8819                                 $alfletter = array(1570,1571,1573,1575);
8820                                 $chardata2 = $chardata;
8821                                 $laaletter = false;
8822                                 $charAL = array();
8823                                 $x = 0;
8824                                 for ($i=0; $i < $numchars; ++$i) {
8825                                         if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
8826                                                 $charAL[$x] = $chardata[$i];
8827                                                 $charAL[$x]['i'] = $i;
8828                                                 $chardata[$i]['x'] = $x;
8829                                                 ++$x;
8830                                         }
8831                                 }
8832                                 $numAL = $x;
8833                                 for ($i=0; $i < $numchars; ++$i) {
8834                                         $thischar = $chardata[$i];
8835                                         if ($i > 0) {
8836                                                 $prevchar = $chardata[($i-1)];
8837                                         } else {
8838                                                 $prevchar = false;
8839                                         }
8840                                         if (($i+1) < $numchars) {
8841                                                 $nextchar = $chardata[($i+1)];
8842                                         } else {
8843                                                 $nextchar = false;
8844                                         }
8845                                         if ($unicode[$thischar['char']] == 'AL') {
8846                                                 $x = $thischar['x'];
8847                                                 if ($x > 0) {
8848                                                         $prevchar = $charAL[($x-1)];
8849                                                 } else {
8850                                                         $prevchar = false;
8851                                                 }
8852                                                 if (($x+1) < $numAL) {
8853                                                         $nextchar = $charAL[($x+1)];
8854                                                 } else {
8855                                                         $nextchar = false;
8856                                                 }
8857                                                 // if laa letter
8858                                                 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
8859                                                         $arabicarr = $laa_array;
8860                                                         $laaletter = true;
8861                                                         if ($x > 1) {
8862                                                                 $prevchar = $charAL[($x-2)];
8863                                                         } else {
8864                                                                 $prevchar = false;
8865                                                         }
8866                                                 } else {
8867                                                         $arabicarr = $unicode_arlet;
8868                                                         $laaletter = false;
8869                                                 }
8870                                                 if (($prevchar !== false) AND ($nextchar !== false) AND
8871                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
8872                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
8873                                                         ($prevchar['type'] == $thischar['type']) AND
8874                                                         ($nextchar['type'] == $thischar['type']) AND
8875                                                         ($nextchar['char'] != 1567)) {
8876                                                         if (in_array($prevchar['char'], $endedletter)) {
8877                                                                 if (isset($arabicarr[$thischar['char']][2])) {
8878                                                                         // initial
8879                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
8880                                                                 }
8881                                                         } else {
8882                                                                 if (isset($arabicarr[$thischar['char']][3])) {
8883                                                                         // medial
8884                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
8885                                                                 }
8886                                                         }
8887                                                 } elseif (($nextchar !== false) AND
8888                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
8889                                                         ($nextchar['type'] == $thischar['type']) AND
8890                                                         ($nextchar['char'] != 1567)) {
8891                                                         if (isset($arabicarr[$chardata[$i]['char']][2])) {
8892                                                                 // initial
8893                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
8894                                                         }
8895                                                 } elseif ((($prevchar !== false) AND
8896                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
8897                                                         ($prevchar['type'] == $thischar['type'])) OR
8898                                                         (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
8899                                                         // final
8900                                                         if (($i > 1) AND ($thischar['char'] == 1607) AND
8901                                                                 ($chardata[$i-1]['char'] == 1604) AND
8902                                                                 ($chardata[$i-2]['char'] == 1604)) {
8903                                                                 //Allah Word
8904                                                                 // mark characters to delete with false
8905                                                                 $chardata2[$i-2]['char'] = false;
8906                                                                 $chardata2[$i-1]['char'] = false;
8907                                                                 $chardata2[$i]['char'] = 65010;
8908                                                         } else {
8909                                                                 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
8910                                                                         if (isset($arabicarr[$thischar['char']][0])) {
8911                                                                                 // isolated
8912                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
8913                                                                         }
8914                                                                 } else {
8915                                                                         if (isset($arabicarr[$thischar['char']][1])) {
8916                                                                                 // final
8917                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
8918                                                                         }
8919                                                                 }
8920                                                         }
8921                                                 } elseif (isset($arabicarr[$thischar['char']][0])) {
8922                                                         // isolated
8923                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
8924                                                 }
8925                                                 // if laa letter
8926                                                 if ($laaletter) {
8927                                                         // mark characters to delete with false
8928                                                         $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
8929                                                 }
8930                                         } // end if AL (Arabic Letter)
8931                                 } // end for each char
8932                                 /*
8933                                  * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
8934                                  * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
8935                                  */
8936                                 $cw = &$this->CurrentFont['cw'];
8937                                 for ($i = 0; $i < ($numchars-1); ++$i) {
8938                                         if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
8939                                                 // check if the subtitution font is defined on current font
8940                                                 if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
8941                                                         $chardata2[$i]['char'] = false;
8942                                                         $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
8943                                                 }
8944                                         }
8945                                 }
8946                                 // remove marked characters
8947                                 foreach ($chardata2 as $key => $value) {
8948                                         if ($value['char'] === false) {
8949                                                 unset($chardata2[$key]);
8950                                         }
8951                                 }
8952                                 $chardata = array_values($chardata2);
8953                                 $numchars = count($chardata);
8954                                 unset($chardata2);
8955                                 unset($arabicarr);
8956                                 unset($laaletter);
8957                                 unset($charAL);
8958                         }
8959
8960                         // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher.
8961                         for ($j=$maxlevel; $j > 0; $j--) {
8962                                 $ordarray = Array();
8963                                 $revarr = Array();
8964                                 $onlevel = false;
8965                                 for ($i=0; $i < $numchars; ++$i) {
8966                                         if ($chardata[$i]['level'] >= $j) {
8967                                                 $onlevel = true;
8968                                                 if (isset($unicode_mirror[$chardata[$i]['char']])) {
8969                                                         // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true.
8970                                                         $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
8971                                                 }
8972                                                 $revarr[] = $chardata[$i];
8973                                         } else {
8974                                                 if ($onlevel) {
8975                                                         $revarr = array_reverse($revarr);
8976                                                         $ordarray = array_merge($ordarray, $revarr);
8977                                                         $revarr = Array();
8978                                                         $onlevel = false;
8979                                                 }
8980                                                 $ordarray[] = $chardata[$i];
8981                                         }
8982                                 }
8983                                 if ($onlevel) {
8984                                         $revarr = array_reverse($revarr);
8985                                         $ordarray = array_merge($ordarray, $revarr);
8986                                 }
8987                                 $chardata = $ordarray;
8988                         }
8989
8990                         $ordarray = array();
8991                         for ($i=0; $i < $numchars; ++$i) {
8992                                 $ordarray[] = $chardata[$i]['char'];
8993                         }
8994
8995                         return $ordarray;
8996                 }
8997
8998                 // END OF BIDIRECTIONAL TEXT SECTION -------------------
8999
9000                 /*
9001                 * Adds a bookmark.
9002                 * @param string $txt bookmark description.
9003                 * @param int $level bookmark level (minimum value is 0).
9004                 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
9005                 * @param int $page target page number (leave empty for current page).
9006                 * @access public
9007                 * @author Olivier Plathey, Nicola Asuni
9008                 * @since 2.1.002 (2008-02-12)
9009                 */
9010                 public function Bookmark($txt, $level=0, $y=-1, $page='') {
9011                         if ($level < 0) {
9012                                 $level = 0;
9013                         }
9014                         if (isset($this->outlines[0])) {
9015                                 $lastoutline = end($this->outlines);
9016                                 $maxlevel = $lastoutline['l'] + 1;
9017                         } else {
9018                                 $maxlevel = 0;
9019                         }
9020                         if ($level > $maxlevel) {
9021                                 $level = $maxlevel;
9022                         }
9023                         if ($y == -1) {
9024                                 $y = $this->GetY();
9025                         }
9026                         if (empty($page)) {
9027                                 $page = $this->PageNo();
9028                         }
9029                         $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $page);
9030                 }
9031
9032                 /*
9033                 * Create a bookmark PDF string.
9034                 * @access protected
9035                 * @author Olivier Plathey, Nicola Asuni
9036                 * @since 2.1.002 (2008-02-12)
9037                 */
9038                 protected function _putbookmarks() {
9039                         $nb = count($this->outlines);
9040                         if ($nb == 0) {
9041                                 return;
9042                         }
9043                         $lru = array();
9044                         $level = 0;
9045                         foreach ($this->outlines as $i => $o) {
9046                                 if ($o['l'] > 0) {
9047                                         $parent = $lru[($o['l'] - 1)];
9048                                         //Set parent and last pointers
9049                                         $this->outlines[$i]['parent'] = $parent;
9050                                         $this->outlines[$parent]['last'] = $i;
9051                                         if ($o['l'] > $level) {
9052                                                 //Level increasing: set first pointer
9053                                                 $this->outlines[$parent]['first'] = $i;
9054                                         }
9055                                 } else {
9056                                         $this->outlines[$i]['parent'] = $nb;
9057                                 }
9058                                 if (($o['l'] <= $level) AND ($i > 0)) {
9059                                         //Set prev and next pointers
9060                                         $prev = $lru[$o['l']];
9061                                         $this->outlines[$prev]['next'] = $i;
9062                                         $this->outlines[$i]['prev'] = $prev;
9063                                 }
9064                                 $lru[$o['l']] = $i;
9065                                 $level = $o['l'];
9066                         }
9067                         //Outline items
9068                         $n = $this->n + 1;
9069                         foreach ($this->outlines as $i => $o) {
9070                                 $this->_newobj();
9071                                 $this->_out('<</Title '.$this->_textstring($o['t']));
9072                                 $this->_out('/Parent '.($n + $o['parent']).' 0 R');
9073                                 if (isset($o['prev']))
9074                                 $this->_out('/Prev '.($n + $o['prev']).' 0 R');
9075                                 if (isset($o['next']))
9076                                 $this->_out('/Next '.($n + $o['next']).' 0 R');
9077                                 if (isset($o['first']))
9078                                 $this->_out('/First '.($n + $o['first']).' 0 R');
9079                                 if (isset($o['last']))
9080                                 $this->_out('/Last '.($n + $o['last']).' 0 R');
9081                                 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2F null]', (1 + (2 * $o['p'])), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k))));
9082                                 $this->_out('/Count 0>>');
9083                                 $this->_out('endobj');
9084                         }
9085                         //Outline root
9086                         $this->_newobj();
9087                         $this->OutlineRoot = $this->n;
9088                         $this->_out('<</Type /Outlines /First '.$n.' 0 R');
9089                         $this->_out('/Last '.($n + $lru[0]).' 0 R>>');
9090                         $this->_out('endobj');
9091                 }
9092
9093
9094                 // --- JAVASCRIPT - FORMS ------------------------------
9095
9096                 /*
9097                 * Adds a javascript
9098                 * @access public
9099                 * @author Johannes G�ntert, Nicola Asuni
9100                 * @since 2.1.002 (2008-02-12)
9101                 */
9102                 public function IncludeJS($script) {
9103                         $this->javascript .= $script;
9104                 }
9105
9106                 /*
9107                 * Create a javascript PDF string.
9108                 * @access protected
9109                 * @author Johannes G�ntert, Nicola Asuni
9110                 * @since 2.1.002 (2008-02-12)
9111                 */
9112                 protected function _putjavascript() {
9113                         if (empty($this->javascript)) {
9114                                 return;
9115                         }
9116                         // the following two lines are uded to avoid form fields duplication after saving
9117                         $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
9118                         $js2 = "getField('tcpdfdocsaved').value = 'saved';";
9119                         $this->_newobj();
9120                         $this->n_js = $this->n;
9121                         $this->_out('<<');
9122                         $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
9123                         $this->_out('>>');
9124                         $this->_out('endobj');
9125                         $this->_newobj();
9126                         $this->_out('<<');
9127                         $this->_out('/S /JavaScript');
9128                         $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
9129                         $this->_out('>>');
9130                         $this->_out('endobj');
9131                 }
9132
9133                 /*
9134                 * Convert color to javascript color.
9135                 * @param string $color color name or #RRGGBB
9136                 * @access protected
9137                 * @author Denis Van Nuffelen, Nicola Asuni
9138                 * @since 2.1.002 (2008-02-12)
9139                 */
9140                 protected function _JScolor($color) {
9141                         static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
9142                         if (substr($color,0,1) == '#') {
9143                                 return sprintf("['RGB',%.3F,%.3F,%.3F]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
9144                         }
9145                         if (!in_array($color,$aColors)) {
9146                                 $this->Error('Invalid color: '.$color);
9147                         }
9148                         return 'color.'.$color;
9149                 }
9150
9151                 /*
9152                 * Adds a javascript form field.
9153                 * @param string $type field type
9154                 * @param string $name field name
9155                 * @param int $x horizontal position
9156                 * @param int $y vertical position
9157                 * @param int $w width
9158                 * @param int $h height
9159                 * @param array $prop array of properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9160                 * @access protected
9161                 * @author Denis Van Nuffelen, Nicola Asuni
9162                 * @since 2.1.002 (2008-02-12)
9163                 */
9164                 protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
9165                         if ($this->rtl) {
9166                                 $x = $x - $w;
9167                         }
9168                         // the followind avoid fields duplication after saving the document
9169                         $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
9170                         $k = $this->k;
9171                         $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
9172                         $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
9173                         while (list($key, $val) = each($prop)) {
9174                                 if (strcmp(substr($key, -5), 'Color') == 0) {
9175                                         $val = $this->_JScolor($val);
9176                                 } else {
9177                                         $val = "'".$val."'";
9178                                 }
9179                                 $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
9180                         }
9181                         if ($this->rtl) {
9182                                 $this->x -= $w;
9183                         } else {
9184                                 $this->x += $w;
9185                         }
9186                         $this->javascript .= '}';
9187                 }
9188
9189                 /*
9190                 * Creates a text field
9191                 * @param string $name field name
9192                 * @param int $w width
9193                 * @param int $h height
9194                 * @param string $prop properties. The value property allows to set the initial value. The multiline property allows to define the field as multiline. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9195                 * @access public
9196                 * @author Denis Van Nuffelen, Nicola Asuni
9197                 * @since 2.1.002 (2008-02-12)
9198                 */
9199                 public function TextField($name, $w, $h, $prop=array()) {
9200                         $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
9201                 }
9202
9203                 /*
9204                 * Creates a RadioButton field
9205                 * @param string $name field name
9206                 * @param int $w width
9207                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9208                 * @access public
9209                 * @author Nicola Asuni
9210                 * @since 2.2.003 (2008-03-03)
9211                 */
9212                 public function RadioButton($name, $w, $prop=array()) {
9213                         if (!isset($prop['strokeColor'])) {
9214                                 $prop['strokeColor']='black';
9215                         }
9216                         $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
9217                 }
9218
9219                 /*
9220                 * Creates a List-box field
9221                 * @param string $name field name
9222                 * @param int $w width
9223                 * @param int $h height
9224                 * @param array $values array containing the list of values.
9225                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9226                 * @access public
9227                 * @author Nicola Asuni
9228                 * @since 2.2.003 (2008-03-03)
9229                 */
9230                 public function ListBox($name, $w, $h, $values, $prop=array()) {
9231                         if (!isset($prop['strokeColor'])) {
9232                                 $prop['strokeColor'] = 'ltGray';
9233                         }
9234                         $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
9235                         $s = '';
9236                         foreach ($values as $value) {
9237                                 $s .= "'".addslashes($value)."',";
9238                         }
9239                         $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
9240                 }
9241
9242                 /*
9243                 * Creates a Combo-box field
9244                 * @param string $name field name
9245                 * @param int $w width
9246                 * @param int $h height
9247                 * @param array $values array containing the list of values.
9248                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9249                 * @access public
9250                 * @author Denis Van Nuffelen, Nicola Asuni
9251                 * @since 2.1.002 (2008-02-12)
9252                 */
9253                 public function ComboBox($name, $w, $h, $values, $prop=array()) {
9254                         $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
9255                         $s = '';
9256                         foreach ($values as $value) {
9257                                 $s .= "'".addslashes($value)."',";
9258                         }
9259                         $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
9260                 }
9261
9262                 /*
9263                 * Creates a CheckBox field
9264                 * @param string $name field name
9265                 * @param int $w width
9266                 * @param boolean $checked define the initial state (default = false).
9267                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9268                 * @access public
9269                 * @author Denis Van Nuffelen, Nicola Asuni
9270                 * @since 2.1.002 (2008-02-12)
9271                 */
9272                 public function CheckBox($name, $w, $checked=false, $prop=array()) {
9273                         $prop['value'] = ($checked ? 'Yes' : 'Off');
9274                         if (!isset($prop['strokeColor'])) {
9275                                 $prop['strokeColor'] = 'black';
9276                         }
9277                         $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
9278                 }
9279
9280                 /*
9281                 * Creates a button field
9282                 * @param string $name field name
9283                 * @param int $w width
9284                 * @param int $h height
9285                 * @param string $caption caption.
9286                 * @param string $action action triggered by the button (JavaScript code).
9287                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
9288                 * @access public
9289                 * @author Denis Van Nuffelen, Nicola Asuni
9290                 * @since 2.1.002 (2008-02-12)
9291                 */
9292                 public function Button($name, $w, $h, $caption, $action, $prop=array()) {
9293                         if (!isset($prop['strokeColor'])) {
9294                                 $prop['strokeColor'] = 'black';
9295                         }
9296                         if (!isset($prop['borderStyle'])) {
9297                                 $prop['borderStyle'] = 'beveled';
9298                         }
9299                         $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
9300                         $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
9301                         $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
9302                         $this->javascript .= 'f'.$name.".highlight='push';\n";
9303                         $this->javascript .= 'f'.$name.".print=false;\n";
9304                 }
9305
9306                 // END JAVASCRIPT - FORMS ------------------------------
9307
9308                 /*
9309                 * Enable Write permissions for PDF Reader.
9310                 * WARNING: This works only using the Adobe private key with the setSignature() method.
9311                 * @access protected
9312                 * @author Nicola Asuni
9313                 * @since 2.9.000 (2008-03-26)
9314                 */
9315                 protected function _putuserrights() {
9316                         if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] > 0))) {
9317                                 return;
9318                         }
9319                         $this->_out('/Perms');
9320                         $this->_out('<<');
9321                         $this->_out('/UR3');
9322                         $this->_out('<<');
9323                         $this->_out('/Type/Sig');
9324                         $this->_out('/Filter/Adobe.PPKLite');
9325                         $this->_out('/SubFilter/adbe.pkcs7.detached');
9326                         $this->_out('/ByteRange[0 ********** ********** **********]');
9327                         $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
9328                         if ($this->ur) {
9329                                 $this->_out('/Reference');
9330                                 $this->_out('[');
9331                                 $this->_out('<<');
9332                                 $this->_out('/Type/SigRef');
9333                                 $this->_out('/TransformMethod/UR3');
9334                                 $this->_out('/TransformParams');
9335                                 $this->_out('<<');
9336                                 $this->_out('/Type/TransformParams');
9337                                 $this->_out('/V/2.2');
9338                                 if (!$this->empty_string($this->ur_document)) {
9339                                         $this->_out('/Document['.$this->ur_document.']');
9340                                 }
9341                                 if (!$this->empty_string($this->ur_annots)) {
9342                                         $this->_out('/Annots['.$this->ur_annots.']');
9343                                 }
9344                                 if (!$this->empty_string($this->ur_form)) {
9345                                         $this->_out('/Form['.$this->ur_form.']');
9346                                 }
9347                                 if (!$this->empty_string($this->ur_signature)) {
9348                                         $this->_out('/Signature['.$this->ur_signature.']');
9349                                 }
9350                                 $this->_out('>>');
9351                                 $this->_out('>>');
9352                                 $this->_out(']');
9353                         }
9354                         $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
9355                         $this->_out('>>');
9356                         $this->_out('>>');
9357                 }
9358
9359                 /*
9360                 * Add certification signature (DocMDP)
9361                 * @access protected
9362                 * @author Nicola Asuni
9363                 * @since 4.6.008 (2009-05-07)
9364                 */
9365                 protected function _putcertification() {
9366                         if ((!$this->sign) OR (isset($this->signature_data['cert_type']) AND ($this->signature_data['cert_type'] <= 0))) {
9367                                 return;
9368                         }
9369                         $this->_out('/Perms');
9370                         $this->_out('<<');
9371                         $this->_out('/DocMDP');
9372                         $this->_out('<<');
9373                         $this->_out('/Type/Sig');
9374                         $this->_out('/Filter/Adobe.PPKLite');
9375                         $this->_out('/SubFilter/adbe.pkcs7.detached');
9376                         $this->_out('/ByteRange[0 ********** ********** **********]');
9377                         $this->_out('/Contents<>'.str_repeat(' ', $this->signature_max_lenght));
9378                         $this->_out('/Reference');
9379                         $this->_out('[');
9380                         $this->_out('<<');
9381                         $this->_out('/Type/SigRef');
9382                         $this->_out('/TransformMethod/DocMDP');
9383                         $this->_out('/TransformParams');
9384                         $this->_out('<<');
9385                         $this->_out('/Type/TransformParams');
9386                         $this->_out('/V/1.2');
9387                         $this->_out('/P '.$this->signature_data['cert_type'].'');
9388                         $this->_out('>>');
9389                         $this->_out('>>');
9390                         $this->_out(']');
9391                         $this->_out('/M '.$this->_datastring('D:'.date('YmdHisO')));
9392                         if (isset($this->signature_data['info']['Name']) AND !$this->empty_string($this->signature_data['info']['Name'])) {
9393                                 $this->_out('/Name '.$this->_textstring($this->signature_data['info']['Name']).'');
9394                         }
9395                         if (isset($this->signature_data['info']['Location']) AND !$this->empty_string($this->signature_data['info']['Location'])) {
9396                                 $this->_out('/Location '.$this->_textstring($this->signature_data['info']['Location']).'');
9397                         }
9398                         if (isset($this->signature_data['info']['Reason']) AND !$this->empty_string($this->signature_data['info']['Reason'])) {
9399                                 $this->_out('/Reason '.$this->_textstring($this->signature_data['info']['Reason']).'');
9400                         }
9401                         if (isset($this->signature_data['info']['ContactInfo']) AND !$this->empty_string($this->signature_data['info']['ContactInfo'])) {
9402                                 $this->_out('/ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo']).'');
9403                         }
9404                         $this->_out('>>');
9405                         $this->_out('>>');
9406                 }
9407
9408                 /*
9409                 * Set User's Rights for PDF Reader
9410                 * WARNING: This works only using the Adobe private key with the setSignature() method!.
9411                 * Check the PDF Reference 8.7.1 Transform Methods,
9412                 * Table 8.105 Entries in the UR transform parameters dictionary
9413                 * @param boolean $enable if true enable user's rights on PDF reader
9414                 * @param string $document Names specifying additional document-wide usage rights for the document. The only defined value is "/FullSave", which permits a user to save the document along with modified form and/or annotation data.
9415                 * @param string $annots Names specifying additional annotation-related usage rights for the document. Valid names in PDF 1.5 and later are /Create/Delete/Modify/Copy/Import/Export, which permit the user to perform the named operation on annotations.
9416                 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
9417                 * @param string $signature Names specifying additional signature-related usage rights for the document. The only defined value is /Modify, which permits a user to apply a digital signature to an existing signature form field or clear a signed signature form field.
9418                 * @access public
9419                 * @author Nicola Asuni
9420                 * @since 2.9.000 (2008-03-26)
9421                 */
9422                 public function setUserRights(
9423                                 $enable=true,
9424                                 $document='/FullSave',
9425                                 $annots='/Create/Delete/Modify/Copy/Import/Export',
9426                                 $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
9427                                 $signature='/Modify') {
9428                         $this->ur = $enable;
9429                         $this->ur_document = $document;
9430                         $this->ur_annots = $annots;
9431                         $this->ur_form = $form;
9432                         $this->ur_signature = $signature;
9433                 }
9434
9435                 /*
9436                 * Enable document signature (requires the OpenSSL Library).
9437                 * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
9438                 * @param mixed $signing_cert signing certificate (string or filename prefixed with 'file://')
9439                 * @param mixed $private_key private key (string or filename prefixed with 'file://')
9440                 * @param string $private_key_password password
9441                 * @param string $extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.
9442                 * @param int $cert_type The access permissions granted for this document. Valid values shall be: 1 = No changes to the document shall be permitted; any change to the document shall invalidate the signature; 2 = Permitted changes shall be filling in forms, instantiating page templates, and signing; other changes shall invalidate the signature; 3 = Permitted changes shall be the same as for 2, as well as annotation creation, deletion, and modification; other changes shall invalidate the signature.
9443                 * @parm array $info array of option information: Name, Location, Reason, ContactInfo.
9444                 * @access public
9445                 * @author Nicola Asuni
9446                 * @since 4.6.005 (2009-04-24)
9447                 */
9448                 public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array()) {
9449                         // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.pem -out tcpdf.pem
9450                         $this->sign = true;
9451                         $this->signature_data = array();
9452                         if (strlen($signing_cert) == 0) {
9453                                 $signing_cert = 'file://'.dirname(__FILE__).'/tcpdf.pem';
9454                         }
9455                         if (strlen($private_key) == 0) {
9456                                 $private_key = $signing_cert;
9457                         }
9458                         $this->signature_data['signcert'] = $signing_cert;
9459                         $this->signature_data['privkey'] = $private_key;
9460                         $this->signature_data['password'] = $private_key_password;
9461                         $this->signature_data['extracerts'] = $extracerts;
9462                         $this->signature_data['cert_type'] = $cert_type;
9463                         $this->signature_data['info'] = array();
9464                 }
9465
9466                 /*
9467                 * Create a new page group.
9468                 * NOTE: call this function before calling AddPage()
9469                 * @param int $page starting group page (leave empty for next page).
9470                 * @access public
9471                 * @since 3.0.000 (2008-03-27)
9472                 */
9473                 public function startPageGroup($page='') {
9474                         if (empty($page)) {
9475                                 $page = $this->page + 1;
9476                         }
9477                         $this->newpagegroup[$page] = true;
9478                 }
9479
9480                 /**
9481                 * Defines an alias for the total number of pages.
9482                 * It will be substituted as the document is closed.
9483                 * @param string $alias The alias.
9484                 * @access public
9485                 * @since 1.4
9486                 * @see getAliasNbPages(), PageNo(), Footer()
9487                 */
9488                 public function AliasNbPages($alias='{nb}') {
9489                         $this->AliasNbPages = $alias;
9490                 }
9491
9492                 /**
9493                  * Returns the string alias used for the total number of pages.
9494          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9495                  * @return string
9496                  * @access public
9497                  * @since 4.0.018 (2008-08-08)
9498                  * @see AliasNbPages(), PageNo(), Footer()
9499                 */
9500                 public function getAliasNbPages() {
9501                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9502                                 return '{'.$this->AliasNbPages.'}';
9503             }
9504                         return $this->AliasNbPages;
9505                 }
9506
9507                 /**
9508                 * Defines an alias for the page number.
9509                 * It will be substituted as the document is closed.
9510                 * @param string $alias The alias.
9511                 * @access public
9512                 * @since 4.5.000 (2009-01-02)
9513                 * @see getAliasNbPages(), PageNo(), Footer()
9514                 */
9515                 public function AliasNumPage($alias='{pnb}') {
9516                         //Define an alias for total number of pages
9517                         $this->AliasNumPage = $alias;
9518                 }
9519
9520                 /**
9521                  * Returns the string alias used for the page number.
9522          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9523                  * @return string
9524                  * @access public
9525                  * @since 4.5.000 (2009-01-02)
9526                  * @see AliasNbPages(), PageNo(), Footer()
9527                 */
9528                 public function getAliasNumPage() {
9529                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9530                                 return '{'.$this->AliasNumPage.'}';
9531             }
9532                         return $this->AliasNumPage;
9533                 }
9534
9535                 /*
9536                 * Return the current page in the group.
9537                 * @return current page in the group
9538                 * @access public
9539                 * @since 3.0.000 (2008-03-27)
9540                 */
9541                 public function getGroupPageNo() {
9542                         return $this->pagegroups[$this->currpagegroup];
9543                 }
9544
9545                 /**
9546                 * Returns the current group page number formatted as a string.
9547                 * @access public
9548                 * @since 4.3.003 (2008-11-18)
9549                 * @see PaneNo(), formatPageNumber()
9550                 */
9551                 public function getGroupPageNoFormatted() {
9552                         return $this->formatPageNumber($this->getGroupPageNo());
9553         }
9554
9555                 /*
9556                  * Return the alias of the current page group
9557          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9558                  * (will be replaced by the total number of pages in this group).
9559                  * @return alias of the current page group
9560                  * @access public
9561                  * @since 3.0.000 (2008-03-27)
9562                 */
9563                 public function getPageGroupAlias() {
9564                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9565                                 return '{'.$this->currpagegroup.'}';
9566             }
9567                         return $this->currpagegroup;
9568                 }
9569
9570                 /*
9571                  * Return the alias for the page number on the current page group
9572          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
9573                  * (will be replaced by the total number of pages in this group).
9574                  * @return alias of the current page group
9575                  * @access public
9576                  * @since 4.5.000 (2009-01-02)
9577                 */
9578                 public function getPageNumGroupAlias() {
9579                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
9580                                 return '{'.str_replace('{nb', '{pnb', $this->currpagegroup).'}';
9581             }
9582                         return str_replace('{nb', '{pnb', $this->currpagegroup);
9583                 }
9584
9585                 /**
9586                 * Format the page numbers.
9587                 * This method can be overriden for custom formats.
9588                 * @param int $num page number
9589                 * @access protected
9590                 * @since 4.2.005 (2008-11-06)
9591                 */
9592                 protected function formatPageNumber($num) {
9593                         return number_format((float)$num, 0, '', '.');
9594                 }
9595
9596                 /**
9597                 * Format the page numbers on the Table Of Content.
9598                 * This method can be overriden for custom formats.
9599                 * @param int $num page number
9600                 * @access protected
9601                 * @since 4.5.001 (2009-01-04)
9602                 * @see addTOC()
9603                 */
9604                 protected function formatTOCPageNumber($num) {
9605                         return number_format((float)$num, 0, '', '.');
9606                 }
9607
9608         /**
9609                 * Returns the current page number formatted as a string.
9610                 * @access public
9611                 * @since 4.2.005 (2008-11-06)
9612                 * @see PaneNo(), formatPageNumber()
9613                 */
9614                 public function PageNoFormatted() {
9615                         return $this->formatPageNumber($this->PageNo());
9616         }
9617
9618         /*
9619                 * Put visibility settings.
9620                 * @access protected
9621                 * @since 3.0.000 (2008-03-27)
9622                 */
9623                 protected function _putocg() {
9624                         $this->_newobj();
9625                         $this->n_ocg_print = $this->n;
9626                         $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
9627                         $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
9628                         $this->_out('endobj');
9629                         $this->_newobj();
9630                         $this->n_ocg_view=$this->n;
9631                         $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
9632                         $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
9633                         $this->_out('endobj');
9634                 }
9635
9636                 /*
9637                 * Set the visibility of the successive elements.
9638                 * This can be useful, for instance, to put a background
9639                 * image or color that will show on screen but won't print.
9640                 * @param string $v visibility mode. Legal values are: all, print, screen.
9641                 * @access public
9642                 * @since 3.0.000 (2008-03-27)
9643                 */
9644                 public function setVisibility($v) {
9645                         if ($this->openMarkedContent) {
9646                                 // close existing open marked-content
9647                                 $this->_out('EMC');
9648                                 $this->openMarkedContent = false;
9649                         }
9650                         switch($v) {
9651                                 case 'print': {
9652                                         $this->_out('/OC /OC1 BDC');
9653                                         $this->openMarkedContent = true;
9654                                         break;
9655                                 }
9656                                 case 'screen': {
9657                                         $this->_out('/OC /OC2 BDC');
9658                                         $this->openMarkedContent = true;
9659                                         break;
9660                                 }
9661                                 case 'all': {
9662                                         $this->_out('');
9663                                         break;
9664                                 }
9665                                 default: {
9666                                         $this->Error('Incorrect visibility: '.$v);
9667                                         break;
9668                                 }
9669                         }
9670                         $this->visibility = $v;
9671                 }
9672
9673                 /*
9674                 * Add transparency parameters to the current extgstate
9675                 * @param array $params parameters
9676                 * @return the number of extgstates
9677                 * @access protected
9678                 * @since 3.0.000 (2008-03-27)
9679                 */
9680                 protected function addExtGState($parms) {
9681                         $n = count($this->extgstates) + 1;
9682                         $this->extgstates[$n]['parms'] = $parms;
9683                         return $n;
9684                 }
9685
9686                 /*
9687                 * Add an extgstate
9688                 * @param array $gs extgstate
9689                 * @access protected
9690                 * @since 3.0.000 (2008-03-27)
9691                 */
9692                 protected function setExtGState($gs) {
9693                         $this->_out(sprintf('/GS%d gs', $gs));
9694                 }
9695
9696                 /*
9697                 * Put extgstates for object transparency
9698                 * @param array $gs extgstate
9699                 * @access protected
9700                 * @since 3.0.000 (2008-03-27)
9701                 */
9702                 protected function _putextgstates() {
9703                         $ne = count($this->extgstates);
9704                         for ($i = 1; $i <= $ne; ++$i) {
9705                                 $this->_newobj();
9706                                 $this->extgstates[$i]['n'] = $this->n;
9707                                 $this->_out('<</Type /ExtGState');
9708                                 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
9709                                         $this->_out('/'.$k.' '.$v);
9710                                 }
9711                                 $this->_out('>>');
9712                                 $this->_out('endobj');
9713                         }
9714                 }
9715
9716                 /*
9717                 * Set alpha for stroking (CA) and non-stroking (ca) operations.
9718                 * @param float $alpha real value from 0 (transparent) to 1 (opaque)
9719                 * @param string $bm blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
9720                 * @access public
9721                 * @since 3.0.000 (2008-03-27)
9722                 */
9723                 public function setAlpha($alpha, $bm='Normal') {
9724                         $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
9725                         $this->setExtGState($gs);
9726                 }
9727
9728                 /*
9729                 * Set the default JPEG compression quality (1-100)
9730                 * @param int $quality JPEG quality, integer between 1 and 100
9731                 * @access public
9732                 * @since 3.0.000 (2008-03-27)
9733                 */
9734                 public function setJPEGQuality($quality) {
9735                         if (($quality < 1) OR ($quality > 100)) {
9736                                 $quality = 75;
9737                         }
9738                         $this->jpeg_quality = intval($quality);
9739                 }
9740
9741                 /*
9742                 * Set the default number of columns in a row for HTML tables.
9743                 * @param int $cols number of columns
9744                 * @access public
9745                 * @since 3.0.014 (2008-06-04)
9746                 */
9747                 public function setDefaultTableColumns($cols=4) {
9748                         $this->default_table_columns = intval($cols);
9749                 }
9750
9751                 /*
9752                 * Set the height of cell repect font height.
9753                 * @param int $h cell proportion respect font height (typical value = 1.25).
9754                 * @access public
9755                 * @since 3.0.014 (2008-06-04)
9756                 */
9757                 public function setCellHeightRatio($h) {
9758                         $this->cell_height_ratio = $h;
9759                 }
9760
9761                 /*
9762                 * return the height of cell repect font height.
9763                 * @access public
9764                 * @since 4.0.012 (2008-07-24)
9765                 */
9766                 public function getCellHeightRatio() {
9767                         return $this->cell_height_ratio;
9768                 }
9769
9770                 /*
9771                 * Set the PDF version (check PDF reference for valid values).
9772                 * Default value is 1.t
9773                 * @access public
9774                 * @since 3.1.000 (2008-06-09)
9775                 */
9776                 public function setPDFVersion($version='1.7') {
9777                         $this->PDFVersion = $version;
9778                 }
9779
9780                 /*
9781                 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
9782                 * (see Section 8.1 of PDF reference, "Viewer Preferences").
9783                 * <ul>
9784                 * <li>HideToolbar boolean (Optional) A flag specifying whether to hide the viewer application's tool bars when the document is active. Default value: false.</li>
9785                 * <li>HideMenubar boolean (Optional) A flag specifying whether to hide the viewer application's menu bar when the document is active. Default value: false.</li>
9786                 * <li>HideWindowUI boolean (Optional) A flag specifying whether to hide user interface elements in the document's window (such as scroll bars and navigation controls), leaving only the document's contents displayed. Default value: false.</li>
9787                 * <li>FitWindow boolean (Optional) A flag specifying whether to resize the document's window to fit the size of the first displayed page. Default value: false.</li>
9788                 * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
9789                 * <li>DisplayDocTitle boolean (Optional; PDF 1.4) A flag specifying whether the window's title bar should display the document title taken from the Title entry of the document information dictionary (see Section 10.2.1, "Document Information Dictionary"). If false, the title bar should instead display the name of the PDF file containing the document. Default value: false.</li>
9790                 * <li>NonFullScreenPageMode name (Optional) The document's page mode, specifying how to display the document on exiting full-screen mode:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>UseOC Optional content group panel visible</li><ul>This entry is meaningful only if the value of the PageMode entry in the catalog dictionary (see Section 3.6.1, "Document Catalog") is FullScreen; it is ignored otherwise. Default value: UseNone.</li>
9791                 * <li>ViewArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be displayed when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9792                 * <li>ViewClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9793                 * <li>PrintArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be rendered when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9794                 * <li>PrintClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
9795                 * <li>PrintScaling name (Optional; PDF 1.6) The page scaling option to be selected when a print dialog is displayed for this document. Valid values are: <ul><li>None, which indicates that the print dialog should reflect no page scaling</li><li>AppDefault (default), which indicates that applications should use the current print scaling</li><ul></li>
9796                 * <li>Duplex name (Optional; PDF 1.7) The paper handling option to use when printing the file from the print dialog. The following values are valid:<ul><li>Simplex - Print single-sided</li><li>DuplexFlipShortEdge - Duplex and flip on the short edge of the sheet</li><li>DuplexFlipLongEdge - Duplex and flip on the long edge of the sheet</li></ul>Default value: none</li>
9797                 * <li>PickTrayByPDFSize boolean (Optional; PDF 1.7) A flag specifying whether the PDF page size is used to select the input paper tray. This setting influences only the preset values used to populate the print dialog presented by a PDF viewer application. If PickTrayByPDFSize is true, the check box in the print dialog associated with input paper tray is checked. Note: This setting has no effect on Mac OS systems, which do not provide the ability to pick the input tray by size.</li>
9798                 * <li>PrintPageRange array (Optional; PDF 1.7) The page numbers used to initialize the print dialog box when the file is printed. The first page of the PDF file is denoted by 1. Each pair consists of the first and last pages in the sub-range. An odd number of integers causes this entry to be ignored. Negative numbers cause the entire array to be ignored. Default value: as defined by PDF viewer application</li>
9799                 * <li>NumCopies integer (Optional; PDF 1.7) The number of copies to be printed when the print dialog is opened for this file. Supported values are the integers 2 through 5. Values outside this range are ignored. Default value: as defined by PDF viewer application, but typically 1</li>
9800                 * </ul>
9801                 * @param array $preferences array of options.
9802                 * @author Nicola Asuni
9803                 * @access public
9804                 * @since 3.1.000 (2008-06-09)
9805                 */
9806                 public function setViewerPreferences($preferences) {
9807                         $this->viewer_preferences = $preferences;
9808                 }
9809
9810                 /**
9811                 * Paints a linear colour gradient.
9812                 * @param float $x abscissa of the top left corner of the rectangle.
9813                 * @param float $y ordinate of the top left corner of the rectangle.
9814                 * @param float $w width of the rectangle.
9815                 * @param float $h height of the rectangle.
9816                 * @param array $col1 first color (RGB components).
9817                 * @param array $col2 second color (RGB components).
9818                 * @param array $coords array of the form (x1, y1, x2, y2) which defines the gradient vector (see linear_gradient_coords.jpg). The default value is from left to right (x1=0, y1=0, x2=1, y2=0).
9819                 * @author Andreas W�rmser, Nicola Asuni
9820                 * @since 3.1.000 (2008-06-09)
9821                 * @access public
9822                 */
9823                 public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
9824                         $this->Clip($x, $y, $w, $h);
9825                         $this->Gradient(2, $col1, $col2, $coords);
9826                 }
9827
9828                 /**
9829                 * Paints a radial colour gradient.
9830                 * @param float $x abscissa of the top left corner of the rectangle.
9831                 * @param float $y ordinate of the top left corner of the rectangle.
9832                 * @param float $w width of the rectangle.
9833                 * @param float $h height of the rectangle.
9834                 * @param array $col1 first color (RGB components).
9835                 * @param array $col2 second color (RGB components).
9836                 * @param array $coords array of the form (fx, fy, cx, cy, r) where (fx, fy) is the starting point of the gradient with color1, (cx, cy) is the center of the circle with color2, and r is the radius of the circle (see radial_gradient_coords.jpg). (fx, fy) should be inside the circle, otherwise some areas will not be defined.
9837                 * @author Andreas W�rmser, Nicola Asuni
9838                 * @since 3.1.000 (2008-06-09)
9839                 * @access public
9840                 */
9841                 public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
9842                         $this->Clip($x, $y, $w, $h);
9843                         $this->Gradient(3, $col1, $col2, $coords);
9844                 }
9845
9846                 /**
9847                 * Paints a coons patch mesh.
9848                 * @param float $x abscissa of the top left corner of the rectangle.
9849                 * @param float $y ordinate of the top left corner of the rectangle.
9850                 * @param float $w width of the rectangle.
9851                 * @param float $h height of the rectangle.
9852                 * @param array $col1 first color (lower left corner) (RGB components).
9853                 * @param array $col2 second color (lower right corner) (RGB components).
9854                 * @param array $col3 third color (upper right corner) (RGB components).
9855                 * @param array $col4 fourth color (upper left corner) (RGB components).
9856                 * @param array $coords <ul><li>for one patch mesh: array(float x1, float y1, .... float x12, float y12): 12 pairs of coordinates (normally from 0 to 1) which specify the Bezier control points that define the patch. First pair is the lower left edge point, next is its right control point (control point 2). Then the other points are defined in the order: control point 1, edge point, control point 2 going counter-clockwise around the patch. Last (x12, y12) is the first edge point's left control point (control point 1).</li><li>for two or more patch meshes: array[number of patches]: arrays with the following keys for each patch: f: where to put that patch (0 = first patch, 1, 2, 3 = right, top and left of precedent patch - I didn't figure this out completely - just try and error ;-) points: 12 pairs of coordinates of the Bezier control points as above for the first patch, 8 pairs of coordinates for the following patches, ignoring the coordinates already defined by the precedent patch (I also didn't figure out the order of these - also: try and see what's happening) colors: must be 4 colors for the first patch, 2 colors for the following patches</li></ul>
9857                 * @param array $coords_min minimum value used by the coordinates. If a coordinate's value is smaller than this it will be cut to coords_min. default: 0
9858                 * @param array $coords_max maximum value used by the coordinates. If a coordinate's value is greater than this it will be cut to coords_max. default: 1
9859                 * @author Andreas W�rmser, Nicola Asuni
9860                 * @since 3.1.000 (2008-06-09)
9861                 * @access public
9862                 */
9863                 public function CoonsPatchMesh($x, $y, $w, $h, $col1=array(), $col2=array(), $col3=array(), $col4=array(), $coords=array(0.00,0.0,0.33,0.00,0.67,0.00,1.00,0.00,1.00,0.33,1.00,0.67,1.00,1.00,0.67,1.00,0.33,1.00,0.00,1.00,0.00,0.67,0.00,0.33), $coords_min=0, $coords_max=1) {
9864                         $this->Clip($x, $y, $w, $h);
9865                         $n = count($this->gradients) + 1;
9866                         $this->gradients[$n]['type'] = 6; //coons patch mesh
9867                         //check the coords array if it is the simple array or the multi patch array
9868                         if (!isset($coords[0]['f'])) {
9869                                 //simple array -> convert to multi patch array
9870                                 if (!isset($col1[1])) {
9871                                         $col1[1] = $col1[2] = $col1[0];
9872                                 }
9873                                 if (!isset($col2[1])) {
9874                                         $col2[1] = $col2[2] = $col2[0];
9875                                 }
9876                                 if (!isset($col3[1])) {
9877                                         $col3[1] = $col3[2] = $col3[0];
9878                                 }
9879                                 if (!isset($col4[1])) {
9880                                         $col4[1] = $col4[2] = $col4[0];
9881                                 }
9882                                 $patch_array[0]['f'] = 0;
9883                                 $patch_array[0]['points'] = $coords;
9884                                 $patch_array[0]['colors'][0]['r'] = $col1[0];
9885                                 $patch_array[0]['colors'][0]['g'] = $col1[1];
9886                                 $patch_array[0]['colors'][0]['b'] = $col1[2];
9887                                 $patch_array[0]['colors'][1]['r'] = $col2[0];
9888                                 $patch_array[0]['colors'][1]['g'] = $col2[1];
9889                                 $patch_array[0]['colors'][1]['b'] = $col2[2];
9890                                 $patch_array[0]['colors'][2]['r'] = $col3[0];
9891                                 $patch_array[0]['colors'][2]['g'] = $col3[1];
9892                                 $patch_array[0]['colors'][2]['b'] = $col3[2];
9893                                 $patch_array[0]['colors'][3]['r'] = $col4[0];
9894                                 $patch_array[0]['colors'][3]['g'] = $col4[1];
9895                                 $patch_array[0]['colors'][3]['b'] = $col4[2];
9896                         } else {
9897                                 //multi patch array
9898                                 $patch_array = $coords;
9899                         }
9900                         $bpcd = 65535; //16 BitsPerCoordinate
9901                         //build the data stream
9902                         $this->gradients[$n]['stream'] = '';
9903                         $count_patch = count($patch_array);
9904                         for ($i=0; $i < $count_patch; ++$i) {
9905                                 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
9906                                 $count_points = count($patch_array[$i]['points']);
9907                                 for ($j=0; $j < $count_points; ++$j) {
9908                                         //each point as 16 bit
9909                                         $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
9910                                         if ($patch_array[$i]['points'][$j] < 0) {
9911                                                 $patch_array[$i]['points'][$j] = 0;
9912                                         }
9913                                         if ($patch_array[$i]['points'][$j] > $bpcd) {
9914                                                 $patch_array[$i]['points'][$j] = $bpcd;
9915                                         }
9916                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
9917                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
9918                                 }
9919                                 $count_cols = count($patch_array[$i]['colors']);
9920                                 for ($j=0; $j < $count_cols; ++$j) {
9921                                         //each color component as 8 bit
9922                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
9923                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
9924                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
9925                                 }
9926                         }
9927                         //paint the gradient
9928                         $this->_out('/Sh'.$n.' sh');
9929                         //restore previous Graphic State
9930                         $this->_out('Q');
9931                 }
9932
9933                 /**
9934                 * Set a rectangular clipping area.
9935                 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
9936                 * @param float $y ordinate of the top left corner of the rectangle.
9937                 * @param float $w width of the rectangle.
9938                 * @param float $h height of the rectangle.
9939                 * @author Andreas W�rmser, Nicola Asuni
9940                 * @since 3.1.000 (2008-06-09)
9941                 * @access protected
9942                 */
9943                 protected function Clip($x, $y, $w, $h) {
9944                         if ($this->rtl) {
9945                                 $x = $this->w - $x - $w;
9946                         }
9947                         //save current Graphic State
9948                         $s = 'q';
9949                         //set clipping area
9950                         $s .= sprintf(' %.2F %.2F %.2F %.2F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
9951                         //set up transformation matrix for gradient
9952                         $s .= sprintf(' %.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
9953                         $this->_out($s);
9954                 }
9955
9956                 /**
9957                 * Output gradient.
9958                 * @param int $type type of gradient.
9959                 * @param array $col1 first color (RGB components).
9960                 * @param array $col2 second color (RGB components).
9961                 * @param array $coords array of coordinates.
9962                 * @author Andreas W�rmser, Nicola Asuni
9963                 * @since 3.1.000 (2008-06-09)
9964                 * @access protected
9965                 */
9966                 protected function Gradient($type, $col1, $col2, $coords) {
9967                         $n = count($this->gradients) + 1;
9968                         $this->gradients[$n]['type'] = $type;
9969                         if (!isset($col1[1])) {
9970                                 $col1[1]=$col1[2]=$col1[0];
9971                         }
9972                         $this->gradients[$n]['col1'] = sprintf('%.3F %.3F %.3F', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
9973                         if (!isset($col2[1])) {
9974                                 $col2[1] = $col2[2] = $col2[0];
9975                         }
9976                         $this->gradients[$n]['col2'] = sprintf('%.3F %.3F %.3F', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
9977                         $this->gradients[$n]['coords'] = $coords;
9978                         //paint the gradient
9979                         $this->_out('/Sh'.$n.' sh');
9980                         //restore previous Graphic State
9981                         $this->_out('Q');
9982                 }
9983
9984                 /**
9985                 * Output shaders.
9986                 * @author Andreas W�rmser, Nicola Asuni
9987                 * @since 3.1.000 (2008-06-09)
9988                 * @access protected
9989                 */
9990                 function _putshaders() {
9991                         foreach ($this->gradients as $id => $grad) {
9992                                 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
9993                                         $this->_newobj();
9994                                         $this->_out('<<');
9995                                         $this->_out('/FunctionType 2');
9996                                         $this->_out('/Domain [0.0 1.0]');
9997                                         $this->_out('/C0 ['.$grad['col1'].']');
9998                                         $this->_out('/C1 ['.$grad['col2'].']');
9999                                         $this->_out('/N 1');
10000                                         $this->_out('>>');
10001                                         $this->_out('endobj');
10002                                         $f1 = $this->n;
10003                                 }
10004                                 $this->_newobj();
10005                                 $this->_out('<<');
10006                                 $this->_out('/ShadingType '.$grad['type']);
10007                                 $this->_out('/ColorSpace /DeviceRGB');
10008                                 if ($grad['type'] == 2) {
10009                                         $this->_out(sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
10010                                         $this->_out('/Function '.$f1.' 0 R');
10011                                         $this->_out('/Extend [true true] ');
10012                                         $this->_out('>>');
10013                                 } elseif ($grad['type'] == 3) {
10014                                         //x0, y0, r0, x1, y1, r1
10015                                         //at this this time radius of inner circle is 0
10016                                         $this->_out(sprintf('/Coords [%.3F %.3F 0 %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]));
10017                                         $this->_out('/Function '.$f1.' 0 R');
10018                                         $this->_out('/Extend [true true] ');
10019                                         $this->_out('>>');
10020                                 } elseif ($grad['type'] == 6) {
10021                                         $this->_out('/BitsPerCoordinate 16');
10022                                         $this->_out('/BitsPerComponent 8');
10023                                         $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
10024                                         $this->_out('/BitsPerFlag 8');
10025                                         $this->_out('/Length '.strlen($grad['stream']));
10026                                         $this->_out('>>');
10027                                         $this->_putstream($grad['stream']);
10028                                 }
10029                                 $this->_out('endobj');
10030                                 $this->gradients[$id]['id'] = $this->n;
10031                         }
10032                 }
10033
10034                 /**
10035                 * Output an arc
10036                 * @author Maxime Delorme, Nicola Asuni
10037                 * @since 3.1.000 (2008-06-09)
10038                 * @access protected
10039                 */
10040                 protected function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
10041                         $h = $this->h;
10042                         $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c', $x1*$this->k, ($h-$y1)*$this->k, $x2*$this->k, ($h-$y2)*$this->k, $x3*$this->k, ($h-$y3)*$this->k));
10043                 }
10044
10045                 /**
10046                 * Draw the sector of a circle.
10047                 * It can be used for instance to render pie charts.
10048                 * @param float $xc abscissa of the center.
10049                 * @param float $yc ordinate of the center.
10050                 * @param float $r radius.
10051                 * @param float $a start angle (in degrees).
10052                 * @param float $b end angle (in degrees).
10053                 * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
10054                 * @param float $cw: indicates whether to go clockwise (default: true).
10055                 * @param float $o: origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). Default: 90.
10056                 * @author Maxime Delorme, Nicola Asuni
10057                 * @since 3.1.000 (2008-06-09)
10058                 * @access public
10059                 */
10060                 public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
10061                         if ($this->rtl) {
10062                                 $xc = $this->w - $xc;
10063                         }
10064                         if ($cw) {
10065                                 $d = $b;
10066                                 $b = $o - $a;
10067                                 $a = $o - $d;
10068                         } else {
10069                                 $b += $o;
10070                                 $a += $o;
10071                         }
10072                         $a = ($a % 360) + 360;
10073                         $b = ($b % 360) + 360;
10074                         if ($a > $b) {
10075                                 $b +=360;
10076                         }
10077                         $b = $b / 360 * 2 * M_PI;
10078                         $a = $a / 360 * 2 * M_PI;
10079                         $d = $b - $a;
10080                         if ($d == 0 ) {
10081                                 $d = 2 * M_PI;
10082                         }
10083                         $k = $this->k;
10084                         $hp = $this->h;
10085                         if ($style=='F') {
10086                                 $op = 'f';
10087                         } elseif ($style=='FD' or $style=='DF') {
10088                                 $op = 'b';
10089                         } else {
10090                                 $op = 's';
10091                         }
10092                         if (sin($d/2)) {
10093                                 $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
10094                         }
10095                         //first put the center
10096                         $this->_out(sprintf('%.2F %.2F m', ($xc)*$k, ($hp-$yc)*$k));
10097                         //put the first point
10098                         $this->_out(sprintf('%.2F %.2F l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
10099                         //draw the arc
10100                         if ($d < (M_PI/2)) {
10101                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10102                         } else {
10103                                 $b = $a + $d/4;
10104                                 $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
10105                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10106                                 $a = $b;
10107                                 $b = $a + $d/4;
10108                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10109                                 $a = $b;
10110                                 $b = $a + $d/4;
10111                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b) );
10112                                 $a = $b;
10113                                 $b = $a + $d/4;
10114                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
10115                         }
10116                         //terminate drawing
10117                         $this->_out($op);
10118                 }
10119
10120                 /**
10121                 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
10122                 * Only vector drawing is supported, not text or bitmap.
10123                 * Although the script was successfully tested with various AI format versions, best results are probably achieved with files that were exported in the AI3 format (tested with Illustrator CS2, Freehand MX and Photoshop CS2).
10124                 * @param string $file Name of the file containing the image.
10125                 * @param float $x Abscissa of the upper-left corner.
10126                 * @param float $y Ordinate of the upper-left corner.
10127                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
10128                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
10129                 * @param mixed $link URL or identifier returned by AddLink().
10130                 * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
10131                 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
10132                 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
10133                 * @param mixed $border Indicates if borders must be drawn around the image. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
10134                 * @author Valentin Schmidt, Nicola Asuni
10135                 * @since 3.1.000 (2008-06-09)
10136                 * @access public
10137                 */
10138                 public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0) {
10139                         if ($x === '') {
10140                                 $x = $this->x;
10141                         }
10142                         if ($y === '') {
10143                                 $y = $this->y;
10144                         }
10145                         $k = $this->k;
10146                         $data = file_get_contents($file);
10147                         if ($data === false) {
10148                                 $this->Error('EPS file not found: '.$file);
10149                         }
10150                         $regs = array();
10151                         // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
10152                         preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
10153                         if (count($regs) > 1) {
10154                                 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
10155                                 if (strpos($version_str, 'Adobe Illustrator') !== false) {
10156                                         $versexp = explode(' ', $version_str);
10157                                         $version = (float)array_pop($versexp);
10158                                         if ($version >= 9) {
10159                                                 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
10160                                         }
10161                                 }
10162                         }
10163                         // strip binary bytes in front of PS-header
10164                         $start = strpos($data, '%!PS-Adobe');
10165                         if ($start > 0) {
10166                                 $data = substr($data, $start);
10167                         }
10168                         // find BoundingBox params
10169                         preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
10170                         if (count($regs) > 1) {
10171                                 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
10172                         } else {
10173                                 $this->Error('No BoundingBox found in EPS file: '.$file);
10174                         }
10175                         $start = strpos($data, '%%EndSetup');
10176                         if ($start === false) {
10177                                 $start = strpos($data, '%%EndProlog');
10178                         }
10179                         if ($start === false) {
10180                                 $start = strpos($data, '%%BoundingBox');
10181                         }
10182                         $data = substr($data, $start);
10183                         $end = strpos($data, '%%PageTrailer');
10184                         if ($end===false) {
10185                                 $end = strpos($data, 'showpage');
10186                         }
10187                         if ($end) {
10188                                 $data = substr($data, 0, $end);
10189                         }
10190                         if ($w > 0) {
10191                                 $scale_x = $w / (($x2 - $x1) / $k);
10192                                 if ($h > 0) {
10193                                         $scale_y = $h / (($y2 - $y1) / $k);
10194                                 } else {
10195                                         $scale_y = $scale_x;
10196                                         $h = ($y2 - $y1) / $k * $scale_y;
10197                                 }
10198                         } else {
10199                                 if ($h > 0) {
10200                                         $scale_y = $h / (($y2 - $y1) / $k);
10201                                         $scale_x = $scale_y;
10202                                         $w = ($x2-$x1) / $k * $scale_x;
10203                                 } else {
10204                                         $w = ($x2 - $x1) / $k;
10205                                         $h = ($y2 - $y1) / $k;
10206                                 }
10207                         }
10208                         // Check whether we need a new page first as this does not fit
10209                         if ($this->checkPageBreak($h, $y)) {
10210                                 $y = $this->GetY() + $this->cMargin;
10211                         }
10212                         // set bottomcoordinates
10213                         $this->img_rb_y = $y + $h;
10214                         // set alignment
10215                         if ($this->rtl) {
10216                                 if ($palign == 'L') {
10217                                         $ximg = $this->lMargin;
10218                                         // set right side coordinate
10219                                         $this->img_rb_x = $ximg + $w;
10220                                 } elseif ($palign == 'C') {
10221                                         $ximg = ($this->w - $x - $w) / 2;
10222                                         // set right side coordinate
10223                                         $this->img_rb_x = $ximg + $w;
10224                                 } else {
10225                                         $ximg = $this->w - $x - $w;
10226                                         // set left side coordinate
10227                                         $this->img_rb_x = $ximg;
10228                                 }
10229                         } else {
10230                                 if ($palign == 'R') {
10231                                         $ximg = $this->w - $this->rMargin - $w;
10232                                         // set left side coordinate
10233                                         $this->img_rb_x = $ximg;
10234                                 } elseif ($palign == 'C') {
10235                                         $ximg = ($this->w - $x - $w) / 2;
10236                                         // set right side coordinate
10237                                         $this->img_rb_x = $ximg + $w;
10238                                 } else {
10239                                         $ximg = $x;
10240                                         // set right side coordinate
10241                                         $this->img_rb_x = $ximg + $w;
10242                                 }
10243                         }
10244                         if ($useBoundingBox) {
10245                                 $dx = $ximg * $k - $x1;
10246                                 $dy = $y * $k - $y1;
10247                         } else {
10248                                 $dx = $ximg * $k;
10249                                 $dy = $y * $k;
10250                         }
10251                         // save the current graphic state
10252                         $this->_out('q'.$this->epsmarker);
10253                         // translate
10254                         $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
10255                         // scale
10256                         if (isset($scale_x)) {
10257                                 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
10258                         }
10259                         // handle pc/unix/mac line endings
10260                         preg_match('/[\r\n]+/s', $data, $regs);
10261                         $lines = explode($regs[0], $data);
10262                         $u=0;
10263                         $cnt = count($lines);
10264                         for ($i=0; $i < $cnt; ++$i) {
10265                                 $line = $lines[$i];
10266                                 if (($line == '') OR ($line{0} == '%')) {
10267                                         continue;
10268                                 }
10269                                 $len = strlen($line);
10270                                 $chunks = explode(' ', $line);
10271                                 $cmd = array_pop($chunks);
10272                                 // RGB
10273                                 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
10274                                         $b = array_pop($chunks);
10275                                         $g = array_pop($chunks);
10276                                         $r = array_pop($chunks);
10277                                         $this->_out(''.$r.' '.$g.' '.$b.' '.($cmd=='Xa'?'rg':'RG')); //substr($line, 0, -2).'rg' -> in EPS (AI8): c m y k r g b rg!
10278                                         continue;
10279                                 }
10280                                 switch ($cmd) {
10281                                         case 'm':
10282                                         case 'l':
10283                                         case 'v':
10284                                         case 'y':
10285                                         case 'c':
10286                                         case 'k':
10287                                         case 'K':
10288                                         case 'g':
10289                                         case 'G':
10290                                         case 's':
10291                                         case 'S':
10292                                         case 'J':
10293                                         case 'j':
10294                                         case 'w':
10295                                         case 'M':
10296                                         case 'd':
10297                                         case 'n':
10298                                         case 'v': {
10299                                                 $this->_out($line);
10300                                                 break;
10301                                         }
10302                                         case 'x': {// custom fill color
10303                                                 list($c,$m,$y,$k) = $chunks;
10304                                                 $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' k');
10305                                                 break;
10306                                         }
10307                                         case 'X': { // custom stroke color
10308                                                 list($c,$m,$y,$k) = $chunks;
10309                                                 $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' K');
10310                                                 break;
10311                                         }
10312                                         case 'Y':
10313                                         case 'N':
10314                                         case 'V':
10315                                         case 'L':
10316                                         case 'C': {
10317                                                 $line{$len-1} = strtolower($cmd);
10318                                                 $this->_out($line);
10319                                                 break;
10320                                         }
10321                                         case 'b':
10322                                         case 'B': {
10323                                                 $this->_out($cmd . '*');
10324                                                 break;
10325                                         }
10326                                         case 'f':
10327                                         case 'F': {
10328                                                 if ($u > 0) {
10329                                                         $isU = false;
10330                                                         $max = min($i+5, $cnt);
10331                                                         for ($j=$i+1; $j < $max; ++$j)
10332                                                           $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
10333                                                         if ($isU) {
10334                                                                 $this->_out('f*');
10335                                                         }
10336                                                 } else {
10337                                                         $this->_out('f*');
10338                                                 }
10339                                                 break;
10340                                         }
10341                                         case '*u': {
10342                                                 ++$u;
10343                                                 break;
10344                                         }
10345                                         case '*U': {
10346                                                 --$u;
10347                                                 break;
10348                                         }
10349                                 }
10350                         }
10351                         // restore previous graphic state
10352                         $this->_out($this->epsmarker.'Q');
10353                         if (!empty($border)) {
10354                                 $bx = $x;
10355                                 $by = $y;
10356                                 $this->x = $x;
10357                                 $this->y = $y;
10358                                 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
10359                                 $this->x = $bx;
10360                                 $this->y = $by;
10361                         }
10362                         if ($link) {
10363                                 $this->Link($ximg, $y, $w, $h, $link, 0);
10364                         }
10365                         // set pointer to align the successive text/objects
10366                         switch($align) {
10367                                 case 'T':{
10368                                         $this->y = $y;
10369                                         $this->x = $this->img_rb_x;
10370                                         break;
10371                                 }
10372                                 case 'M':{
10373                                         $this->y = $y + round($h/2);
10374                                         $this->x = $this->img_rb_x;
10375                                         break;
10376                                 }
10377                                 case 'B':{
10378                                         $this->y = $this->img_rb_y;
10379                                         $this->x = $this->img_rb_x;
10380                                         break;
10381                                 }
10382                                 case 'N':{
10383                                         $this->SetY($this->img_rb_y);
10384                                         break;
10385                                 }
10386                                 default:{
10387                                         break;
10388                                 }
10389                         }
10390                         $this->endlinex = $this->img_rb_x;
10391                 }
10392
10393                 /**
10394                  * Set document barcode.
10395                  * @param string $bc barcode
10396                  * @access public
10397                  */
10398                 public function setBarcode($bc='') {
10399                         $this->barcode = $bc;
10400                 }
10401
10402                 /**
10403                  * Get current barcode.
10404                  * @return string
10405                  * @access public
10406                  * @since 4.0.012 (2008-07-24)
10407                  */
10408                 public function getBarcode() {
10409                         return $this->barcode;
10410                 }
10411
10412                 /**
10413                  * Print a Linear Barcode.
10414                  * @param string $code code to print
10415                  * @param string $type type of barcode.
10416                  * @param int $x x position in user units
10417                  * @param int $y y position in user units
10418                  * @param int $w width in user units
10419                  * @param int $h height in user units
10420                  * @param float $xres width of the smallest bar in user units
10421                  * @param array $style array of options:<ul><li>string $style['position'] barcode position inside the specified width: L = left (default for LTR); C = center; R = right (default for RTL); S = stretch</li><li>boolean $style['border'] if true prints a border around the barcode</li><li>int $style['padding'] padding to leave around the barcode in user units</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background or false for transparent</li><li>boolean $style["text"] boolean if true prints text below the barcode</li><li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li><li>int $style['stretchtext']: 0 = disabled; 1 = horizontal scaling only if necessary; 2 = forced horizontal scaling; 3 = character spacing only if necessary; 4 = forced character spacing</li></ul>
10422                  * @param string $align Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
10423                  * @author Nicola Asuni
10424                  * @since 3.1.000 (2008-06-09)
10425                  * @access public
10426                  */
10427                 public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
10428                         if ($this->empty_string($code)) {
10429                                 return;
10430                         }
10431                         require_once(dirname(__FILE__).'/barcodes.php');
10432                         // save current graphic settings
10433                         $gvars = $this->getGraphicVars();
10434                         // create new barcode object
10435                         $barcodeobj = new TCPDFBarcode($code, $type);
10436                         $arrcode = $barcodeobj->getBarcodeArray();
10437                         if ($arrcode === false) {
10438                                 $this->Error('Error in 1D barcode string');
10439                         }
10440                         // set default values
10441                         if (!isset($style['position'])) {
10442                                 if ($this->rtl) {
10443                                         $style['position'] = 'R';
10444                                 } else {
10445                                         $style['position'] = 'L';
10446                                 }
10447                         }
10448                         if (!isset($style['padding'])) {
10449                                 $style['padding'] = 0;
10450                         }
10451                         if (!isset($style['fgcolor'])) {
10452                                 $style['fgcolor'] = array(0,0,0); // default black
10453                         }
10454                         if (!isset($style['bgcolor'])) {
10455                                 $style['bgcolor'] = false; // default transparent
10456                         }
10457                         if (!isset($style['border'])) {
10458                                 $style['border'] = false;
10459                         }
10460                         if (!isset($style['text'])) {
10461                                 $style['text'] = false;
10462                                 $fontsize = 0;
10463                         }
10464                         if ($style['text'] AND isset($style['font'])) {
10465                                 if (isset($style['fontsize'])) {
10466                                         $fontsize = $style['fontsize'];
10467                                 } else {
10468                                         $fontsize = 0;
10469                                 }
10470                                 $this->SetFont($style['font'], '', $fontsize);
10471                         }
10472                         if (!isset($style['stretchtext'])) {
10473                                 $style['stretchtext'] = 4;
10474                         }
10475                         // set foreground color
10476                         $this->SetDrawColorArray($style['fgcolor']);
10477                         $this->SetTextColorArray($style['fgcolor']);
10478                         if ($this->empty_string($w) OR ($w <= 0)) {
10479                                 if ($this->rtl) {
10480                                         $w = $this->x - $this->lMargin;
10481                                 } else {
10482                                         $w = $this->w - $this->rMargin - $this->x;
10483                                 }
10484                         }
10485                         if ($this->empty_string($x)) {
10486                                 $x = $this->GetX();
10487                         }
10488                         if ($this->rtl) {
10489                                 $x = $this->w - $x;
10490                         }
10491                         if ($this->empty_string($y)) {
10492                                 $y = $this->GetY();
10493                         }
10494                         if ($this->empty_string($xres)) {
10495                                 $xres = 0.4;
10496                         }
10497                         $fbw = ($arrcode['maxw'] * $xres) + (2 * $style['padding']);
10498                         $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style['padding']);
10499                         if ($this->empty_string($h) OR ($h <= 0)) {
10500                                 $h = 10 + $extraspace;
10501                         }
10502                         if ($this->checkPageBreak($h)) {
10503                                 $y = $this->y;
10504                         }
10505                         // maximum bar heigth
10506                         $barh = $h - $extraspace;
10507                         switch ($style['position']) {
10508                                 case 'L': { // left
10509                                         if ($this->rtl) {
10510                                                 $xpos = $x - $w;
10511                                         } else {
10512                                                 $xpos = $x;
10513                                         }
10514                                         break;
10515                                 }
10516                                 case 'C': { // center
10517                                         $xdiff = (($w - $fbw) / 2);
10518                                         if ($this->rtl) {
10519                                                 $xpos = $x - $w + $xdiff;
10520                                         } else {
10521                                                 $xpos = $x + $xdiff;
10522                                         }
10523                                         break;
10524                                 }
10525                                 case 'R': { // right
10526                                         if ($this->rtl) {
10527                                                 $xpos = $x - $fbw;
10528                                         } else {
10529                                                 $xpos = $x + $w - $fbw;
10530                                         }
10531                                         break;
10532                                 }
10533                                 case 'S': { // stretch
10534                                         $fbw = $w;
10535                                         $xres = ($w - (2 * $style['padding'])) / $arrcode['maxw'];
10536                                         if ($this->rtl) {
10537                                                 $xpos = $x - $w;
10538                                         } else {
10539                                                 $xpos = $x;
10540                                         }
10541                                         break;
10542                                 }
10543                         }
10544                         $xpos_rect = $xpos;
10545                         $xpos = $xpos_rect + $style['padding'];
10546                         $xpos_text = $xpos;
10547                         // barcode is always printed in LTR direction
10548                         $tempRTL = $this->rtl;
10549                         $this->rtl = false;
10550                         // print background color
10551                         if ($style['bgcolor']) {
10552                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style['bgcolor']);
10553                         } elseif ($style['border']) {
10554                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
10555                         }
10556                         // print bars
10557                         if ($arrcode !== false) {
10558                                 foreach ($arrcode['bcode'] as $k => $v) {
10559                                         $bw = ($v['w'] * $xres);
10560                                         if ($v['t']) {
10561                                                 // draw a vertical bar
10562                                                 $ypos = $y + $style['padding'] + ($v['p'] * $barh / $arrcode['maxh']);
10563                                                 $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh  / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
10564                                         }
10565                                         $xpos += $bw;
10566                                 }
10567                         }
10568                         // print text
10569                         if ($style['text']) {
10570                                 // print text
10571                                 $this->x = $xpos_text;
10572                                 $this->y = $y + $style['padding'] + $barh;
10573                                 $this->Cell(($arrcode['maxw'] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style['stretchtext']);
10574                         }
10575                         // restore original direction
10576                         $this->rtl = $tempRTL;
10577                         // restore previous settings
10578                         $this->setGraphicVars($gvars);
10579                         // set bottomcoordinates
10580                         $this->img_rb_y = $y + $h;
10581                         if ($this->rtl) {
10582                                 // set left side coordinate
10583                                 $this->img_rb_x = ($this->w - $x - $w);
10584                         } else {
10585                                 // set right side coordinate
10586                                 $this->img_rb_x = $x + $w;
10587                         }
10588                         // set pointer to align the successive text/objects
10589                         switch($align) {
10590                                 case 'T':{
10591                                         $this->y = $y;
10592                                         $this->x = $this->img_rb_x;
10593                                         break;
10594                                 }
10595                                 case 'M':{
10596                                         $this->y = $y + round($h/2);
10597                                         $this->x = $this->img_rb_x;
10598                                         break;
10599                                 }
10600                                 case 'B':{
10601                                         $this->y = $this->img_rb_y;
10602                                         $this->x = $this->img_rb_x;
10603                                         break;
10604                                 }
10605                                 case 'N':{
10606                                         $this->SetY($this->img_rb_y);
10607                                         break;
10608                                 }
10609                                 default:{
10610                                         break;
10611                                 }
10612                         }
10613                 }
10614
10615                 /**
10616                  * This function is DEPRECATED, please use the new write1DBarcode() function.
10617                  * @param int $x x position in user units
10618                  * @param int $y y position in user units
10619                  * @param int $w width in user units
10620                  * @param int $h height position in user units
10621                  * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
10622                  * @param string $style barcode style
10623                  * @param string $font font for text
10624                  * @param int $xres x resolution
10625                  * @param string $code code to print
10626                  * @deprecated deprecated since version 3.1.000 (2008-06-10)
10627                  * @access public
10628                  * @see write1DBarcode()
10629                  */
10630                 public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
10631                         // convert old settings for the new write1DBarcode() function.
10632                         $xres = 1 / $xres;
10633                         $newstyle = array(
10634                                 'position' => 'L',
10635                                 'border' => false,
10636                                 'padding' => 0,
10637                                 'fgcolor' => array(0,0,0),
10638                                 'bgcolor' => false,
10639                                 'text' => true,
10640                                 'font' => $font,
10641                                 'fontsize' => 8,
10642                                 'stretchtext' => 4
10643                         );
10644                         if ($style & 1) {
10645                                 $newstyle['border'] = true;
10646                         }
10647                         if ($style & 2) {
10648                                 $newstyle['bgcolor'] = false;
10649                         }
10650                         if ($style & 4) {
10651                                 $newstyle['position'] = 'C';
10652                         } elseif ($style & 8) {
10653                                 $newstyle['position'] = 'L';
10654                         } elseif ($style & 16) {
10655                                 $newstyle['position'] = 'R';
10656                         }
10657                         if ($style & 128) {
10658                                 $newstyle['text'] = true;
10659                         }
10660                         if ($style & 256) {
10661                                 $newstyle['stretchtext'] = 4;
10662                         }
10663                         $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
10664                 }
10665
10666                 /**
10667                  * Print 2D Barcode.
10668                  * @param string $code code to print
10669                  * @param string $type type of barcode.
10670                  * @param int $x x position in user units
10671                  * @param int $y y position in user units
10672                  * @param int $w width in user units
10673                  * @param int $h height in user units
10674                  * @param array $style array of options:<ul><li>boolean $style['border'] if true prints a border around the barcode</li><li>int $style['padding'] padding to leave around the barcode in user units</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background or false for transparent</li></ul>
10675                  * @param string $align Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
10676                  * @author Nicola Asuni
10677                  * @since 4.5.037 (2009-04-07)
10678                  * @access public
10679                  */
10680                 public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='') {
10681                         if ($this->empty_string($code)) {
10682                                 return;
10683                         }
10684                         require_once(dirname(__FILE__).'/2dbarcodes.php');
10685                         // save current graphic settings
10686                         $gvars = $this->getGraphicVars();
10687                         // create new barcode object
10688                         $barcodeobj = new TCPDF2DBarcode($code, $type);
10689                         $arrcode = $barcodeobj->getBarcodeArray();
10690                         if ($arrcode === false) {
10691                                 $this->Error('Error in 2D barcode string');
10692                         }
10693                         // set default values
10694                         if (!isset($style['padding'])) {
10695                                 $style['padding'] = 0;
10696                         }
10697                         if (!isset($style['fgcolor'])) {
10698                                 $style['fgcolor'] = array(0,0,0); // default black
10699                         }
10700                         if (!isset($style['bgcolor'])) {
10701                                 $style['bgcolor'] = false; // default transparent
10702                         }
10703                         if (!isset($style['border'])) {
10704                                 $style['border'] = false;
10705                         }
10706                         // set foreground color
10707                         $this->SetDrawColorArray($style['fgcolor']);
10708                         if ($this->empty_string($x)) {
10709                                 $x = $this->GetX();
10710                         }
10711                         if ($this->rtl) {
10712                                 $x = $this->w - $x;
10713                         }
10714                         if ($this->empty_string($y)) {
10715                                 $y = $this->GetY();
10716                         }
10717                         if ($this->empty_string($w) OR ($w <= 0)) {
10718                                 if ($this->rtl) {
10719                                         $w = $x - $this->lMargin;
10720                                 } else {
10721                                         $w = $this->w - $this->rMargin - $x;
10722                                 }
10723                         }
10724                         if ($this->empty_string($h) OR ($h <= 0)) {
10725                                 // 2d barcodes are square by default
10726                                 $h = $w;
10727                         }
10728                         if ($this->checkPageBreak($h)) {
10729                                 $y = $this->y;
10730                         }
10731                         // calculate barcode size (excluding padding)
10732                         $bw = $w - (2 * $style['padding']);
10733                         $bh = $h - (2 * $style['padding']);
10734                         // calculate starting coordinates
10735                         if ($this->rtl) {
10736                                 $xpos = $x - $w;
10737                         } else {
10738                                 $xpos = $x;
10739                         }
10740                         $xpos += $style['padding'];
10741                         $ypos = $y + $style['padding'];
10742                         // barcode is always printed in LTR direction
10743                         $tempRTL = $this->rtl;
10744                         $this->rtl = false;
10745                         // print background color
10746                         if ($style['bgcolor']) {
10747                                 $this->Rect($x, $y, $w, $h, 'DF', '', $style['bgcolor']);
10748                         } elseif ($style['border']) {
10749                                 $this->Rect($x, $y, $w, $h, 'D');
10750                         }
10751                         // print barcode cells
10752                         if ($arrcode !== false) {
10753                                 $rows = $arrcode['num_rows'];
10754                                 $cols = $arrcode['num_cols'];
10755                                 // calculate dimension of single barcode cell
10756                                 $cw = $bw / $cols;
10757                                 $ch = $bh / $rows;
10758                                 // for each row
10759                                 for ($r = 0; $r < $rows; ++$r) {
10760                                         $xr = $xpos;
10761                                         // for each column
10762                                         for ($c = 0; $c < $cols; ++$c) {
10763                                                 if ($arrcode['bcode'][$r][$c] == 1) {
10764                                                         // draw a single barcode cell
10765                                                         $this->Rect($xr, $ypos, $cw, $ch, 'F', array(), $style['fgcolor']);
10766                                                 }
10767                                                 $xr += $cw;
10768                                         }
10769                                         $ypos += $ch;
10770                                 }
10771                         }
10772                         // restore original direction
10773                         $this->rtl = $tempRTL;
10774                         // restore previous settings
10775                         $this->setGraphicVars($gvars);
10776                         // set bottomcoordinates
10777                         $this->img_rb_y = $y + $h;
10778                         if ($this->rtl) {
10779                                 // set left side coordinate
10780                                 $this->img_rb_x = ($this->w - $x - $w);
10781                         } else {
10782                                 // set right side coordinate
10783                                 $this->img_rb_x = $x + $w;
10784                         }
10785                         // set pointer to align the successive text/objects
10786                         switch($align) {
10787                                 case 'T':{
10788                                         $this->y = $y;
10789                                         $this->x = $this->img_rb_x;
10790                                         break;
10791                                 }
10792                                 case 'M':{
10793                                         $this->y = $y + round($h/2);
10794                                         $this->x = $this->img_rb_x;
10795                                         break;
10796                                 }
10797                                 case 'B':{
10798                                         $this->y = $this->img_rb_y;
10799                                         $this->x = $this->img_rb_x;
10800                                         break;
10801                                 }
10802                                 case 'N':{
10803                                         $this->SetY($this->img_rb_y);
10804                                         break;
10805                                 }
10806                                 default:{
10807                                         break;
10808                                 }
10809                         }
10810                 }
10811
10812                 /**
10813                  * Returns an array containing current margins:
10814                  * <ul>
10815                                 <li>$ret['left'] = left  margin</li>
10816                                 <li>$ret['right'] = right margin</li>
10817                                 <li>$ret['top'] = top margin</li>
10818                                 <li>$ret['bottom'] = bottom margin</li>
10819                                 <li>$ret['header'] = header margin</li>
10820                                 <li>$ret['footer'] = footer margin</li>
10821                                 <li>$ret['cell'] = cell margin</li>
10822                  * </ul>
10823                  * @return array containing all margins measures
10824                  * @access public
10825                  * @since 3.2.000 (2008-06-23)
10826                  */
10827                 public function getMargins() {
10828                         $ret = array(
10829                                 'left' => $this->lMargin,
10830                                 'right' => $this->rMargin,
10831                                 'top' => $this->tMargin,
10832                                 'bottom' => $this->bMargin,
10833                                 'header' => $this->header_margin,
10834                                 'footer' => $this->footer_margin,
10835                                 'cell' => $this->cMargin,
10836                         );
10837                         return $ret;
10838                 }
10839
10840                 /**
10841                  * Returns an array containing original margins:
10842                  * <ul>
10843                                 <li>$ret['left'] = left  margin</li>
10844                                 <li>$ret['right'] = right margin</li>
10845                  * </ul>
10846                  * @return array containing all margins measures
10847                  * @access public
10848                  * @since 4.0.012 (2008-07-24)
10849                  */
10850                 public function getOriginalMargins() {
10851                         $ret = array(
10852                                 'left' => $this->original_lMargin,
10853                                 'right' => $this->original_rMargin
10854                         );
10855                         return $ret;
10856                 }
10857
10858                 /**
10859                  * Returns the current font size.
10860                  * @return current font size
10861                  * @access public
10862                  * @since 3.2.000 (2008-06-23)
10863                  */
10864                 public function getFontSize() {
10865                         return $this->FontSize;
10866                 }
10867
10868                 /**
10869                  * Returns the current font size in points unit.
10870                  * @return current font size in points unit
10871                  * @access public
10872                  * @since 3.2.000 (2008-06-23)
10873                  */
10874                 public function getFontSizePt() {
10875                         return $this->FontSizePt;
10876                 }
10877
10878                 /**
10879                  * Returns the current font family name.
10880                  * @return string current font family name
10881                  * @access public
10882                  * @since 4.3.008 (2008-12-05)
10883                  */
10884                 public function getFontFamily() {
10885                         return $this->FontFamily;
10886                 }
10887
10888                 /**
10889                  * Returns the current font style.
10890                  * @return string current font style
10891                  * @access public
10892                  * @since 4.3.008 (2008-12-05)
10893                  */
10894                 public function getFontStyle() {
10895                         return $this->FontStyle;
10896                 }
10897
10898                 /**
10899                  * Prints a cell (rectangular area) with optional borders, background color and html text string.
10900                  * The upper-left corner of the cell corresponds to the current position. After the call, the current position moves to the right or to the next line.<br />
10901                  * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
10902                  * @param float $w Cell width. If 0, the cell extends up to the right margin.
10903                  * @param float $h Cell minimum height. The cell extends automatically if needed.
10904                  * @param float $x upper-left corner X coordinate
10905                  * @param float $y upper-left corner Y coordinate
10906                  * @param string $html html text to print. Default value: empty string.
10907                  * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
10908                  * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL language)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
10909         Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
10910                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
10911                  * @param boolean $reseth if true reset the last cell height (default true).
10912                  * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
10913                  * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
10914                  * @access public
10915                  * @uses MultiCell()
10916                  * @see Multicell(), writeHTML()
10917                  */
10918                 public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true) {
10919                         return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0);
10920                 }
10921
10922                 /**
10923                  * Returns the HTML DOM array.
10924                  * <ul><li>$dom[$key]['tag'] = true if tag, false otherwise;</li><li>$dom[$key]['value'] = tag name or text;</li><li>$dom[$key]['opening'] = true if opening tag, false otherwise;</li><li>$dom[$key]['attribute'] = array of attributes (attribute name is the key);</li><li>$dom[$key]['style'] = array of style attributes (attribute name is the key);</li><li>$dom[$key]['parent'] = id of parent element;</li><li>$dom[$key]['fontname'] = font family name;</li><li>$dom[$key]['fontstyle'] = font style;</li><li>$dom[$key]['fontsize'] = font size in points;</li><li>$dom[$key]['bgcolor'] = RGB array of background color;</li><li>$dom[$key]['fgcolor'] = RGB array of foreground color;</li><li>$dom[$key]['width'] = width in pixels;</li><li>$dom[$key]['height'] = height in pixels;</li><li>$dom[$key]['align'] = text alignment;</li><li>$dom[$key]['cols'] = number of colums in table;</li><li>$dom[$key]['rows'] = number of rows in table;</li></ul>
10925                  * @param string $html html code
10926                  * @return array
10927                  * @access protected
10928                  * @since 3.2.000 (2008-06-20)
10929                  */
10930                 protected function getHtmlDomArray($html) {
10931                         // remove all unsupported tags (the line below lists all supported tags)
10932                         $html = strip_tags($html, '<marker/><a><b><blockquote><br><br/><dd><del><div><dl><dt><em><font><h1><h2><h3><h4><h5><h6><hr><i><img><li><ol><p><pre><small><span><strong><sub><sup><table><tcpdf><td><th><thead><tr><tt><u><ul>');
10933                         //replace some blank characters
10934                         $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
10935                         $html = preg_replace('/<(table|tr|td|th|tcpdf|blockquote|dd|div|dt|h1|h2|h3|h4|h5|h6|br|hr|li|ol|ul|p)([^\>]*)>[\n\r\t]+/', '<\\1\\2>', $html);
10936                         $html = preg_replace('@(\r\n|\r)@', "\n", $html);
10937                         $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
10938                         $html = strtr($html, $repTable);
10939                         while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html)) {
10940                                 // preserve newlines on <pre> tag
10941                                 $html = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html);
10942                         }
10943                         $html = str_replace("\n", ' ', $html);
10944                         // remove extra spaces from code
10945                         $html = preg_replace('/[\s]+<\/(table|tr|td|th|ul|ol|li)>/', '</\\1>', $html);
10946                         $html = preg_replace('/[\s]+<(tr|td|th|ul|ol|li|br)/', '<\\1', $html);
10947                         $html = preg_replace('/<\/(table|tr|td|th|blockquote|dd|div|dt|h1|h2|h3|h4|h5|h6|hr|li|ol|ul|p)>[\s]+</', '</\\1><', $html);
10948                         $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
10949                         $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
10950                         $html = preg_replace('/<img/', ' <img', $html);
10951                         $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span></span>', $html);
10952                         $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
10953                         // trim string
10954                         $html = preg_replace('/^[\s]+/', '', $html);
10955                         $html = preg_replace('/[\s]+$/', '', $html);
10956                         // pattern for generic tag
10957                         $tagpattern = '/(<[^>]+>)/';
10958                         // explodes the string
10959                         $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
10960                         // count elements
10961                         $maxel = count($a);
10962                         $elkey = 0;
10963                         $key = 0;
10964                         // create an array of elements
10965                         $dom = array();
10966                         $dom[$key] = array();
10967                         // set first void element
10968                         $dom[$key]['tag'] = false;
10969                         $dom[$key]['value'] = '';
10970                         $dom[$key]['parent'] = 0;
10971                         $dom[$key]['fontname'] = $this->FontFamily;
10972                         $dom[$key]['fontstyle'] = $this->FontStyle;
10973                         $dom[$key]['fontsize'] = $this->FontSizePt;
10974                         $dom[$key]['bgcolor'] = false;
10975                         $dom[$key]['fgcolor'] = $this->fgcolor;
10976                         $dom[$key]['align'] = '';
10977                         $dom[$key]['listtype'] = '';
10978                         $thead = false; // true when we are inside the THEAD tag
10979                         ++$key;
10980                         $level = array();
10981                         array_push($level, 0); // root
10982                         while ($elkey < $maxel) {
10983                                 $dom[$key] = array();
10984                                 $element = $a[$elkey];
10985                                 $dom[$key]['elkey'] = $elkey;
10986                                 if (preg_match($tagpattern, $element)) {
10987                                         // html tag
10988                                         $element = substr($element, 1, -1);
10989                                         // get tag name
10990                                         preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
10991                                         $tagname = strtolower($tag[1]);
10992                                         // check if we are inside a table header
10993                                         if ($tagname == 'thead') {
10994                                                 if ($element{0} == '/') {
10995                                                         $thead = false;
10996                                                 } else {
10997                                                         $thead = true;
10998                                                 }
10999                                                 ++$elkey;
11000                                                 continue;
11001                                         }
11002                                         $dom[$key]['tag'] = true;
11003                                         $dom[$key]['value'] = $tagname;
11004                                         if ($element{0} == '/') {
11005                                                 // closing html tag
11006                                                 $dom[$key]['opening'] = false;
11007                                                 $dom[$key]['parent'] = end($level);
11008                                                 array_pop($level);
11009                                                 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
11010                                                 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
11011                                                 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
11012                                                 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
11013                                                 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
11014                                                 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
11015                                                 if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
11016                                                         $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
11017                                                 }
11018                                                 // set the number of columns in table tag
11019                                                 if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
11020                                                         $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
11021                                                 }
11022                                                 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
11023                                                         $dom[($dom[$key]['parent'])]['content'] = '';
11024                                                         for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
11025                                                                 $dom[($dom[$key]['parent'])]['content'] .= $a[$dom[$i]['elkey']];
11026                                                         }
11027                                                         $key = $i;
11028                                                 }
11029                                                 // store header rows on a new table
11030                                                 if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] == true)) {
11031                                                         if ($this->empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
11032                                                                 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
11033                                                         }
11034                                                         for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
11035                                                                 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
11036                                                         }
11037                                                 }
11038                                                 if (($dom[$key]['value'] == 'table') AND (!$this->empty_string($dom[($dom[$key]['parent'])]['thead']))) {
11039                                                         $dom[($dom[$key]['parent'])]['thead'] .= '</table>';
11040                                                 }
11041                                         } else {
11042                                                 // opening html tag
11043                                                 $dom[$key]['opening'] = true;
11044                                                 $dom[$key]['parent'] = end($level);
11045                                                 if (substr($element, -1, 1) != '/') {
11046                                                         // not self-closing tag
11047                                                         array_push($level, $key);
11048                                                         $dom[$key]['self'] = false;
11049                                                 } else {
11050                                                         $dom[$key]['self'] = true;
11051                                                 }
11052                                                 // copy some values from parent
11053                                                 $parentkey = 0;
11054                                                 if ($key > 0) {
11055                                                         $parentkey = $dom[$key]['parent'];
11056                                                         $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
11057                                                         $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
11058                                                         $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
11059                                                         $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
11060                                                         $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
11061                                                         $dom[$key]['align'] = $dom[$parentkey]['align'];
11062                                                         $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
11063                                                 }
11064                                                 // get attributes
11065                                                 preg_match_all('/([^=\s]*)=["]?([^"]*)["]?/', $element, $attr_array, PREG_PATTERN_ORDER);
11066                                                 $dom[$key]['attribute'] = array(); // reset attribute array
11067                                                 while (list($id, $name) = each($attr_array[1])) {
11068                                                         $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
11069                                                 }
11070                                                 // split style attributes
11071                                                 if (isset($dom[$key]['attribute']['style'])) {
11072                                                         // get style attributes
11073                                                         preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
11074                                                         $dom[$key]['style'] = array(); // reset style attribute array
11075                                                         while (list($id, $name) = each($style_array[1])) {
11076                                                                 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
11077                                                         }
11078                                                         // --- get some style attributes ---
11079                                                         if (isset($dom[$key]['style']['font-family'])) {
11080                                                                 // font family
11081                                                                 if (isset($dom[$key]['style']['font-family'])) {
11082                                                                         $fontslist = explode(',', strtolower($dom[$key]['style']['font-family']));
11083                                                                         foreach ($fontslist as $font) {
11084                                                                                 $font = trim(strtolower($font));
11085                                                                                 if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
11086                                                                                         $dom[$key]['fontname'] = $font;
11087                                                                                         break;
11088                                                                                 }
11089                                                                         }
11090                                                                 }
11091                                                         }
11092                                                         // list-style-type
11093                                                         if (isset($dom[$key]['style']['list-style-type'])) {
11094                                                                 $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
11095                                                                 if ($dom[$key]['listtype'] == 'inherit') {
11096                                                                         $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
11097                                                                 }
11098                                                         }
11099                                                         // font size
11100                                                         if (isset($dom[$key]['style']['font-size'])) {
11101                                                                 $fsize = trim($dom[$key]['style']['font-size']);
11102                                                                 switch ($fsize) {
11103                                                                         // absolute-size
11104                                                                         case 'xx-small': {
11105                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
11106                                                                                 break;
11107                                                                         }
11108                                                                         case 'x-small': {
11109                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
11110                                                                                 break;
11111                                                                         }
11112                                                                         case 'small': {
11113                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
11114                                                                                 break;
11115                                                                         }
11116                                                                         case 'medium': {
11117                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
11118                                                                                 break;
11119                                                                         }
11120                                                                         case 'large': {
11121                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
11122                                                                                 break;
11123                                                                         }
11124                                                                         case 'x-large': {
11125                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
11126                                                                                 break;
11127                                                                         }
11128                                                                         case 'xx-large': {
11129                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
11130                                                                                 break;
11131                                                                         }
11132                                                                         // relative-size
11133                                                                         case 'smaller': {
11134                                                                                 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] - 3;
11135                                                                                 break;
11136                                                                         }
11137                                                                         case 'larger': {
11138                                                                                 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] + 3;
11139                                                                                 break;
11140                                                                         }
11141                                                                         default: {
11142                                                                                 $dom[$key]['fontsize'] = $this->getHTMLUnitToUnits($fsize, $dom[$parentkey]['fontsize'], 'pt', true);
11143                                                                         }
11144                                                                 }
11145                                                         }
11146                                                         // font style
11147                                                         if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == 'b')) {
11148                                                                 $dom[$key]['fontstyle'] .= 'B';
11149                                                         }
11150                                                         if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == 'i')) {
11151                                                                 $dom[$key]['fontstyle'] .= '"I';
11152                                                         }
11153                                                         // font color
11154                                                         if (isset($dom[$key]['style']['color']) AND (!$this->empty_string($dom[$key]['style']['color']))) {
11155                                                                 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
11156                                                         }
11157                                                         // background color
11158                                                         if (isset($dom[$key]['style']['background-color']) AND (!$this->empty_string($dom[$key]['style']['background-color']))) {
11159                                                                 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
11160                                                         }
11161                                                         // text-decoration
11162                                                         if (isset($dom[$key]['style']['text-decoration'])) {
11163                                                                 $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
11164                                                                 foreach ($decors as $dec) {
11165                                                                         $dec = trim($dec);
11166                                                                         if (!$this->empty_string($dec)) {
11167                                                                                 if ($dec{0} == 'u') {
11168                                                                                         $dom[$key]['fontstyle'] .= 'U';
11169                                                                                 } elseif ($dec{0} == 'l') {
11170                                                                                         $dom[$key]['fontstyle'] .= 'D';
11171                                                                                 }
11172                                                                         }
11173                                                                 }
11174                                                         }
11175                                                         // check for width attribute
11176                                                         if (isset($dom[$key]['style']['width'])) {
11177                                                                 $dom[$key]['width'] = $dom[$key]['style']['width'];
11178                                                         }
11179                                                         // check for height attribute
11180                                                         if (isset($dom[$key]['style']['height'])) {
11181                                                                 $dom[$key]['height'] = $dom[$key]['style']['height'];
11182                                                         }
11183                                                         // check for text alignment
11184                                                         if (isset($dom[$key]['style']['text-align'])) {
11185                                                                 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
11186                                                         }
11187                                                         // check for border attribute
11188                                                         if (isset($dom[$key]['style']['border'])) {
11189                                                                 $dom[$key]['attribute']['border'] = $dom[$key]['style']['border'];
11190                                                         }
11191                                                 }
11192                                                 // check for font tag
11193                                                 if ($dom[$key]['value'] == 'font') {
11194                                                         // font family
11195                                                         if (isset($dom[$key]['attribute']['face'])) {
11196                                                                 $fontslist = explode(',', strtolower($dom[$key]['attribute']['face']));
11197                                                                 foreach ($fontslist as $font) {
11198                                                                         $font = trim(strtolower($font));
11199                                                                         if (in_array($font, $this->fontlist) OR in_array($font, $this->fontkeys)) {
11200                                                                                 $dom[$key]['fontname'] = $font;
11201                                                                                 break;
11202                                                                         }
11203                                                                 }
11204                                                         }
11205                                                         // font size
11206                                                         if (isset($dom[$key]['attribute']['size'])) {
11207                                                                 if ($key > 0) {
11208                                                                         if ($dom[$key]['attribute']['size']{0} == '+') {
11209                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
11210                                                                         } elseif ($dom[$key]['attribute']['size']{0} == '-') {
11211                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
11212                                                                         } else {
11213                                                                                 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
11214                                                                         }
11215                                                                 } else {
11216                                                                         $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
11217                                                                 }
11218                                                         }
11219                                                 }
11220                                                 // force natural alignment for lists
11221                                                 if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
11222                                                         AND (!isset($dom[$key]['align']) OR $this->empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
11223                                                         if ($this->rtl) {
11224                                                                 $dom[$key]['align'] = 'R';
11225                                                         } else {
11226                                                                 $dom[$key]['align'] = 'L';
11227                                                         }
11228                                                 }
11229                                                 if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
11230                                                         $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
11231                                                 }
11232                                                 if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
11233                                                         $dom[$key]['fontstyle'] .= 'B';
11234                                                 }
11235                                                 if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
11236                                                         $dom[$key]['fontstyle'] .= 'I';
11237                                                 }
11238                                                 if ($dom[$key]['value'] == 'u') {
11239                                                         $dom[$key]['fontstyle'] .= 'U';
11240                                                 }
11241                                                 if ($dom[$key]['value'] == 'del') {
11242                                                         $dom[$key]['fontstyle'] .= 'D';
11243                                                 }
11244                                                 if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
11245                                                         $dom[$key]['fontname'] = $this->default_monospaced_font;
11246                                                 }
11247                                                 if (($dom[$key]['value']{0} == 'h') AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
11248                                                         $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
11249                                                         $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
11250                                                         $dom[$key]['fontstyle'] .= 'B';
11251                                                 }
11252                                                 if (($dom[$key]['value'] == 'table')) {
11253                                                         $dom[$key]['rows'] = 0; // number of rows
11254                                                         $dom[$key]['trids'] = array(); // IDs of TR elements
11255                                                         $dom[$key]['thead'] = ''; // table header rows
11256                                                 }
11257                                                 if (($dom[$key]['value'] == 'tr')) {
11258                                                         $dom[$key]['cols'] = 0;
11259                                                         // store the number of rows on table element
11260                                                         ++$dom[($dom[$key]['parent'])]['rows'];
11261                                                         // store the TR elements IDs on table element
11262                                                         array_push($dom[($dom[$key]['parent'])]['trids'], $key);
11263                                                         if ($thead) {
11264                                                                 $dom[$key]['thead'] = true;
11265                                                         } else {
11266                                                                 $dom[$key]['thead'] = false;
11267                                                         }
11268                                                 }
11269                                                 if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
11270                                                         if (isset($dom[$key]['attribute']['colspan'])) {
11271                                                                 $colspan = intval($dom[$key]['attribute']['colspan']);
11272                                                         } else {
11273                                                                 $colspan = 1;
11274                                                         }
11275                                                         $dom[$key]['attribute']['colspan'] = $colspan;
11276                                                         $dom[($dom[$key]['parent'])]['cols'] += $colspan;
11277                                                 }
11278                                                 // set foreground color attribute
11279                                                 if (isset($dom[$key]['attribute']['color']) AND (!$this->empty_string($dom[$key]['attribute']['color']))) {
11280                                                         $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
11281                                                 }
11282                                                 // set background color attribute
11283                                                 if (isset($dom[$key]['attribute']['bgcolor']) AND (!$this->empty_string($dom[$key]['attribute']['bgcolor']))) {
11284                                                         $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
11285                                                 }
11286                                                 // check for width attribute
11287                                                 if (isset($dom[$key]['attribute']['width'])) {
11288                                                         $dom[$key]['width'] = $dom[$key]['attribute']['width'];
11289                                                 }
11290                                                 // check for height attribute
11291                                                 if (isset($dom[$key]['attribute']['height'])) {
11292                                                         $dom[$key]['height'] = $dom[$key]['attribute']['height'];
11293                                                 }
11294                                                 // check for text alignment
11295                                                 if (isset($dom[$key]['attribute']['align']) AND (!$this->empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
11296                                                         $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
11297                                                 }
11298                                         } // end opening tag
11299                                 } else {
11300                                         // text
11301                                         $dom[$key]['tag'] = false;
11302                                         $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
11303                                         $dom[$key]['parent'] = end($level);
11304                                 }
11305                                 ++$elkey;
11306                                 ++$key;
11307                         }
11308                         return $dom;
11309                 }
11310
11311                 /**
11312                  * Allows to preserve some HTML formatting (limited support).<br />
11313                  * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
11314                  * Supported tags are: a, b, blockquote, br, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, li, ol, p, pre, small, span, strong, sub, sup, table, tcpdf, td, th, thead, tr, tt, u, ul
11315                  * @param string $html text to display
11316                  * @param boolean $ln if true add a new line after text (default = true)
11317                  * @param int $fill Indicates if the background must be painted (true) or transparent (false).
11318                  * @param boolean $reseth if true reset the last cell height (default false).
11319                  * @param boolean $cell if true add the default cMargin space to each Write (default false).
11320                  * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
11321                  * @access public
11322                  */
11323                 public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
11324                         $gvars = $this->getGraphicVars();
11325                         // store current values
11326                         $prevPage = $this->page;
11327                         $prevlMargin = $this->lMargin;
11328                         $prevrMargin = $this->rMargin;
11329                         $curfontname = $this->FontFamily;
11330                         $curfontstyle = $this->FontStyle;
11331                         $curfontsize = $this->FontSizePt;
11332                         $this->newline = true;
11333                         $minstartliney = $this->y;
11334                         $yshift = 0;
11335                         $startlinepage = $this->page;
11336                         $newline = true;
11337                         $loop = 0;
11338                         $curpos = 0;
11339                         $blocktags = array('blockquote','br','dd','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','ul','tcpdf');
11340                         $this->premode = false;
11341                         if (isset($this->PageAnnots[$this->page])) {
11342                                 $pask = count($this->PageAnnots[$this->page]);
11343                         } else {
11344                                 $pask = 0;
11345                         }
11346                         if (isset($this->footerlen[$this->page])) {
11347                                 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11348                         } else {
11349                                 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11350                         }
11351                         $startlinepos = $this->footerpos[$this->page];
11352                         $lalign = $align;
11353                         $plalign = $align;
11354                         if ($this->rtl) {
11355                                 $w = $this->x - $this->lMargin;
11356                         } else {
11357                                 $w = $this->w - $this->rMargin - $this->x;
11358                         }
11359                         $w -= (2 * $this->cMargin);
11360                         if ($cell) {
11361                                 if ($this->rtl) {
11362                                         $this->x -= $this->cMargin;
11363                                 } else {
11364                                         $this->x += $this->cMargin;
11365                                 }
11366                         }
11367                         if ($this->customlistindent >= 0) {
11368                                 $this->listindent = $this->customlistindent;
11369                         } else {
11370                                 $this->listindent = $this->GetStringWidth('0000');
11371                         }
11372                         $this->listnum = 0;
11373                         if (($this->empty_string($this->lasth)) OR ($reseth)) {
11374                                 //set row height
11375                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11376                         }
11377                         $dom = $this->getHtmlDomArray($html);
11378                         $maxel = count($dom);
11379                         $key = 0;
11380                         while ($key < $maxel) {
11381                                 if ($dom[$key]['tag'] OR ($key == 0)) {
11382                                         if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
11383                                                 $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
11384                                         }
11385                                         // vertically align image in line
11386                                         if ((!$this->newline)
11387                                                 AND ($dom[$key]['value'] == 'img')
11388                                                 AND (isset($dom[$key]['attribute']['height']))
11389                                                 AND ($dom[$key]['attribute']['height'] > 0)) {
11390                                                 // get image height
11391                                                 $imgh = $this->getHTMLUnitToUnits($dom[$key]['attribute']['height'], $this->lasth, 'px');
11392                                                 if (!$this->InFooter) {
11393                                                         // check for page break
11394                                                         $this->checkPageBreak($imgh);
11395                                                 }
11396                                                 if ($this->page > $startlinepage) {
11397                                                         // fix lines splitted over two pages
11398                                                         if (isset($this->footerlen[$startlinepage])) {
11399                                                                 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11400                                                         }
11401                                                         // line to be moved one page forward
11402                                                         $pagebuff = $this->getPageBuffer($startlinepage);
11403                                                         $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
11404                                                         $tstart = substr($pagebuff, 0, $startlinepos);
11405                                                         $tend = substr($this->getPageBuffer($startlinepage), $curpos);
11406                                                         // remove line start from previous page
11407                                                         $this->setPageBuffer($startlinepage, $tstart.''.$tend);
11408                                                         $pagebuff = $this->getPageBuffer($this->page);
11409                                                         $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
11410                                                         $tend = substr($pagebuff, $this->intmrk[$this->page]);
11411                                                         // add line start to current page
11412                                                         $yshift = $minstartliney - $this->y;
11413                                                         $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
11414                                                         $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
11415                                                         // shift the annotations and links
11416                                                         if (isset($this->PageAnnots[$startlinepage])) {
11417                                                                 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
11418                                                                         if ($pak >= $pask) {
11419                                                                                 $this->PageAnnots[$this->page][] = $pac;
11420                                                                                 unset($this->PageAnnots[$startlinepage][$pak]);
11421                                                                                 $npak = count($this->PageAnnots[$this->page]) - 1;
11422                                                                                 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
11423                                                                         }
11424                                                                 }
11425                                                         }
11426                                                         $startlinepos = $this->intmrk[$this->page];
11427                                                         $startlinepage = $this->page;
11428                                                         $startliney = $this->y;
11429                                                 }
11430
11431                                                 $this->y += (($curfontsize / $this->k) - $imgh);
11432                                                 $minstartliney = min($this->y, $minstartliney);
11433
11434                                         } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
11435                                                 // account for different font size
11436                                                 $pfontname = $curfontname;
11437                                                 $pfontstyle = $curfontstyle;
11438                                                 $pfontsize = $curfontsize;
11439                                                 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
11440                                                 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
11441                                                 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
11442                                                 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
11443                                                         $this->SetFont($fontname, $fontstyle, $fontsize);
11444                                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
11445                                                         if (is_numeric($fontsize) AND ($fontsize > 0)
11446                                                                 AND is_numeric($curfontsize) AND ($curfontsize > 0)
11447                                                                 AND ($fontsize != $curfontsize) AND (!$this->newline)
11448                                                                 AND ($key < ($maxel - 1))
11449                                                                 ) {
11450                                                                 if ((!$this->newline) AND ($this->page > $startlinepage)) {
11451                                                                         // fix lines splitted over two pages
11452                                                                         if (isset($this->footerlen[$startlinepage])) {
11453                                                                                 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11454                                                                         }
11455                                                                         // line to be moved one page forward
11456                                                                         $pagebuff = $this->getPageBuffer($startlinepage);
11457                                                                         $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
11458                                                                         $tstart = substr($pagebuff, 0, $startlinepos);
11459                                                                         $tend = substr($this->getPageBuffer($startlinepage), $curpos);
11460                                                                         // remove line start from previous page
11461                                                                         $this->setPageBuffer($startlinepage, $tstart.''.$tend);
11462                                                                         $pagebuff = $this->getPageBuffer($this->page);
11463                                                                         $tstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
11464                                                                         $tend = substr($pagebuff, $this->intmrk[$this->page]);
11465                                                                         // add line start to current page
11466                                                                         $yshift = $minstartliney - $this->y;
11467                                                                         $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
11468                                                                         $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
11469                                                                         // shift the annotations and links
11470                                                                         if (isset($this->PageAnnots[$startlinepage])) {
11471                                                                                 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
11472                                                                                         if ($pak >= $pask) {
11473                                                                                                 $this->PageAnnots[$this->page][] = $pac;
11474                                                                                                 unset($this->PageAnnots[$startlinepage][$pak]);
11475                                                                                                 $npak = count($this->PageAnnots[$this->page]) - 1;
11476                                                                                                 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
11477                                                                                         }
11478                                                                                 }
11479                                                                         }
11480                                                                 }
11481                                                                 $this->y += (($curfontsize - $fontsize) / $this->k);
11482                                                                 $minstartliney = min($this->y, $minstartliney);
11483                                                         }
11484                                                         $curfontname = $fontname;
11485                                                         $curfontstyle = $fontstyle;
11486                                                         $curfontsize = $fontsize;
11487                                                 }
11488                                         }
11489                                         if (($plalign == 'J') AND (in_array($dom[$key]['value'], $blocktags))) {
11490                                                 $plalign = '';
11491                                         }
11492                                         // get current position on page buffer
11493                                         $curpos = $this->pagelen[$startlinepage];
11494                                         if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
11495                                                 $this->SetFillColorArray($dom[$key]['bgcolor']);
11496                                                 $wfill = true;
11497                                         } else {
11498                                                 $wfill = $fill | false;
11499                                         }
11500                                         if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
11501                                                 $this->SetTextColorArray($dom[$key]['fgcolor']);
11502                                         }
11503                                         if (isset($dom[$key]['align'])) {
11504                                                 $lalign = $dom[$key]['align'];
11505                                         }
11506                                         if ($this->empty_string($lalign)) {
11507                                                 $lalign = $align;
11508                                         }
11509                                 }
11510                                 // align lines
11511                                 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
11512                                         $newline = true;
11513                                         // we are at the beginning of a new line
11514                                         if (isset($startlinex)) {
11515                                                 $yshift = $minstartliney - $startliney;
11516                                                 if (($yshift > 0) OR ($this->page > $startlinepage)) {
11517                                                         $yshift = 0;
11518                                                 }
11519                                                 if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
11520                                                         // the last line must be shifted to be aligned as requested
11521                                                         $linew = abs($this->endlinex - $startlinex);
11522                                                         $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
11523                                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
11524                                                                 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11525                                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
11526                                                         } elseif (isset($opentagpos)) {
11527                                                                 $midpos = $opentagpos;
11528                                                         } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
11529                                                                 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
11530                                                                 $midpos = $this->footerpos[$startlinepage];
11531                                                         } else {
11532                                                                 $midpos = 0;
11533                                                         }
11534                                                         if ($midpos > 0) {
11535                                                                 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
11536                                                                 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
11537                                                         } else {
11538                                                                 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
11539                                                                 $pend = '';
11540                                                         }
11541                                                         // calculate shifting amount
11542                                                         $tw = $w;
11543                                                         if ($this->lMargin != $prevlMargin) {
11544                                                                 $tw += ($prevlMargin - $this->lMargin);
11545                                                         }
11546                                                         if ($this->rMargin != $prevrMargin) {
11547                                                                 $tw += ($prevrMargin - $this->rMargin);
11548                                                         }
11549                                                         $mdiff = abs($tw - $linew);
11550                                                         $t_x = 0;
11551                                                         if ($plalign == 'C') {
11552                                                                 if ($this->rtl) {
11553                                                                         $t_x = -($mdiff / 2);
11554                                                                 } else {
11555                                                                         $t_x = ($mdiff / 2);
11556                                                                 }
11557                                                         } elseif (($plalign == 'R') AND (!$this->rtl)) {
11558                                                                 // right alignment on LTR document
11559                                                                 $t_x = $mdiff;
11560                                                         } elseif (($plalign == 'L') AND ($this->rtl)) {
11561                                                                 // left alignment on RTL document
11562                                                                 $t_x = -$mdiff;
11563                                                         } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
11564                                                                 // Justification
11565                                                                 if ($this->rtl OR $this->tmprtl) {
11566                                                                         $t_x = $this->lMargin - $this->endlinex;
11567                                                                 }
11568                                                                 $no = 0;
11569                                                                 $ns = 0;
11570                                                                 $pmidtemp = $pmid;
11571                                                                 // escape special characters
11572                                                                 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
11573                                                                 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
11574                                                                 // search spaces
11575                                                                 if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
11576                                                                         $maxkk = count($lnstring[1]) - 1;
11577                                                                         for ($kk=0; $kk <= $maxkk; ++$kk) {
11578                                                                                 // restore special characters
11579                                                                                 $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
11580                                                                                 $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
11581                                                                                 if ($kk == $maxkk) {
11582                                                                                         if ($this->rtl OR $this->tmprtl) {
11583                                                                                                 $tvalue = ltrim($lnstring[1][$kk]);
11584                                                                                         } else {
11585                                                                                                 $tvalue = rtrim($lnstring[1][$kk]);
11586                                                                                         }
11587                                                                                 } else {
11588                                                                                         $tvalue = $lnstring[1][$kk];
11589                                                                                 }
11590                                                                                 // count spaces on line
11591                                                                                 $no += substr_count($lnstring[1][$kk], chr(32));
11592                                                                                 $ns += substr_count($tvalue, chr(32));
11593                                                                         }
11594                                                                         if ($this->rtl OR $this->tmprtl) {
11595                                                                                 $t_x = $this->lMargin - $this->endlinex - (($no - $ns - 1) * $this->GetStringWidth(chr(32)));
11596                                                                         }
11597                                                                         // calculate additional space to add to each space
11598                                                                         $spacewidth = (($tw - $linew + (($no - $ns) * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1)) * $this->k;
11599                                                                         $spacewidthu = ($tw - $linew + ($no * $this->GetStringWidth(chr(32)))) / ($ns?$ns:1) / $this->FontSize / $this->k;
11600                                                                         $nsmax = $ns;
11601                                                                         $ns = 0;
11602                                                                         reset($lnstring);
11603                                                                         $offset = 0;
11604                                                                         $strcount = 0;
11605                                                                         $prev_epsposbeg = 0;
11606                                                                         global $spacew;
11607                                                                         while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
11608                                                                                 if ($this->rtl OR $this->tmprtl) {
11609                                                                                         $spacew = ($spacewidth * ($nsmax - $ns));
11610                                                                                 } else {
11611                                                                                         $spacew = ($spacewidth * $ns);
11612                                                                                 }
11613                                                                                 $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
11614                                                                                 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
11615                                                                                 $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset) + strlen($this->epsmarker.'Q');
11616                                                                                 if ((($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend))
11617                                                                                         OR (($epsposbeg === false) AND ($epsposend > 0) AND ($offset < $epsposend))) {
11618                                                                                         // shift EPS images
11619                                                                                         $trx = sprintf('1 0 0 1 %.3F 0 cm', $spacew);
11620                                                                                         $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
11621                                                                                         $pmid_b = substr($pmid, 0, $epsposbeg);
11622                                                                                         $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
11623                                                                                         $pmid_e = substr($pmid, $epsposend);
11624                                                                                         $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
11625                                                                                         $offset = $epsposend;
11626                                                                                         continue;
11627                                                                                 }
11628                                                                                 $prev_epsposbeg = $epsposbeg;
11629                                                                                 $currentxpos = 0;
11630                                                                                 // shift blocks of code
11631                                                                                 switch ($strpiece[2][0]) {
11632                                                                                         case 'Td':
11633                                                                                         case 'cm':
11634                                                                                         case 'm':
11635                                                                                         case 'l': {
11636                                                                                                 // get current X position
11637                                                                                                 preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11638                                                                                                 $currentxpos = $xmatches[1];
11639                                                                                                 if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
11640                                                                                                         if ($strcount == $maxkk) {
11641                                                                                                                 if ($this->rtl OR $this->tmprtl) {
11642                                                                                                                         $tvalue = $lnstring[1][$strcount];
11643                                                                                                                 } else {
11644                                                                                                                         $tvalue = rtrim($lnstring[1][$strcount]);
11645                                                                                                                 }
11646                                                                                                         } else {
11647                                                                                                                 $tvalue = $lnstring[1][$strcount];
11648                                                                                                         }
11649                                                                                                         $ns += substr_count($tvalue, chr(32));
11650                                                                                                         ++$strcount;
11651                                                                                                 }
11652                                                                                                 if ($this->rtl OR $this->tmprtl) {
11653                                                                                                         $spacew = ($spacewidth * ($nsmax - $ns));
11654                                                                                                 }
11655                                                                                                 // justify block
11656                                                                                                 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11657                                                                                                         create_function('$matches', 'global $spacew;
11658                                                                                                         $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
11659                                                                                                         return "".$newx." ".$matches[2]." x*#!#*x".$matches[3].$matches[4];'), $pmid, 1);
11660                                                                                                 break;
11661                                                                                         }
11662                                                                                         case 're': {
11663                                                                                                 // get current X position
11664                                                                                                 preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11665                                                                                                 $currentxpos = $xmatches[1];
11666                                                                                                 // justify block
11667                                                                                                 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11668                                                                                                         create_function('$matches', 'global $spacew;
11669                                                                                                         $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
11670                                                                                                         return "".$newx." ".$matches[2]." ".$matches[3]." ".$matches[4]." x*#!#*x".$matches[5].$matches[6];'), $pmid, 1);
11671                                                                                                 break;
11672                                                                                         }
11673                                                                                         case 'c': {
11674                                                                                                 // get current X position
11675                                                                                                 preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
11676                                                                                                 $currentxpos = $xmatches[1];
11677                                                                                                 // justify block
11678                                                                                                 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
11679                                                                                                         create_function('$matches', 'global $spacew;
11680                                                                                                         $newx1 = sprintf("%.3F",(floatval($matches[1]) + $spacew));
11681                                                                                                         $newx2 = sprintf("%.3F",(floatval($matches[3]) + $spacew));
11682                                                                                                         $newx3 = sprintf("%.3F",(floatval($matches[5]) + $spacew));
11683                                                                                                         return "".$newx1." ".$matches[2]." ".$newx2." ".$matches[4]." ".$newx3." ".$matches[6]." x*#!#*x".$matches[7].$matches[8];'), $pmid, 1);
11684                                                                                                 break;
11685                                                                                         }
11686                                                                                 }
11687                                                                                 // shift the annotations and links
11688                                                                                 if (isset($this->PageAnnots[$this->page])) {
11689                                                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
11690                                                                                                 if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
11691                                                                                                         $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
11692                                                                                                         $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
11693                                                                                                         break;
11694                                                                                                 }
11695                                                                                         }
11696                                                                                 }
11697                                                                         } // end of while
11698                                                                         // remove markers
11699                                                                         $pmid = str_replace('x*#!#*x', '', $pmid);
11700                                                                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
11701                                                                                 // multibyte characters
11702                                                                                 $spacew = $spacewidthu;
11703                                                                                 $pmidtemp = $pmid;
11704                                                                                 // escape special characters
11705                                                                                 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
11706                                                                                 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
11707                                                                                 $pmid = preg_replace_callback("/\[\(([^\)]*)\)\]/x",
11708                                                                                                         create_function('$matches', 'global $spacew;
11709                                                                                                         $matches[1] = str_replace("#!#OP#!#", "(", $matches[1]);
11710                                                                                                         $matches[1] = str_replace("#!#CP#!#", ")", $matches[1]);
11711                                                                                                         return "[(".str_replace(chr(0).chr(32), ") ".(-2830 * $spacew)." (", $matches[1]).")]";'), $pmidtemp);
11712                                                                                 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
11713                                                                                 $endlinepos = strlen($pstart."\n".$pmid."\n");
11714                                                                         } else {
11715                                                                                 // non-unicode (single-byte characters)
11716                                                                                 $rs = sprintf("%.3F Tw", $spacewidth);
11717                                                                                 $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
11718                                                                                 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
11719                                                                                 $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
11720                                                                         }
11721                                                                 }
11722                                                         } // end of J
11723                                                         if (($t_x != 0) OR ($yshift < 0)) {
11724                                                                 // shift the line
11725                                                                 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
11726                                                                 $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
11727                                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
11728                                                                 // shift the annotations and links
11729                                                                 if (isset($this->PageAnnots[$this->page])) {
11730                                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
11731                                                                                 if ($pak >= $pask) {
11732                                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
11733                                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
11734                                                                                 }
11735                                                                         }
11736                                                                 }
11737                                                                 $this->y -= $yshift;
11738                                                         }
11739                                                 }
11740                                         }
11741                                         $this->newline = false;
11742                                         $pbrk = $this->checkPageBreak($this->lasth);
11743                                         $this->SetFont($fontname, $fontstyle, $fontsize);
11744                                         if ($wfill) {
11745                                                 $this->SetFillColorArray($this->bgcolor);
11746                                         }
11747                                         $startlinex = $this->x;
11748                                         $startliney = $this->y;
11749                                         $minstartliney = $this->y;
11750                                         $startlinepage = $this->page;
11751                                         if (isset($endlinepos) AND (!$pbrk)) {
11752                                                 $startlinepos = $endlinepos;
11753                                                 unset($endlinepos);
11754                                         } else {
11755                                                 if (isset($this->footerlen[$this->page])) {
11756                                                         $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11757                                                 } else {
11758                                                         $this->footerpos[$this->page] = $this->pagelen[$this->page];
11759                                                 }
11760                                                 $startlinepos = $this->footerpos[$this->page];
11761                                         }
11762                                         $plalign = $lalign;
11763                                         if (isset($this->PageAnnots[$this->page])) {
11764                                                 $pask = count($this->PageAnnots[$this->page]);
11765                                         } else {
11766                                                 $pask = 0;
11767                                         }
11768                                 }
11769                                 if (isset($opentagpos)) {
11770                                         unset($opentagpos);
11771                                 }
11772                                 if ($dom[$key]['tag']) {
11773                                         if ($dom[$key]['opening']) {
11774                                                 if ($dom[$key]['value'] == 'table') {
11775                                                         if ($this->rtl) {
11776                                                                 $wtmp = $this->x - $this->lMargin;
11777                                                         } else {
11778                                                                 $wtmp = $this->w - $this->rMargin - $this->x;
11779                                                         }
11780                                                         $wtmp -= (2 * $this->cMargin);
11781                                                         // calculate cell width
11782                                                         if (isset($dom[$key]['width'])) {
11783                                                                 $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
11784                                                         } else {
11785                                                                 $table_width = $wtmp;
11786                                                         }
11787                                                 }
11788                                                 // table content is handled in a special way
11789                                                 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
11790                                                         $trid = $dom[$key]['parent'];
11791                                                         $table_el = $dom[$trid]['parent'];
11792                                                         if (!isset($dom[$table_el]['cols'])) {
11793                                                                 $dom[$table_el]['cols'] = $trid['cols'];
11794                                                         }
11795                                                         $oldmargin = $this->cMargin;
11796                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
11797                                                                 $currentcmargin = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
11798                                                         } else {
11799                                                                 $currentcmargin = 0;
11800                                                         }
11801                                                         $this->cMargin = $currentcmargin;
11802                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
11803                                                                 $cellspacing = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'], 1, 'px');
11804                                                         } else {
11805                                                                 $cellspacing = 0;
11806                                                         }
11807                                                         if ($this->rtl) {
11808                                                                 $cellspacingx = -$cellspacing;
11809                                                         } else {
11810                                                                 $cellspacingx = $cellspacing;
11811                                                         }
11812                                                         $colspan = $dom[$key]['attribute']['colspan'];
11813                                                         $wtmp = ($colspan * ($table_width / $dom[$table_el]['cols']));
11814                                                         if (isset($dom[$key]['width'])) {
11815                                                                 $cellw = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
11816                                                         } else {
11817                                                                 $cellw = $wtmp;
11818                                                         }
11819                                                         if (isset($dom[$key]['height'])) {
11820                                                                 // minimum cell height
11821                                                                 $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
11822                                                         } else {
11823                                                                 $cellh = 0;
11824                                                         }
11825                                                         $cellw -= $cellspacing;
11826                                                         if (isset($dom[$key]['content'])) {
11827                                                                 $cell_content = $dom[$key]['content'];
11828                                                         } else {
11829                                                                 $cell_content = '&nbsp;';
11830                                                         }
11831                                                         $tagtype = $dom[$key]['value'];
11832                                                         $parentid = $key;
11833                                                         while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
11834                                                                 // move $key index forward
11835                                                                 ++$key;
11836                                                         }
11837                                                         if (!isset($dom[$trid]['startpage'])) {
11838                                                                 $dom[$trid]['startpage'] = $this->page;
11839                                                         } else {
11840                                                                 $this->setPage($dom[$trid]['startpage']);
11841                                                         }
11842                                                         if (!isset($dom[$trid]['starty'])) {
11843                                                                 $dom[$trid]['starty'] = $this->y;
11844                                                         } else {
11845                                                                 $this->y = $dom[$trid]['starty'];
11846                                                         }
11847                                                         if (!isset($dom[$trid]['startx'])) {
11848                                                                 $dom[$trid]['startx'] = $this->x;
11849                                                         }
11850                                                         $this->x += ($cellspacingx / 2);
11851                                                         if (isset($dom[$parentid]['attribute']['rowspan'])) {
11852                                                                 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
11853                                                         } else {
11854                                                                 $rowspan = 1;
11855                                                         }
11856                                                         // skip row-spanned cells started on the previous rows
11857                                                         if (isset($dom[$table_el]['rowspans'])) {
11858                                                                 $rsk = 0;
11859                                                                 $rskmax = count($dom[$table_el]['rowspans']);
11860                                                                 while ($rsk < $rskmax) {
11861                                                                         $trwsp = $dom[$table_el]['rowspans'][$rsk];
11862                                                                         $rsstartx = $trwsp['startx'];
11863                                                                         $rsendx = $trwsp['endx'];
11864                                                                         // account for margin changes
11865                                                                         if ($trwsp['startpage'] < $this->page) {
11866                                                                                 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
11867                                                                                         $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
11868                                                                                         $rsstartx -= $dl;
11869                                                                                         $rsendx -= $dl;
11870                                                                                 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
11871                                                                                         $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
11872                                                                                         $rsstartx += $dl;
11873                                                                                         $rsendx += $dl;
11874                                                                                 }
11875                                                                         }
11876                                                                         if  (($trwsp['rowspan'] > 0)
11877                                                                                 AND ($rsstartx > ($this->x - $cellspacing - $currentcmargin - $this->feps))
11878                                                                                 AND ($rsstartx < ($this->x + $cellspacing + $currentcmargin + $this->feps))
11879                                                                                 AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page))) {
11880                                                                                 // set the starting X position of the current cell
11881                                                                                 $this->x = $rsendx + $cellspacingx;
11882                                                                                 if (($trwsp['rowspan'] == 1)
11883                                                                                         AND (isset($dom[$trid]['endy']))
11884                                                                                         AND (isset($dom[$trid]['endpage']))
11885                                                                                         AND ($trwsp['endpage'] == $dom[$trid]['endpage'])) {
11886                                                                                         // set ending Y position for row
11887                                                                                         $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
11888                                                                                         $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
11889                                                                                 }
11890                                                                                 $rsk = 0;
11891                                                                         } else {
11892                                                                                 ++$rsk;
11893                                                                         }
11894                                                                 }
11895                                                         }
11896                                                         // add rowspan information to table element
11897                                                         if ($rowspan > 1) {
11898                                                                 if (isset($this->footerlen[$this->page])) {
11899                                                                         $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11900                                                                 } else {
11901                                                                         $this->footerpos[$this->page] = $this->pagelen[$this->page];
11902                                                                 }
11903                                                                 $trintmrkpos = $this->footerpos[$this->page];
11904                                                                 $trsid = array_push($dom[$table_el]['rowspans'], array('trid' => $trid, 'rowspan' => $rowspan, 'mrowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startx' => $this->x, 'starty' => $this->y, 'intmrkpos' => $trintmrkpos));
11905                                                         }
11906                                                         $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
11907                                                         if ($rowspan > 1) {
11908                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
11909                                                         }
11910                                                         // push background colors
11911                                                         if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
11912                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
11913                                                         }
11914                                                         $prevLastH = $this->lasth;
11915                                                         // ****** write the cell content ******
11916                                                         $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
11917                                                         $this->lasth = $prevLastH;
11918                                                         $this->cMargin = $oldmargin;
11919                                                         $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
11920                                                         // update the end of row position
11921                                                         if ($rowspan <= 1) {
11922                                                                 if (isset($dom[$trid]['endy'])) {
11923                                                                         if ($this->page == $dom[$trid]['endpage']) {
11924                                                                                 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
11925                                                                         } elseif ($this->page > $dom[$trid]['endpage']) {
11926                                                                                 $dom[$trid]['endy'] = $this->y;
11927                                                                         }
11928                                                                 } else {
11929                                                                         $dom[$trid]['endy'] = $this->y;
11930                                                                 }
11931                                                                 if (isset($dom[$trid]['endpage'])) {
11932                                                                         $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
11933                                                                 } else {
11934                                                                         $dom[$trid]['endpage'] = $this->page;
11935                                                                 }
11936                                                         } else {
11937                                                                 // account for row-spanned cells
11938                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
11939                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
11940                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
11941                                                         }
11942                                                         if (isset($dom[$table_el]['rowspans'])) {
11943                                                                 // update endy and endpage on rowspanned cells
11944                                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
11945                                                                         if ($trwsp['rowspan'] > 0) {
11946                                                                                 if (isset($dom[$trid]['endpage'])) {
11947                                                                                         if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
11948                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
11949                                                                                         } elseif ($trwsp['endpage'] < $dom[$trid]['endpage']) {
11950                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
11951                                                                                                 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
11952                                                                                         } else {
11953                                                                                                 $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
11954                                                                                         }
11955                                                                                 }
11956                                                                         }
11957                                                                 }
11958                                                         }
11959                                                         $this->x += ($cellspacingx / 2);
11960                                                 } else {
11961                                                         // opening tag (or self-closing tag)
11962                                                         if (!isset($opentagpos)) {
11963                                                                 if (!$this->InFooter) {
11964                                                                         if (isset($this->footerlen[$this->page])) {
11965                                                                                 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
11966                                                                         } else {
11967                                                                                 $this->footerpos[$this->page] = $this->pagelen[$this->page];
11968                                                                         }
11969                                                                         $opentagpos = $this->footerpos[$this->page];
11970                                                                 }
11971                                                         }
11972                                                         $this->openHTMLTagHandler($dom, $key, $cell);
11973                                                 }
11974                                         } else {
11975                                                 // closing tag
11976                                                 $this->closeHTMLTagHandler($dom, $key, $cell);
11977                                         }
11978                                 } elseif (strlen($dom[$key]['value']) > 0) {
11979                                         // print list-item
11980                                         if (!$this->empty_string($this->lispacer)) {
11981                                                 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
11982                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11983                                                 $minstartliney = $this->y;
11984                                                 $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
11985                                                 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
11986                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
11987                                                 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
11988                                                         $this->y += (($pfontsize - $curfontsize) / $this->k);
11989                                                         $minstartliney = min($this->y, $minstartliney);
11990                                                 }
11991                                         }
11992                                         // text
11993                                         $this->htmlvspace = 0;
11994                                         if ((!$this->premode) AND ($this->rtl OR $this->tmprtl)) {
11995                                                 // reverse spaces order
11996                                                 $len1 = strlen($dom[$key]['value']);
11997                                                 $lsp = $len1 - strlen(ltrim($dom[$key]['value']));
11998                                                 $rsp = $len1 - strlen(rtrim($dom[$key]['value']));
11999                                                 $tmpstr = '';
12000                                                 if ($rsp > 0) {
12001                                                         $tmpstr .= substr($dom[$key]['value'], -$rsp);
12002                                                 }
12003                                                 $tmpstr .= trim($dom[$key]['value']);
12004                                                 if ($lsp > 0) {
12005                                                         $tmpstr .= substr($dom[$key]['value'], 0, $lsp);
12006                                                 }
12007                                                 $dom[$key]['value'] = $tmpstr;
12008                                         }
12009                                         if ($newline) {
12010                                                 if (!$this->premode) {
12011                                                         if (($this->rtl OR $this->tmprtl)) {
12012                                                                 $dom[$key]['value'] = rtrim($dom[$key]['value']);
12013                                                         } else {
12014                                                                 $dom[$key]['value'] = ltrim($dom[$key]['value']);
12015                                                         }
12016                                                 }
12017                                                 $newline = false;
12018                                                 $firstblock = true;
12019                                         } else {
12020                                                 $firstblock = false;
12021                                         }
12022                                         $strrest = '';
12023                                         if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
12024                                                 // HTML <a> Link
12025                                                 $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $this->HREF['color'], $this->HREF['style']);
12026                                         } else {
12027                                                 $ctmpmargin = $this->cMargin;
12028                                                 $this->cMargin = 0;
12029                                                 // ****** write only until the end of the line and get the rest ******
12030                                                 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock);
12031                                                 $this->cMargin = $ctmpmargin;
12032                                         }
12033                                         if (strlen($strrest) > 0) {
12034                                                 // store the remaining string on the previous $key position
12035                                                 $this->newline = true;
12036                                                 if ($cell) {
12037                                                         if ($this->rtl) {
12038                                                                 $this->x -= $this->cMargin;
12039                                                         } else {
12040                                                                 $this->x += $this->cMargin;
12041                                                         }
12042                                                 }
12043                                                 if ($strrest == $dom[$key]['value']) {
12044                                                         // used to avoid infinite loop
12045                                                         ++$loop;
12046                                                 } else {
12047                                                         $loop = 0;
12048                                                 }
12049                                                 $dom[$key]['value'] = ltrim($strrest);
12050                                                 if ($loop < 3) {
12051                                                         --$key;
12052                                                 }
12053                                         } else {
12054                                                 $loop = 0;
12055                                         }
12056                                 }
12057                                 ++$key;
12058                         } // end for each $key
12059                         // align the last line
12060                         if (isset($startlinex)) {
12061                                 $yshift = $minstartliney - $startliney;
12062                                 if (($yshift > 0) OR ($this->page > $startlinepage)) {
12063                                         $yshift = 0;
12064                                 }
12065                                 if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl))))) OR ($yshift < 0)) {
12066                                         // the last line must be shifted to be aligned as requested
12067                                         $linew = abs($this->endlinex - $startlinex);
12068                                         $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
12069                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
12070                                                 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
12071                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
12072                                         } elseif (isset($opentagpos)) {
12073                                                 $midpos = $opentagpos;
12074                                         } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
12075                                                 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
12076                                                 $midpos = $this->footerpos[$startlinepage];
12077                                         } else {
12078                                                 $midpos = 0;
12079                                         }
12080                                         if ($midpos > 0) {
12081                                                 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
12082                                                 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
12083                                         } else {
12084                                                 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
12085                                                 $pend = '';
12086                                         }
12087                                         // calculate shifting amount
12088                                         $tw = $w;
12089                                         if ($this->lMargin != $prevlMargin) {
12090                                                 $tw += ($prevlMargin - $this->lMargin);
12091                                         }
12092                                         if ($this->rMargin != $prevrMargin) {
12093                                                 $tw += ($prevrMargin - $this->rMargin);
12094                                         }
12095                                         $mdiff = abs($tw - $linew);
12096                                         if ($plalign == 'C') {
12097                                                 if ($this->rtl) {
12098                                                         $t_x = -($mdiff / 2);
12099                                                 } else {
12100                                                         $t_x = ($mdiff / 2);
12101                                                 }
12102                                         } elseif (($plalign == 'R') AND (!$this->rtl)) {
12103                                                 // right alignment on LTR document
12104                                                 $t_x = $mdiff;
12105                                         } elseif (($plalign == 'L') AND ($this->rtl)) {
12106                                                 // left alignment on RTL document
12107                                                 $t_x = -$mdiff;
12108                                         } else {
12109                                                 $t_x = 0;
12110                                         }
12111                                         if (($t_x != 0) OR ($yshift < 0)) {
12112                                                 // shift the line
12113                                                 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
12114                                                 $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend);
12115                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
12116                                                 // shift the annotations and links
12117                                                 if (isset($this->PageAnnots[$this->page])) {
12118                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
12119                                                                 if ($pak >= $pask) {
12120                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
12121                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
12122                                                                 }
12123                                                         }
12124                                                 }
12125                                                 $this->y -= $yshift;
12126                                         }
12127                                 }
12128                         }
12129                         if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
12130                                 $this->Ln($this->lasth);
12131                         }
12132                         // restore previous values
12133                         $this->setGraphicVars($gvars);
12134                         if ($this->page > $prevPage) {
12135                                 $this->lMargin = $this->pagedim[$this->page]['olm'];
12136                                 $this->rMargin = $this->pagedim[$this->page]['orm'];
12137                         }
12138                         unset($dom);
12139                 }
12140
12141                 /**
12142                  * Process opening tags.
12143                  * @param array $dom html dom array
12144                  * @param int $key current element id
12145                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
12146                  * @access protected
12147                  */
12148                 protected function openHTMLTagHandler(&$dom, $key, $cell=false) {
12149                         $tag = $dom[$key];
12150                         $parent = $dom[($dom[$key]['parent'])];
12151                         $firstorlast = ($key == 1);
12152                         // check for text direction attribute
12153                         if (isset($tag['attribute']['dir'])) {
12154                                 $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
12155                         } else {
12156                                 $this->tmprtl = false;
12157                         }
12158                         //Opening tag
12159                         switch($tag['value']) {
12160                                 case 'table': {
12161                                         $cp = 0;
12162                                         $cs = 0;
12163                                         $dom[$key]['rowspans'] = array();
12164                                         if (!$this->empty_string($dom[$key]['thead'])) {
12165                                                 // set table header
12166                                                 $this->thead = $dom[$key]['thead'];
12167                                         }
12168                                         if (isset($tag['attribute']['cellpadding'])) {
12169                                                 $cp = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
12170                                                 $this->oldcMargin = $this->cMargin;
12171                                                 $this->cMargin = $cp;
12172                                         }
12173                                         if (isset($tag['attribute']['cellspacing'])) {
12174                                                 $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
12175                                         }
12176                                         $this->checkPageBreak((2 * $cp) + (2 * $cs) + $this->lasth);
12177                                         break;
12178                                 }
12179                                 case 'tr': {
12180                                         // array of columns positions
12181                                         $dom[$key]['cellpos'] = array();
12182                                         break;
12183                                 }
12184                                 case 'hr': {
12185                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12186                                         $this->htmlvspace = 0;
12187                                         $wtmp = $this->w - $this->lMargin - $this->rMargin;
12188                                         if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
12189                                                 $hrWidth = $this->getHTMLUnitToUnits($tag['attribute']['width'], $wtmp, 'px');
12190                                         } else {
12191                                                 $hrWidth = $wtmp;
12192                                         }
12193                                         $x = $this->GetX();
12194                                         $y = $this->GetY();
12195                                         $prevlinewidth = $this->GetLineWidth();
12196                                         $this->Line($x, $y, $x + $hrWidth, $y);
12197                                         $this->SetLineWidth($prevlinewidth);
12198                                         $this->addHTMLVertSpace(1, $cell, '', !isset($dom[($key + 1)]), $tag['value'], false);
12199                                         break;
12200                                 }
12201                                 case 'a': {
12202                                         if (array_key_exists('href', $tag['attribute'])) {
12203                                                 $this->HREF['url'] = $tag['attribute']['href'];
12204                                         }
12205                                         $this->HREF['color'] = $this->htmlLinkColorArray;
12206                                         $this->HREF['style'] = $this->htmlLinkFontStyle;
12207                                         if (array_key_exists('style', $tag['attribute'])) {
12208                                                 // get style attributes
12209                                                 preg_match_all('/([^;:\s]*):([^;]*)/', $tag['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
12210                                                 $astyle = array();
12211                                                 while (list($id, $name) = each($style_array[1])) {
12212                                                         $name = strtolower($name);
12213                                                         $astyle[$name] = trim($style_array[2][$id]);
12214                                                 }
12215                                                 if (isset($astyle['color'])) {
12216                                                         $this->HREF['color'] = $this->convertHTMLColorToDec($astyle['color']);
12217                                                 }
12218                                                 if (isset($astyle['text-decoration'])) {
12219                                                         $this->HREF['style'] = '';
12220                                                         $decors = explode(' ', strtolower($astyle['text-decoration']));
12221                                                         foreach ($decors as $dec) {
12222                                                                 $dec = trim($dec);
12223                                                                 if (!$this->empty_string($dec)) {
12224                                                                         if ($dec{0} == 'u') {
12225                                                                                 $this->HREF['style'] .= 'U';
12226                                                                         } elseif ($dec{0} == 'l') {
12227                                                                                 $this->HREF['style'] .= 'D';
12228                                                                         }
12229                                                                 }
12230                                                         }
12231                                                 }
12232                                         }
12233                                         break;
12234                                 }
12235                                 case 'img': {
12236                                         if (isset($tag['attribute']['src'])) {
12237                                                 // replace relative path with real server path
12238                                                 if ($tag['attribute']['src'][0] == '/') {
12239                                                         $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
12240                                                 }
12241                                                 $tag['attribute']['src'] = urldecode($tag['attribute']['src']);
12242                                                 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
12243                                                 if (!isset($tag['attribute']['width'])) {
12244                                                         $tag['attribute']['width'] = 0;
12245                                                 }
12246                                                 if (!isset($tag['attribute']['height'])) {
12247                                                         $tag['attribute']['height'] = 0;
12248                                                 }
12249                                                 //if (!isset($tag['attribute']['align'])) {
12250                                                         // the only alignment supported is "bottom"
12251                                                         // further development is required for other modes.
12252                                                         $tag['attribute']['align'] = 'bottom';
12253                                                 //}
12254                                                 switch($tag['attribute']['align']) {
12255                                                         case 'top': {
12256                                                                 $align = 'T';
12257                                                                 break;
12258                                                         }
12259                                                         case 'middle': {
12260                                                                 $align = 'M';
12261                                                                 break;
12262                                                         }
12263                                                         case 'bottom': {
12264                                                                 $align = 'B';
12265                                                                 break;
12266                                                         }
12267                                                         default: {
12268                                                                 $align = 'B';
12269                                                                 break;
12270                                                         }
12271                                                 }
12272                                                 $fileinfo = pathinfo($tag['attribute']['src']);
12273                                                 if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
12274                                                         $type = strtolower($fileinfo['extension']);
12275                                                 }
12276                                                 $prevy = $this->y;
12277                                                 $xpos = $this->GetX();
12278                                                 if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == ' ')) {
12279                                                         if ($this->rtl) {
12280                                                                 $xpos += $this->GetStringWidth(' ');
12281                                                         } else {
12282                                                                 $xpos -= $this->GetStringWidth(' ');
12283                                                         }
12284                                                 }
12285                                                 $imglink = '';
12286                                                 if (isset($this->HREF['url']) AND !$this->empty_string($this->HREF['url'])) {
12287                                                         $imglink = $this->HREF['url'];
12288                                                         if ($imglink{0} == '#') {
12289                                                                 // convert url to internal link
12290                                                                 $page = intval(substr($imglink, 1));
12291                                                                 $imglink = $this->AddLink();
12292                                                                 $this->SetLink($imglink, 0, $page);
12293                                                         }
12294                                                 }
12295                                                 $border = 0;
12296                                                 if (isset($tag['attribute']['border']) AND !empty($tag['attribute']['border'])) {
12297                                                         // currently only support 1 (frame) or a combination of 'LTRB'
12298                                                         $border = $tag['attribute']['border'];
12299                                                 }
12300                                                 $iw = '';
12301                                                 if (isset($tag['attribute']['width'])) {
12302                                                         $iw = $this->getHTMLUnitToUnits($tag['attribute']['width'], 1, 'px', false);
12303                                                 }
12304                                                 $ih = '';
12305                                                 if (isset($tag['attribute']['height'])) {
12306                                                         $ih = $this->getHTMLUnitToUnits($tag['attribute']['height'], 1, 'px', false);
12307                                                 }
12308                                                 if (($type == 'eps') OR ($type == 'ai')) {
12309                                                         $this->ImageEps($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, $imglink, true, $align, '', $border);
12310                                                 } else {
12311                                                         $this->Image($tag['attribute']['src'], $xpos, $this->GetY(), $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border);
12312                                                 }
12313                                                 switch($align) {
12314                                                         case 'T': {
12315                                                                 $this->y = $prevy;
12316                                                                 break;
12317                                                         }
12318                                                         case 'M': {
12319                                                                 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
12320                                                                 break;
12321                                                         }
12322                                                         case 'B': {
12323                                                                 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
12324                                                                 break;
12325                                                         }
12326                                                 }
12327                                         }
12328                                         break;
12329                                 }
12330                                 case 'dl': {
12331                                         ++$this->listnum;
12332                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12333                                         break;
12334                                 }
12335                                 case 'dt': {
12336                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12337                                         break;
12338                                 }
12339                                 case 'dd': {
12340                                         if ($this->rtl) {
12341                                                 $this->rMargin += $this->listindent;
12342                                         } else {
12343                                                 $this->lMargin += $this->listindent;
12344                                         }
12345                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12346                                         break;
12347                                 }
12348                                 case 'ul':
12349                                 case 'ol': {
12350                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12351                                         $this->htmlvspace = 0;
12352                                         ++$this->listnum;
12353                                         if ($tag['value'] == 'ol') {
12354                                                 $this->listordered[$this->listnum] = true;
12355                                         } else {
12356                                                 $this->listordered[$this->listnum] = false;
12357                                         }
12358                                         if (isset($tag['attribute']['start'])) {
12359                                                 $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
12360                                         } else {
12361                                                 $this->listcount[$this->listnum] = 0;
12362                                         }
12363                                         if ($this->rtl) {
12364                                                 $this->rMargin += $this->listindent;
12365                                         } else {
12366                                                 $this->lMargin += $this->listindent;
12367                                         }
12368                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], false);
12369                                         $this->htmlvspace = 0;
12370                                         break;
12371                                 }
12372                                 case 'li': {
12373                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12374                                         if ($this->listordered[$this->listnum]) {
12375                                                 // ordered item
12376                                                 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
12377                                                         $this->lispacer = $parent['attribute']['type'];
12378                                                 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
12379                                                         $this->lispacer = $parent['listtype'];
12380                                                 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
12381                                                         $this->lispacer = $this->lisymbol;
12382                                                 } else {
12383                                                         $this->lispacer = '#';
12384                                                 }
12385                                                 ++$this->listcount[$this->listnum];
12386                                                 if (isset($tag['attribute']['value'])) {
12387                                                         $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
12388                                                 }
12389                                         } else {
12390                                                 // unordered item
12391                                                 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
12392                                                         $this->lispacer = $parent['attribute']['type'];
12393                                                 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
12394                                                         $this->lispacer = $parent['listtype'];
12395                                                 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
12396                                                         $this->lispacer = $this->lisymbol;
12397                                                 } else {
12398                                                         $this->lispacer = '!';
12399                                                 }
12400                                         }
12401                                         break;
12402                                 }
12403                                 case 'blockquote': {
12404                                         if ($this->rtl) {
12405                                                 $this->rMargin += $this->listindent;
12406                                         } else {
12407                                                 $this->lMargin += $this->listindent;
12408                                         }
12409                                         $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
12410                                         break;
12411                                 }
12412                                 case 'br': {
12413                                         $this->Ln('', $cell);
12414                                         break;
12415                                 }
12416                                 case 'div': {
12417                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12418                                         break;
12419                                 }
12420                                 case 'p': {
12421                                         $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], false);
12422                                         break;
12423                                 }
12424                                 case 'pre': {
12425                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], false);
12426                                         $this->premode = true;
12427                                         break;
12428                                 }
12429                                 case 'sup': {
12430                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
12431                                         break;
12432                                 }
12433                                 case 'sub': {
12434                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
12435                                         break;
12436                                 }
12437                                 case 'h1':
12438                                 case 'h2':
12439                                 case 'h3':
12440                                 case 'h4':
12441                                 case 'h5':
12442                                 case 'h6': {
12443                                         $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], false);
12444                                         break;
12445                                 }
12446                                 case 'tcpdf': {
12447                                         if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
12448                                                  // Special tag used to call TCPDF methods
12449                         if (isset($tag['attribute']['method'])) {
12450                             $tcpdf_method = $tag['attribute']['method'];
12451                             if (method_exists($this, $tcpdf_method)) {
12452                                 if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
12453                                     $params = unserialize(urldecode($tag['attribute']['params']));
12454                                     call_user_func_array(array($this, $tcpdf_method), $params);
12455                                 } else {
12456                                     $this->$tcpdf_method();
12457                                 }
12458                                 $this->newline = true;
12459                             }
12460                         }
12461                     }
12462                                 }
12463                                 default: {
12464                                         break;
12465                                 }
12466                         }
12467                 }
12468
12469                 /**
12470                  * Process closing tags.
12471                  * @param array $dom html dom array
12472                  * @param int $key current element id
12473                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
12474                  * @access protected
12475                  */
12476                 protected function closeHTMLTagHandler(&$dom, $key, $cell=false) {
12477                         $tag = $dom[$key];
12478                         $parent = $dom[($dom[$key]['parent'])];
12479                         $firstorlast = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
12480                         //Closing tag
12481                         switch($tag['value']) {
12482                                 case 'tr': {
12483                                         $table_el = $dom[($dom[$key]['parent'])]['parent'];
12484                                         if(!isset($parent['endy'])) {
12485                                                 $dom[($dom[$key]['parent'])]['endy'] = $this->y;
12486                                                 $parent['endy'] = $this->y;
12487                                         }
12488                                         if(!isset($parent['endpage'])) {
12489                                                 $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
12490                                                 $parent['endpage'] = $this->page;
12491                                         }
12492                                         // update row-spanned cells
12493                                         if (isset($dom[$table_el]['rowspans'])) {
12494                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12495                                                         $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
12496                                                         if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12497                                                                 if ($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) {
12498                                                                         $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
12499                                                                 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) {
12500                                                                         $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
12501                                                                         $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
12502                                                                 }
12503                                                         }
12504                                                 }
12505                                                 // report new endy and endpage to the rowspanned cells
12506                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12507                                                         if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12508                                                                 $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
12509                                                                 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
12510                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
12511                                                                 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
12512                                                         }
12513                                                 }
12514                                                 // update remaining rowspanned cells
12515                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
12516                                                         if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
12517                                                                 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
12518                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
12519                                                         }
12520                                                 }
12521                                         }
12522                                         $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
12523                                         $this->y = $dom[($dom[$key]['parent'])]['endy'];
12524                                         if (isset($dom[$table_el]['attribute']['cellspacing'])) {
12525                                                 $cellspacing = $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
12526                                                 $this->y += $cellspacing;
12527                                         }
12528                                         $this->Ln(0, $cell);
12529                                         $this->x = $parent['startx'];
12530                                         // account for booklet mode
12531                                         if ($this->page > $parent['startpage']) {
12532                                                 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
12533                                                         $this->x += ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
12534                                                 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
12535                                                         $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
12536                                                 }
12537                                         }
12538                                         break;
12539                                 }
12540                                 case 'table': {
12541                                         // draw borders
12542                                         $table_el = $parent;
12543                                         if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
12544                                                 OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
12545                                                         $border = 1;
12546                                         } else {
12547                                                 $border = 0;
12548                                         }
12549                                         // fix bottom line alignment of last line before page break
12550                                         foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
12551                                                 // update row-spanned cells
12552                                                 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
12553                                                         foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
12554                                                                 if ($trwsp['trid'] == $trkey) {
12555                                                                         $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
12556                                                                 }
12557                                                                 if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0)) {
12558                                                                         $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
12559                                                                 }
12560                                                         }
12561                                                 }
12562                                                 if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
12563                                                         $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
12564                                                         $dom[$prevtrkey]['endy'] = $pgendy;
12565                                                         // update row-spanned cells
12566                                                         if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
12567                                                                 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
12568                                                                         if (($trwsp['trid'] == $trkey) AND ($trwsp['mrowspan'] == 1) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
12569                                                                                 $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
12570                                                                                 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
12571                                                                         }
12572                                                                 }
12573                                                         }
12574                                                 }
12575                                                 $prevtrkey = $trkey;
12576                                                 $table_el = $dom[($dom[$key]['parent'])];
12577                                         }
12578                                         // for each row
12579                                         foreach ($table_el['trids'] as $j => $trkey) {
12580                                                 $parent = $dom[$trkey];
12581                                                 // for each cell on the row
12582                                                 foreach ($parent['cellpos'] as $k => $cellpos) {
12583                                                         if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
12584                                                                 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
12585                                                                 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
12586                                                                 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
12587                                                                 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
12588                                                                 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
12589                                                         } else {
12590                                                                 $endy = $parent['endy'];
12591                                                                 $startpage = $parent['startpage'];
12592                                                                 $endpage = $parent['endpage'];
12593                                                         }
12594                                                         if ($endpage > $startpage) {
12595                                                                 // design borders around HTML cells.
12596                                                                 for ($page=$startpage; $page <= $endpage; ++$page) {
12597                                                                         $this->setPage($page);
12598                                                                         if ($page == $startpage) {
12599                                                                                 $this->y = $parent['starty']; // put cursor at the beginning of row on the first page
12600                                                                                 $ch = $this->getPageHeight() - $parent['starty'] - $this->getBreakMargin();
12601                                                                                 $cborder = $this->getBorderMode($border, $position='start');
12602                                                                         } elseif ($page == $endpage) {
12603                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of last page
12604                                                                                 $ch = $endy - $this->tMargin;
12605                                                                                 $cborder = $this->getBorderMode($border, $position='end');
12606                                                                         } else {
12607                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of the current page
12608                                                                                 $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
12609                                                                                 $cborder = $this->getBorderMode($border, $position='middle');
12610                                                                         }
12611                                                                         if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
12612                                                                                 $this->SetFillColorArray($cellpos['bgcolor']);
12613                                                                                 $fill = true;
12614                                                                         } else {
12615                                                                                 $fill = false;
12616                                                                         }
12617                                                                         $cw = abs($cellpos['endx'] - $cellpos['startx']);
12618                                                                         $this->x = $cellpos['startx'];
12619                                                                         // account for margin changes
12620                                                                         if ($page > $startpage) {
12621                                                                                 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
12622                                                                                         $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
12623                                                                                 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['lm'] != $this->pagedim[$startpage]['olm'])) {
12624                                                                                         $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
12625                                                                                 }
12626                                                                         }
12627                                                                         // design a cell around the text
12628                                                                         $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $cborder, 1, '', $fill, '', 0, true);
12629                                                                         if ($cborder OR $fill) {
12630                                                                                 $pagebuff = $this->getPageBuffer($this->page);
12631                                                                                 $pstart = substr($pagebuff, 0, $this->intmrk[$this->page]);
12632                                                                                 $pend = substr($pagebuff, $this->intmrk[$this->page]);
12633                                                                                 $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
12634                                                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
12635                                                                         }
12636                                                                 }
12637                                                         } else {
12638                                                                 $this->setPage($startpage);
12639                                                                 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
12640                                                                         $this->SetFillColorArray($cellpos['bgcolor']);
12641                                                                         $fill = true;
12642                                                                 } else {
12643                                                                         $fill = false;
12644                                                                 }
12645                                                                 $this->x = $cellpos['startx'];
12646                                                                 $this->y = $parent['starty'];
12647                                                                 $cw = abs($cellpos['endx'] - $cellpos['startx']);
12648                                                                 $ch = $endy - $parent['starty'];
12649                                                                 // design a cell around the text
12650                                                                 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, '', $border, 1, '', $fill, '', 0, true);
12651                                                                 if ($border OR $fill) {
12652                                                                         if (end($this->transfmrk[$this->page]) !== false) {
12653                                                                                 $pagemarkkey = key($this->transfmrk[$this->page]);
12654                                                                                 $pagemark = &$this->transfmrk[$this->page][$pagemarkkey];
12655                                                                         } elseif ($this->InFooter) {
12656                                                                                 $pagemark = &$this->footerpos[$this->page];
12657                                                                         } else {
12658                                                                                 $pagemark = &$this->intmrk[$this->page];
12659                                                                         }
12660                                                                         $pagebuff = $this->getPageBuffer($this->page);
12661                                                                         $pstart = substr($pagebuff, 0, $pagemark);
12662                                                                         $pend = substr($pagebuff, $pagemark);
12663                                                                         $this->setPageBuffer($this->page, $pstart.$ccode."\n".$pend);
12664                                                                         $pagemark += strlen($ccode."\n");
12665                                                                 }
12666                                                         }
12667                                                 }
12668                                                 if (isset($table_el['attribute']['cellspacing'])) {
12669                                                         $cellspacing = $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
12670                                                         $this->y += $cellspacing;
12671                                                 }
12672                                                 $this->Ln(0, $cell);
12673                                                 $this->x = $parent['startx'];
12674                                                 if ($endpage > $startpage) {
12675                                                         if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
12676                                                                 $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
12677                                                         } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
12678                                                                 $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
12679                                                         }
12680                                                 }
12681                                         }
12682                                         if (isset($parent['cellpadding'])) {
12683                                                 $this->cMargin = $this->oldcMargin;
12684                                         }
12685                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
12686                                         if (!$this->empty_string($this->theadMargin)) {
12687                                                 // restore top margin
12688                                                 $this->tMargin = $this->theadMargin;
12689                                                 $this->pagedim[$this->page]['tm'] = $this->theadMargin;
12690                                         }
12691                                         // reset table header
12692                                         $this->thead = '';
12693                                         $this->theadMargin = '';
12694                                         break;
12695                                 }
12696                                 case 'a': {
12697                                         $this->HREF = '';
12698                                         break;
12699                                 }
12700                                 case 'sup': {
12701                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
12702                                         break;
12703                                 }
12704                                 case 'sub': {
12705                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
12706                                         break;
12707                                 }
12708                                 case 'div': {
12709                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
12710                                         break;
12711                                 }
12712                                 case 'blockquote': {
12713                                         if ($this->rtl) {
12714                                                 $this->rMargin -= $this->listindent;
12715                                         } else {
12716                                                 $this->lMargin -= $this->listindent;
12717                                         }
12718                                         $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12719                                         break;
12720                                 }
12721                                 case 'p': {
12722                                         $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12723                                         break;
12724                                 }
12725                                 case 'pre': {
12726                                         $this->addHTMLVertSpace(1, $cell, '', $firstorlast, $tag['value'], true);
12727                                         $this->premode = false;
12728                                         break;
12729                                 }
12730                                 case 'dl': {
12731                                         --$this->listnum;
12732                                         if ($this->listnum <= 0) {
12733                                                 $this->listnum = 0;
12734                                                 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12735                                         }
12736                                         break;
12737                                 }
12738                                 case 'dt': {
12739                                         $this->lispacer = '';
12740                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12741                                         break;
12742                                 }
12743                                 case 'dd': {
12744                                         $this->lispacer = '';
12745                                         if ($this->rtl) {
12746                                                 $this->rMargin -= $this->listindent;
12747                                         } else {
12748                                                 $this->lMargin -= $this->listindent;
12749                                         }
12750                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12751                                         break;
12752                                 }
12753                                 case 'ul':
12754                                 case 'ol': {
12755                                         --$this->listnum;
12756                                         $this->lispacer = '';
12757                                         if ($this->rtl) {
12758                                                 $this->rMargin -= $this->listindent;
12759                                         } else {
12760                                                 $this->lMargin -= $this->listindent;
12761                                         }
12762                                         if ($this->listnum <= 0) {
12763                                                 $this->listnum = 0;
12764                                                 $this->addHTMLVertSpace(2, $cell, '', $firstorlast, $tag['value'], true);
12765                                         }
12766                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
12767                                         break;
12768                                 }
12769                                 case 'li': {
12770                                         $this->lispacer = '';
12771                                         $this->addHTMLVertSpace(0, $cell, '', $firstorlast, $tag['value'], true);
12772                                         break;
12773                                 }
12774                                 case 'h1':
12775                                 case 'h2':
12776                                 case 'h3':
12777                                 case 'h4':
12778                                 case 'h5':
12779                                 case 'h6': {
12780                                         $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k, $firstorlast, $tag['value'], true);
12781                                         break;
12782                                 }
12783                                 default : {
12784                                         break;
12785                                 }
12786                         }
12787                         $this->tmprtl = false;
12788                 }
12789
12790                 /**
12791                  * Add vertical spaces if needed.
12792                  * @param int $n number of spaces to add
12793                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
12794                  * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
12795                  * @param boolean $firstorlast if true do not print additional empty lines.
12796                  * @param string $tag HTML tag to which this space will be applied
12797                  * @param boolean $closing true if this space will be applied to a closing tag, false otherwise
12798                  * @access protected
12799                  */
12800                 protected function addHTMLVertSpace($n, $cell=false, $h='', $firstorlast=false, $tag='', $closing=false) {
12801                         if ($firstorlast) {
12802                                 $this->Ln(0, $cell);
12803                                 $this->htmlvspace = 0;
12804                                 return;
12805                         }
12806                         if (isset($this->tagvspaces[$tag][intval($closing)]['n'])) {
12807                                 $n = $this->tagvspaces[$tag][intval($closing)]['n'];
12808                         }
12809                         if (isset($this->tagvspaces[$tag][intval($closing)]['h'])) {
12810                                 $h = $this->tagvspaces[$tag][intval($closing)]['h'];
12811                         }
12812                         if (is_string($h)) {
12813                                 $vsize = $n * $this->lasth;
12814                         } else {
12815                                 $vsize = $n * $h;
12816                         }
12817                         if ($vsize > $this->htmlvspace) {
12818                                 $this->Ln(($vsize - $this->htmlvspace), $cell);
12819                                 $this->htmlvspace = $vsize;
12820                         }
12821                 }
12822
12823                 /**
12824                  * Set the default bullet to be used as LI bullet symbol
12825                  * @param string $symbol character or string to be used (legal values are: '' = automatic, '!' = auto bullet, '#' = auto numbering, 'disc', 'disc', 'circle', 'square', '1', 'decimal', 'decimal-leading-zero', 'i', 'lower-roman', 'I', 'upper-roman', 'a', 'lower-alpha', 'lower-latin', 'A', 'upper-alpha', 'upper-latin', 'lower-greek')
12826                  * @access public
12827                  * @since 4.0.028 (2008-09-26)
12828                  */
12829                 public function setLIsymbol($symbol='!') {
12830                         $symbol = strtolower($symbol);
12831                         switch ($symbol) {
12832                                 case '!' :
12833                                 case '#' :
12834                                 case 'disc' :
12835                                 case 'disc' :
12836                                 case 'circle' :
12837                                 case 'square' :
12838                                 case '1':
12839                                 case 'decimal':
12840                                 case 'decimal-leading-zero':
12841                                 case 'i':
12842                                 case 'lower-roman':
12843                                 case 'I':
12844                                 case 'upper-roman':
12845                                 case 'a':
12846                                 case 'lower-alpha':
12847                                 case 'lower-latin':
12848                                 case 'A':
12849                                 case 'upper-alpha':
12850                                 case 'upper-latin':
12851                                 case 'lower-greek': {
12852                                         $this->lisymbol = $symbol;
12853                                         break;
12854                                 }
12855                                 default : {
12856                                         $this->lisymbol = '';
12857                                 }
12858                         }
12859                 }
12860
12861                 /**
12862                 * Set the booklet mode for double-sided pages.
12863                 * @param boolean $booklet true set the booklet mode on, fals eotherwise.
12864                 * @param float $inner Inner page margin.
12865                 * @param float $outer Outer page margin.
12866                 * @access public
12867                 * @since 4.2.000 (2008-10-29)
12868                 */
12869                 public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
12870                         $this->booklet = $booklet;
12871                         if ($inner >= 0) {
12872                                 $this->lMargin = $inner;
12873                         }
12874                         if ($outer >= 0) {
12875                                 $this->rMargin = $outer;
12876                         }
12877                 }
12878
12879                 /**
12880                 * Swap the left and right margins.
12881                 * @param boolean $reverse if true swap left and right margins.
12882                 * @access protected
12883                 * @since 4.2.000 (2008-10-29)
12884                 */
12885                 protected function swapMargins($reverse=true) {
12886                         if ($reverse) {
12887                                 // swap left and right margins
12888                                 $mtemp = $this->original_lMargin;
12889                                 $this->original_lMargin = $this->original_rMargin;
12890                                 $this->original_rMargin = $mtemp;
12891                                 $deltam = $this->original_lMargin - $this->original_rMargin;
12892                                 $this->lMargin += $deltam;
12893                                 $this->rMargin -= $deltam;
12894                         }
12895                 }
12896
12897                 /**
12898                 * Set the vertical spaces for HTML tags.
12899                 * The array must have the following structure (example):
12900                 * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
12901                 * The first array level contains the tag names,
12902                 * the second level contains 0 for opening tags or 1 for closing tags,
12903                 * the third level contains the vertical space unit (h) and the number spaces to add (n).
12904                 * If the h parameter is not specified, default values are used.
12905                 * @param array $tagvs array of tags and relative vertical spaces.
12906                 * @access public
12907                 * @since 4.2.001 (2008-10-30)
12908                 */
12909                 public function setHtmlVSpace($tagvs) {
12910                         $this->tagvspaces = $tagvs;
12911                 }
12912
12913         /**
12914                 * Set custom width for list indentation.
12915                 * @param float $width width of the indentation. Use negative value to disable it.
12916                 * @access public
12917                 * @since 4.2.007 (2008-11-12)
12918                 */
12919                 public function setListIndentWidth($width) {
12920                         return $this->customlistindent = floatval($width);
12921         }
12922
12923         /**
12924                 * Set the top/bottom cell sides to be open or closed when the cell cross the page.
12925                 * @param boolean $isopen if true keeps the top/bottom border open for the cell sides that cross the page.
12926                 * @access public
12927                 * @since 4.2.010 (2008-11-14)
12928                 */
12929                 public function setOpenCell($isopen) {
12930                         $this->opencell = $isopen;
12931         }
12932
12933         /**
12934                 * Set the color and font style for HTML links.
12935                 * @param array $color RGB array of colors
12936                 * @param string $fontstyle additional font styles to add
12937                 * @access public
12938                 * @since 4.4.003 (2008-12-09)
12939                 */
12940                 public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
12941                         $this->htmlLinkColorArray = $color;
12942                         $this->htmlLinkFontStyle = $fontstyle;
12943         }
12944
12945         /**
12946                 * convert html string containing value and unit of measure to user's units or points.
12947                 * @param string $htmlval string containing values and unit
12948                 * @param string $refsize reference value in points
12949                 * @param string $defaultunit default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
12950                 * @param boolean $point if true returns points, otherwise returns value in user's units
12951                 * @return float value in user's unit or point if $points=true
12952                 * @access public
12953                 * @since 4.4.004 (2008-12-10)
12954                 */
12955         public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
12956                         $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
12957                         $retval = 0;
12958                         $value = 0;
12959                         $unit = 'px';
12960                         $k = $this->k;
12961                         if ($points) {
12962                                 $k = 1;
12963                         }
12964                         if (in_array($defaultunit, $supportedunits)) {
12965                                 $unit = $defaultunit;
12966                         }
12967                         if (is_numeric($htmlval)) {
12968                                 $value = floatval($htmlval);
12969                         } elseif (preg_match('/([0-9\.]+)/', $htmlval, $mnum)) {
12970                                 $value = floatval($mnum[1]);
12971                                 if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
12972                                         if (in_array($munit[1], $supportedunits)) {
12973                                                 $unit = $munit[1];
12974                                         }
12975                                 }
12976                         }
12977                         switch ($unit) {
12978                                 // percentage
12979                                 case '%': {
12980                                         $retval = (($value * $refsize) / 100);
12981                                         break;
12982                                 }
12983                                 // relative-size
12984                                 case 'em': {
12985                                         $retval = ($value * $refsize);
12986                                         break;
12987                                 }
12988                                 case 'ex': {
12989                                         $retval = $value * ($refsize / 2);
12990                                         break;
12991                                 }
12992                                 // absolute-size
12993                                 case 'in': {
12994                                         $retval = ($value * $this->dpi) / $k;
12995                                         break;
12996                                 }
12997                                 case 'cm': {
12998                                         $retval = ($value / 2.54 * $this->dpi) / $k;
12999                                         break;
13000                                 }
13001                                 case 'mm': {
13002                                         $retval = ($value / 25.4 * $this->dpi) / $k;
13003                                         break;
13004                                 }
13005                                 case 'pc': {
13006                                         // one pica is 12 points
13007                                         $retval = ($value * 12) / $k;
13008                                         break;
13009                                 }
13010                                 case 'pt': {
13011                                         $retval = $value / $k;
13012                                         break;
13013                                 }
13014                                 case 'px': {
13015                                         $retval = $this->pixelsToUnits($value);
13016                                         break;
13017                                 }
13018                         }
13019                         return $retval;
13020                 }
13021
13022                 /**
13023                 * Returns the Roman representation of an integer number
13024                 * @param int number to convert
13025                 * @return string roman representation of the specified number
13026                 * @access public
13027                 * @since 4.4.004 (2008-12-10)
13028                 */
13029                 public function intToRoman($number) {
13030                         $roman = '';
13031                         while ($number >= 1000) {
13032                                 $roman .= 'M';
13033                                 $number -= 1000;
13034                         }
13035                         while ($number >= 900) {
13036                                 $roman .= 'CM';
13037                                 $number -= 900;
13038                         }
13039                         while ($number >= 500) {
13040                                 $roman .= 'D';
13041                                 $number -= 500;
13042                         }
13043                         while ($number >= 400) {
13044                                 $roman .= 'CD';
13045                                 $number -= 400;
13046                         }
13047                         while ($number >= 100) {
13048                                 $roman .= 'C';
13049                                 $number -= 100;
13050                         }
13051                         while ($number >= 90) {
13052                         $roman .= 'XC';
13053                         $number -= 90;
13054                         }
13055                         while ($number >= 50) {
13056                                 $roman .= 'L';
13057                                 $number -= 50;
13058                         }
13059                         while ($number >= 40) {
13060                                 $roman .= 'XL';
13061                                 $number -= 40;
13062                         }
13063                         while ($number >= 10) {
13064                         $roman .= 'X';
13065                         $number -= 10;
13066                         }
13067                         while ($number >= 9) {
13068                                 $roman .= 'IX';
13069                                 $number -= 9;
13070                         }
13071                         while ($number >= 5) {
13072                                 $roman .= 'V';
13073                                 $number -= 5;
13074                         }
13075                         while ($number >= 4) {
13076                         $roman .= 'IV';
13077                         $number -= 4;
13078                         }
13079                         while ($number >= 1) {
13080                                 $roman .= 'I';
13081                                 --$number;
13082                         }
13083                         return $roman;
13084                 }
13085
13086                 /**
13087                 * Output an HTML list bullet or ordered item symbol
13088                 * @param int $listdepth list nesting level
13089                 * @param string $listtype type of list
13090                 * @param float $size current font size
13091                 * @access protected
13092                 * @since 4.4.004 (2008-12-10)
13093                 */
13094                 protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
13095                     $size /= $this->k;
13096                     $fill = '';
13097                     $color = $this->fgcolor;
13098                     $width = 0;
13099                     $textitem = '';
13100                     $tmpx = $this->x;
13101                         $lspace = $this->GetStringWidth('  ');
13102                         if ($listtype == '!') {
13103                                 // set default list type for unordered list
13104                                 $deftypes = array('disc', 'circle', 'square');
13105                                 $listtype = $deftypes[($listdepth - 1) % 3];
13106                         } elseif ($listtype == '#') {
13107                                 // set default list type for ordered list
13108                                 $listtype = 'decimal';
13109                         }
13110                 switch ($listtype) {
13111                         // unordered types
13112                                 case 'none': {
13113                                         break;
13114                                 }
13115                                 case 'disc': {
13116                                         $fill = 'F';
13117                                 }
13118                                 case 'circle': {
13119                                         $fill .= 'D';
13120                                         $r = $size / 6;
13121                                         $lspace += (2 * $r);
13122                                         if ($this->rtl) {
13123                                                 $this->x = $this->w - $this->x - $lspace;
13124                                         } else {
13125                                                 $this->x -= $lspace;
13126                                         }
13127                                         $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, $fill, array('color'=>$color), $color, 8);
13128                                         break;
13129                                 }
13130                                 case 'square': {
13131                                         $l = $size / 3;
13132                                         $lspace += $l;
13133                                         if ($this->rtl) {
13134                                                 $this->x = $this->w - $this->x - $lspace;
13135                                         } else {
13136                                                 $this->x -= $lspace;
13137                                         }
13138                                         $this->Rect($this->x, ($this->y + (($this->lasth - $l)/ 2)), $l, $l, 'F', array(), $color);
13139                                         break;
13140                                 }
13141                                 // ordered types
13142
13143                                 // $this->listcount[$this->listnum];
13144                                 // $textitem
13145                                 case '1':
13146                                 case 'decimal': {
13147                                         $textitem = $this->listcount[$this->listnum];
13148                                         break;
13149                                 }
13150                                 case 'decimal-leading-zero': {
13151                                         $textitem = sprintf("%02d", $this->listcount[$this->listnum]);
13152                                         break;
13153                                 }
13154                                 case 'i':
13155                                 case 'lower-roman': {
13156                                         $textitem = strtolower($this->intToRoman($this->listcount[$this->listnum]));
13157                                         break;
13158                                 }
13159                                 case 'I':
13160                                 case 'upper-roman': {
13161                                         $textitem = $this->intToRoman($this->listcount[$this->listnum]);
13162                                         break;
13163                                 }
13164                                 case 'a':
13165                                 case 'lower-alpha':
13166                                 case 'lower-latin': {
13167                                         $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
13168                                         break;
13169                                 }
13170                                 case 'A':
13171                                 case 'upper-alpha':
13172                                 case 'upper-latin': {
13173                                         $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
13174                                         break;
13175                                 }
13176                                 case 'lower-greek': {
13177                                         $textitem = $this->unichr(945 + $this->listcount[$this->listnum] - 1);
13178                                         break;
13179                                 }
13180                                 /*
13181                                 // Types to be implemented (special handling)
13182                                 case 'hebrew': {
13183                                         break;
13184                                 }
13185                                 case 'armenian': {
13186                                         break;
13187                                 }
13188                                 case 'georgian': {
13189                                         break;
13190                                 }
13191                                 case 'cjk-ideographic': {
13192                                         break;
13193                                 }
13194                                 case 'hiragana': {
13195                                         break;
13196                                 }
13197                                 case 'katakana': {
13198                                         break;
13199                                 }
13200                                 case 'hiragana-iroha': {
13201                                         break;
13202                                 }
13203                                 case 'katakana-iroha': {
13204                                         break;
13205                                 }
13206                                 */
13207                                 default: {
13208                                         $textitem = $this->listcount[$this->listnum];
13209                                 }
13210                         }
13211                         if (!$this->empty_string($textitem)) {
13212                                 // print ordered item
13213                                 if ($this->rtl) {
13214                                         $textitem = '.'.$textitem;
13215                                 } else {
13216                                         $textitem = $textitem.'.';
13217                                 }
13218                                 $lspace += $this->GetStringWidth($textitem);
13219                                 if ($this->rtl) {
13220                                         $this->x += $lspace;
13221                                 } else {
13222                                         $this->x -= $lspace;
13223                                 }
13224                                 $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
13225                         }
13226                         $this->x = $tmpx;
13227                         $this->lispacer = '';
13228                 }
13229
13230         /**
13231                 * Returns current graphic variables as array.
13232                 * @return array graphic variables
13233                 * @access protected
13234                 * @since 4.2.010 (2008-11-14)
13235                 */
13236                 protected function getGraphicVars() {
13237                         $grapvars = array(
13238                                 'FontFamily' => $this->FontFamily,
13239                                 'FontStyle' => $this->FontStyle,
13240                                 'FontSizePt' => $this->FontSizePt,
13241                                 'rMargin' => $this->rMargin,
13242                                 'lMargin' => $this->lMargin,
13243                                 'cMargin' => $this->cMargin,
13244                                 'LineWidth' => $this->LineWidth,
13245                                 'linestyleWidth' => $this->linestyleWidth,
13246                                 'linestyleCap' => $this->linestyleCap,
13247                                 'linestyleJoin' => $this->linestyleJoin,
13248                                 'linestyleDash' => $this->linestyleDash,
13249                                 'DrawColor' => $this->DrawColor,
13250                                 'FillColor' => $this->FillColor,
13251                                 'TextColor' => $this->TextColor,
13252                                 'ColorFlag' => $this->ColorFlag,
13253                                 'bgcolor' => $this->bgcolor,
13254                                 'fgcolor' => $this->fgcolor,
13255                                 'htmlvspace' => $this->htmlvspace,
13256                                 'lasth' => $this->lasth
13257                                 );
13258                         return $grapvars;
13259                 }
13260
13261         /**
13262                 * Set graphic variables.
13263                 * @param $gvars array graphic variables
13264                 * @access protected
13265                 * @since 4.2.010 (2008-11-14)
13266                 */
13267                 protected function setGraphicVars($gvars) {
13268                         $this->FontFamily = $gvars['FontFamily'];
13269                         $this->FontStyle = $gvars['FontStyle'];
13270                         $this->FontSizePt = $gvars['FontSizePt'];
13271                         $this->rMargin = $gvars['rMargin'];
13272                         $this->lMargin = $gvars['lMargin'];
13273                         $this->cMargin = $gvars['cMargin'];
13274                         $this->LineWidth = $gvars['LineWidth'];
13275                         $this->linestyleWidth = $gvars['linestyleWidth'];
13276                         $this->linestyleCap = $gvars['linestyleCap'];
13277                         $this->linestyleJoin = $gvars['linestyleJoin'];
13278                         $this->linestyleDash = $gvars['linestyleDash'];
13279                         $this->DrawColor = $gvars['DrawColor'];
13280                         $this->FillColor = $gvars['FillColor'];
13281                         $this->TextColor = $gvars['TextColor'];
13282                         $this->ColorFlag = $gvars['ColorFlag'];
13283                         $this->bgcolor = $gvars['bgcolor'];
13284                         $this->fgcolor = $gvars['fgcolor'];
13285                         $this->htmlvspace = $gvars['htmlvspace'];
13286                         //$this->lasth = $gvars['lasth'];
13287                         $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
13288                         if (!$this->empty_string($this->FontFamily)) {
13289                                 $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
13290                         }
13291                 }
13292
13293                 /**
13294                 * Returns a temporary filename for caching object on filesystem.
13295                 * @param string $prefix prefix to add to filename
13296                 * return string filename.
13297                 * @access protected
13298                 * @since 4.5.000 (2008-12-31)
13299                 */
13300                 protected function getObjFilename($name) {
13301                         return tempnam(K_PATH_CACHE, $name.'_');
13302                 }
13303
13304         /**
13305                 * Writes data to a temporary file on filesystem.
13306                 * @param string $file file name
13307                 * @param mixed $data data to write on file
13308                 * @param boolean $append if true append data, false replace.
13309                 * @access protected
13310                 * @since 4.5.000 (2008-12-31)
13311                 */
13312                 protected function writeDiskCache($filename, $data, $append=false) {
13313                         if ($append) {
13314                                 $fmode = 'ab+';
13315                         } else {
13316                                 $fmode = 'wb+';
13317                         }
13318                         $f = @fopen($filename, $fmode);
13319                         if (!$f) {
13320                                 $this->Error('Unable to write cache file: '.$filename);
13321                         } else {
13322                                 fwrite($f, $data);
13323                                 fclose($f);
13324                         }
13325                         // update file lenght (needed for transactions)
13326                         if (!isset($this->cache_file_lenght['_'.$filename])) {
13327                                 $this->cache_file_lenght['_'.$filename] = strlen($data);
13328                         } else {
13329                                 $this->cache_file_lenght['_'.$filename] += strlen($data);
13330                         }
13331                 }
13332
13333         /**
13334                 * Read data from a temporary file on filesystem.
13335                 * @param string $file file name
13336                 * @return mixed retrieved data
13337                 * @access protected
13338                 * @since 4.5.000 (2008-12-31)
13339                 */
13340                 protected function readDiskCache($filename) {
13341                         return file_get_contents($filename);
13342                 }
13343
13344                 /**
13345                 * Set buffer content (always append data).
13346                 * @param string $data data
13347                 * @access protected
13348                 * @since 4.5.000 (2009-01-02)
13349                 */
13350                 protected function setBuffer($data) {
13351                         $this->bufferlen += strlen($data);
13352                         if ($this->diskcache) {
13353                                 if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
13354                                         $this->buffer = $this->getObjFilename('buffer');
13355                                 }
13356                                 $this->writeDiskCache($this->buffer, $data, true);
13357                         } else {
13358                                 $this->buffer .= $data;
13359                         }
13360                 }
13361
13362         /**
13363                 * Get buffer content.
13364                 * @return string buffer content
13365                 * @access protected
13366                 * @since 4.5.000 (2009-01-02)
13367                 */
13368                 protected function getBuffer() {
13369                         if ($this->diskcache) {
13370                                 return $this->readDiskCache($this->buffer);
13371                         } else {
13372                                 return $this->buffer;
13373                         }
13374                 }
13375
13376         /**
13377                 * Set page buffer content.
13378                 * @param int $page page number
13379                 * @param string $data page data
13380                 * @param boolean $append if true append data, false replace.
13381                 * @access protected
13382                 * @since 4.5.000 (2008-12-31)
13383                 */
13384                 protected function setPageBuffer($page, $data, $append=false) {
13385                         if ($this->diskcache) {
13386                                 if (!isset($this->pages[$page])) {
13387                                         $this->pages[$page] = $this->getObjFilename('page'.$page);
13388                                 }
13389                                 $this->writeDiskCache($this->pages[$page], $data, $append);
13390                         } else {
13391                                 if ($append) {
13392                                         $this->pages[$page] .= $data;
13393                                 } else {
13394                                         $this->pages[$page] = $data;
13395                                 }
13396                         }
13397                         if ($append AND isset($this->pagelen[$page])) {
13398                                 $this->pagelen[$page] += strlen($data);
13399                         } else {
13400                                 $this->pagelen[$page] = strlen($data);
13401                         }
13402                 }
13403
13404         /**
13405                 * Get page buffer content.
13406                 * @param int $page page number
13407                 * @return string page buffer content or false in case of error
13408                 * @access protected
13409                 * @since 4.5.000 (2008-12-31)
13410                 */
13411                 protected function getPageBuffer($page) {
13412                         if ($this->diskcache) {
13413                                 return $this->readDiskCache($this->pages[$page]);
13414                         } elseif (isset($this->pages[$page])) {
13415                                 return $this->pages[$page];
13416                         }
13417                         return false;
13418                 }
13419
13420         /**
13421                 * Set image buffer content.
13422                 * @param string $image image key
13423                 * @param array $data image data
13424                 * @access protected
13425                 * @since 4.5.000 (2008-12-31)
13426                 */
13427                 protected function setImageBuffer($image, $data) {
13428                         if ($this->diskcache) {
13429                                 if (!isset($this->images[$image])) {
13430                                         $this->images[$image] = $this->getObjFilename('image'.$image);
13431                                 }
13432                                 $this->writeDiskCache($this->images[$image], serialize($data));
13433                         } else {
13434                                 $this->images[$image] = $data;
13435                         }
13436                         if (!in_array($image, $this->imagekeys)) {
13437                                 $this->imagekeys[] = $image;
13438                         }
13439                         ++$this->numimages;
13440                 }
13441
13442         /**
13443                 * Set image buffer content.
13444                 * @param string $image image key
13445                 * @param string $key image sub-key
13446                 * @param array $data image data
13447                 * @access protected
13448                 * @since 4.5.000 (2008-12-31)
13449                 */
13450                 protected function setImageSubBuffer($image, $key, $data) {
13451                         if (!isset($this->images[$image])) {
13452                                 $this->setImageBuffer($image, array());
13453                         }
13454                         if ($this->diskcache) {
13455                                 $tmpimg = $this->getImageBuffer($image);
13456                                 $tmpimg[$key] = $data;
13457                                 $this->writeDiskCache($this->images[$image], serialize($tmpimg));
13458                         } else {
13459                                 $this->images[$image][$key] = $data;
13460                         }
13461                 }
13462
13463         /**
13464                 * Get page buffer content.
13465                 * @param string $image image key
13466                 * @return string image buffer content or false in case of error
13467                 * @access protected
13468                 * @since 4.5.000 (2008-12-31)
13469                 */
13470                 protected function getImageBuffer($image) {
13471                         if ($this->diskcache AND isset($this->images[$image])) {
13472                                 return unserialize($this->readDiskCache($this->images[$image]));
13473                         } elseif (isset($this->images[$image])) {
13474                                 return $this->images[$image];
13475                         }
13476                         return false;
13477                 }
13478
13479                 /**
13480                 * Set font buffer content.
13481                 * @param string $font font key
13482                 * @param array $data font data
13483                 * @access protected
13484                 * @since 4.5.000 (2009-01-02)
13485                 */
13486                 protected function setFontBuffer($font, $data) {
13487                         if ($this->diskcache) {
13488                                 if (!isset($this->fonts[$font])) {
13489                                         $this->fonts[$font] = $this->getObjFilename('font');
13490                                 }
13491                                 $this->writeDiskCache($this->fonts[$font], serialize($data));
13492                         } else {
13493                                 $this->fonts[$font] = $data;
13494                         }
13495                         if (!in_array($font, $this->fontkeys)) {
13496                                 $this->fontkeys[] = $font;
13497                         }
13498                 }
13499
13500         /**
13501                 * Set font buffer content.
13502                 * @param string $font font key
13503                 * @param string $key font sub-key
13504                 * @param array $data font data
13505                 * @access protected
13506                 * @since 4.5.000 (2009-01-02)
13507                 */
13508                 protected function setFontSubBuffer($font, $key, $data) {
13509                         if (!isset($this->fonts[$font])) {
13510                                 $this->setFontBuffer($font, array());
13511                         }
13512                         if ($this->diskcache) {
13513                                 $tmpfont = $this->getFontBuffer($font);
13514                                 $tmpfont[$key] = $data;
13515                                 $this->writeDiskCache($this->fonts[$font], serialize($tmpfont));
13516                         } else {
13517                                 $this->fonts[$font][$key] = $data;
13518                         }
13519                 }
13520
13521         /**
13522                 * Get font buffer content.
13523                 * @param string $font font key
13524                 * @return string font buffer content or false in case of error
13525                 * @access protected
13526                 * @since 4.5.000 (2009-01-02)
13527                 */
13528                 protected function getFontBuffer($font) {
13529                         if ($this->diskcache AND isset($this->fonts[$font])) {
13530                                 return unserialize($this->readDiskCache($this->fonts[$font]));
13531                         } elseif (isset($this->fonts[$font])) {
13532                                 return $this->fonts[$font];
13533                         }
13534                         return false;
13535                 }
13536
13537         /**
13538                 * Move a page to a previous position.
13539                 * @param int $frompage number of the source page
13540                 * @param int $topage number of the destination page (must be less than $frompage)
13541                 * @return true in case of success, false in case of error.
13542                 * @access public
13543                 * @since 4.5.000 (2009-01-02)
13544                 */
13545                 public function movePage($frompage, $topage) {
13546                         if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
13547                                 return false;
13548                         }
13549                         if ($frompage == $this->page) {
13550                                 // close the page before moving it
13551                                 $this->endPage();
13552                         }
13553                         // move all page-related states
13554                         $tmppage = $this->pages[$frompage];
13555                         $tmppagedim = $this->pagedim[$frompage];
13556                         $tmppagelen = $this->pagelen[$frompage];
13557                         $tmpintmrk = $this->intmrk[$frompage];
13558                         if (isset($this->footerpos[$frompage])) {
13559                                 $tmpfooterpos = $this->footerpos[$frompage];
13560                         }
13561                         if (isset($this->footerlen[$frompage])) {
13562                                 $tmpfooterlen = $this->footerlen[$frompage];
13563                         }
13564                         if (isset($this->transfmrk[$frompage])) {
13565                                 $tmptransfmrk = $this->transfmrk[$frompage];
13566                         }
13567                         if (isset($this->PageAnnots[$frompage])) {
13568                                 $tmpannots = $this->PageAnnots[$frompage];
13569                         }
13570                         if (isset($this->newpagegroup[$frompage])) {
13571                                 $tmpnewpagegroup = $this->newpagegroup[$frompage];
13572                         }
13573                         for ($i = $frompage; $i > $topage; --$i) {
13574                                 $j = $i - 1;
13575                                 // shift pages down
13576                                 $this->pages[$i] = $this->pages[$j];
13577                                 $this->pagedim[$i] = $this->pagedim[$j];
13578                                 $this->pagelen[$i] = $this->pagelen[$j];
13579                                 $this->intmrk[$i] = $this->intmrk[$j];
13580                                 if (isset($this->footerpos[$j])) {
13581                                         $this->footerpos[$i] = $this->footerpos[$j];
13582                                 } elseif (isset($this->footerpos[$i])) {
13583                                         unset($this->footerpos[$i]);
13584                                 }
13585                                 if (isset($this->footerlen[$j])) {
13586                                         $this->footerlen[$i] = $this->footerlen[$j];
13587                                 } elseif (isset($this->footerlen[$i])) {
13588                                         unset($this->footerlen[$i]);
13589                                 }
13590                                 if (isset($this->transfmrk[$j])) {
13591                                         $this->transfmrk[$i] = $this->transfmrk[$j];
13592                                 } elseif (isset($this->transfmrk[$i])) {
13593                                         unset($this->transfmrk[$i]);
13594                                 }
13595                                 if (isset($this->PageAnnots[$j])) {
13596                                         $this->PageAnnots[$i] = $this->PageAnnots[$j];
13597                                 } elseif (isset($this->PageAnnots[$i])) {
13598                                         unset($this->PageAnnots[$i]);
13599                                 }
13600                                 if (isset($this->newpagegroup[$j])) {
13601                                         $this->newpagegroup[$i] = $this->newpagegroup[$j];
13602                                 } elseif (isset($this->newpagegroup[$i])) {
13603                                         unset($this->newpagegroup[$i]);
13604                                 }
13605                         }
13606                         $this->pages[$topage] = $tmppage;
13607                         $this->pagedim[$topage] = $tmppagedim;
13608                         $this->pagelen[$topage] = $tmppagelen;
13609                         $this->intmrk[$topage] = $tmpintmrk;
13610                         if (isset($tmpfooterpos)) {
13611                                 $this->footerpos[$topage] = $tmpfooterpos;
13612                         } elseif (isset($this->footerpos[$topage])) {
13613                                 unset($this->footerpos[$topage]);
13614                         }
13615                         if (isset($tmpfooterlen)) {
13616                                 $this->footerlen[$topage] = $tmpfooterlen;
13617                         } elseif (isset($this->footerlen[$topage])) {
13618                                 unset($this->footerlen[$topage]);
13619                         }
13620                         if (isset($tmptransfmrk)) {
13621                                 $this->transfmrk[$topage] = $tmptransfmrk;
13622                         } elseif (isset($this->transfmrk[$topage])) {
13623                                 unset($this->transfmrk[$topage]);
13624                         }
13625                         if (isset($tmpannots)) {
13626                                 $this->PageAnnots[$topage] = $tmpannots;
13627                         } elseif (isset($this->PageAnnots[$topage])) {
13628                                 unset($this->PageAnnots[$topage]);
13629                         }
13630                         if (isset($tmpnewpagegroup)) {
13631                                 $this->newpagegroup[$topage] = $tmpnewpagegroup;
13632                         } elseif (isset($this->newpagegroup[$topage])) {
13633                                 unset($this->newpagegroup[$topage]);
13634                         }
13635                         // adjust outlines
13636                         $tmpoutlines = $this->outlines;
13637                         foreach ($tmpoutlines as $key => $outline) {
13638                                 if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
13639                                         $this->outlines[$key]['p'] = $outline['p'] + 1;
13640                                 } elseif ($outline['p'] == $frompage) {
13641                                         $this->outlines[$key]['p'] = $topage;
13642                                 }
13643                         }
13644                         // adjust links
13645                         $tmplinks = $this->links;
13646                         foreach ($tmplinks as $key => $link) {
13647                                 if (($link[0] >= $topage) AND ($link[0] < $frompage)) {
13648                                         $this->links[$key][0] = $link[0] + 1;
13649                                 } elseif ($link[0] == $frompage) {
13650                                         $this->links[$key][0] = $topage;
13651                                 }
13652                         }
13653                         // adjust javascript
13654                         $tmpjavascript = $this->javascript;
13655                         global $jfrompage, $jtopage;
13656                         $jfrompage = $frompage;
13657                         $jtopage = $topage;
13658                         $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
13659                                 create_function('$matches', 'global $jfrompage, $jtopage;
13660                                 $pagenum = intval($matches[3]) + 1;
13661                                 if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
13662                                         $newpage = ($pagenum + 1);
13663                                 } elseif ($pagenum == $jfrompage) {
13664                                         $newpage = $jtopage;
13665                                 } else {
13666                                         $newpage = $pagenum;
13667                                 }
13668                                 --$newpage;
13669                                 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
13670                         // return to last page
13671                         $this->lastPage(true);
13672                         return true;
13673                 }
13674
13675         /**
13676                 * Remove the specified page.
13677                 * @param int $page page to remove
13678                 * @return true in case of success, false in case of error.
13679                 * @access public
13680                 * @since 4.6.004 (2009-04-23)
13681                 */
13682                 public function deletePage($page) {
13683                         if ($page > $this->numpages) {
13684                                 return false;
13685                         }
13686                         // delete current page
13687                         unset($this->pages[$page]);
13688                         unset($this->pagedim[$page]);
13689                         unset($this->pagelen[$page]);
13690                         unset($this->intmrk[$page]);
13691                         if (isset($this->footerpos[$page])) {
13692                                 unset($this->footerpos[$page]);
13693                         }
13694                         if (isset($this->footerlen[$page])) {
13695                                 unset($this->footerlen[$page]);
13696                         }
13697                         if (isset($this->transfmrk[$page])) {
13698                                 unset($this->transfmrk[$page]);
13699                         }
13700                         if (isset($this->PageAnnots[$page])) {
13701                                 unset($this->PageAnnots[$page]);
13702                         }
13703                         if (isset($this->newpagegroup[$page])) {
13704                                 unset($this->newpagegroup[$page]);
13705                         }
13706                         if (isset($this->pageopen[$page])) {
13707                                 unset($this->pageopen[$page]);
13708                         }
13709                         // update remaining pages
13710                         for ($i = $page; $i < $this->numpages; ++$i) {
13711                                 $j = $i + 1;
13712                                 // shift pages
13713                                 $this->pages[$i] = $this->pages[$j];
13714                                 $this->pagedim[$i] = $this->pagedim[$j];
13715                                 $this->pagelen[$i] = $this->pagelen[$j];
13716                                 $this->intmrk[$i] = $this->intmrk[$j];
13717                                 if (isset($this->footerpos[$j])) {
13718                                         $this->footerpos[$i] = $this->footerpos[$j];
13719                                 } elseif (isset($this->footerpos[$i])) {
13720                                         unset($this->footerpos[$i]);
13721                                 }
13722                                 if (isset($this->footerlen[$j])) {
13723                                         $this->footerlen[$i] = $this->footerlen[$j];
13724                                 } elseif (isset($this->footerlen[$i])) {
13725                                         unset($this->footerlen[$i]);
13726                                 }
13727                                 if (isset($this->transfmrk[$j])) {
13728                                         $this->transfmrk[$i] = $this->transfmrk[$j];
13729                                 } elseif (isset($this->transfmrk[$i])) {
13730                                         unset($this->transfmrk[$i]);
13731                                 }
13732                                 if (isset($this->PageAnnots[$j])) {
13733                                         $this->PageAnnots[$i] = $this->PageAnnots[$j];
13734                                 } elseif (isset($this->PageAnnots[$i])) {
13735                                         unset($this->PageAnnots[$i]);
13736                                 }
13737                                 if (isset($this->newpagegroup[$j])) {
13738                                         $this->newpagegroup[$i] = $this->newpagegroup[$j];
13739                                 } elseif (isset($this->newpagegroup[$i])) {
13740                                         unset($this->newpagegroup[$i]);
13741                                 }
13742                                 if (isset($this->pageopen[$j])) {
13743                                         $this->pageopen[$i] = $this->pageopen[$j];
13744                                 } elseif (isset($this->pageopen[$i])) {
13745                                         unset($this->pageopen[$i]);
13746                                 }
13747                         }
13748                         // remove last page
13749                         unset($this->pages[$this->numpages]);
13750                         unset($this->pagedim[$this->numpages]);
13751                         unset($this->pagelen[$this->numpages]);
13752                         unset($this->intmrk[$this->numpages]);
13753                         if (isset($this->footerpos[$this->numpages])) {
13754                                 unset($this->footerpos[$this->numpages]);
13755                         }
13756                         if (isset($this->footerlen[$this->numpages])) {
13757                                 unset($this->footerlen[$this->numpages]);
13758                         }
13759                         if (isset($this->transfmrk[$this->numpages])) {
13760                                 unset($this->transfmrk[$this->numpages]);
13761                         }
13762                         if (isset($this->PageAnnots[$this->numpages])) {
13763                                 unset($this->PageAnnots[$this->numpages]);
13764                         }
13765                         if (isset($this->newpagegroup[$this->numpages])) {
13766                                 unset($this->newpagegroup[$this->numpages]);
13767                         }
13768                         if (isset($this->pageopen[$this->numpages])) {
13769                                 unset($this->pageopen[$this->numpages]);
13770                         }
13771                         --$this->numpages;
13772                         $this->page = $this->numpages;
13773                         // adjust outlines
13774                         $tmpoutlines = $this->outlines;
13775                         foreach ($tmpoutlines as $key => $outline) {
13776                                 if ($outline['p'] > $page) {
13777                                         $this->outlines[$key]['p'] = $outline['p'] - 1;
13778                                 } elseif ($outline['p'] == $page) {
13779                                         unset($this->outlines[$key]);
13780                                 }
13781                         }
13782                         // adjust links
13783                         $tmplinks = $this->links;
13784                         foreach ($tmplinks as $key => $link) {
13785                                 if ($link[0] > $page) {
13786                                         $this->links[$key][0] = $link[0] - 1;
13787                                 } elseif ($link[0] == $page) {
13788                                         unset($this->links[$key]);
13789                                 }
13790                         }
13791                         // adjust javascript
13792                         $tmpjavascript = $this->javascript;
13793                         global $jpage;
13794                         $jpage = $page;
13795                         $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
13796                                 create_function('$matches', 'global $jpage;
13797                                 $pagenum = intval($matches[3]) + 1;
13798                                 if ($pagenum >= $jpage) {
13799                                         $newpage = ($pagenum - 1);
13800                                 } elseif ($pagenum == $jpage) {
13801                                         $newpage = 1;
13802                                 } else {
13803                                         $newpage = $pagenum;
13804                                 }
13805                                 --$newpage;
13806                                 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
13807                         // return to last page
13808                         $this->lastPage(true);
13809                         return true;
13810                 }
13811
13812                 /**
13813                 * Output a Table of Content Index (TOC).
13814                 * You can override this method to achieve different styles.
13815                 * @param int $page page number where this TOC should be inserted (leave empty for current page).
13816                 * @param string $numbersfont set the font for page numbers (please use monospaced font for better alignment).
13817                 * @param string $filler string used to fill the space between text and page number.
13818                 * @access public
13819                 * @author Nicola Asuni
13820                 * @since 4.5.000 (2009-01-02)
13821                 */
13822                 public function addTOC($page='', $numbersfont='', $filler='.') {
13823                         $fontsize = $this->FontSizePt;
13824                         $fontfamily = $this->FontFamily;
13825                         $fontstyle = $this->FontStyle;
13826                         $w = $this->w - $this->lMargin - $this->rMargin;
13827                         $spacer = $this->GetStringWidth(' ') * 4;
13828                         $page_first = $this->getPage();
13829                         $lmargin = $this->lMargin;
13830                         $rmargin = $this->rMargin;
13831                         $x_start = $this->GetX();
13832                         if ($this->empty_string($numbersfont)) {
13833                                 $numbersfont = $this->default_monospaced_font;
13834                         }
13835                         if ($this->empty_string($filler)) {
13836                                 $filler = ' ';
13837                         }
13838                         if ($this->empty_string($page)) {
13839                                 $gap = ' ';
13840                         } else {
13841                                 $gap = '';
13842                         }
13843                         foreach ($this->outlines as $key => $outline) {
13844                                 if ($this->rtl) {
13845                                         $aligntext = 'R';
13846                                         $alignnum = 'L';
13847                                 } else {
13848                                         $aligntext = 'L';
13849                                         $alignnum = 'R';
13850                                 }
13851                                 if ($outline['l'] == 0) {
13852                                         $this->SetFont($fontfamily, $fontstyle.'B', $fontsize);
13853                                 } else {
13854                                         $this->SetFont($fontfamily, $fontstyle, $fontsize - $outline['l']);
13855                                 }
13856                                 $indent = ($spacer * $outline['l']);
13857                                 if ($this->rtl) {
13858                                         $this->rMargin += $indent;
13859                                         $this->x -= $indent;
13860                                 } else {
13861                                         $this->lMargin += $indent;
13862                                         $this->x += $indent;
13863                                 }
13864                                 $link = $this->AddLink();
13865                                 $this->SetLink($link, 0, $outline['p']);
13866                                 // write the text
13867                                 $this->Write(0, $outline['t'], $link, 0, $aligntext, false, 0, false, false, 0);
13868                                 $this->SetFont($numbersfont, $fontstyle, $fontsize);
13869                                 if ($this->empty_string($page)) {
13870                                         $pagenum = $outline['p'];
13871                                 } else {
13872                                         // placemark to be replaced with the correct number
13873                                         $pagenum = '{#'.($outline['p']).'}';
13874                                         if (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')) {
13875                                                 $pagenum = '{'.$pagenum.'}';
13876                                     }
13877                                 }
13878                                 $numwidth = $this->GetStringWidth($pagenum);
13879                                 if ($this->rtl) {
13880                                         $tw = $this->x - $this->lMargin;
13881                                 } else {
13882                                         $tw = $this->w - $this->rMargin - $this->x;
13883                                 }
13884                                 $fw = $tw - $numwidth - $this->GetStringWidth(' ');
13885                                 $numfills = floor($fw / $this->GetStringWidth($filler));
13886                                 if ($numfills > 0) {
13887                                         $rowfill = str_repeat($filler, $numfills);
13888                                 } else {
13889                                         $rowfill = '';
13890                                 }
13891                                 if ($this->rtl) {
13892                                         $pagenum = $pagenum.$gap.$rowfill.' ';
13893                                 } else {
13894                                         $pagenum = ' '.$rowfill.$gap.$pagenum;
13895                                 }
13896                                 // write the number
13897                                 //$this->SetX($x_start);
13898                                 $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
13899                                 $this->SetX($x_start);
13900                                 $this->lMargin = $lmargin;
13901                                 $this->rMargin = $rmargin;
13902                         }
13903                         $page_last = $this->getPage();
13904                         $numpages = $page_last - $page_first + 1;
13905                         if (!$this->empty_string($page)) {
13906                                 for ($p = $page_first; $p <= $page_last; ++$p) {
13907                                         // get page data
13908                                         $temppage = $this->getPageBuffer($p);
13909                                         for ($n = 1; $n <= $this->numpages; ++$n) {
13910                                                 // update page numbers
13911                                                 $k = '{#'.$n.'}';
13912                                                 $ku = '{'.$k.'}';
13913                                                 $alias_a = $this->_escape($k);
13914                                                 $alias_au = $this->_escape('{'.$k.'}');
13915                                                 if ($this->isunicode) {
13916                                                         $alias_b = $this->_escape($this->UTF8ToLatin1($k));
13917                                                         $alias_bu = $this->_escape($this->UTF8ToLatin1($ku));
13918                                                         $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
13919                                                         $alias_cu = $this->_escape($this->utf8StrRev($ku, false, $this->tmprtl));
13920                                                 }
13921                                                 if ($n >= $page) {
13922                                                         $np = $n + $numpages;
13923                                                 } else {
13924                                                         $np = $n;
13925                                                 }
13926                                                 $ns = $this->formatTOCPageNumber($np);
13927                                                 $nu = $ns;
13928                                                 $sdiff = strlen($k) - strlen($ns) - 1;
13929                                                 $sdiffu = strlen($ku) - strlen($ns) - 1;
13930                                                 $sfill = str_repeat($filler, $sdiff);
13931                                                 $sfillu = str_repeat($filler, $sdiffu);
13932                                                 if ($this->rtl) {
13933                                                         $ns = $ns.' '.$sfill;
13934                                                         $nu = $nu.' '.$sfillu;
13935                                                 } else {
13936                                                         $ns = $sfill.' '.$ns;
13937                                                         $nu = $sfillu.' '.$nu;
13938                                                 }
13939                                                 $nu = $this->UTF8ToUTF16BE($nu, false);
13940                                                 $temppage = str_replace($alias_au, $nu, $temppage);
13941                                                 if ($this->isunicode) {
13942                                                         $temppage = str_replace($alias_bu, $nu, $temppage);
13943                                                         $temppage = str_replace($alias_cu, $nu, $temppage);
13944                                                         $temppage = str_replace($alias_b, $ns, $temppage);
13945                                                         $temppage = str_replace($alias_c, $ns, $temppage);
13946                                                 }
13947                                                 $temppage = str_replace($alias_a, $ns, $temppage);
13948                                         }
13949                                         // save changes
13950                                         $this->setPageBuffer($p, $temppage);
13951                                 }
13952                                 // move pages
13953                                 for ($i = 0; $i < $numpages; ++$i) {
13954                                         $this->movePage($page_last, $page);
13955                                 }
13956                         }
13957                         $this->SetFont($fontfamily, $fontstyle, $fontsize);
13958                 }
13959
13960                 /**
13961                 * Stores a copy of the current TCPDF object used for undo operation.
13962                 * @access public
13963                 * @since 4.5.029 (2009-03-19)
13964                 */
13965                 public function startTransaction() {
13966                         if (isset($this->objcopy)) {
13967                                 // remove previous copy
13968                                 $this->commitTransaction();
13969                         }
13970                         // clone current object
13971                         $this->objcopy = $this->objclone($this);
13972                 }
13973
13974                 /**
13975                 * Delete the copy of the current TCPDF object used for undo operation.
13976                 * @access public
13977                 * @since 4.5.029 (2009-03-19)
13978                 */
13979                 public function commitTransaction() {
13980                         if (isset($this->objcopy)) {
13981                                 $this->objcopy->_destroy(true, true);
13982                                 unset($this->objcopy);
13983                         }
13984                 }
13985
13986                 /**
13987                 * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
13988                 * @return TCPDF object.
13989                 * @access public
13990                 * @since 4.5.029 (2009-03-19)
13991                 */
13992                 public function rollbackTransaction() {
13993                         if (isset($this->objcopy)) {
13994                                 if (isset($this->objcopy->diskcache) AND $this->objcopy->diskcache) {
13995                                         // truncate files to previous values
13996                                         foreach ($this->objcopy->cache_file_lenght as $file => $lenght) {
13997                                                 $file = substr($file, 1);
13998                                                 $handle = fopen($file, 'r+');
13999                                                 ftruncate($handle, $lenght);
14000                                         }
14001                                 }
14002                                 $this->_destroy(true, true);
14003                                 return $this->objcopy;
14004                         }
14005                         return $this;
14006                 }
14007
14008                 /**
14009                 * Creates a copy of a class object
14010                 * @param object $object class object to be cloned
14011                 * @return cloned object
14012                 * @access public
14013                 * @since 4.5.029 (2009-03-19)
14014                 */
14015                 public function objclone($object) {
14016                         return @clone($object);
14017                 }
14018
14019                 /**
14020                 * Determine whether a string is empty.
14021                 * @param srting $str string to be checked
14022                 * @return boolean true if string is empty
14023                 * @access public
14024                 * @since 4.5.044 (2009-04-16)
14025                 */
14026                 public function empty_string($str) {
14027                         return (is_null($str) OR (is_string($str) AND (strlen($str) == 0)));
14028                 }
14029
14030         } // END OF TCPDF CLASS
14031 }
14032 //============================================================+
14033 // END OF FILE
14034 //============================================================+
14035 ?>