Fix for exchange variation when allocating payments. re-inserted in System and GL...
[fa-stable.git] / reporting / includes / tcpdf.php
1 <?php
2 //============================================================+
3 // File name   : tcpdf.php
4 // Begin       : 2002-08-03
5 // Last Update : 2008-09-19
6 // Author      : Nicola Asuni - info@tecnick.com - http://www.tcpdf.org
7 // Version     : 4.0.027_PHP4
8 // License     : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
9 //      ----------------------------------------------------------------------------
10 //  Copyright (C) 2002-2008  Nicola Asuni - Tecnick.com S.r.l.
11 //
12 //      This program is free software: you can redistribute it and/or modify
13 //      it under the terms of the GNU Lesser General Public License as published by
14 //      the Free Software Foundation, either version 2.1 of the License, or
15 //      (at your option) any later version.
16 //
17 //      This program is distributed in the hope that it will be useful,
18 //      but WITHOUT ANY WARRANTY; without even the implied warranty of
19 //      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 //      GNU Lesser General Public License for more details.
21 //
22 //      You should have received a copy of the GNU Lesser General Public License
23 //      along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 //
25 //      See LICENSE.TXT file for more information.
26 //  ----------------------------------------------------------------------------
27 //
28 // Description : This is a PHP class for generating PDF documents without
29 //               requiring external extensions.
30 //
31 // NOTE:
32 // This class was originally derived in 2002 from the Public
33 // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
34 // but now is almost entirely rewritten.
35 //
36 // Main features:
37 //  * no external libraries are required for the basic functions;
38 //      * supports all ISO page formats;
39 //      * supports UTF-8 Unicode and Right-To-Left languages;
40 //      * supports document encryption;
41 //      * includes methods to publish some XHTML code;
42 //      * includes graphic (geometric) and transformation methods;
43 //      * includes bookmarks;
44 //      * includes Javascript and forms support;
45 //      * includes a method to print various barcode formats;
46 //      * supports TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;
47 //      * supports custom page formats, margins and units of measure;
48 //      * includes methods for page header and footer management;
49 //      * supports automatic page break;
50 //      * supports automatic page numbering and page groups;
51 //      * supports automatic line break and text justification;
52 //      * supports JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
53 //      * supports stroke and clipping mode for text;
54 //      * supports clipping masks;
55 //      * supports Grayscale, RGB, CMYK, Spot colors and transparency;
56 //      * supports links and annotations;
57 //      * supports page compression (requires zlib extension);
58 //      * supports PDF user's rights.
59 //
60 // -----------------------------------------------------------
61 // THANKS TO:
62 //
63 // Olivier Plathey (http://www.fpdf.org) for original FPDF.
64 // Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support.
65 // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm.
66 // Warren Sherliker (wsherliker@gmail.com) for better image handling.
67 // dullus for text Justification.
68 // Bob Vincent (pillarsdotnet@users.sourceforge.net) for <li> value attribute.
69 // Patrick Benny for text stretch suggestion on Cell().
70 // Johannes Güntert for JavaScript support.
71 // Denis Van Nuffelen for Dynamic Form.
72 // Jacek Czekaj for multibyte justification
73 // Anthony Ferrara for the reintroduction of legacy image methods.
74 // Sourceforge user 1707880 (hucste) for line-trough mode.
75 // Larry Stanbery for page groups.
76 // Martin Hall-May for transparency.
77 // Aaron C. Spike for Polycurve method.
78 // Mohamad Ali Golkar, Saleh AlMatrafe, Charles Abbott for Arabic and Persian support.
79 // Moritz Wagner and Andreas Wurmser for graphic functions.
80 // Andrew Whitehead for core fonts support.
81 // Esteban Joël Marín for OpenType font conversion.
82 // Teus Hagen for several suggestions and fixes.
83 // Yukihiro Nakadaira for CID-0 CJK fonts fixes.
84 // Kosmas Papachristos for some CSS improvements.
85 // Anyone that has reported a bug or sent a suggestion.
86 //============================================================+
87
88 /**
89  * This is a PHP class for generating PDF documents without requiring external extensions.<br>
90  * TCPDF project (http://www.tcpdf.org) was originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
91  * <h3>TCPDF main features are:</h3>
92  * <ul>
93  * <li>no external libraries are required for the basic functions;</li>
94  * <li>supports all ISO page formats;</li>
95  * <li>supports UTF-8 Unicode and Right-To-Left languages;</li>
96  * <li>supports document encryption;</li>
97  * <li>includes methods to publish some XHTML code;</li>
98  * <li>includes graphic (geometric) and transformation methods;</li>
99  * <li>includes bookmarks;</li>
100  * <li>includes Javascript and forms support;</li>
101  * <li>includes a method to print various barcode formats;</li>
102  * <li>supports TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;</li>
103  * <li>supports custom page formats, margins and units of measure;</li>
104  * <li>includes methods for page header and footer management;</li>
105  * <li>supports automatic page break;</li>
106  * <li>supports automatic page numbering and page groups;</li>
107  * <li>supports automatic line break and text justification;
108  * <li>supports JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;</li>
109  * <li>supports stroke and clipping mode for text;</li>
110  * <li>supports clipping masks;</li>
111  * <li>supports Grayscale, RGB and CMYK colors and transparency;</li>
112  * <li>supports links and annotations;</li>
113  * <li>supports page compression (requires zlib extension);</li>
114  * <li>supports PDF user's rights.</li>
115  * </ul>
116  * Tools to encode your unicode fonts are on fonts/utils directory.</p>
117  * @package com.tecnick.tcpdf
118  * @abstract Class for generating PDF files on-the-fly without requiring external extensions.
119  * @author Nicola Asuni
120  * @copyright 2004-2008 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
121  * @link http://www.tcpdf.org
122  * @license http://www.gnu.org/copyleft/lesser.html LGPL
123  * @version 4.0.027_PHP4
124  */
125
126 /**
127  * main configuration file
128  */
129 /** -------------------------------FrontAccounting 2.0  ---------------------------
130   * following changes are done for FrontAccounting 2.0 - Joe Hunt 06.08.2008
131   * 1. /config/tcpdf_config.php is not included, commented out
132   * 2. Following 3 defines instead:
133   *    if (!defined("K_PATH_FONTS"))
134   *        define ("K_PATH_FONTS", '../reporting/fonts/');
135   *    define ("K_PATH_CACHE", '../reporting/fonts/');
136   *    define("K_CELL_HEIGHT_RATIO", 1.25);
137   * 3. ./unicode_data2.php only included if unicode is set. (in class constructor)
138   *    We only use a reduced variant of unicode_data.php (unicode_data.php).af wrap the
139   *    following defines
140   *    if (!defined("K_RE_PATTERN_RTL"))
141   *    and
142   *    if (!defined("K_RE_PATTERN_ARABIC"))
143   * 4. Parameter $unicode in constructor renamed to $uni.
144   * 4. Header function renamed to Header1 (due to conflict with FrontReport Header)
145   * -------------------------------------------------------------------------------
146   */
147 if (!defined("K_PATH_FONTS"))
148         define ("K_PATH_FONTS", '../reporting/fonts/');
149 define ("K_PATH_CACHE", '../reporting/fonts/');
150 define("K_CELL_HEIGHT_RATIO", 1.25);
151
152 //require_once(dirname(__FILE__).'/config/tcpdf_config.php');
153
154 // includes some support files
155
156 /**
157  * unicode data
158  */
159 // only included if unicode
160 //include_once(dirname(__FILE__)."/unicode_data2.php");
161
162 /**
163  * html colors table
164  */
165 require_once(dirname(__FILE__).'/htmlcolors.php');
166
167 /**
168  * barcode class
169  */
170 require_once(dirname(__FILE__)."/barcodes.php");
171
172 /**
173  * HTML entity decode functions
174  */
175 require_once(dirname(__FILE__)."/html_entity_decode_php4.php");
176
177 if (!class_exists('TCPDF')) {
178         /**
179          * define default PDF document producer
180          */
181         define('PDF_PRODUCER','TCPDF 4.0.027_PHP4 (http://www.tcpdf.org)');
182
183         /**
184         * This is a PHP class for generating PDF documents without requiring external extensions.<br>
185         * TCPDF project (http://www.tcpdf.org) has been originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
186         * @name TCPDF
187         * @package com.tecnick.tcpdf
188         * @version 4.0.027_PHP4
189         * @author Nicola Asuni - info@tecnick.com
190         * @link http://www.tcpdf.org
191         * @license http://www.gnu.org/copyleft/lesser.html LGPL
192         */
193         class TCPDF {
194                 
195                 // protected or Protected properties
196
197                 /**
198                 * @var current page number
199                 * @access protected
200                 */
201                 var $page;
202
203                 /**
204                 * @var current object number
205                 * @access protected
206                 */
207                 var $n;
208
209                 /**
210                 * @var array of object offsets
211                 * @access protected
212                 */
213                 var $offsets;
214
215                 /**
216                 * @var buffer holding in-memory PDF
217                 * @access protected
218                 */
219                 var $buffer;
220
221                 /**
222                 * @var array containing pages
223                 * @access protected
224                 */
225                 var $pages = array();
226
227                 /**
228                 * @var current document state
229                 * @access protected
230                 */
231                 var $state;
232
233                 /**
234                 * @var compression flag
235                 * @access protected
236                 */
237                 var $compress;
238
239                 /**
240                 * @var current page orientation (P = Portrait, L = Landscape)
241                 * @access protected
242                 */
243                 var $CurOrientation;
244
245                 /**
246                 * @var array that stores page dimensions.<ul><li>$this->pagedim[$this->page]['w'] => page_width_in_points</li><li>$this->pagedim[$this->page]['h'] => height</li><li>$this->pagedim[$this->page]['tm'] => top_margin</li><li>$this->pagedim[$this->page]['bm'] => bottom_margin</li><li>$this->pagedim[$this->page]['lm'] => left_margin</li><li>$this->pagedim[$this->page]['rm'] => right_margin</li><li>$this->pagedim[$this->page]['pb'] => auto_page_break</li><li>$this->pagedim[$this->page]['or'] => page_orientation</li></ul>
247                 * @access protected
248                 */
249                 var $pagedim = array();
250
251                 /**
252                 * @var scale factor (number of points in user unit)
253                 * @access protected
254                 */
255                 var $k;
256
257                 /**
258                 * @var width of page format in points
259                 * @access protected
260                 */
261                 var $fwPt;
262
263                 /**
264                 * @var height of page format in points
265                 * @access protected
266                 */
267                 var $fhPt;
268
269                 /**
270                 * @var current width of page in points
271                 * @access protected
272                 */
273                 var $wPt;
274
275                 /**
276                 * @var current height of page in points
277                 * @access protected
278                 */
279                 var $hPt;
280
281                 /**
282                 * @var current width of page in user unit
283                 * @access protected
284                 */
285                 var $w;
286
287                 /**
288                 * @var current height of page in user unit
289                 * @access protected
290                 */
291                 var $h;
292
293                 /**
294                 * @var left margin
295                 * @access protected
296                 */
297                 var $lMargin;
298
299                 /**
300                 * @var top margin
301                 * @access protected
302                 */
303                 var $tMargin;
304
305                 /**
306                 * @var right margin
307                 * @access protected
308                 */
309                 var $rMargin;
310
311                 /**
312                 * @var page break margin
313                 * @access protected
314                 */
315                 var $bMargin;
316
317                 /**
318                 * @var cell internal padding
319                 * @access protected
320                 */
321                 var $cMargin;
322
323                 /**
324                 * @var cell internal padding (previous value)
325                 * @access protected
326                 */
327                 var $oldcMargin;
328
329                 /**
330                 * @var current horizontal position in user unit for cell positioning
331                 * @access protected
332                 */
333                 var $x;
334
335                 /**
336                 * @var current vertical position in user unit for cell positioning
337                 * @access protected
338                 */
339                 var $y;
340
341                 /**
342                 * @var height of last cell printed
343                 * @access protected
344                 */
345                 var $lasth;
346
347                 /**
348                 * @var line width in user unit
349                 * @access protected
350                 */
351                 var $LineWidth;
352
353                 /**
354                 * @var array of standard font names
355                 * @access protected
356                 */
357                 var $CoreFonts;
358
359                 /**
360                 * @var array of used fonts
361                 * @access protected
362                 */
363                 var $fonts = array();
364
365                 /**
366                 * @var array of font files
367                 * @access protected
368                 */
369                 var $FontFiles = array();
370
371                 /**
372                 * @var array of encoding differences
373                 * @access protected
374                 */
375                 var $diffs = array();
376
377                 /**
378                 * @var array of used images
379                 * @access protected
380                 */
381                 var $images = array();
382
383                 /**
384                 * @var array of Annotations in pages
385                 * @access protected
386                 */
387                 var $PageAnnots = array();
388
389                 /**
390                 * @var array of internal links
391                 * @access protected
392                 */
393                 var $links = array();
394
395                 /**
396                 * @var current font family
397                 * @access protected
398                 */
399                 var $FontFamily;
400
401                 /**
402                 * @var current font style
403                 * @access protected
404                 */
405                 var $FontStyle;
406
407                 /**
408                 * @var current font ascent (distance between font top and baseline)
409                 * @access protected
410                 * @since 2.8.000 (2007-03-29)
411                 */
412                 var $FontAscent;
413
414                 /**
415                 * @var current font descent (distance between font bottom and baseline)
416                 * @access protected
417                 * @since 2.8.000 (2007-03-29)
418                 */
419                 var $FontDescent;
420
421                 /**
422                 * @var underlining flag
423                 * @access protected
424                 */
425                 var $underline;
426
427                 /**
428                 * @var current font info
429                 * @access protected
430                 */
431                 var $CurrentFont;
432
433                 /**
434                 * @var current font size in points
435                 * @access protected
436                 */
437                 var $FontSizePt;
438
439                 /**
440                 * @var current font size in user unit
441                 * @access protected
442                 */
443                 var $FontSize;
444
445                 /**
446                 * @var commands for drawing color
447                 * @access protected
448                 */
449                 var $DrawColor;
450
451                 /**
452                 * @var commands for filling color
453                 * @access protected
454                 */
455                 var $FillColor;
456
457                 /**
458                 * @var commands for text color
459                 * @access protected
460                 */
461                 var $TextColor;
462
463                 /**
464                 * @var indicates whether fill and text colors are different
465                 * @access protected
466                 */
467                 var $ColorFlag;
468
469                 /**
470                 * @var word spacing
471                 * @access protected
472                 */
473                 var $ws;
474
475                 /**
476                 * @var automatic page breaking
477                 * @access protected
478                 */
479                 var $AutoPageBreak;
480
481                 /**
482                 * @var threshold used to trigger page breaks
483                 * @access protected
484                 */
485                 var $PageBreakTrigger;
486
487                 /**
488                 * @var flag set when processing footer
489                 * @access protected
490                 */
491                 var $InFooter;
492
493                 /**
494                 * @var zoom display mode
495                 * @access protected
496                 */
497                 var $ZoomMode;
498
499                 /**
500                 * @var layout display mode
501                 * @access protected
502                 */
503                 var $LayoutMode;
504
505                 /**
506                 * @var title
507                 * @access protected
508                 */
509                 var $title;
510
511                 /**
512                 * @var subject
513                 * @access protected
514                 */
515                 var $subject;
516
517                 /**
518                 * @var author
519                 * @access protected
520                 */
521                 var $author;
522
523                 /**
524                 * @var keywords
525                 * @access protected
526                 */
527                 var $keywords;
528
529                 /**
530                 * @var creator
531                 * @access protected
532                 */
533                 var $creator;
534
535                 /**
536                 * @var alias for total number of pages
537                 * @access protected
538                 */
539                 var $AliasNbPages;
540
541                 /**
542                 * @var right-bottom corner X coordinate of inserted image
543                 * @since 2002-07-31
544                 * @author Nicola Asuni
545                 * @access protected
546                 */
547                 var $img_rb_x;
548
549                 /**
550                 * @var right-bottom corner Y coordinate of inserted image
551                 * @since 2002-07-31
552                 * @author Nicola Asuni
553                 * @access protected
554                 */
555                 var $img_rb_y;
556
557                 /**
558                 * @var image scale factor
559                 * @since 2004-06-14
560                 * @author Nicola Asuni
561                 * @access protected
562                 */
563                 var $imgscale = 1;
564
565                 /**
566                 * @var boolean set to true when the input text is unicode (require unicode fonts)
567                 * @since 2005-01-02
568                 * @author Nicola Asuni
569                 * @access protected
570                 */
571                 var $isunicode = false;
572
573                 /**
574                 * @var PDF version
575                 * @since 1.5.3
576                 * @access protected
577                 */
578                 var $PDFVersion = "1.7";
579
580
581                 // ----------------------
582
583                 /**
584                  * @var Minimum distance between header and top page margin.
585                  * @access protected
586                  */
587                 var $header_margin;
588
589                 /**
590                  * @var Minimum distance between footer and bottom page margin.
591                  * @access protected
592                  */
593                 var $footer_margin;
594
595                 /**
596                  * @var original left margin value
597                  * @access protected
598                  * @since 1.53.0.TC013
599                  */
600                 var $original_lMargin;
601
602                 /**
603                  * @var original right margin value
604                  * @access protected
605                  * @since 1.53.0.TC013
606                  */
607                 var $original_rMargin;
608
609                 /**
610                  * @var Header font.
611                  * @access protected
612                  */
613                 var $header_font;
614
615                 /**
616                  * @var Footer font.
617                  * @access protected
618                  */
619                 var $footer_font;
620
621                 /**
622                  * @var Language templates.
623                  * @access protected
624                  */
625                 var $l;
626
627                 /**
628                  * @var Barcode to print on page footer (only if set).
629                  * @access protected
630                  */
631                 var $barcode = false;
632
633                 /**
634                  * @var If true prints header
635                  * @access protected
636                  */
637                 var $print_header = true;
638
639                 /**
640                  * @var If true prints footer.
641                  * @access protected
642                  */
643                 var $print_footer = true;
644
645                 /**
646                  * @var Header image logo.
647                  * @access protected
648                  */
649                 var $header_logo = "";
650
651                 /**
652                  * @var Header image logo width in mm.
653                  * @access protected
654                  */
655                 var $header_logo_width = 30;
656
657                 /**
658                  * @var String to print as title on document header.
659                  * @access protected
660                  */
661                 var $header_title = "";
662
663                 /**
664                  * @var String to print on document header.
665                  * @access protected
666                  */
667                 var $header_string = "";
668
669                 /**
670                  * @var Default number of columns for html table.
671                  * @access protected
672                  */
673                 var $default_table_columns = 4;
674
675
676                 // variables for html parser
677
678                 /**
679                  * @var HTML PARSER: store current link.
680                  * @access protected
681                  */
682                 var $HREF;
683
684                 /**
685                  * @var store available fonts list.
686                  * @access protected
687                  */
688                 var $fontlist = array();
689
690                 /**
691                  * @var current foreground color
692                  * @access protected
693                  */
694                 var $fgcolor;
695
696                 /**
697                  * @var HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
698                  * @access protected
699                  */
700                 var $listordered = array();
701
702                 /**
703                  * @var HTML PARSER: array count list items on nested lists.
704                  * @access protected
705                  */
706                 var $listcount = array();
707
708                 /**
709                  * @var HTML PARSER: current list nesting level.
710                  * @access protected
711                  */
712                 var $listnum = 0;
713
714                 /**
715                  * @var HTML PARSER: indent amount for lists.
716                  * @access protected
717                  */
718                 var $listindent;
719
720                 /**
721                  * @var current background color
722                  * @access protected
723                  */
724                 var $bgcolor;
725
726                 /**
727                  * @var Store temporary font size in points.
728                  * @access protected
729                  */
730                 var $tempfontsize = 10;
731
732                 /**
733                  * @var Bold font style status.
734                  * @access protected
735                  */
736                 var $b;
737
738                 /**
739                  * @var Underlined font style status.
740                  * @access protected
741                  */
742                 var $u;
743
744                 /**
745                  * @var Italic font style status.
746                  * @access protected
747                  */
748                 var $i;
749
750                 /**
751                  * @var Line through font style status.
752                  * @access protected
753                  * @since 2.8.000 (2008-03-19)
754                  */
755                 var $d;
756
757                 /**
758                  * @var spacer for LI tags.
759                  * @access protected
760                  */
761                 var $lispacer = "";
762
763                 /**
764                  * @var default encoding
765                  * @access protected
766                  * @since 1.53.0.TC010
767                  */
768                 var $encoding = "UTF-8";
769
770                 /**
771                  * @var PHP internal encoding
772                  * @access protected
773                  * @since 1.53.0.TC016
774                  */
775                 var $internal_encoding;
776
777                 /**
778                  * @var indicates if the document language is Right-To-Left
779                  * @access protected
780                  * @since 2.0.000
781                  */
782                 var $rtl = false;
783
784                 /**
785                  * @var used to force RTL or LTR string inversion
786                  * @access protected
787                  * @since 2.0.000
788                  */
789                 var $tmprtl = false;
790
791                 // --- Variables used for document encryption:
792
793                 /**
794                  * Indicates whether document is protected
795                  * @access protected
796                  * @since 2.0.000 (2008-01-02)
797                  */
798                 var $encrypted;
799
800                 /**
801                  * U entry in pdf document
802                  * @access protected
803                  * @since 2.0.000 (2008-01-02)
804                  */
805                 var $Uvalue;
806
807                 /**
808                  * O entry in pdf document
809                  * @access protected
810                  * @since 2.0.000 (2008-01-02)
811                  */
812                 var $Ovalue;
813
814                 /**
815                  * P entry in pdf document
816                  * @access protected
817                  * @since 2.0.000 (2008-01-02)
818                  */
819                 var $Pvalue;
820
821                 /**
822                  * encryption object id
823                  * @access protected
824                  * @since 2.0.000 (2008-01-02)
825                  */
826                 var $enc_obj_id;
827
828                 /**
829                  * last RC4 key encrypted (cached for optimisation)
830                  * @access protected
831                  * @since 2.0.000 (2008-01-02)
832                  */
833                 var $last_rc4_key;
834
835                 /**
836                  * last RC4 computed key
837                  * @access protected
838                  * @since 2.0.000 (2008-01-02)
839                  */
840                 var $last_rc4_key_c;
841
842                 // --- bookmark ---
843
844                 /**
845                  * Outlines for bookmark
846                  * @access protected
847                  * @since 2.1.002 (2008-02-12)
848                  */
849                 var $outlines = array();
850
851                 /**
852                  * Outline root for bookmark
853                  * @access protected
854                  * @since 2.1.002 (2008-02-12)
855                  */
856                 var $OutlineRoot;
857
858
859                 // --- javascript and form ---
860
861                 /**
862                  * javascript code
863                  * @access protected
864                  * @since 2.1.002 (2008-02-12)
865                  */
866                 var $javascript = "";
867
868                 /**
869                  * javascript counter
870                  * @access protected
871                  * @since 2.1.002 (2008-02-12)
872                  */
873                 var $n_js;
874
875                 /**
876                  * line trough state
877                  * @access protected
878                  * @since 2.8.000 (2008-03-19)
879                  */
880                 var $linethrough;
881
882                 // --- Variables used for User's Rights ---
883                 // See PDF reference chapter 8.7 Digital Signatures
884
885                 /**
886                  * If true enables user's rights on PDF reader
887                  * @access protected
888                  * @since 2.9.000 (2008-03-26)
889                  */
890                 var $ur;
891
892                 /**
893                  * Names specifying additional document-wide usage rights for the document.
894                  * @access protected
895                  * @since 2.9.000 (2008-03-26)
896                  */
897                 var $ur_document;
898
899                 /**
900                  * Names specifying additional annotation-related usage rights for the document.
901                  * @access protected
902                  * @since 2.9.000 (2008-03-26)
903                  */
904                 var $ur_annots;
905
906                 /**
907                  * Names specifying additional form-field-related usage rights for the document.
908                  * @access protected
909                  * @since 2.9.000 (2008-03-26)
910                  */
911                 var $ur_form;
912
913                 /**
914                  * Names specifying additional signature-related usage rights for the document.
915                  * @access protected
916                  * @since 2.9.000 (2008-03-26)
917                  */
918                 var $ur_signature;
919
920                 /**
921                  * Dot Per Inch Document Resolution (do not change)
922                  * @access protected
923                  * @since 3.0.000 (2008-03-27)
924                  */
925                 var $dpi = 72;
926
927                 /**
928                  * Indicates whether a new page group was requested
929                  * @access protected
930                  * @since 3.0.000 (2008-03-27)
931                  */
932                 var $newpagegroup;
933
934                 /**
935                  * Contains the number of pages of the groups
936                  * @access protected
937                  * @since 3.0.000 (2008-03-27)
938                  */
939                 var $pagegroups;
940
941                 /**
942                  * Contains the alias of the current page group
943                  * @access protected
944                  * @since 3.0.000 (2008-03-27)
945                  */
946                 var $currpagegroup;
947
948                 /**
949                  * Restrict the rendering of some elements to screen or printout.
950                  * @access protected
951                  * @since 3.0.000 (2008-03-27)
952                  */
953                 var $visibility="all";
954
955                 /**
956                  * Print visibility.
957                  * @access protected
958                  * @since 3.0.000 (2008-03-27)
959                  */
960                 var $n_ocg_print;
961
962                 /**
963                  * View visibility.
964                  * @access protected
965                  * @since 3.0.000 (2008-03-27)
966                  */
967                 var $n_ocg_view;
968
969                 /**
970                  * Array of transparency objects and parameters.
971                  * @access protected
972                  * @since 3.0.000 (2008-03-27)
973                  */
974                 var $extgstates;
975
976                 /**
977                  * Set the default JPEG compression quality (1-100)
978                  * @access protected
979                  * @since 3.0.000 (2008-03-27)
980                  */
981                 var $jpeg_quality;
982
983                 /**
984                  * Default cell height ratio.
985                  * @access protected
986                  * @since 3.0.014 (2008-05-23)
987                  */
988                 var $cell_height_ratio = K_CELL_HEIGHT_RATIO;
989
990                 /**
991                  * PDF viewer preferences.
992                  * @access protected
993                  * @since 3.1.000 (2008-06-09)
994                  */
995                 var $viewer_preferences;
996
997                 /**
998                  * A name object specifying how the document should be displayed when opened.
999                  * @access protected
1000                  * @since 3.1.000 (2008-06-09)
1001                  */
1002                 var $PageMode;
1003
1004                 /**
1005                  * Array for storing gradient information.
1006                  * @access protected
1007                  * @since 3.1.000 (2008-06-09)
1008                  */
1009                 var $gradients = array();
1010
1011                 /**
1012                  * Array used to store positions inside the pages buffer.
1013                  * keys are the page numbers
1014                  * @access protected
1015                  * @since 3.2.000 (2008-06-26)
1016                  */
1017                 var $intmrk = array();
1018
1019                 /**
1020                  * Array used to store footer positions of each page.
1021                  * @access protected
1022                  * @since 3.2.000 (2008-07-01)
1023                  */
1024                 var $footerpos = array();
1025
1026
1027                 /**
1028                  * Array used to store footer lenght of each page.
1029                  * @access protected
1030                  * @since 4.0.014 (2008-07-29)
1031                  */
1032                 var $footerlen = array();
1033
1034                 /**
1035                  * True if a newline is created.
1036                  * @access protected
1037                  * @since 3.2.000 (2008-07-01)
1038                  */
1039                 var $newline = true;
1040
1041                 /**
1042                  * End position of the latest inserted line
1043                  * @access protected
1044                  * @since 3.2.000 (2008-07-01)
1045                  */
1046                 var $endlinex = 0;
1047
1048                 /**
1049                  * PDF string for last line width
1050                  * @access protected
1051                  * @since 4.0.006 (2008-07-16)
1052                  */
1053                 var $linestyleWidth = "";
1054
1055                 /**
1056                  * PDF string for last line width
1057                  * @access protected
1058                  * @since 4.0.006 (2008-07-16)
1059                  */
1060                 var $linestyleCap = "0 J";
1061
1062                 /**
1063                  * PDF string for last line width
1064                  * @access protected
1065                  * @since 4.0.006 (2008-07-16)
1066                  */
1067                 var $linestyleJoin = "0 j";
1068
1069                 /**
1070                  * PDF string for last line width
1071                  * @access protected
1072                  * @since 4.0.006 (2008-07-16)
1073                  */
1074                 var $linestyleDash = "[] 0 d";
1075
1076                 /**
1077                  * True if marked-content sequence is open
1078                  * @access protected
1079                  * @since 4.0.013 (2008-07-28)
1080                  */
1081                 var $openMarkedContent = false;
1082
1083                 /**
1084                  * Count the latest inserted vertical spaces on HTML.
1085                  * @access protected
1086                  * @since 4.0.021 (2008-08-24)
1087                  */
1088                 var $htmlvspace = 0;
1089                 
1090                 /**
1091                  * Array of Spot colors
1092                  * @access protected
1093                  * @since 4.0.024 (2008-09-12)
1094                  */
1095                 var $spot_colors = array();
1096
1097                 //------------------------------------------------------------
1098                 // METHODS
1099                 //------------------------------------------------------------
1100
1101                 /**
1102                  * This is the class constructor.
1103                  * It allows to set up the page format, the orientation and
1104                  * the measure unit used in all the methods (except for the font sizes).
1105                  * @since 1.0
1106                  * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
1107                  * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
1108                  * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
1109                  * @param boolean $unicode TRUE means that the input text is unicode (default = true)
1110                  * @param String $encoding charset encoding; default is UTF-8
1111                  */
1112                 function TCPDF($orientation='P', $unit='mm', $format='A4', $uni=true, $encoding="UTF-8") {
1113                         if ($uni) // Fix for FrontAccounting
1114                         {
1115                                 global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
1116                                 include_once(dirname(__FILE__)."/unicode_data2.php");
1117                         }
1118                         /* Set internal character encoding to ASCII */
1119                         if (function_exists("mb_internal_encoding") AND mb_internal_encoding()) {
1120                                 $this->internal_encoding = mb_internal_encoding();
1121                                 mb_internal_encoding("ASCII");
1122                         }
1123                         // set language direction
1124                         $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
1125                         $this->tmprtl = false;
1126                         //Some checks
1127                         $this->_dochecks();
1128                         //Initialization of properties
1129                         $this->isunicode = $uni;
1130                         $this->page = 0;
1131                         $this->pagedim = array();
1132                         $this->n = 2;
1133                         $this->buffer = '';
1134                         $this->pages = array();
1135                         $this->state = 0;
1136                         $this->fonts = array();
1137                         $this->FontFiles = array();
1138                         $this->diffs = array();
1139                         $this->images = array();
1140                         $this->links = array();
1141                         $this->gradients = array();
1142                         $this->InFooter = false;
1143                         $this->lasth = 0;
1144                         $this->FontFamily = 'helvetica';
1145                         $this->FontStyle = '';
1146                         $this->FontSizePt = 12;
1147                         $this->underline = false;
1148                         $this->linethrough = false;
1149                         $this->DrawColor = '0 G';
1150                         $this->FillColor = '0 g';
1151                         $this->TextColor = '0 g';
1152                         $this->ColorFlag = false;
1153                         $this->ws = 0;
1154                         // encryption values
1155                         $this->encrypted = false;
1156                         $this->last_rc4_key = '';
1157                         $this->padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
1158                         //Standard Unicode fonts
1159                         $this->CoreFonts = array(
1160                                 'courier'=>'Courier',
1161                                 'courierB'=>'Courier-Bold',
1162                                 'courierI'=>'Courier-Oblique',
1163                                 'courierBI'=>'Courier-BoldOblique',
1164                                 'helvetica'=>'Helvetica',
1165                                 'helveticaB'=>'Helvetica-Bold',
1166                                 'helveticaI'=>'Helvetica-Oblique',
1167                                 'helveticaBI'=>'Helvetica-BoldOblique',
1168                                 'times'=>'Times-Roman',
1169                                 'timesB'=>'Times-Bold',
1170                                 'timesI'=>'Times-Italic',
1171                                 'timesBI'=>'Times-BoldItalic',
1172                                 'symbol'=>'Symbol',
1173                                 'zapfdingbats'=>'ZapfDingbats'
1174                         );
1175                         //Set scale factor
1176                         $this->setPageUnit($unit);
1177                         // set page format and orientation
1178                         $this->setPageFormat($format, $orientation);
1179                         //Page margins (1 cm)
1180                         $margin = 28.35 / $this->k;
1181                         $this->SetMargins($margin,$margin);
1182                         //Interior cell margin (1 mm)
1183                         $this->cMargin = $margin / 10;
1184                         //Line width (0.2 mm)
1185                         $this->LineWidth = 0.57 / $this->k;
1186                         $this->linestyleWidth = sprintf('%.2f w', ($this->LineWidth * $this->k));
1187                         $this->linestyleCap = "0 J";
1188                         $this->linestyleJoin = "0 j";
1189                         $this->linestyleDash = "[] 0 d";
1190                         //Automatic page break
1191                         $this->SetAutoPageBreak(true, 2*$margin);
1192                         //Full width display mode
1193                         $this->SetDisplayMode('fullwidth');
1194                         //Compression
1195                         $this->SetCompression(true);
1196                         //Set default PDF version number
1197                         $this->PDFVersion = "1.7";
1198                         $this->encoding = $encoding;
1199                         $this->HREF = '';
1200                         $this->getFontsList();
1201                         $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
1202                         $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
1203                         $this->extgstates = array();
1204                         // user's rights
1205                         $this->ur = false;
1206                         $this->ur_document = "/FullSave";
1207                         $this->ur_annots = "/Create/Delete/Modify/Copy/Import/Export";
1208                         $this->ur_form = "/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate";
1209                         $this->ur_signature = "/Modify";
1210                         // set default JPEG quality
1211                         $this->jpeg_quality = 75;
1212                         // initialize some settings
1213                         $this->utf8Bidi(array(""));
1214                 }
1215
1216                 /**
1217                  * Default destructor.
1218                  * @since 1.53.0.TC016
1219                  */
1220                 function TCPDFDestruct() {
1221                         // restore internal encoding
1222                         if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
1223                                 mb_internal_encoding($this->internal_encoding);
1224                         }
1225                 }
1226
1227                 /**
1228                 * Set the units of measure for the document.
1229                 * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
1230                 * @since 3.0.015 (2008-06-06)
1231                 */
1232                 function setPageUnit($unit) {
1233                 //Set scale factor
1234                         switch (strtolower($unit)) {
1235                                 // points
1236                                 case 'pt': {
1237                                         $this->k = 1;
1238                                         break;
1239                                 }
1240                                 // millimeters
1241                                 case 'mm': {
1242                                         $this->k = $this->dpi / 25.4;
1243                                         break;
1244                                 }
1245                                 // centimeters
1246                                 case 'cm': {
1247                                         $this->k = $this->dpi / 2.54;
1248                                         break;
1249                                 }
1250                                 // inches
1251                                 case 'in': {
1252                                         $this->k = $this->dpi;
1253                                         break;
1254                                 }
1255                                 // unsupported unit
1256                                 default : {
1257                                         $this->Error('Incorrect unit: '.$unit);
1258                                         break;
1259                                 }
1260                         }
1261                         if (isset($this->CurOrientation)) {
1262                                         $this->setPageOrientation($this->CurOrientation);
1263                         }
1264                 }
1265
1266                 /**
1267                 * Set the page format
1268                 * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
1269                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1270                 * @since 3.0.015 (2008-06-06)
1271                 */
1272                 function setPageFormat($format, $orientation="P") {
1273                         //Page format
1274                         if (is_string($format)) {
1275                                 // Page formats (45 standard ISO paper formats and 4 american common formats).
1276                                 // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm)
1277                                 switch (strtoupper($format)){
1278                                         case '4A0': {$format = array(4767.87,6740.79); break;}
1279                                         case '2A0': {$format = array(3370.39,4767.87); break;}
1280                                         case 'A0': {$format = array(2383.94,3370.39); break;}
1281                                         case 'A1': {$format = array(1683.78,2383.94); break;}
1282                                         case 'A2': {$format = array(1190.55,1683.78); break;}
1283                                         case 'A3': {$format = array(841.89,1190.55); break;}
1284                                         case 'A4': default: {$format = array(595.28,841.89); break;}
1285                                         case 'A5': {$format = array(419.53,595.28); break;}
1286                                         case 'A6': {$format = array(297.64,419.53); break;}
1287                                         case 'A7': {$format = array(209.76,297.64); break;}
1288                                         case 'A8': {$format = array(147.40,209.76); break;}
1289                                         case 'A9': {$format = array(104.88,147.40); break;}
1290                                         case 'A10': {$format = array(73.70,104.88); break;}
1291                                         case 'B0': {$format = array(2834.65,4008.19); break;}
1292                                         case 'B1': {$format = array(2004.09,2834.65); break;}
1293                                         case 'B2': {$format = array(1417.32,2004.09); break;}
1294                                         case 'B3': {$format = array(1000.63,1417.32); break;}
1295                                         case 'B4': {$format = array(708.66,1000.63); break;}
1296                                         case 'B5': {$format = array(498.90,708.66); break;}
1297                                         case 'B6': {$format = array(354.33,498.90); break;}
1298                                         case 'B7': {$format = array(249.45,354.33); break;}
1299                                         case 'B8': {$format = array(175.75,249.45); break;}
1300                                         case 'B9': {$format = array(124.72,175.75); break;}
1301                                         case 'B10': {$format = array(87.87,124.72); break;}
1302                                         case 'C0': {$format = array(2599.37,3676.54); break;}
1303                                         case 'C1': {$format = array(1836.85,2599.37); break;}
1304                                         case 'C2': {$format = array(1298.27,1836.85); break;}
1305                                         case 'C3': {$format = array(918.43,1298.27); break;}
1306                                         case 'C4': {$format = array(649.13,918.43); break;}
1307                                         case 'C5': {$format = array(459.21,649.13); break;}
1308                                         case 'C6': {$format = array(323.15,459.21); break;}
1309                                         case 'C7': {$format = array(229.61,323.15); break;}
1310                                         case 'C8': {$format = array(161.57,229.61); break;}
1311                                         case 'C9': {$format = array(113.39,161.57); break;}
1312                                         case 'C10': {$format = array(79.37,113.39); break;}
1313                                         case 'RA0': {$format = array(2437.80,3458.27); break;}
1314                                         case 'RA1': {$format = array(1729.13,2437.80); break;}
1315                                         case 'RA2': {$format = array(1218.90,1729.13); break;}
1316                                         case 'RA3': {$format = array(864.57,1218.90); break;}
1317                                         case 'RA4': {$format = array(609.45,864.57); break;}
1318                                         case 'SRA0': {$format = array(2551.18,3628.35); break;}
1319                                         case 'SRA1': {$format = array(1814.17,2551.18); break;}
1320                                         case 'SRA2': {$format = array(1275.59,1814.17); break;}
1321                                         case 'SRA3': {$format = array(907.09,1275.59); break;}
1322                                         case 'SRA4': {$format = array(637.80,907.09); break;}
1323                                         case 'LETTER': {$format = array(612.00,792.00); break;}
1324                                         case 'LEGAL': {$format = array(612.00,1008.00); break;}
1325                                         case 'EXECUTIVE': {$format = array(521.86,756.00); break;}
1326                                         case 'FOLIO': {$format = array(612.00,936.00); break;}
1327                                 }
1328                                 $this->fwPt = $format[0];
1329                                 $this->fhPt = $format[1];
1330                         }
1331                         else {
1332                                 $this->fwPt = $format[0] * $this->k;
1333                                 $this->fhPt = $format[1] * $this->k;
1334                         }
1335                         $this->setPageOrientation($orientation);
1336                 }
1337
1338
1339                 /**
1340                 * Set page orientation.
1341                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1342                 * @param boolean $autopagebreak Boolean indicating if auto-page-break mode should be on or off.
1343                 * @param float $bottommargin bottom margin of the page.
1344                 * @since 3.0.015 (2008-06-06)
1345                 */
1346                 function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
1347                         $orientation = strtoupper($orientation);
1348                         if (($orientation == 'P') OR ($orientation == 'PORTRAIT')) {
1349                                 $this->CurOrientation = 'P';
1350                                 $this->wPt = $this->fwPt;
1351                                 $this->hPt = $this->fhPt;
1352                         } elseif (($orientation == 'L') OR ($orientation == 'LANDSCAPE')) {
1353                                 $this->CurOrientation = 'L';
1354                                 $this->wPt = $this->fhPt;
1355                                 $this->hPt = $this->fwPt;
1356                         }
1357                         else {
1358                                 $this->Error('Incorrect orientation: '.$orientation);
1359                         }
1360                         $this->w = $this->wPt / $this->k;
1361                         $this->h = $this->hPt / $this->k;
1362                         if (empty($autopagebreak)) {
1363                                 if (isset($this->AutoPageBreak)) {
1364                                         $autopagebreak = $this->AutoPageBreak;
1365                                 } else {
1366                                         $autopagebreak = true;
1367                                 }
1368                         }
1369                         if (empty($bottommargin)) {
1370                                 if (isset($this->bMargin)) {
1371                                         $bottommargin = $this->bMargin;
1372                                 } else {
1373                                         // default value = 2 cm
1374                                         $bottommargin = 2 * 28.35 / $this->k;
1375                                 }
1376                         }
1377                         $this->SetAutoPageBreak($autopagebreak, $bottommargin);
1378                         // store page dimensions
1379                         $this->pagedim[$this->page] = array('w' => $this->wPt, 'h' => $this->hPt, 'tm' => $this->tMargin, 'bm' => $bottommargin, 'lm' => $this->lMargin, 'rm' => $this->rMargin, 'pb' => $autopagebreak, 'or' => $this->CurOrientation);
1380                 }
1381
1382                 /**
1383                  * Enable or disable Right-To-Left language mode
1384                  * @param Boolean $enable if true enable Right-To-Left language mode.
1385                  * @since 2.0.000 (2008-01-03)
1386                  */
1387                 function setRTL($enable) {
1388                         $this->rtl = $enable ? true : false;
1389                         $this->tmprtl = false;
1390                 }
1391
1392                 /**
1393                  * Return the RTL status
1394                  * @return boolean
1395                  * @since 4.0.012 (2008-07-24)
1396                  */
1397                 function getRTL() {
1398                         return $this->rtl;
1399                 }
1400
1401                 /**
1402                 * Force temporary RTL language direction
1403                 * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL
1404                 * @since 2.1.000 (2008-01-09)
1405                 */
1406                 function setTempRTL($mode) {
1407                         switch ($mode) {
1408                                 case false:
1409                                 case 'L':
1410                                 case 'R': {
1411                                         $this->tmprtl = $mode;
1412                                 }
1413                         }
1414                 }
1415
1416                 /**
1417                 * Set the last cell height.
1418                 * @param float $h cell height.
1419                 * @author Nicola Asuni
1420                 * @since 1.53.0.TC034
1421                 */
1422                 function setLastH($h) {
1423                         $this->lasth = $h;
1424                 }
1425
1426                 /**
1427                 * Get the last cell height.
1428                 * @return last cell height
1429                 * @since 4.0.017 (2008-08-05)
1430                 */
1431                 function getLastH() {
1432                         return $this->lasth;
1433                 }
1434
1435                 /**
1436                 * Set the image scale.
1437                 * @param float $scale image scale.
1438                 * @author Nicola Asuni
1439                 * @since 1.5.2
1440                 */
1441                 function setImageScale($scale) {
1442                         $this->imgscale = $scale;
1443                 }
1444
1445                 /**
1446                 * Returns the image scale.
1447                 * @return float image scale.
1448                 * @author Nicola Asuni
1449                 * @since 1.5.2
1450                 */
1451                 function getImageScale() {
1452                         return $this->imgscale;
1453                 }
1454
1455                 /**
1456                 * Returns the page width in units.
1457                 * @return int page width.
1458                 * @author Nicola Asuni
1459                 * @since 1.5.2
1460                 */
1461                 function getPageWidth() {
1462                         return $this->w;
1463                 }
1464
1465                 /**
1466                 * Returns the page height in units.
1467                 * @return int page height.
1468                 * @author Nicola Asuni
1469                 * @since 1.5.2
1470                 */
1471                 function getPageHeight() {
1472                         return $this->h;
1473                 }
1474
1475                 /**
1476                 * Returns the page break margin.
1477                 * @return int page break margin.
1478                 * @author Nicola Asuni
1479                 * @since 1.5.2
1480                 */
1481                 function getBreakMargin() {
1482                         return $this->bMargin;
1483                 }
1484
1485                 /**
1486                 * Returns the scale factor (number of points in user unit).
1487                 * @return int scale factor.
1488                 * @author Nicola Asuni
1489                 * @since 1.5.2
1490                 */
1491                 function getScaleFactor() {
1492                         return $this->k;
1493                 }
1494
1495                 /**
1496                 * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
1497                 * @param float $left Left margin.
1498                 * @param float $top Top margin.
1499                 * @param float $right Right margin. Default value is the left one.
1500                 * @since 1.0
1501                 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
1502                 */
1503                 function SetMargins($left, $top, $right=-1) {
1504                         //Set left, top and right margins
1505                         $this->lMargin = $left;
1506                         $this->tMargin = $top;
1507                         if ($right == -1) {
1508                                 $right = $left;
1509                         }
1510                         $this->rMargin = $right;
1511                 }
1512
1513                 /**
1514                 * Defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin.
1515                 * @param float $margin The margin.
1516                 * @since 1.4
1517                 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1518                 */
1519                 function SetLeftMargin($margin) {
1520                         //Set left margin
1521                         $this->lMargin=$margin;
1522                         if (($this->page > 0) AND ($this->x < $margin)) {
1523                                 $this->x = $margin;
1524                         }
1525                 }
1526
1527                 /**
1528                 * Defines the top margin. The method can be called before creating the first page.
1529                 * @param float $margin The margin.
1530                 * @since 1.5
1531                 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1532                 */
1533                 function SetTopMargin($margin) {
1534                         //Set top margin
1535                         $this->tMargin=$margin;
1536                         if (($this->page > 0) AND ($this->y < $margin)) {
1537                                 $this->y = $margin;
1538                         }
1539                 }
1540
1541                 /**
1542                 * Defines the right margin. The method can be called before creating the first page.
1543                 * @param float $margin The margin.
1544                 * @since 1.5
1545                 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1546                 */
1547                 function SetRightMargin($margin) {
1548                         $this->rMargin=$margin;
1549                         if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
1550                                 $this->x = $this->w - $margin;
1551                         }
1552                 }
1553
1554                 /**
1555                 * Set the internal Cell padding.
1556                 * @param float $pad internal padding.
1557                 * @since 2.1.000 (2008-01-09)
1558                 * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1559                 */
1560                 function SetCellPadding($pad) {
1561                         $this->cMargin = $pad;
1562                 }
1563
1564                 /**
1565                 * Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm.
1566                 * @param boolean $auto Boolean indicating if mode should be on or off.
1567                 * @param float $margin Distance from the bottom of the page.
1568                 * @since 1.0
1569                 * @see Cell(), MultiCell(), AcceptPageBreak()
1570                 */
1571                 function SetAutoPageBreak($auto, $margin=0) {
1572                         //Set auto page break mode and triggering margin
1573                         $this->AutoPageBreak = $auto;
1574                         $this->bMargin = $margin;
1575                         $this->PageBreakTrigger = $this->h - $margin;
1576                 }
1577
1578                 /**
1579                 * Defines the way the document is to be displayed by the viewer.
1580                 * @param mixed $zoom The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul>
1581                 * @param string $layout The page layout. Possible values are:<ul><li>SinglePage Display one page at a time</li><li>OneColumn Display the pages in one column</li><li>TwoColumnLeft Display the pages in two columns, with odd-numbered pages on the left</li><li>TwoColumnRight Display the pages in two columns, with odd-numbered pages on the right</li><li>TwoPageLeft (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the left</li><li>TwoPageRight (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the right</li></ul>
1582                 * @param string $mode A name object specifying how the document should be displayed when opened:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>FullScreen Full-screen mode, with no menu bar, window controls, or any other window visible</li><li>UseOC (PDF 1.5) Optional content group panel visible</li><li>UseAttachments (PDF 1.6) Attachments panel visible</li></ul>
1583                 * @since 1.2
1584                 */
1585                 function SetDisplayMode($zoom, $layout='SinglePage', $mode="UseNone") {
1586                         //Set display mode in viewer
1587                         if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
1588                                 $this->ZoomMode = $zoom;
1589                         } else {
1590                                 $this->Error('Incorrect zoom display mode: '.$zoom);
1591                         }
1592                         switch ($layout) {
1593                                 case "default":
1594                                 case "single":
1595                                 case "SinglePage": {
1596                                         $this->LayoutMode = "SinglePage";
1597                                         break;
1598                                 }
1599                                 case "continuous":
1600                                 case "OneColumn": {
1601                                         $this->LayoutMode = "OneColumn";
1602                                         break;
1603                                 }
1604                                 case "two":
1605                                 case "TwoColumnLeft": {
1606                                         $this->LayoutMode = "TwoColumnLeft";
1607                                         break;
1608                                 }
1609                                 case "TwoColumnRight": {
1610                                         $this->LayoutMode = "TwoColumnRight";
1611                                         break;
1612                                 }
1613                                 case "TwoPageLeft": {
1614                                         $this->LayoutMode = "TwoPageLeft";
1615                                         break;
1616                                 }
1617                                 case "TwoPageRight": {
1618                                         $this->LayoutMode = "TwoPageRight";
1619                                         break;
1620                                 }
1621                                 default: {
1622                                         $this->LayoutMode = "SinglePage";
1623                                 }
1624                         }
1625                         switch ($mode) {
1626                                 case "UseNone": {
1627                                         $this->PageMode = "UseNone";
1628                                         break;
1629                                 }
1630                                 case "UseOutlines": {
1631                                         $this->PageMode = "UseOutlines";
1632                                         break;
1633                                 }
1634                                 case "UseThumbs": {
1635                                         $this->PageMode = "UseThumbs";
1636                                         break;
1637                                 }
1638                                 case "FullScreen": {
1639                                         $this->PageMode = "FullScreen";
1640                                         break;
1641                                 }
1642                                 case "UseOC": {
1643                                         $this->PageMode = "UseOC";
1644                                         break;
1645                                 }
1646                                 case "": {
1647                                         $this->PageMode = "UseAttachments";
1648                                         break;
1649                                 }
1650                                 default: {
1651                                         $this->PageMode = "UseNone";
1652                                 }
1653                         }
1654                 }
1655
1656                 /**
1657                 * Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default.
1658                 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
1659                 * @param boolean $compress Boolean indicating if compression must be enabled.
1660                 * @since 1.4
1661                 */
1662                 function SetCompression($compress) {
1663                         //Set page compression
1664                         if (function_exists('gzcompress')) {
1665                                 $this->compress = $compress;
1666                         } else {
1667                                 $this->compress = false;
1668                         }
1669                 }
1670
1671                 /**
1672                 * Defines the title of the document.
1673                 * @param string $title The title.
1674                 * @since 1.2
1675                 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
1676                 */
1677                 function SetTitle($title) {
1678                         //Title of document
1679                         $this->title = $title;
1680                 }
1681
1682                 /**
1683                 * Defines the subject of the document.
1684                 * @param string $subject The subject.
1685                 * @since 1.2
1686                 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
1687                 */
1688                 function SetSubject($subject) {
1689                         //Subject of document
1690                         $this->subject = $subject;
1691                 }
1692
1693                 /**
1694                 * Defines the author of the document.
1695                 * @param string $author The name of the author.
1696                 * @since 1.2
1697                 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
1698                 */
1699                 function SetAuthor($author) {
1700                         //Author of document
1701                         $this->author = $author;
1702                 }
1703
1704                 /**
1705                 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
1706                 * @param string $keywords The list of keywords.
1707                 * @since 1.2
1708                 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
1709                 */
1710                 function SetKeywords($keywords) {
1711                         //Keywords of document
1712                         $this->keywords = $keywords;
1713                 }
1714
1715                 /**
1716                 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
1717                 * @param string $creator The name of the creator.
1718                 * @since 1.2
1719                 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
1720                 */
1721                 function SetCreator($creator) {
1722                         //Creator of document
1723                         $this->creator = $creator;
1724                 }
1725
1726                 /**
1727                 * Defines an alias for the total number of pages. It will be substituted as the document is closed.<br />
1728                 * @param string $alias The alias. Default value: {nb}.
1729                 * @since 1.4
1730                 * @see getAliasNbPages(), PageNo(), Footer()
1731                 */
1732                 function AliasNbPages($alias='{nb}') {
1733                         //Define an alias for total number of pages
1734                         $this->AliasNbPages = $alias;
1735                 }
1736                 
1737                 /**
1738                  * Returns the string alias used for the total number of pages.
1739          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
1740                  * @return string
1741                  * @since 4.0.018 (2008-08-08)
1742                  * @see AliasNbPages(), PageNo(), Footer()
1743                 */
1744                 function getAliasNbPages() {
1745                         if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
1746                                 return "{".$this->AliasNbPages."}";
1747             }
1748                         return $this->AliasNbPages;
1749                 }
1750
1751                 /**
1752                 * This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid.
1753                 * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
1754                 * @param string $msg The error message
1755                 * @since 1.0
1756                 */
1757                 function Error($msg) {
1758                         //Fatal error
1759                         die('<strong>TCPDF error: </strong>'.$msg);
1760                 }
1761
1762                 /**
1763                 * This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.
1764                 * Note: no page is created by this method
1765                 * @since 1.0
1766                 * @see AddPage(), Close()
1767                 */
1768                 function Open() {
1769                         //Begin document
1770                         $this->state = 1;
1771                 }
1772
1773                 /**
1774                 * Terminates the PDF document. It is not necessary to call this method explicitly because Output() does it automatically. If the document contains no page, AddPage() is called to prevent from getting an invalid document.
1775                 * @since 1.0
1776                 * @see Open(), Output()
1777                 */
1778                 function Close() {
1779                         //Terminate document
1780                         if ($this->state == 3) {
1781                                 return;
1782                         }
1783                         if ($this->page == 0) {
1784                                 $this->AddPage();
1785                         }
1786                         //Page footer
1787                         $this->setFooter();
1788                         //Close page
1789                         $this->_endpage();
1790                         //Close document
1791                         $this->_enddoc();
1792                 }
1793
1794                 /**
1795                 * Move pointer at the specified document page and update page dimensions.
1796                 * @param int $pnum page number
1797                 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
1798                 * @since 2.1.000 (2008-01-07)
1799                 * @see getPage(), lastpage(), getNumPages()
1800                 */
1801                 function setPage($pnum, $resetmargins=false) {
1802                         if (($pnum > 0) AND ($pnum <= count($this->pages))) {
1803                                 $this->page = $pnum;
1804                                 $this->wPt = $this->pagedim[$this->page]['w'];
1805                                 $this->hPt = $this->pagedim[$this->page]['h'];
1806                                 $this->w = $this->wPt / $this->k;
1807                                 $this->h = $this->hPt / $this->k;
1808                                 $this->tMargin = $this->pagedim[$this->page]['tm'];
1809                                 $this->bMargin = $this->pagedim[$this->page]['bm'];
1810                                 $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
1811                                 $this->CurOrientation = $this->pagedim[$this->page]['or'];
1812                                 $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
1813                                 if ($resetmargins) {
1814                                         $this->lMargin = $this->pagedim[$this->page]['lm'];
1815                                         $this->rMargin = $this->pagedim[$this->page]['rm'];
1816                                         $this->SetY($this->tMargin);
1817                                 }
1818                         } else {
1819                                 $this->Error('Wrong page number on setPage() function.');
1820                         }
1821                 }
1822
1823                 /**
1824                 * Reset pointer to the last document page.
1825                 * @since 2.0.000 (2008-01-04)
1826                 * @see setPage(), getPage(), getNumPages()
1827                 */
1828                 function lastPage() {
1829                         $this->setPage($this->getNumPages());
1830                 }
1831
1832                 /**
1833                 * Get current document page number.
1834                 * @return int page number
1835                 * @since 2.1.000 (2008-01-07)
1836                 * @see setPage(), lastpage(), getNumPages()
1837                 */
1838                 function getPage() {
1839                         return $this->page;
1840                 }
1841
1842
1843                 /**
1844                 * Get the total number of insered pages.
1845                 * @return int number of pages
1846                 * @since 2.1.000 (2008-01-07)
1847                 * @see setPage(), getPage(), lastpage()
1848                 */
1849                 function getNumPages() {
1850                         return count($this->pages);
1851                 }
1852
1853                 /**
1854                 * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer. Then the page is added, the current position set to the top-left corner according to the left and top margins, and Header() is called to display the header.
1855                 * The font which was set before calling is automatically restored. There is no need to call SetFont() again if you want to continue with the same font. The same is true for colors and line width.
1856                 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
1857                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1858                 * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
1859                 * @since 1.0
1860                 * @see TCPDF(), Header(), Footer(), SetMargins()
1861                 */
1862                 function AddPage($orientation='', $format='') {
1863                         if (!isset($this->original_lMargin)) {
1864                                 $this->original_lMargin = $this->lMargin;
1865                         }
1866                         if (!isset($this->original_rMargin)) {
1867                                 $this->original_rMargin = $this->rMargin;
1868                         }
1869                         if (count($this->pages) > $this->page) {
1870                                 // this page has been already added
1871                                 $this->setPage(($this->page + 1));
1872                                 $this->SetY($this->tMargin);
1873                                 return;
1874                         }
1875                         //Start a new page
1876                         if ($this->state == 0) {
1877                                 $this->Open();
1878                         }
1879                         // save current settings
1880                         $font_family = $this->FontFamily;
1881                         $font_style = $this->FontStyle.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '');
1882                         $font_size = $this->FontSizePt;
1883                         $prev_rMargin = $this->rMargin;
1884                         $prev_lMargin = $this->lMargin;
1885                         $prev_cMargin = $this->cMargin;
1886                         $prev_linestyleWidth = $this->linestyleWidth;
1887                         $prev_linestyleCap = $this->linestyleCap;
1888                         $prev_linestyleJoin = $this->linestyleJoin;
1889                         $prev_linestyleDash = $this->linestyleDash;
1890                         $prev_DrawColor = $this->DrawColor;
1891                         $prev_FillColor = $this->FillColor;
1892                         $prev_TextColor = $this->TextColor;
1893                         $prev_ColorFlag = $this->ColorFlag;
1894                         if ($this->page > 0) {
1895                                 //Page footer
1896                                 $this->setFooter();
1897                                 //Close page
1898                                 $this->_endpage();
1899                         }
1900                         //Start new page
1901                         $this->_beginpage($orientation, $format);
1902                         // restore graphic styles
1903                         $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1904                         if (!empty($font_family)) {
1905                                 $this->SetFont($font_family, $font_style, $font_size);
1906                         }
1907                         //Page header
1908                         $this->setHeader();
1909                         // restore graphic styles
1910                         $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1911                         if (!empty($font_family)) {
1912                                 $this->SetFont($font_family, $font_style, $font_size);
1913                         }
1914                         // restore settings
1915                         $this->FontFamily = $font_family;
1916                         $this->FontStyle = $font_style;
1917                         $this->FontSizePt = $font_size;
1918                         $this->rMargin = $prev_rMargin;
1919                         $this->lMargin = $prev_lMargin;
1920                         $this->cMargin = $prev_cMargin;
1921                         $this->linestyleWidth = $prev_linestyleWidth;
1922                         $this->linestyleCap = $prev_linestyleCap;
1923                         $this->linestyleJoin = $prev_linestyleJoin;
1924                         $this->linestyleDash = $prev_linestyleDash;
1925                         $this->DrawColor = $prev_DrawColor;
1926                         $this->FillColor = $prev_FillColor;
1927                         $this->TextColor = $prev_TextColor;
1928                         $this->ColorFlag = $prev_ColorFlag;
1929                         // mark this point
1930                         $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1931                 }
1932
1933                 /**
1934                  * Set start-writing mark on current page for multicell borders and fills.
1935                  * This function must be called after calling Image() function for a background image.
1936                  * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
1937                  * @access public
1938                  * @since 4.0.016 (2008-07-30)
1939                  */
1940                 function setPageMark() {
1941                         $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1942                 }
1943
1944                 /**
1945                  * Set header data.
1946                  * @param string $ln header image logo
1947                  * @param string $lw header image logo width in mm
1948                  * @param string $ht string to print as title on document header
1949                  * @param string $hs string to print on document header
1950                 */
1951                 function setHeaderData($ln="", $lw=0, $ht="", $hs="") {
1952                         $this->header_logo = $ln;
1953                         $this->header_logo_width = $lw;
1954                         $this->header_title = $ht;
1955                         $this->header_string = $hs;
1956                 }
1957
1958                 /**
1959                  * Returns header data:
1960                  * <ul><li>$ret['logo'] = logo image</li><li>$ret['logo_width'] = width of the image logo in user units</li><li>$ret['title'] = header title</li><li>$ret['string'] = header description string</li></ul>
1961                  * @return array()
1962                  * @since 4.0.012 (2008-07-24)
1963                  */
1964                 function getHeaderData() {
1965                         $ret = array();
1966                         $ret['logo'] = $this->header_logo;
1967                         $ret['logo_width'] = $this->header_logo_width;
1968                         $ret['title'] = $this->header_title;
1969                         $ret['string'] = $this->header_string;
1970                         return $ret;
1971                 }
1972
1973                 /**
1974                  * Set header margin.
1975                  * (minimum distance between header and top page margin)
1976                  * @param int $hm distance in user units
1977                 */
1978                 function setHeaderMargin($hm=10) {
1979                         $this->header_margin = $hm;
1980                 }
1981
1982                 /**
1983                  * Returns header margin in user units.
1984                  * @return float
1985                  * @since 4.0.012 (2008-07-24)
1986                 */
1987                 function getHeaderMargin() {
1988                         return $this->header_margin;
1989                 }
1990
1991                 /**
1992                  * Set footer margin.
1993                  * (minimum distance between footer and bottom page margin)
1994                  * @param int $fm distance in user units
1995                 */
1996                 function setFooterMargin($fm=10) {
1997                         $this->footer_margin = $fm;
1998                 }
1999
2000                 /**
2001                  * Returns footer margin in user units.
2002                  * @return float
2003                  * @since 4.0.012 (2008-07-24)
2004                 */
2005                 function getFooterMargin() {
2006                         return $this->footer_margin;
2007                 }
2008                 /**
2009                  * Set a flag to print page header.
2010                  * @param boolean $val set to true to print the page header (default), false otherwise.
2011                  */
2012                 function setPrintHeader($val=true) {
2013                         $this->print_header = $val;
2014                 }
2015
2016                 /**
2017                  * Set a flag to print page footer.
2018                  * @param boolean $value set to true to print the page footer (default), false otherwise.
2019                  */
2020                 function setPrintFooter($val=true) {
2021                         $this->print_footer = $val;
2022                 }
2023
2024                 /**
2025                  * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
2026                  * @return float
2027                  */
2028                 function getImageRBX() {
2029                         return $this->img_rb_x;
2030                 }
2031
2032                 /**
2033                  * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
2034                  * @return float
2035                  */
2036                 function getImageRBY() {
2037                         return $this->img_rb_y;
2038                 }
2039
2040                 /**
2041                  * This method is used to render the page header.
2042                  * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2043                  */
2044                 function Header1() {
2045                         $ormargins = $this->getOriginalMargins();
2046                         $headerfont = $this->getHeaderFont();
2047                         $headerdata = $this->getHeaderData();
2048                         if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
2049                                 $this->Image(K_PATH_IMAGES.$headerdata['logo'], $this->GetX(), $this->getHeaderMargin(), $headerdata['logo_width']);
2050                                 $imgy = $this->getImageRBY();
2051                         } else {
2052                                 $imgy = $this->GetY();
2053                         }
2054                         $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2);
2055                         // set starting margin for text data cell
2056                         if ($this->getRTL()) {
2057                                 $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1);
2058                         } else {
2059                                 $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1);
2060                         }
2061                         $this->SetTextColor(0, 0, 0);
2062                         // header title
2063                         $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
2064                         $this->SetX($header_x);
2065                         $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '');
2066                         // header string
2067                         $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
2068                         $this->SetX($header_x);
2069                         $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, 0, 0, true, 0);
2070                         // print an ending header line
2071                         $this->SetLineStyle(array("width" => 0.85 / $this->getScaleFactor(), "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2072                         $this->SetY(1 + max($imgy, $this->GetY()));
2073                         if ($this->getRTL()) {
2074                                 $this->SetX($ormargins['right']);
2075                         } else {
2076                                 $this->SetX($ormargins['left']);
2077                         }
2078                         $this->Cell(0, 0, '', 'T', 0, 'C');
2079                 }
2080
2081                 /**
2082                  * This method is used to render the page footer.
2083                  * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2084                  */
2085                 function Footer() {
2086                         $cur_y = $this->GetY();
2087                         $ormargins = $this->getOriginalMargins();
2088                         $this->SetTextColor(0, 0, 0);
2089                         //set style for cell border
2090                         $line_width = 0.85 / $this->getScaleFactor();
2091                         $this->SetLineStyle(array("width" => $line_width, "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2092                         //print document barcode
2093                         $barcode = $this->getBarcode();
2094                         if (!empty($barcode)) {
2095                                 $this->Ln();
2096                                 $barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right'])/3);
2097                                 $this->write1DBarcode($barcode, "C128B", $this->GetX(), $cur_y + $line_width, $barcode_width, (($this->getFooterMargin() / 3) - $line_width), 0.3, '', '');
2098                         }
2099                         $pagenumtxt = $this->l['w_page']." ".$this->PageNo().' / '.$this->getAliasNbPages();
2100                         $this->SetY($cur_y);
2101                         //Print page number
2102                         if ($this->getRTL()) {
2103                                 $this->SetX($ormargins['right']);
2104                                 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
2105                         } else {
2106                                 $this->SetX($ormargins['left']);
2107                                 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R');
2108                         }
2109                 }
2110
2111                 /**
2112                  * This method is used to render the page header.
2113                  * @access protected
2114                  * @since 4.0.012 (2008-07-24)
2115                  */
2116                 function setHeader() {
2117                         if ($this->print_header) {
2118                                 $lasth = $this->lasth;
2119                                 $this->_out("q");
2120                                 $this->rMargin = $this->original_rMargin;
2121                                 $this->lMargin = $this->original_lMargin;
2122                                 //set current position
2123                                 if ($this->rtl) {
2124                                         $this->SetXY($this->original_rMargin, $this->header_margin);
2125                                 } else {
2126                                         $this->SetXY($this->original_lMargin, $this->header_margin);
2127                                 }
2128                                 $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
2129                                 $this->Header1();
2130                                 //restore position
2131                                 if ($this->rtl) {
2132                                         $this->SetXY($this->original_rMargin, $this->tMargin);
2133                                 } else {
2134                                         $this->SetXY($this->original_lMargin, $this->tMargin);
2135                                 }
2136                                 $this->_out("Q");
2137                                 $this->lasth = $lasth;
2138                         }
2139                 }
2140
2141                 /**
2142                  * This method is used to render the page footer.
2143                  * @access protected
2144                  * @since 4.0.012 (2008-07-24)
2145                  */
2146                 function setFooter() {
2147                         //Page footer
2148                         $this->InFooter = true;
2149                         // mark this point
2150                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
2151                         if ($this->print_footer) {
2152                                 $lasth = $this->lasth;
2153                                 $this->_out("q");
2154                                 $this->rMargin = $this->original_rMargin;
2155                                 $this->lMargin = $this->original_lMargin;
2156                                 //set current position
2157                                 $footer_y = $this->h - $this->footer_margin;
2158                                 if ($this->rtl) {
2159                                         $this->SetXY($this->original_rMargin, $footer_y);
2160                                 } else {
2161                                         $this->SetXY($this->original_lMargin, $footer_y);
2162                                 }
2163                                 $this->SetFont($this->footer_font[0], $this->footer_font[1] , $this->footer_font[2]);
2164                                 $this->Footer();
2165                                 //restore position
2166                                 if ($this->rtl) {
2167                                         $this->SetXY($this->original_rMargin, $this->tMargin);
2168                                 } else {
2169                                         $this->SetXY($this->original_lMargin, $this->tMargin);
2170                                 }
2171                                 $this->_out("Q");
2172                                 $this->lasth = $lasth;
2173                         }
2174                         $this->footerlen[$this->page] = strlen($this->pages[$this->page]) - $this->footerpos[$this->page];
2175                         $this->InFooter = false;
2176                 }
2177
2178                 /**
2179                 * Returns the current page number.
2180                 * @return int page number
2181                 * @since 1.0
2182                 * @see AliasNbPages(), getAliasNbPages()
2183                 */
2184                 function PageNo() {
2185                         return $this->page;
2186                 }
2187
2188                 /**
2189                 * Defines a new spot color. 
2190                 * It can be expressed in RGB components or gray scale. 
2191                 * The method can be called before the first page is created and the value is retained from page to page.
2192                 * @param int $c Cyan color for CMYK. Value between 0 and 255
2193                 * @param int $m Magenta color for CMYK. Value between 0 and 255
2194                 * @param int $y Yellow color for CMYK. Value between 0 and 255
2195                 * @param int $k Key (Black) color for CMYK. Value between 0 and 255
2196                 * @since 4.0.024 (2008-09-12)
2197                 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2198                 */
2199                 function AddSpotColor($name, $c, $m, $y, $k) {
2200                         if (!isset($this->spot_colors[$name])) {
2201                                 $i = 1 + count($this->spot_colors);
2202                                 $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k);
2203                         }
2204                 }
2205
2206                 /**
2207                 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
2208                 * It can be expressed in RGB components or gray scale.
2209                 * The method can be called before the first page is created and the value is retained from page to page.
2210                 * @param array $color array of colors
2211                 * @since 3.1.000 (2008-06-11)
2212                 * @see SetDrawColor()
2213                 */
2214                 function SetDrawColorArray($color) {
2215                         if (isset($color)) {
2216                                 $color = array_values($color);
2217                                 $r = isset($color[0]) ? $color[0] : -1;
2218                                 $g = isset($color[1]) ? $color[1] : -1;
2219                                 $b = isset($color[2]) ? $color[2] : -1;
2220                                 $k = isset($color[3]) ? $color[3] : -1;
2221                                 if ($r >= 0) {
2222                                         $this->SetDrawColor($r, $g, $b, $k);
2223                                 }
2224                         }
2225                 }
2226
2227                 /**
2228                 * Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
2229                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2230                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2231                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2232                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2233                 * @since 1.3
2234                 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
2235                 */
2236                 function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2237                         // set default values
2238                         if (!is_numeric($col1)) {
2239                                 $col1 = 0;
2240                         }
2241                         if (!is_numeric($col2)) {
2242                                 $col2 = -1;
2243                         }
2244                         if (!is_numeric($col3)) {
2245                                 $col3 = -1;
2246                         }
2247                         if (!is_numeric($col4)) {
2248                                 $col4 = -1;
2249                         }
2250                         //Set color for all stroking operations
2251                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2252                                 // Grey scale
2253                                 $this->DrawColor = sprintf('%.3f G', $col1/255);
2254                         } elseif ($col4 == -1) {
2255                                 // RGB
2256                                 $this->DrawColor = sprintf('%.3f %.3f %.3f RG', $col1/255, $col2/255, $col3/255);
2257                         } else {
2258                                 // CMYK
2259                                 $this->DrawColor = sprintf('%.3f %.3f %.3f %.3f K', $col1/100, $col2/100, $col3/100, $col4/100);
2260                         }
2261                         if ($this->page > 0) {
2262                                 $this->_out($this->DrawColor);
2263                         }
2264                 }
2265                 
2266                 /**
2267                 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
2268                 * @param string $name name of the spot color
2269                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2270                 * @since 4.0.024 (2008-09-12)
2271                 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2272                 */
2273                 function SetDrawSpotColor($name, $tint=100) {
2274                         if (!isset($this->spot_colors[$name])) {
2275                                 $this->Error('Undefined spot color: '.$name);
2276                         }
2277                         $this->DrawColor = sprintf('/CS%d CS %.3f SCN', $this->spot_colors[$name]['i'], $tint/100);
2278                         if ($this->page > 0) {
2279                                 $this->_out($this->DrawColor);
2280                         }
2281                 }
2282
2283                 /**
2284                 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
2285                 * It can be expressed in RGB components or gray scale.
2286                 * The method can be called before the first page is created and the value is retained from page to page.
2287                 * @param array $color array of colors
2288                 * @since 3.1.000 (2008-6-11)
2289                 * @see SetFillColor()
2290                 */
2291                 function SetFillColorArray($color) {
2292                         if (isset($color)) {
2293                                 $color = array_values($color);
2294                                 $r = isset($color[0]) ? $color[0] : -1;
2295                                 $g = isset($color[1]) ? $color[1] : -1;
2296                                 $b = isset($color[2]) ? $color[2] : -1;
2297                                 $k = isset($color[3]) ? $color[3] : -1;
2298                                 if ($r >= 0) {
2299                                         $this->SetFillColor($r, $g, $b, $k);
2300                                 }
2301                         }
2302                 }
2303
2304                 /**
2305                 * Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
2306                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2307                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2308                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2309                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2310                 * @since 1.3
2311                 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
2312                 */
2313                 function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2314                         // set default values
2315                         if (!is_numeric($col1)) {
2316                                 $col1 = 0;
2317                         }
2318                         if (!is_numeric($col2)) {
2319                                 $col2 = -1;
2320                         }
2321                         if (!is_numeric($col3)) {
2322                                 $col3 = -1;
2323                         }
2324                         if (!is_numeric($col4)) {
2325                                 $col4 = -1;
2326                         }
2327                         //Set color for all filling operations
2328                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2329                                 // Grey scale
2330                                 $this->FillColor = sprintf('%.3f g', $col1/255);
2331                                 $this->bgcolor = array('G' => $col1);
2332                         } elseif ($col4 == -1) {
2333                                 // RGB
2334                                 $this->FillColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2335                                 $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2336                         } else {
2337                                 // CMYK
2338                                 $this->FillColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2339                                 $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2340                         }
2341                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2342                         if ($this->page > 0) {
2343                                 $this->_out($this->FillColor);
2344                         }
2345                 }
2346                 
2347                 /**
2348                 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
2349                 * @param string $name name of the spot color
2350                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2351                 * @since 4.0.024 (2008-09-12)
2352                 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
2353                 */
2354                 function SetFillSpotColor($name, $tint=100) {
2355                         if (!isset($this->spot_colors[$name])) {
2356                                 $this->Error('Undefined spot color: '.$name);
2357                         }
2358                         $this->FillColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2359                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2360                         if ($this->page > 0) {
2361                                 $this->_out($this->FillColor);
2362                         }
2363                 }
2364
2365                 /**
2366                 * Defines the color used for text. It can be expressed in RGB components or gray scale.
2367                 * The method can be called before the first page is created and the value is retained from page to page.
2368                 * @param array $color array of colors
2369                 * @since 3.1.000 (2008-6-11)
2370                 * @see SetFillColor()
2371                 */
2372                 function SetTextColorArray($color) {
2373                         if (isset($color)) {
2374                                 $color = array_values($color);
2375                                 $r = isset($color[0]) ? $color[0] : -1;
2376                                 $g = isset($color[1]) ? $color[1] : -1;
2377                                 $b = isset($color[2]) ? $color[2] : -1;
2378                                 $k = isset($color[3]) ? $color[3] : -1;
2379                                 if ($r >= 0) {
2380                                         $this->SetTextColor($r, $g, $b, $k);
2381                                 }
2382                         }
2383                 }
2384
2385                 /**
2386                 * Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
2387                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2388                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2389                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2390                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2391                 * @since 1.3
2392                 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
2393                 */
2394                 function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2395                         // set default values
2396                         if (!is_numeric($col1)) {
2397                                 $col1 = 0;
2398                         }
2399                         if (!is_numeric($col2)) {
2400                                 $col2 = -1;
2401                         }
2402                         if (!is_numeric($col3)) {
2403                                 $col3 = -1;
2404                         }
2405                         if (!is_numeric($col4)) {
2406                                 $col4 = -1;
2407                         }
2408                         //Set color for text
2409                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2410                                 // Grey scale
2411                                 $this->TextColor = sprintf('%.3f g', $col1/255);
2412                                 $this->fgcolor = array('G' => $col1);
2413                         } elseif ($col4 == -1) {
2414                                 // RGB
2415                                 $this->TextColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2416                                 $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2417                         } else {
2418                                 // CMYK
2419                                 $this->TextColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2420                                 $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2421                         }
2422                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2423                 }
2424
2425                 /**
2426                 * Defines the spot color used for text.
2427                 * @param string $name name of the spot color
2428                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2429                 * @since 4.0.024 (2008-09-12)
2430                 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
2431                 */
2432                 function SetTextSpotColor($name, $tint=100) {
2433                         if (!isset($this->spot_colors[$name])) {
2434                                 $this->Error('Undefined spot color: '.$name);
2435                         }
2436                         $this->TextColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2437                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2438                         if ($this->page > 0) {
2439                                 $this->_out($this->TextColor);
2440                         }
2441                 }
2442
2443                 /**
2444                 * Returns the length of a string in user unit. A font must be selected.<br>
2445                 * @param string $s The string whose length is to be computed
2446                 * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
2447                 * @param string $fontstyle Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li></ul> or any combination. The default value is regular.
2448                 * @param float $fontsize Font size in points. The default value is the current size.
2449                 * @return int string length
2450                 * @author Nicola Asuni
2451                 * @since 1.2
2452                 */
2453                 function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0) {
2454                         return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $this->tmprtl), $fontname, $fontstyle, $fontsize);
2455                 }
2456
2457                 /**
2458                 * Returns the string length of an array of chars in user unit. A font must be selected.<br>
2459                 * @param string $arr The array of chars whose total length is to be computed
2460                 * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
2461                 * @param string $fontstyle Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li></ul> or any combination. The default value is regular.
2462                 * @param float $fontsize Font size in points. The default value is the current size.
2463                 * @return int string length
2464                 * @author Nicola Asuni
2465                 * @since 2.4.000 (2008-03-06)
2466                 */
2467                 function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0) {
2468                         // store current values
2469                         if (!empty($fontname)) {
2470                                 $prev_FontFamily = $this->FontFamily;
2471                                 $prev_FontStyle = $this->FontStyle;
2472                                 $prev_FontSizePt = $this->FontSizePt;
2473                                 $this->SetFont($fontname, $fontstyle, $fontsize);
2474                         }
2475                         $w = 0;
2476                         foreach($sa as $char) {
2477                                 $w += $this->GetCharWidth($char);
2478                         }
2479                         // restore previous values
2480                         if (!empty($fontname)) {
2481                                 $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt);
2482                         }
2483                         return $w;
2484                 }
2485
2486                 /**
2487                 * Returns the length of the char in user unit for the current font.<br>
2488                 * @param int $char The char code whose length is to be returned
2489                 * @return int char width
2490                 * @author Nicola Asuni
2491                 * @since 2.4.000 (2008-03-06)
2492                 */
2493                 function GetCharWidth($char) {
2494                         $cw = &$this->CurrentFont['cw'];
2495                         if (isset($cw[$char])) {
2496                                 $w = $cw[$char];
2497                                 /*
2498                         } elseif (isset($cw[ord($char)])) {
2499                                 $w = $cw[ord($char)];
2500                         } elseif (isset($cw[chr($char)])) {
2501                                 $w = $cw[chr($char)];
2502                                 */
2503                         } elseif (isset($this->CurrentFont['dw'])) {
2504                                 $w = $this->CurrentFont['dw'];
2505                         } elseif (isset($this->CurrentFont['desc']['MissingWidth'])) {
2506                                 $w = $this->CurrentFont['desc']['MissingWidth']; // set default size
2507                         } else {
2508                                 $w = 500; // default width
2509                         }
2510                         return ($w * $this->FontSize / 1000);
2511                 }
2512
2513                 /**
2514                 * Returns the numbero of characters in a string.
2515                 * @param string $s The input string.
2516                 * @return int number of characters
2517                 * @since 2.0.0001 (2008-01-07)
2518                 */
2519                 function GetNumChars($s) {
2520                         if ($this->isunicode) {
2521                                 return count($this->UTF8StringToArray($s));
2522                         }
2523                         return strlen($s);
2524                 }
2525
2526                 /**
2527                 * Fill the list of available fonts ($this->fontlist).
2528                 * @access protected
2529                 * @since 4.0.013 (2008-07-28)
2530                 */
2531                 function getFontsList() {
2532                         $fontsdir = opendir($this->_getfontpath());
2533                         while (($file = readdir($fontsdir)) !== false) {
2534                                 if (substr($file, -4) == ".php") {
2535                                                 array_push($this->fontlist, strtolower(basename($file, ".php")));
2536                                 }
2537                         }
2538                         closedir($fontsdir);
2539                 }
2540
2541                 /**
2542                 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
2543                 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
2544                 * The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.
2545                 * Changed to support UTF-8 Unicode [Nicola Asuni, 2005-01-02].
2546                 * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
2547                 * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
2548                 * @param string $file The font definition file. By default, the name is built from the family and style, in lower case with no space.
2549                 * @return array containing the font data, or false in case of error.
2550                 * @since 1.5
2551                 * @see SetFont()
2552                 */
2553                 function AddFont($family, $style='', $file='') {
2554                         if (empty($family)) {
2555                                 if (!empty($this->FontFamily)) {
2556                                         $family = $this->FontFamily;
2557                                 } else {
2558                                         $this->Error('Empty font family');
2559                                 }
2560                         }
2561                         $family = strtolower($family);
2562                         if ((!$this->isunicode) AND ($family == 'arial')) {
2563                                 $family = 'helvetica';
2564                         }
2565                         if (($family == "symbol") OR ($family == "zapfdingbats")) {
2566                                 $style = '';
2567                         }
2568                         $style = strtoupper($style);
2569                         // underline
2570                         if (strpos($style,'U') !== false) {
2571                                 $this->underline = true;
2572                                 $style = str_replace('U', '', $style);
2573                         } else {
2574                                 $this->underline = false;
2575                         }
2576                         //line through (deleted)
2577                         if (strpos($style,'D') !== false) {
2578                                 $this->linethrough = true;
2579                                 $style = str_replace('D', '', $style);
2580                         } else {
2581                                 $this->linethrough = false;
2582                         }
2583                         if ($style == 'IB') {
2584                                 $style = 'BI';
2585                         }
2586                         $fontkey = $family.$style;
2587                         $fontdata = array("fontkey" => $fontkey, "family" => $family, "style" => $style);
2588                         // check if the font has been already added
2589                         if (isset($this->fonts[$fontkey])) {
2590                                 return $fontdata;
2591                         }
2592                         if ($file == '') {
2593                                 $file = str_replace(' ', '', $family).strtolower($style).'.php';
2594                         }
2595                         if (!file_exists($this->_getfontpath().$file)) {
2596                                 // try to load the basic file without styles
2597                                 $file = str_replace(' ', '', $family).'.php';
2598                         }
2599                         if (isset($type)) {
2600                                 unset($type);
2601                         }
2602                         if (isset($cw)) {
2603                                 unset($cw);
2604                         }
2605                         include($this->_getfontpath().$file);
2606                         if ((!isset($type)) OR (!isset($cw))) {
2607                                 $this->Error('Could not include font definition file');
2608                         }
2609                         $i = count($this->fonts) + 1;
2610                         // register CID font (all styles at once)
2611                         if ($type == 'cidfont0') {
2612                                 $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
2613                                 foreach ($styles as $skey => $qual) {
2614                                         $sname = $name.$qual;
2615                                         $sfontkey = $family.$skey;
2616                                         $this->fonts[$sfontkey] = array('i' => $i, 'type' => $type, 'name' => $sname, 'desc' => $desc, 'cidinfo' => $cidinfo, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc);
2617                                         $i = count($this->fonts) + 1;
2618                                 }
2619                                 $file = '';
2620                         } elseif ($type == 'core') {
2621                                 $def_width = $cw[ord('?')];
2622                                 $this->fonts[$fontkey] = array('i' => $i, 'type' => 'core', 'name' => $this->CoreFonts[$fontkey], 'up' => -100, 'ut' => 50, 'cw' => $cw, 'dw' => $def_width);
2623                         } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
2624                                 if (!isset($file)) {
2625                                         $file = '';
2626                                 }
2627                                 if (!isset($enc)) {
2628                                         $enc = '';
2629                                 }
2630                                 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'file' => $file, 'enc' => $enc, 'desc' => $desc);
2631                         } elseif ($type == 'TrueTypeUnicode') {
2632                                 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'enc' => $enc, 'file' => $file, 'ctg' => $ctg);
2633                         } else {
2634                                 $this->Error('Unknow font type');
2635                         }
2636                         if (isset($diff) AND (!empty($diff))) {
2637                                 //Search existing encodings
2638                                 $d = 0;
2639                                 $nb = count($this->diffs);
2640                                 for($i=1; $i <= $nb; $i++) {
2641                                         if ($this->diffs[$i] == $diff) {
2642                                                 $d = $i;
2643                                                 break;
2644                                         }
2645                                 }
2646                                 if ($d == 0) {
2647                                         $d = $nb + 1;
2648                                         $this->diffs[$d] = $diff;
2649                                 }
2650                                 $this->fonts[$fontkey]['diff'] = $d;
2651                         }
2652                         if (!empty($file)) {
2653                                 if ((strcasecmp($type,"TrueType") == 0) OR (strcasecmp($type,"TrueTypeUnicode") == 0)) {
2654                                         $this->FontFiles[$file] = array('length1' => $originalsize);
2655                                 } elseif ($type != 'core') {
2656                                         $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2);
2657                                 }
2658                         }
2659                         return $fontdata;
2660                 }
2661
2662                 /**
2663                 * Sets the font used to print character strings.
2664                 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
2665                 * The method can be called before the first page is created and the font is retained from page to page.
2666                 * If you just wish to change the current font size, it is simpler to call SetFontSize().
2667                 * Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this:<ul><li>They are in the current directory (the one where the running script lies)</li><li>They are in one of the directories defined by the include_path parameter</li><li>They are in the directory defined by the K_PATH_FONTS constant</li></ul><br />
2668                 * @param string $family Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained.
2669                 * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.
2670                 * @param float $size Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
2671                 * @since 1.0
2672                 * @see AddFont(), SetFontSize()
2673                 */
2674                 function SetFont($family, $style='', $size=0) {
2675                         //Select a font; size given in points
2676                         if ($size == 0) {
2677                                 $size = $this->FontSizePt;
2678                         }
2679                         // try to add font (if not already added)
2680                         $fontdata =  $this->AddFont($family, $style);
2681                         $this->FontFamily = $fontdata['family'];
2682                         $this->FontStyle = $fontdata['style'];
2683                         $this->CurrentFont = &$this->fonts[$fontdata['fontkey']];
2684                         $this->SetFontSize($size);
2685                 }
2686
2687                 /**
2688                 * Defines the size of the current font.
2689                 * @param float $size The size (in points)
2690                 * @since 1.0
2691                 * @see SetFont()
2692                 */
2693                 function SetFontSize($size) {
2694                         //Set font size in points
2695                         $this->FontSizePt = $size;
2696                         $this->FontSize = $size / $this->k;
2697                         if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
2698                                 $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000;
2699                         } else {
2700                                 $this->FontAscent = 0.8 * $this->FontSize;
2701                         }
2702                         if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] > 0)) {
2703                                 $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000;
2704                         } else {
2705                                 $this->FontDescent = 0.2 * $this->FontSize;
2706                         }
2707                         if (($this->page > 0) AND (isset($this->CurrentFont['i']))) {
2708                                 $this->_out(sprintf('BT /F%d %.2f Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
2709                         }
2710                 }
2711
2712                 /**
2713                 * Creates a new internal link and returns its identifier. An internal link is a clickable area which directs to another place within the document.<br />
2714                 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
2715                 * @since 1.5
2716                 * @see Cell(), Write(), Image(), Link(), SetLink()
2717                 */
2718                 function AddLink() {
2719                         //Create a new internal link
2720                         $n = count($this->links) + 1;
2721                         $this->links[$n] = array(0, 0);
2722                         return $n;
2723                 }
2724
2725                 /**
2726                 * Defines the page and position a link points to.
2727                 * @param int $link The link identifier returned by AddLink()
2728                 * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
2729                 * @param int $page Number of target page; -1 indicates the current page. This is the default value
2730                 * @since 1.5
2731                 * @see AddLink()
2732                 */
2733                 function SetLink($link, $y=0, $page=-1) {
2734                         if ($y == -1) {
2735                                 $y = $this->y;
2736                         }
2737                         if ($page == -1) {
2738                                 $page = $this->page;
2739                         }
2740                         $this->links[$link] = array($page, $y);
2741                 }
2742
2743                 /**
2744                 * Puts a link on a rectangular area of the page.
2745                 * Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image.
2746                 * @param float $x Abscissa of the upper-left corner of the rectangle
2747                 * @param float $y Ordinate of the upper-left corner of the rectangle
2748                 * @param float $w Width of the rectangle
2749                 * @param float $h Height of the rectangle
2750                 * @param mixed $link URL or identifier returned by AddLink()
2751                 * @since 1.5
2752                 * @see AddLink(), Annotation(), Cell(), Write(), Image()
2753                 */
2754                 function Link($x, $y, $w, $h, $link) {
2755                         $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'));
2756                 }
2757                 
2758                 /**
2759                 * Puts a text annotation on a rectangular area of the page.
2760                 * !!!! THIS FUNCTION IS NOT YET FULLY IMPLEMENTED !!!!
2761                 * @param float $x Abscissa of the upper-left corner of the rectangle
2762                 * @param float $y Ordinate of the upper-left corner of the rectangle
2763                 * @param float $w Width of the rectangle
2764                 * @param float $h Height of the rectangle
2765                 * @param string $text annotation text
2766                 * @param array $opt array of options (see section 8.4 of PDF reference 1.7).
2767                 * @since 4.0.018 (2008-08-06)
2768                 */
2769                 function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text')) {
2770                         $this->PageAnnots[$this->page][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt);
2771                 }
2772
2773                 /**
2774                 * Prints a character string. The origin is on the left of the first charcter, on the baseline. This method allows to place a string precisely on the page, but it is usually easier to use Cell(), MultiCell() or Write() which are the standard methods to print text.
2775                 * @param float $x Abscissa of the origin
2776                 * @param float $y Ordinate of the origin
2777                 * @param string $txt String to print
2778                 * @param int $stroke outline size in points (0 = disable)
2779                 * @param boolean $clip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
2780                 * @since 1.0
2781                 * @see SetFont(), SetTextColor(), Cell(), MultiCell(), Write()
2782                 */
2783                 function Text($x, $y, $txt, $stroke=0, $clip=false) {
2784                         //Output a string
2785                         if ($this->rtl) {
2786                                 // bidirectional algorithm (some chars may be changed affecting the line length)
2787                                 $s = $this->utf8Bidi($this->UTF8StringToArray($txt), $this->tmprtl);
2788                                 $l = $this->GetArrStringWidth($s);
2789                                 $xr = $this->w - $x - $this->GetArrStringWidth($s);
2790                         } else {
2791                                 $xr = $x;
2792                         }
2793                         $opt = "";
2794                         if (($stroke > 0) AND (!$clip)) {
2795                                 $opt .= "1 Tr ".intval($stroke)." w ";
2796                         } elseif (($stroke > 0) AND $clip) {
2797                                 $opt .= "5 Tr ".intval($stroke)." w ";
2798                         } elseif ($clip) {
2799                                 $opt .= "7 Tr ";
2800                         }
2801                         $s = sprintf('BT %.2f %.2f Td %s(%s) Tj ET 0 Tr', $xr * $this->k, ($this->h-$y) * $this->k, $opt, $this->_escapetext($txt));
2802                         if ($this->underline AND ($txt!='')) {
2803                                 $s .= ' '.$this->_dounderline($xr, $y, $txt);
2804                         }
2805                         if ($this->linethrough AND ($txt!='')) {
2806                                 $s .= ' '.$this->_dolinethrough($xr, $y, $txt);
2807                         }
2808                         if ($this->ColorFlag AND (!$clip)) {
2809                                 $s='q '.$this->TextColor.' '.$s.' Q';
2810                         }
2811                         $this->_out($s);
2812                 }
2813
2814                 /**
2815                 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
2816                 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
2817                 * This method is called automatically and should not be called directly by the application.
2818                 * @return boolean
2819                 * @since 1.4
2820                 * @see SetAutoPageBreak()
2821                 */
2822                 function AcceptPageBreak() {
2823                         return $this->AutoPageBreak;
2824                 }
2825
2826                 /**
2827                 * Add page if needed.
2828                 * @param float $h Cell height. Default value: 0.
2829                 * @since 3.2.000 (2008-07-01)
2830                 * @access protected
2831                 */
2832                 function checkPageBreak($h) {
2833                         if ((($this->y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
2834                                 $rs = "";
2835                                 //Automatic page break
2836                                 $x = $this->x;
2837                                 $ws = $this->ws;
2838                                 if ($ws > 0) {
2839                                         $this->ws = 0;
2840                                         $rs .= '0 Tw';
2841                                 }
2842                                 $this->AddPage($this->CurOrientation);
2843                                 if ($ws > 0) {
2844                                         $this->ws = $ws;
2845                                         $rs .= sprintf('%.3f Tw', $ws * $k);
2846                                 }
2847                                 $this->_out($rs);
2848                                 $this->y = $this->tMargin;
2849                                 $this->x = $x;
2850                         }
2851                 }
2852
2853                 /**
2854                 * Prints a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
2855                 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2856                 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2857                 * @param float $h Cell height. Default value: 0.
2858                 * @param string $txt String to print. Default value: empty string.
2859                 * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
2860                 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
2861                 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
2862                 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
2863                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2864                 * @param mixed $link URL or identifier returned by AddLink().
2865                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
2866                 * @since 1.0
2867                 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
2868                 */
2869                 function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2870                         //$min_cell_height = $this->FontAscent + $this->FontDescent;
2871                         $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2872                         if ($h < $min_cell_height) {
2873                                 $h = $min_cell_height;
2874                         }
2875                         $this->checkPageBreak($h);
2876                         $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch));
2877                 }
2878
2879                 /**
2880                 * Returns the PDF string code to print a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
2881                 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2882                 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2883                 * @param float $h Cell height. Default value: 0.
2884                 * @param string $txt String to print. Default value: empty string.
2885                 * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
2886                 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
2887                 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
2888                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2889                 * @param mixed $link URL or identifier returned by AddLink().
2890                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
2891                 * @since 1.0
2892                 * @see Cell()
2893                 */
2894                 function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2895                         $rs = ""; //string to be returned
2896                         $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2897                         if ($h < $min_cell_height) {
2898                                 $h = $min_cell_height;
2899                         }
2900                         $k = $this->k;
2901                         if (empty($w) OR ($w <= 0)) {
2902                                 if ($this->rtl) {
2903                                         $w = $this->x - $this->lMargin;
2904                                 } else {
2905                                         $w = $this->w - $this->rMargin - $this->x;
2906                                 }
2907                         }
2908                         $s = '';
2909                         if (($fill == 1) OR ($border == 1)) {
2910                                 if ($fill == 1) {
2911                                         $op = ($border == 1) ? 'B' : 'f';
2912                                 } else {
2913                                         $op = 'S';
2914                                 }
2915                                 if ($this->rtl) {
2916                                         $xk = (($this->x  - $w) * $k);
2917                                 } else {
2918                                         $xk = ($this->x * $k);
2919                                 }
2920                                 $s .= sprintf('%.2f %.2f %.2f %.2f re %s ', $xk, (($this->h - $this->y) * $k), ($w * $k), (-$h * $k), $op);
2921                         }
2922
2923                         if (is_string($border)) {
2924                                 $x = $this->x;
2925                                 $y = $this->y;
2926                                 if (strpos($border,'L') !== false) {
2927                                         if ($this->rtl) {
2928                                                 $xk = ($x - $w) * $k;
2929                                         } else {
2930                                                 $xk = $x * $k;
2931                                         }
2932                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h)) * $k));
2933                                 }
2934                                 if (strpos($border,'T') !== false) {
2935                                         if ($this->rtl) {
2936                                                 $xk = ($x - $w) * $k;
2937                                                 $xwk = $x * $k;
2938                                         } else {
2939                                                 $xk = $x * $k;
2940                                                 $xwk = ($x + $w) * $k;
2941                                         }
2942                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xwk, (($this->h - $y) * $k));
2943                                 }
2944                                 if (strpos($border,'R') !== false) {
2945                                         if ($this->rtl) {
2946                                                 $xk = $x * $k;
2947                                         } else {
2948                                                 $xk = ($x + $w) * $k;
2949                                         }
2950                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h))* $k));
2951                                 }
2952                                 if (strpos($border,'B') !== false) {
2953                                         if ($this->rtl) {
2954                                                 $xk = ($x - $w) * $k;
2955                                                 $xwk = $x * $k;
2956                                         } else {
2957                                                 $xk = $x * $k;
2958                                                 $xwk = ($x + $w) * $k;
2959                                         }
2960                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - ($y + $h)) * $k), $xwk, (($this->h - ($y + $h)) * $k));
2961                                 }
2962                         }
2963                         if ($txt != '') {
2964                                 // text lenght
2965                                 $width = $this->GetStringWidth($txt);
2966                                 // ratio between cell lenght and text lenght
2967                                 $ratio = ($w - (2 * $this->cMargin)) / $width;
2968
2969                                 // stretch text if required
2970                                 if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) {
2971                                         if ($stretch > 2) {
2972                                                 // spacing
2973                                                 //Calculate character spacing in points
2974                                                 $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1);
2975                                                 //Set character spacing
2976                                                 $rs .= sprintf('BT %.2f Tc ET ', $char_space);
2977                                         } else {
2978                                                 // scaling
2979                                                 //Calculate horizontal scaling
2980                                                 $horiz_scale = $ratio * 100.0;
2981                                                 //Set horizontal scaling
2982                                                 $rs .= sprintf('BT %.2f Tz ET ', $horiz_scale);
2983                                         }
2984                                         $align = '';
2985                                         $width = $w - (2 * $this->cMargin);
2986                                 } else {
2987                                         $stretch == 0;
2988                                 }
2989                                 if ($align == 'L') {
2990                                         if ($this->rtl) {
2991                                                 $dx = $w - $width - $this->cMargin;
2992                                         } else {
2993                                                 $dx = $this->cMargin;
2994                                         }
2995                                 } elseif ($align == 'R') {
2996                                         if ($this->rtl) {
2997                                                 $dx = $this->cMargin;
2998                                         } else {
2999                                                 $dx = $w - $width - $this->cMargin;
3000                                         }
3001                                 } elseif ($align == 'C') {
3002                                         $dx = ($w - $width) / 2;
3003                                 } elseif ($align == 'J') {
3004                                         if ($this->rtl) {
3005                                                 $dx = $w - $width - $this->cMargin;
3006                                         } else {
3007                                                 $dx = $this->cMargin;
3008                                         }
3009                                 } else {
3010                                         $dx = $this->cMargin;
3011                                 }
3012                                 if ($this->ColorFlag) {
3013                                         $s .= 'q '.$this->TextColor.' ';
3014                                 }
3015                                 $txt2 = $this->_escapetext($txt);
3016                                 if ($this->rtl) {
3017                                         $xdk = ($this->x - $dx - $width) * $k;
3018                                 } else {
3019                                         $xdk = ($this->x + $dx) * $k;
3020                                 }
3021                                 // Justification
3022                                 if ($align == 'J') {
3023                                         // count number of spaces
3024                                         $ns = substr_count($txt, ' ');
3025                                         //if ($this->isunicode) {
3026                                         if (($this->CurrentFont['type'] == "TrueTypeUnicode") OR ($this->CurrentFont['type'] == "cidfont0")) {
3027                                                 // get string width without spaces
3028                                                 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
3029                                                 // calculate average space width
3030                                                 $spacewidth = ($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1) / $this->FontSize / $this->k;
3031                                                 // set word position to be used with TJ operator
3032                                                 $txt2 = str_replace(chr(0).' ', ') '.(-2830 * $spacewidth).' (', $txt2);
3033                                         } else {
3034                                                 // get string width
3035                                                 $width = $this->GetStringWidth($txt);
3036                                                 $spacewidth = (($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1)) * $this->k;
3037                                                 $rs .= sprintf('BT %.3f Tw ET ', $spacewidth);
3038                                         }
3039                                 }
3040                                 // calculate approximate position of the font base line
3041                                 //$basefonty = $this->y + (($h + $this->FontAscent - $this->FontDescent)/2);
3042                                 $basefonty = $this->y + ($h/2) + ($this->FontSize/3);
3043                                 // print text
3044                                 $s .= sprintf('BT %.2f %.2f Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
3045                                 if ($this->rtl) {
3046                                         $xdx = $this->x - $dx - $width;
3047                                 } else {
3048                                         $xdx = $this->x + $dx;
3049                                 }
3050                                 if ($this->underline)  {
3051                                         $s .= ' '.$this->_dounderline($xdx, $basefonty, $txt);
3052                                 }
3053                                 if ($this->linethrough) {
3054                                         $s .= ' '.$this->_dolinethrough($xdx, $basefonty, $txt);
3055                                 }
3056                                 if ($this->ColorFlag) {
3057                                         $s .= ' Q';
3058                                 }
3059                                 if ($link) {
3060                                         $this->Link($xdx, $this->y + (($h - $this->FontSize)/2), $width, $this->FontSize, $link);
3061                                 }
3062                         }
3063                         // output cell
3064                         if ($s) {
3065                                 // output cell
3066                                 $rs .= $s;
3067                                 // reset text stretching
3068                                 if ($stretch > 2) {
3069                                         //Reset character horizontal spacing
3070                                         $rs .= ' BT 0 Tc ET';
3071                                 } elseif ($stretch > 0) {
3072                                         //Reset character horizontal scaling
3073                                         $rs .= ' BT 100 Tz ET';
3074                                 }
3075                         }
3076                         // reset word spacing
3077                         if ((!$this->isunicode) AND ($align == 'J')) {
3078                                 $rs .= ' BT 0 Tw ET';
3079                         }
3080                         $this->lasth = $h;
3081                         if ($ln > 0) {
3082                                 //Go to the beginning of the next line
3083                                 $this->y += $h;
3084                                 if ($ln == 1) {
3085                                         if ($this->rtl) {
3086                                                 $this->x = $this->w - $this->rMargin;
3087                                         } else {
3088                                                 $this->x = $this->lMargin;
3089                                         }
3090                                 }
3091                         } else {
3092                                 // go left or right by case
3093                                 if ($this->rtl) {
3094                                         $this->x -= $w;
3095                                 } else {
3096                                         $this->x += $w;
3097                                 }
3098                         }
3099                         $gstyles = $this->linestyleWidth." ".$this->linestyleCap." ".$this->linestyleJoin." ".$this->linestyleDash." ".$this->DrawColor." ".$this->FillColor."\n";
3100                         $rs = $gstyles.$rs;
3101                         return $rs;
3102                 }
3103
3104                 /**
3105                 * This method allows printing text with line breaks.
3106                 * They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other.<br />
3107                 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
3108                 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
3109                 * @param float $h Cell minimum height. The cell extends automatically if needed.
3110                 * @param string $txt String to print
3111                 * @param mixed $border Indicates if borders must be drawn around the cell block. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
3112                 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value when $ishtml=false)</li></ul>
3113                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3114                 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul>
3115                 * @param int $x x position in user units
3116                 * @param int $y y position in user units
3117                 * @param boolean $reseth if true reset the last cell height (default true).
3118                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
3119                 * @param boolean $ishtml se to true if $txt is HTML content (default = false).
3120                 * @return int Return the number of cells or 1 for html mode.
3121                 * @since 1.3
3122                 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
3123                 */
3124                 function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false) {
3125                         if ((empty($this->lasth))OR ($reseth)) {
3126                                 //set row height
3127                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
3128                         }
3129                         if (!empty($y)) {
3130                                 $this->SetY($y);
3131                         } else {
3132                                 $y = $this->GetY();
3133                         }
3134                         // check for page break
3135                         $this->checkPageBreak($h);
3136                         $y = $this->GetY();
3137                         // get current page number
3138                         $startpage = $this->page;
3139                         if (!empty($x)) {
3140                                 $this->SetX($x);
3141                         } else {
3142                                 $x = $this->GetX();
3143                         }
3144                         if (empty($w) OR ($w <= 0)) {
3145                                 if ($this->rtl) {
3146                                         $w = $this->x - $this->lMargin;
3147                                 } else {
3148                                         $w = $this->w - $this->rMargin - $this->x;
3149                                 }
3150                         }
3151                         // store original margin values
3152                         $lMargin = $this->lMargin;
3153                         $rMargin = $this->rMargin;
3154                         if ($this->rtl) {
3155                                 $this->SetRightMargin($this->w - $this->x);
3156                                 $this->SetLeftMargin($this->x - $w);
3157                         } else {
3158                                 $this->SetLeftMargin($this->x);
3159                                 $this->SetRightMargin($this->w - $this->x - $w);
3160                         }
3161                         // calculate remaining vertical space on first page ($startpage)
3162                         $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin();
3163                         // Adjust internal padding
3164                         if ($this->cMargin < ($this->LineWidth / 2)) {
3165                                 $this->cMargin = ($this->LineWidth / 2);
3166                         }
3167                         // Add top space if needed
3168                         if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3169                                 $this->y += $this->LineWidth / 2;
3170                         }
3171                         // add top padding
3172                         $this->y += $this->cMargin;
3173                         if ($ishtml) {
3174                                 // Write HTML text
3175                                 $this->writeHTML($txt, true, 0, $reseth, true, $align);
3176                                 $nl = 1;
3177                         } else {
3178                                 // Write text
3179                                 $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false);
3180                         }
3181                         // add bottom padding
3182                         $this->y += $this->cMargin;
3183                         // Add bottom space if needed
3184                         if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3185                                 $this->y += $this->LineWidth / 2;
3186                         }
3187                         // Get end-of-text Y position
3188                         $currentY = $this->GetY();
3189                         // get latest page number
3190                         $endpage = $this->page;
3191                         // check if a new page has been created
3192                         if ($endpage > $startpage) {
3193                                 // design borders around HTML cells.
3194                                 for ($page=$startpage; $page <= $endpage; $page++) {
3195                                         $this->setPage($page);
3196                                         if ($page == $startpage) {
3197                                                 $this->SetY($this->getPageHeight() - $restspace - $this->getBreakMargin());
3198                                                 $h = $restspace;
3199                                         } elseif ($page == $endpage) {
3200                                                 $this->SetY($this->tMargin); // put cursor at the beginning of text
3201                                                 $h = $currentY - $this->tMargin;
3202                                         } else {
3203                                                 $this->SetY($this->tMargin); // put cursor at the beginning of text
3204                                                 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
3205                                         }
3206                                         $this->SetX($x);
3207                                         $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3208                                         if ($border OR $fill) {
3209                                                 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3210                                                 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3211                                                 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3212                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
3213                                         }
3214                                 }
3215                         } else {
3216                                 $h = max($h, ($currentY - $y));
3217                                 // put cursor at the beginning of text
3218                                 $this->SetY($y);
3219                                 $this->SetX($x);
3220                                 $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3221                                 if ($border OR $fill) {
3222                                         // design a cell around the text
3223                                         $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3224                                         $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3225                                         $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3226                                         $this->intmrk[$this->page] += strlen($ccode."\n");
3227                                 }
3228                         }
3229                         // Get end-of-cell Y position
3230                         $currentY = $this->GetY();
3231                         // restore original margin values
3232                         $this->SetLeftMargin($lMargin);
3233                         $this->SetRightMargin($rMargin);
3234                         if ($ln > 0) {
3235                                 //Go to the beginning of the next line
3236                                 $this->SetY($currentY);
3237                                 if ($ln == 2) {
3238                                         $this->SetX($x + $w);
3239                                 }
3240                         } else {
3241                                 // go left or right by case
3242                                 $this->setPage($startpage);
3243                                 $this->y = $y;
3244                                 $this->SetX($x + $w);
3245                         }
3246                         return $nl;
3247                 }
3248
3249                 /**
3250                 * This method prints text from the current position.<br />
3251                 * @param float $h Line height
3252                 * @param string $txt String to print
3253                 * @param mixed $link URL or identifier returned by AddLink()
3254                 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
3255                 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
3256                 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
3257                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
3258                 * @param boolean $firstline if true prints only the first line and return the remaining string.
3259                 * @return mixed Return the number of cells or the remaining string if $firstline = true.
3260                 * @since 1.5
3261                 */
3262                 function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false) {
3263                         // remove carriage returns
3264                         $s = str_replace("\r", '', $txt);
3265                         // check if string contains arabic text
3266                         if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
3267                                 $arabic = true;
3268                         } else {
3269                                 $arabic = false;
3270                         }
3271                         // get array of chars
3272                         $chars = $this->UTF8StringToArray($s);
3273                         // get the number of characters
3274                         $nb = count($chars);
3275                         // handle single space character
3276                         if (($nb == 1) AND preg_match("/[\s]/u", $s)) {
3277                                 if ($this->rtl) {
3278                                         $this->x -= $this->GetStringWidth($s);
3279                                 } else {
3280                                         $this->x += $this->GetStringWidth($s);
3281                                 }
3282                                 return;
3283                         }
3284                         // store current position
3285                         $prevx = $this->x;
3286                         $prevy = $this->y;
3287                         // calculate remaining line width ($w)
3288                         if ($this->rtl) {
3289                                 $w = $this->x - $this->lMargin;
3290                         } else {
3291                                 $w = $this->w - $this->rMargin - $this->x;
3292                         }
3293                         // max column width
3294                         $wmax = $w - (2 * $this->cMargin);
3295                         $i = 0; // character position
3296                         $j = 0; // current starting position
3297                         $sep = -1; // position of the last blank space
3298                         $l = 0; // current string lenght
3299                         $nl = 0; //number of lines
3300                         $linebreak = false;
3301                         // for each character
3302                         while ($i < $nb) {
3303                                 //Get the current character
3304                                 $c = $chars[$i];
3305                                 if ($c == 10) { // 10 = "\n" = new line
3306                                         //Explicit line break
3307                                         if ($align == "J") {
3308                                                 if ($this->rtl) {
3309                                                         $talign = "R";
3310                                                 } else {
3311                                                         $talign = "L";
3312                                                 }
3313                                         } else {
3314                                                 $talign = $align;
3315                                         }
3316                                         if ($firstline) {
3317                                                 $startx = $this->x;
3318                                                 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3319                                                 if ($this->rtl) {
3320                                                         $this->endlinex = $startx - $linew;
3321                                                 } else {
3322                                                         $this->endlinex = $startx + $linew;
3323                                                 }
3324                                                 $w = $linew;
3325                                                 $tmpcmargin = $this->cMargin;
3326                                                 $this->cMargin = 0;
3327                                         }
3328                                         $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $talign, $fill, $link, $stretch);
3329                                         if ($firstline) {
3330                                                 $this->cMargin = $tmpcmargin;
3331                                                 return ($this->UTF8ArrSubString($chars, $i));
3332                                         }
3333                                         $nl++;
3334                                         $j = $i + 1;
3335                                         $l = 0;
3336                                         $sep = -1;
3337                                         $w = $this->getRemainingWidth();
3338                                         $wmax = $w - (2 * $this->cMargin);
3339                                 } else {
3340                                         if (preg_match("/[\s]/u", $this->unichr($c))) {
3341                                                 // update last blank space position
3342                                                 $sep = $i;
3343                                         }
3344                                         // update string length
3345                                         if (($this->isunicode) AND ($arabic)) {
3346                                                 // with bidirectional algorithm some chars may be changed affecting the line length
3347                                                 // *** very slow ***
3348                                                 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), $this->tmprtl));
3349                                         } else {
3350                                                 $l += $this->GetCharWidth($c);
3351                                         }
3352                                         if ($l > $wmax) {
3353                                                 // we have reached the end of column
3354                                                 if ($sep == -1) {
3355                                                         // check if the line was already started
3356                                                         if (($this->rtl AND ($this->x < ($this->w - $this->rMargin)))
3357                                                                 OR ((!$this->rtl) AND ($this->x > $this->lMargin))) {
3358                                                                 // print a void cell and go to next line
3359                                                                 $this->Cell($w, $h, "", 0, 1);
3360                                                                 $linebreak = true;
3361                                                                 if ($firstline) {
3362                                                                         return ($this->UTF8ArrSubString($chars, $j));
3363                                                                 }
3364                                                         } else {
3365                                                                 // truncate the word because do not fit on column
3366                                                                 if ($firstline) {
3367                                                                         $startx = $this->x;
3368                                                                         $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3369                                                                         if ($this->rtl) {
3370                                                                                 $this->endlinex = $startx - $linew;
3371                                                                         } else {
3372                                                                                 $this->endlinex = $startx + $linew;
3373                                                                         }
3374                                                                         $w = $linew;
3375                                                                         $tmpcmargin = $this->cMargin;
3376                                                                         $this->cMargin = 0;
3377                                                                 }
3378                                                                 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $align, $fill, $link, $stretch);
3379                                                                 if ($firstline) {
3380                                                                         $this->cMargin = $tmpcmargin;
3381                                                                         return ($this->UTF8ArrSubString($chars, $i));
3382                                                                 }
3383                                                                 $j = $i;
3384                                                                 $i--;
3385                                                         }
3386                                                 } else {
3387                                                         // word wrapping
3388                                                         if ($firstline) {
3389                                                                 $startx = $this->x;
3390                                                                 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $sep), $this->tmprtl));
3391                                                                 if ($this->rtl) {
3392                                                                         $this->endlinex = $startx - $linew;
3393                                                                 } else {
3394                                                                         $this->endlinex = $startx + $linew;
3395                                                                 }
3396                                                                 $w = $linew;
3397                                                                 $tmpcmargin = $this->cMargin;
3398                                                                 $this->cMargin = 0;
3399                                                         }
3400                                                         $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $sep), 0, 1, $align, $fill, $link, $stretch);
3401                                                         if ($firstline) {
3402                                                                 $this->cMargin = $tmpcmargin;
3403                                                                 return ($this->UTF8ArrSubString($chars, $sep));
3404                                                         }
3405                                                         $i = $sep;
3406                                                         $sep = -1;
3407                                                         $j = ($i+1);
3408                                                 }
3409                                                 $w = $this->getRemainingWidth();
3410                                                 $wmax = $w - (2 * $this->cMargin);
3411                                                 if ($linebreak) {
3412                                                         $linebreak = false;
3413                                                 } else {
3414                                                         $nl++;
3415                                                         $l = 0;
3416                                                 }
3417                                         }
3418                                 }
3419                                 $i++;
3420                         } // end while i < nb
3421                         // print last substring (if any)
3422                         if ($l > 0) {
3423                                 switch ($align) {
3424                                         case "J":
3425                                         case "C": {
3426                                                 $w = $w;
3427                                                 break;
3428                                         }
3429                                         case "L": {
3430                                                 if ($this->rtl) {
3431                                                         $w = $w;
3432                                                 } else {
3433                                                         $w = $l;
3434                                                 }
3435                                                 break;
3436                                         }
3437                                         case "R": {
3438                                                 if ($this->rtl) {
3439                                                         $w = $l;
3440                                                 } else {
3441                                                         $w = $w;
3442                                                 }
3443                                                 break;
3444                                         }
3445                                         default: {
3446                                                 $w = $l;
3447                                                 break;
3448                                         }
3449                                 }
3450                                 if ($firstline) {
3451                                         $startx = $this->x;
3452                                         $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $nb), $this->tmprtl));
3453                                         if ($this->rtl) {
3454                                                 $this->endlinex = $startx - $linew;
3455                                         } else {
3456                                                 $this->endlinex = $startx + $linew;
3457                                         }
3458                                         $w = $linew;
3459                                         $tmpcmargin = $this->cMargin;
3460                                         $this->cMargin = 0;
3461                                 }
3462                                 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $nb), 0, $ln, $align, $fill, $link, $stretch);
3463                                 if ($firstline) {
3464                                         $this->cMargin = $tmpcmargin;
3465                                         return ($this->UTF8ArrSubString($chars, $nb));
3466                                 }
3467                                 $nl++;
3468                         }
3469                         if ($firstline) {
3470                                 return "";
3471                         }
3472                         return $nl;
3473                 }
3474
3475                 /**
3476                 * Returns the remaining width between the current position and margins.
3477                 * @return int Return the remaining width
3478                 * @access protected
3479                 */
3480                 function getRemainingWidth() {
3481                         if ($this->rtl) {
3482                                 return ($this->x - $this->lMargin);
3483                         } else {
3484                                 return ($this->w - $this->rMargin - $this->x);
3485                         }
3486                 }
3487
3488          /**
3489                 * Extract a slice of the $strarr array and return it as string.
3490                 * @param string $strarr The input array of characters.
3491                 * @param int $start the starting element of $strarr.
3492                 * @param int $end first element that will not be returned.
3493                 * @return Return part of a string
3494                 */
3495                 function UTF8ArrSubString($strarr, $start='', $end='') {
3496                         if (strlen($start) == 0) {
3497                                 $start = 0;
3498                         }
3499                         if (strlen($end) == 0) {
3500                                 $end = count($strarr);
3501                         }
3502                         $string = "";
3503                         for ($i=$start; $i < $end; $i++) {
3504                                 $string .= $this->unichr($strarr[$i]);
3505                         }
3506                         return $string;
3507                 }
3508
3509                 /**
3510                 * Returns the unicode caracter specified by UTF-8 code
3511                 * @param int $c UTF-8 code
3512                 * @return Returns the specified character.
3513                 * @author Miguel Perez, Nicola Asuni
3514                 * @since 2.3.000 (2008-03-05)
3515                 */
3516                 function unichr($c) {
3517                         if (!$this->isunicode) {
3518                                 return chr($c);
3519                         } elseif ($c <= 0x7F) {
3520                                 // one byte
3521                                 return chr($c);
3522                         } elseif ($c <= 0x7FF) {
3523                                 // two bytes
3524                                 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
3525                         } elseif ($c <= 0xFFFF) {
3526                                 // three bytes
3527                                 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3528                         } elseif ($c <= 0x10FFFF) {
3529                                 // four bytes
3530                                 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3531                         } else {
3532                                 return "";
3533                         }
3534                 }
3535
3536                 /**
3537                 * Puts an image in the page.
3538                 * The upper-left corner must be given.
3539                 * The dimensions can be specified in different ways:<ul>
3540                 * <li>explicit width and height (expressed in user unit)</li>
3541                 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
3542                 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
3543                 * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
3544                 * The format can be specified explicitly or inferred from the file extension.<br />
3545                 * It is possible to put a link on the image.<br />
3546                 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
3547                 * @param string $file Name of the file containing the image.
3548                 * @param float $x Abscissa of the upper-left corner.
3549                 * @param float $y Ordinate of the upper-left corner.
3550                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
3551                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
3552                 * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
3553                 * @param mixed $link URL or identifier returned by AddLink().
3554                 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
3555                 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
3556                 * @param int $dpi dot-per-inch resolution used on resize
3557                 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
3558                 * @since 1.1
3559                 * @see AddLink()
3560                 */
3561                 function Image($file, $x, $y, $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
3562                         // get image size
3563                         list($pixw, $pixh) = getimagesize($file);
3564                         // calculate image width and height on document
3565                         if (($w <= 0) AND ($h <= 0)) {
3566                                 // convert image size to document unit
3567                                 $w = $pixw / ($this->imgscale * $this->k);
3568                                 $h = $pixh / ($this->imgscale * $this->k);
3569                         } elseif ($w <= 0) {
3570                                 $w = $h * $pixw / $pixh;
3571                         } elseif ($h <= 0) {
3572                                 $h = $w * $pixh / $pixw;
3573                         }
3574                         // calculate new minimum dimensions in pixels
3575                         $neww = round($w * $this->k * $dpi / $this->dpi);
3576                         $newh = round($h * $this->k * $dpi / $this->dpi);
3577                         // check if resize is necessary (resize is used only to reduce the image)
3578                         if (($neww * $newh) >= ($pixw * $pixh)) {
3579                                 $resize = false;
3580                         }
3581                         // check if image has been already added on document
3582                         if (!isset($this->images[$file])) {
3583                                 //First use of image, get info
3584                                 if ($type == '') {
3585                                         $fileinfo = pathinfo($file);
3586                                         if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
3587                                                 $type = $fileinfo['extension'];
3588                                         } else {
3589                                                 $this->Error('Image file has no extension and no type was specified: '.$file);
3590                                         }
3591                                 }
3592                                 $type = strtolower($type);
3593                                 if ($type == "jpg") {
3594                                         $type = "jpeg";
3595                                 }
3596                                 $mqr = get_magic_quotes_runtime();
3597                                 set_magic_quotes_runtime(0);
3598                                 // Specific image handlers
3599                                 $mtd = '_parse'.$type;
3600                                 // GD image handler function
3601                                 $gdfunction = "imagecreatefrom".$type;
3602                                 $info = false;
3603                                 if ((method_exists($this,$mtd)) AND (!($resize AND function_exists($gdfunction)))) {
3604                                         $info = $this->$mtd($file);
3605                                 }
3606                                 if (!$info) {
3607                                         if (function_exists($gdfunction)) {
3608                                                 $img = $gdfunction($file);
3609                                                 if ($resize) {
3610                                                         $imgr = imagecreatetruecolor($neww, $newh);
3611                                                         imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
3612                                                         $info = $this->_toJPEG($imgr);
3613                                                 } else {
3614                                                         $info = $this->_toJPEG($img);
3615                                                 }
3616                                         } else {
3617                                                 return;
3618                                         }
3619                                 }
3620                                 if ($info === false) {
3621                                         //If false, we cannot process image
3622                                         return;
3623                                 }
3624                                 set_magic_quotes_runtime($mqr);
3625                                 $info['i'] = count($this->images) + 1;
3626                                 // add image to document
3627                                 $this->images[$file] = $info;
3628                         } else {
3629                                 $info = $this->images[$file];
3630                         }
3631                         // Check whether we need a new page first as this does not fit
3632                         if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
3633                                 // Automatic page break
3634                                 $this->AddPage($this->CurOrientation);
3635                                 // Reset coordinates to top fo next page
3636                                 //$x = $this->GetX();
3637                                 $y = $this->GetY() + $this->cMargin;
3638                         }
3639                         // 2007-10-19 Warren Sherliker: End Edit
3640                         // set bottomcoordinates
3641                         $this->img_rb_y = $y + $h;
3642                         // set alignment
3643                         if ($this->rtl) {
3644                                 if ($palign == 'L') {
3645                                         $ximg = $this->lMargin;
3646                                         // set right side coordinate
3647                                         $this->img_rb_x = $ximg + $w;
3648                                 } elseif ($palign == 'C') {
3649                                         $ximg = ($this->w - $x - $w) / 2;
3650                                         // set right side coordinate
3651                                         $this->img_rb_x = $ximg + $w;
3652                                 } else {
3653                                         $ximg = $this->w - $x - $w;
3654                                         // set left side coordinate
3655                                         $this->img_rb_x = $ximg;
3656                                 }
3657                         } else {
3658                                 if ($palign == 'R') {
3659                                         $ximg = $this->w - $this->rMargin - $w;
3660                                         // set left side coordinate
3661                                         $this->img_rb_x = $ximg;
3662                                 } elseif ($palign == 'C') {
3663                                         $ximg = ($this->w - $x - $w) / 2;
3664                                         // set right side coordinate
3665                                         $this->img_rb_x = $ximg + $w;
3666                                 } else {
3667                                         $ximg = $x;
3668                                         // set right side coordinate
3669                                         $this->img_rb_x = $ximg + $w;
3670                                 }
3671                         }
3672                         $xkimg = $ximg * $this->k;
3673                         $this->_out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
3674                         if ($link) {
3675                                 $this->Link($ximg, $y, $w, $h, $link);
3676                         }
3677                         // set pointer to align the successive text/objects
3678                         switch($align) {
3679                                 case 'T': {
3680                                         $this->y = $y;
3681                                         $this->x = $this->img_rb_x;
3682                                         break;
3683                                 }
3684                                 case 'M': {
3685                                         $this->y = $y + round($h/2);
3686                                         $this->x = $this->img_rb_x;
3687                                         break;
3688                                 }
3689                                 case 'B': {
3690                                         $this->y = $this->img_rb_y;
3691                                         $this->x = $this->img_rb_x;
3692                                         break;
3693                                 }
3694                                 case 'N': {
3695                                         $this->SetY($this->img_rb_y);
3696                                         break;
3697                                 }
3698                                 default:{
3699                                         break;
3700                                 }
3701                         }
3702                         $this->endlinex = $this->img_rb_x;
3703                 }
3704
3705                 /**
3706                 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
3707                 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
3708                 * @param string $file Image file name.
3709                 * @param image $image Image object.
3710                 * return image JPEG image object.
3711                 * @access protected
3712                 */
3713                 function _toJPEG($image) {
3714                         $tempname = tempnam(K_PATH_CACHE,'jpg');
3715                         imagejpeg($image, $tempname, $this->jpeg_quality);
3716                         imagedestroy($image);
3717                         $retvars = $this->_parsejpeg($tempname);
3718                         // tidy up by removing temporary image
3719                         unlink($tempname);
3720                         return $retvars;
3721                 }
3722
3723                 /**
3724                 * Extract info from a JPEG file without using the GD library.
3725                 * @param string $file image file to parse
3726                 * @return array structure containing the image data
3727                 * @access protected
3728                 */
3729                 function _parsejpeg($file) {
3730                         $a = getimagesize($file);
3731                         if (empty($a)) {
3732                                 $this->Error('Missing or incorrect image file: '.$file);
3733                         }
3734                         if ($a[2] != 2) {
3735                                 $this->Error('Not a JPEG file: '.$file);
3736                         }
3737                         if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
3738                                 $colspace = 'DeviceRGB';
3739                         } elseif ($a['channels'] == 4) {
3740                                 $colspace = 'DeviceCMYK';
3741                         }       else {
3742                                 $colspace = 'DeviceGray';
3743                         }
3744                         $bpc = isset($a['bits']) ? $a['bits'] : 8;
3745                         $data = file_get_contents($file);
3746                         return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
3747                 }
3748
3749                 /**
3750                 * Extract info from a PNG file without using the GD library.
3751                 * @param string $file image file to parse
3752                 * @return array structure containing the image data
3753                 * @access protected
3754                 */
3755                 function _parsepng($file) {
3756                         $f = fopen($file,'rb');
3757                         if (empty($f)) {
3758                                 $this->Error('Can\'t open image file: '.$file);
3759                         }
3760                         //Check signature
3761                         if (fread($f,8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3762                                 $this->Error('Not a PNG file: '.$file);
3763                         }
3764                         //Read header chunk
3765                         fread($f,4);
3766                         if (fread($f,4) != 'IHDR') {
3767                                 $this->Error('Incorrect PNG file: '.$file);
3768                         }
3769                         $w = $this->_freadint($f);
3770                         $h = $this->_freadint($f);
3771                         $bpc = ord(fread($f,1));
3772                         if ($bpc > 8) {
3773                                 //$this->Error('16-bit depth not supported: '.$file);
3774                                 return false;
3775                         }
3776                         $ct = ord(fread($f,1));
3777                         if ($ct == 0) {
3778                                 $colspace = 'DeviceGray';
3779                         } elseif ($ct == 2) {
3780                                 $colspace = 'DeviceRGB';
3781                         } elseif ($ct == 3) {
3782                                 $colspace = 'Indexed';
3783                         } else {
3784                                 //$this->Error('Alpha channel not supported: '.$file);
3785                                 return false;
3786                         }
3787                         if (ord(fread($f,1)) != 0) {
3788                                 //$this->Error('Unknown compression method: '.$file);
3789                                 return false;
3790                         }
3791                         if (ord(fread($f,1)) != 0) {
3792                                 //$this->Error('Unknown filter method: '.$file);
3793                                 return false;
3794                         }
3795                         if (ord(fread($f,1)) != 0) {
3796                                 //$this->Error('Interlacing not supported: '.$file);
3797                                 return false;
3798                         }
3799                         fread($f,4);
3800                         $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
3801                         //Scan chunks looking for palette, transparency and image data
3802                         $pal = '';
3803                         $trns = '';
3804                         $data = '';
3805                         do {
3806                                 $n = $this->_freadint($f);
3807                                 $type = fread($f,4);
3808                                 if ($type == 'PLTE') {
3809                                         //Read palette
3810                                         $pal = fread($f,$n);
3811                                         fread($f,4);
3812                                 } elseif ($type == 'tRNS') {
3813                                         //Read transparency info
3814                                         $t = fread($f,$n);
3815                                         if ($ct == 0) {
3816                                                 $trns = array(ord(substr($t,1,1)));
3817                                         }
3818                                         elseif ($ct == 2) {
3819                                                 $trns = array(ord(substr($t,1,1)), ord(substr($t,3,1)), ord(substr($t,5,1)));
3820                                         } else {
3821                                                 $pos = strpos($t,chr(0));
3822                                                 if ($pos !== false) {
3823                                                         $trns = array($pos);
3824                                                 }
3825                                         }
3826                                         fread($f, 4);
3827                                 } elseif ($type == 'IDAT') {
3828                                         //Read image data block
3829                                         $data .= fread($f,$n);
3830                                         fread($f, 4);
3831                                 } elseif ($type == 'IEND') {
3832                                         break;
3833                                 } else {
3834                                         fread($f, $n+4);
3835                                 }
3836                         }
3837                         while ($n);
3838                         if (($colspace == 'Indexed') AND (empty($pal))) {
3839                                 //$this->Error('Missing palette in '.$file);
3840                                 return false;
3841                         }
3842                         fclose($f);
3843                         return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
3844                 }
3845
3846                 /**
3847                 * Performs a line break.
3848                 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
3849                 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
3850                 * @param boolean $cell if true add a cMargin to the x coordinate
3851                 * @since 1.0
3852                 * @see Cell()
3853                 */
3854                 function Ln($h='', $cell=false) {
3855                         //Line feed; default value is last cell height
3856                         if ($cell) {
3857                                 $cellmargin = $this->cMargin;
3858                         } else {
3859                                 $cellmargin = 0;
3860                         }
3861                         if ($this->rtl) {
3862                                 $this->x = $this->w - $this->rMargin - $cellmargin;
3863                         } else {
3864                                 $this->x = $this->lMargin + $cellmargin;
3865                         }
3866                         if (is_string($h)) {
3867                                 $this->y += $this->lasth;
3868                         } else {
3869                                 $this->y += $h;
3870                         }
3871                         $this->newline = true;
3872                 }
3873
3874                 /**
3875                 * Returns the relative X value of current position.
3876                 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
3877                 * @return float
3878                 * @since 1.2
3879                 * @see SetX(), GetY(), SetY()
3880                 */
3881                 function GetX() {
3882                         //Get x position
3883                         if ($this->rtl) {
3884                                 return ($this->w - $this->x);
3885                         } else {
3886                                 return $this->x;
3887                         }
3888                 }
3889
3890                 /**
3891                 * Returns the absolute X value of current position.
3892                 * @return float
3893                 * @since 1.2
3894                 * @see SetX(), GetY(), SetY()
3895                 */
3896                 function GetAbsX() {
3897                         return $this->x;
3898                 }
3899
3900                 /**
3901                 * Returns the ordinate of the current position.
3902                 * @return float
3903                 * @since 1.0
3904                 * @see SetY(), GetX(), SetX()
3905                 */
3906                 function GetY() {
3907                         //Get y position
3908                         return $this->y;
3909                 }
3910
3911                 /**
3912                 * Defines the abscissa of the current position.
3913                 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
3914                 * @param float $x The value of the abscissa.
3915                 * @since 1.2
3916                 * @see GetX(), GetY(), SetY(), SetXY()
3917                 */
3918                 function SetX($x) {
3919                         //Set x position
3920                         if ($this->rtl) {
3921                                 if ($x >= 0) {
3922                                         $this->x = $this->w - $x;
3923                                 } else {
3924                                         $this->x = abs($x);
3925                                 }
3926                         } else {
3927                                 if ($x >= 0) {
3928                                         $this->x = $x;
3929                                 } else {
3930                                         $this->x = $this->w + $x;
3931                                 }
3932                         }
3933                 }
3934
3935                 /**
3936                 * Moves the current abscissa back to the left margin and sets the ordinate.
3937                 * If the passed value is negative, it is relative to the bottom of the page.
3938                 * @param float $y The value of the ordinate.
3939                 * @since 1.0
3940                 * @see GetX(), GetY(), SetY(), SetXY()
3941                 */
3942                 function SetY($y) {
3943                         //Set y position and reset x
3944                         if ($this->rtl) {
3945                                 $this->x = $this->w - $this->rMargin;
3946                         } else {
3947                                 $this->x = $this->lMargin;
3948                         }
3949                         if ($y >= 0) {
3950                                 $this->y = $y;
3951                         } else {
3952                                 $this->y = $this->h + $y;
3953                         }
3954                 }
3955
3956                 /**
3957                 * Defines the abscissa and ordinate of the current position.
3958                 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
3959                 * @param float $x The value of the abscissa
3960                 * @param float $y The value of the ordinate
3961                 * @since 1.2
3962                 * @see SetX(), SetY()
3963                 */
3964                 function SetXY($x, $y) {
3965                         //Set x and y positions
3966                         $this->SetY($y);
3967                         $this->SetX($x);
3968                 }
3969
3970                 /**
3971                 * Send the document to a given destination: string, local file or browser.
3972                 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
3973                 * The method first calls Close() if necessary to terminate the document.
3974                 * @param string $name The name of the file when saved.
3975                 * @param string $dest Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local file with the name given by name.</li><li>S: return the document as a string. name is ignored.</li></ul>
3976                 * @since 1.0
3977                 * @see Close()
3978                 */
3979                 function Output($name='doc.pdf', $dest='I') {
3980                         //Output PDF to some destination
3981                         //Finish document if necessary
3982                         if ($this->state < 3) {
3983                                 $this->Close();
3984                         }
3985                         //Normalize parameters
3986                         if (is_bool($dest)) {
3987                                 $dest = $dest ? 'D' : 'F';
3988                         }
3989                         $dest = strtoupper($dest);
3990                         if ($dest != 'F') {
3991                                 $name = str_replace("+", "%20", urlencode($name));
3992                                 $name = preg_replace('/[\r\n]+\s*/', '' , $name);
3993                         }
3994                         switch($dest) {
3995                                 case 'I': {
3996                                         //Send to standard output
3997                                         if (ob_get_contents()) {
3998                                                 $this->Error('Some data has already been output, can\'t send PDF file');
3999                                         }
4000                                         if (php_sapi_name() != 'cli') {
4001                                                 //We send to a browser
4002                                                 header('Content-Type: application/pdf');
4003                                                 if (headers_sent()) {
4004                                                         $this->Error('Some data has already been output to browser, can\'t send PDF file');
4005                                                 }
4006                                                 header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4007                                                 header("Pragma: public");
4008                                                 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4009                                                 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");      
4010                                                 header('Content-Length: '.strlen($this->buffer));
4011                                                 header('Content-Disposition: inline; filename="'.basename($name).'";');
4012                                         }
4013                                         echo $this->buffer;
4014                                         break;
4015                                 }
4016                                 case 'D': {
4017                                         //Download file
4018                                         if (ob_get_contents()) {
4019                                                 $this->Error('Some data has already been output, can\'t send PDF file');
4020                                         }
4021                                         header('Content-Description: File Transfer');
4022                                         if (headers_sent()) {
4023                                                 $this->Error('Some data has already been output to browser, can\'t send PDF file');
4024                                         }
4025                                         header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4026                                         header("Pragma: public");
4027                                         header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4028                                         header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
4029                                         // force download dialog
4030                                         header("Content-Type: application/force-download");
4031                                         header("Content-Type: application/octet-stream", false);
4032                                         header("Content-Type: application/download", false);
4033                                         // use the Content-Disposition header to supply a recommended filename
4034                                         header('Content-Disposition: attachment; filename="'.basename($name).'";');
4035                                         header("Content-Transfer-Encoding: binary");
4036                                         header("Content-Length: ".strlen($this->buffer));
4037                                         echo $this->buffer;
4038                                         break;
4039                                 }
4040                                 case 'F': {
4041                                         //Save to local file
4042                                         $f = fopen($name, 'wb');
4043                                         if (!$f) {
4044                                                 $this->Error('Unable to create output file: '.$name);
4045                                         }
4046                                         fwrite($f, $this->buffer,strlen($this->buffer));
4047                                         fclose($f);
4048                                         break;
4049                                 }
4050                                 case 'S': {
4051                                         //Return as a string
4052                                         return $this->buffer;
4053                                 }
4054                                 default: {
4055                                         $this->Error('Incorrect output destination: '.$dest);
4056                                 }
4057                         }
4058                         return '';
4059                 }
4060
4061                 /**
4062                 * Check for locale-related bug
4063                 * @access protected
4064                 */
4065                 function _dochecks() {
4066                         //Check for locale-related bug
4067                         if (1.1 == 1) {
4068                                 $this->Error('Don\'t alter the locale before including class file');
4069                         }
4070                         //Check for decimal separator
4071                         if (sprintf('%.1f', 1.0) != '1.0') {
4072                                 setlocale(LC_NUMERIC, 'C');
4073                         }
4074                 }
4075
4076                 /**
4077                 * Return fonts path
4078                 * @return string
4079                 * @access protected
4080                 */
4081                 function _getfontpath() {
4082                         if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
4083                                 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
4084                         }
4085                         return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
4086                 }
4087
4088                 /**
4089                 * Output pages.
4090                 * @access protected
4091                 */
4092                 function _putpages() {
4093                         $nb = count($this->pages);
4094                         if (!empty($this->pagegroups)) {
4095                                 // do page number replacement
4096                                 foreach ($this->pagegroups as $k => $v) {
4097                                         $vu = $this->UTF8ToUTF16BE($v, false);
4098                                         $alias_a = $this->_escape($k);
4099                                         $alias_au = $this->_escape("{".$k."}");
4100                                         if ($this->isunicode) {
4101                                                 $alias_b = $this->_escape($this->UTF8ToLatin1($k));
4102                                                 $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$k."}"));
4103                                                 $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
4104                                                 $alias_cu = $this->_escape($this->utf8StrRev("{".$k."}", false, $this->tmprtl));
4105                                         }
4106                                         for ($n = 1; $n <= $nb; $n++) {
4107                                                 $this->pages[$n] = str_replace($alias_au, $vu, $this->pages[$n]);
4108                                                 if ($this->isunicode) {
4109                                                         $this->pages[$n] = str_replace($alias_bu, $vu, $this->pages[$n]);
4110                                                         $this->pages[$n] = str_replace($alias_cu, $vu, $this->pages[$n]);
4111                                                         $this->pages[$n] = str_replace($alias_b, $v, $this->pages[$n]);
4112                                                         $this->pages[$n] = str_replace($alias_c, $v, $this->pages[$n]);
4113                                                 }
4114                                                 $this->pages[$n] = str_replace($alias_a, $v, $this->pages[$n]);
4115                                         }
4116                                 }
4117                         }
4118                         if (!empty($this->AliasNbPages)) {
4119                                 $nbu = $this->UTF8ToUTF16BE($nb, false); // replacement for unicode font
4120                                 $alias_a = $this->_escape($this->AliasNbPages);
4121                                 $alias_au = $this->_escape("{".$this->AliasNbPages."}");
4122                                 if ($this->isunicode) {
4123                                         $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
4124                                         $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$this->AliasNbPages."}"));
4125                                         $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
4126                                         $alias_cu = $this->_escape($this->utf8StrRev("{".$this->AliasNbPages."}", false, $this->tmprtl));
4127                                 }
4128                                 //Replace number of pages
4129                                 for($n = 1; $n <= $nb; $n++) {
4130                                         $this->pages[$n] = str_replace($alias_au, $nbu, $this->pages[$n]);
4131                                         if ($this->isunicode) {
4132                                                 $this->pages[$n] = str_replace($alias_bu, $nbu, $this->pages[$n]);
4133                                                 $this->pages[$n] = str_replace($alias_cu, $nbu, $this->pages[$n]);
4134                                                 $this->pages[$n] = str_replace($alias_b, $nb, $this->pages[$n]);
4135                                                 $this->pages[$n] = str_replace($alias_c, $nb, $this->pages[$n]);
4136                                         }
4137                                         $this->pages[$n] = str_replace($alias_a, $nb, $this->pages[$n]);
4138                                 }
4139                         }
4140                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4141                         for($n=1; $n <= $nb; $n++) {
4142                                 //Page
4143                                 $this->_newobj();
4144                                 $this->_out('<</Type /Page');
4145                                 $this->_out('/Parent 1 0 R');
4146                                 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
4147                                 $this->_out('/Resources 2 0 R');
4148                                 $this->_putannots($n);
4149                                 $this->_out('/Contents '.($this->n + 1).' 0 R>>');
4150                                 $this->_out('endobj');
4151                                 //Page content
4152                                 $p = ($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n];
4153                                 $this->_newobj();
4154                                 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
4155                                 $this->_putstream($p);
4156                                 $this->_out('endobj');
4157                         }
4158                         //Pages root
4159                         $this->offsets[1] = strlen($this->buffer);
4160                         $this->_out('1 0 obj');
4161                         $this->_out('<</Type /Pages');
4162                         $kids='/Kids [';
4163                         for($i=0; $i < $nb; $i++) {
4164                                 $kids .= (3+2*$i).' 0 R ';
4165                         }
4166                         $this->_out($kids.']');
4167                         $this->_out('/Count '.$nb);
4168                         //$this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
4169                         $this->_out('>>');
4170                         $this->_out('endobj');
4171                 }
4172
4173                 /**
4174                 * Output Page Annotations.
4175                 * See section 8.4 of PDF reference.
4176                 * @param int $n page number
4177                 * @access protected
4178                 * @author Nicola Asuni
4179                 * @since 4.0.018 (2008-08-06)
4180                 */
4181                 function _putannots($n) {
4182                         if (isset($this->PageAnnots[$n])) {
4183                                 $annots = '/Annots [';
4184                                 foreach ($this->PageAnnots[$n] as $key => $pl) {
4185                                         $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
4186                                         $a = $pl['x'] * $this->k;
4187                                         $b = $this->hPt - $pl['y'] * $this->k;
4188                                         $c = $pl['w'] * $this->k;
4189                                         $d = $pl['h'] * $this->k;
4190                                         $rect = sprintf('%.2f %.2f %.2f %.2f', $a, $b, $a+$c, $b-$d);
4191                                         $annots .= '<</Type /Annot';
4192                                         $annots .= ' /Subtype /'.$pl['opt']['subtype'];
4193                                         $annots .= ' /Rect ['.$rect.']';
4194                                         $annots .= ' /Contents '.$this->_textstring($pl['txt']);
4195                                         //$annots .= ' /P ';
4196                                         $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
4197                                         $annots .= ' /M '.$this->_datestring('D:'.date('YmdHis'));
4198                                         if (isset($pl['opt']['f'])) {
4199                                                 $val = 0;
4200                                                 if (is_array($pl['opt']['f'])) {
4201                                                         foreach ($pl['opt']['f'] as $f) {
4202                                                                 switch (strtolower($f)) {
4203                                                                         case 'invisible': {
4204                                                                                 $val += 1 << 0;
4205                                                                                 break;
4206                                                                         }
4207                                                                         case 'hidden': {
4208                                                                                 $val += 1 << 1;
4209                                                                                 break;
4210                                                                         }
4211                                                                         case 'print': {
4212                                                                                 $val += 1 << 2;
4213                                                                                 break;
4214                                                                         }
4215                                                                         case 'nozoom': {
4216                                                                                 $val += 1 << 3;
4217                                                                                 break;
4218                                                                         }
4219                                                                         case 'norotate': {
4220                                                                                 $val += 1 << 4;
4221                                                                                 break;
4222                                                                         }
4223                                                                         case 'noview': {
4224                                                                                 $val += 1 << 5;
4225                                                                                 break;
4226                                                                         }
4227                                                                         case 'readonly': {
4228                                                                                 $val += 1 << 6;
4229                                                                                 break;
4230                                                                         }
4231                                                                         case 'locked': {
4232                                                                                 $val += 1 << 8;
4233                                                                                 break;
4234                                                                         }
4235                                                                         case 'togglenoview': {
4236                                                                                 $val += 1 << 9;
4237                                                                                 break;
4238                                                                         }
4239                                                                         case 'lockedcontents': {
4240                                                                                 $val += 1 << 10;
4241                                                                                 break;
4242                                                                         }
4243                                                                         default: {
4244                                                                                 break;
4245                                                                         }
4246                                                                 }
4247                                                         }
4248                                                 }
4249                                                 $annots .= ' /F '.intval($val);
4250                                         }
4251                                         //$annots .= ' /AP ';
4252                                         //$annots .= ' /AS ';
4253                                         $annots .= ' /Border [';
4254                                         if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
4255                                                 $annots .= intval($pl['opt']['border'][0]).' ';
4256                                                 $annots .= intval($pl['opt']['border'][1]).' ';
4257                                                 $annots .= intval($pl['opt']['border'][2]);
4258                                                 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
4259                                                         $annots .= ' [';
4260                                                         foreach ($pl['opt']['border'][3] as $dash) {
4261                                                                 $annots .= intval($dash).' ';
4262                                                         }
4263                                                         $annots .= ']';
4264                                                 }
4265                                         } else {
4266                                                 $annots .= '0 0 0';
4267                                         }
4268                                         $annots .= ']';
4269                                         if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
4270                                                 $annots .= ' /BS <<Type /Border';
4271                                                 if (isset($pl['opt']['bs']['w'])) {
4272                                                         $annots .= ' /W '.sprintf("%.4f", floatval($pl['opt']['bs']['w']));
4273                                                 }
4274                                                 $bstyles = array('S', 'D', 'B', 'I', 'U');
4275                                                 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $markups)) {
4276                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
4277                                                 }
4278                                                 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
4279                                                         $annots .= ' /D [';
4280                                                         foreach ($pl['opt']['bs']['d'] as $cord) {
4281                                                                 $cord = floatval($cord);
4282                                                                 $annots .= sprintf(" %.4f", $cord);
4283                                                         }
4284                                                         $annots .= ']';
4285                                                 }
4286                                                 $annots .= '>>';
4287                                         }
4288                                         if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
4289                                                 $annots .= ' /BE <<';
4290                                                 $bstyles = array('S', 'C');
4291                                                 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
4292                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
4293                                                 } else {
4294                                                         $annots .= ' /S /S';
4295                                                 }
4296                                                 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
4297                                                         $annots .= ' /I '.sprintf(" %.4f", $pl['opt']['be']['i']);
4298                                                 }
4299                                                 $annots .= '>>';
4300                                         }
4301                                         $annots .= ' /C [';
4302                                         if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
4303                                                 foreach ($pl['opt']['c'] as $col) {
4304                                                         $col = intval($col);
4305                                                         $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
4306                                                         $annots .= sprintf(" %.4f", $color);
4307                                                 }
4308                                         }
4309                                         $annots .= ']';
4310                                         //$annots .= ' /StructParent ';
4311                                         //$annots .= ' /OC ';
4312                                         $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight',  'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
4313                                         if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
4314                                                 // this is a markup type
4315                                                 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
4316                                                         $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
4317                                                 }
4318                                                 //$annots .= ' /Popup ';
4319                                                 if (isset($pl['opt']['ca'])) {
4320                                                         $annots .= ' /CA '.sprintf("%.4f", floatval($pl['opt']['ca']));
4321                                                 }
4322                                                 if (isset($pl['opt']['rc'])) {
4323                                                         $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4324                                                 }
4325                                                 $annots .= ' /CreationDate '.$this->_datestring('D:'.date('YmdHis'));
4326                                                 //$annots .= ' /IRT ';
4327                                                 if (isset($pl['opt']['subj'])) {
4328                                                         $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
4329                                                 }
4330                                                 //$annots .= ' /RT ';
4331                                                 //$annots .= ' /IT ';
4332                                                 //$annots .= ' /ExData ';
4333                                         }
4334                                         switch (strtolower($pl['opt']['subtype'])) {
4335                                                 case 'text': {
4336                                                         if (isset($pl['opt']['open'])) {
4337                                                                 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
4338                                                         }
4339                                                         $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
4340                                                         if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
4341                                                                 $annots .= ' /Name /'.$pl['opt']['name'];
4342                                                         } else {
4343                                                                 $annots .= ' /Name /Note';
4344                                                         }
4345                                                         $statemodels = array('Marked', 'Review');
4346                                                         if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
4347                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4348                                                         } else {
4349                                                                 $pl['opt']['statemodel'] = 'Marked';
4350                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4351                                                         }
4352                                                         if ($pl['opt']['statemodel'] == 'Marked') {
4353                                                                 $states = array('Accepted', 'Unmarked');
4354                                                         } else {
4355                                                                 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
4356                                                         }
4357                                                         if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
4358                                                                 $annots .= ' /State /'.$pl['opt']['state'];
4359                                                         } else {
4360                                                                 if ($pl['opt']['statemodel'] == 'Marked') {
4361                                                                         $annots .= ' /State /Unmarked';
4362                                                                 } else {
4363                                                                         $annots .= ' /State /None';
4364                                                                 }
4365                                                         }
4366                                                         break;
4367                                                 }
4368                                                 case 'link': {
4369                                                         $annots .= ' /A <</S /URI /URI '.$this->_uristring($pl['txt']).'>>';
4370                                                         $hmodes = array('N', 'I', 'O', 'P');
4371                                                         if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
4372                                                                 $annots .= ' /H /'.$pl['opt']['h'];
4373                                                         } else {
4374                                                                 $annots .= ' /H /I';
4375                                                         }
4376                                                         //$annots .= ' /Dest ';
4377                                                         //$annots .= ' /PA ';
4378                                                         //$annots .= ' /Quadpoints ';
4379                                                         break;
4380                                                 }
4381                                                 case 'freetext': {
4382                                                         $annots .= ' /DA '.$this->_textstring($pl['txt']);
4383                                                         if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
4384                                                                 $annots .= ' /Q '.intval($pl['opt']['q']);
4385                                                         }
4386                                                         if (isset($pl['opt']['rc'])) {
4387                                                                 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4388                                                         }
4389                                                         if (isset($pl['opt']['ds'])) {
4390                                                                 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
4391                                                         }
4392                                                         if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
4393                                                                 $annots .= ' /CL [';
4394                                                                 foreach ($pl['opt']['cl'] as $cl) {
4395                                                                         $annots .= sprintf("%.4f ", $cl * $this->k);
4396                                                                 }
4397                                                                 $annots .= ']';
4398                                                         }
4399                                                         $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
4400                                                         if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
4401                                                                 $annots .= ' /IT '.$pl['opt']['it'];
4402                                                         }
4403                                                         if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
4404                                                                 $l = $pl['opt']['rd'][0] * $this->k;
4405                                                                 $r = $pl['opt']['rd'][1] * $this->k;
4406                                                                 $t = $pl['opt']['rd'][2] * $this->k;
4407                                                                 $b = $pl['opt']['rd'][3] * $this->k;
4408                                                                 $annots .= ' /RD ['.sprintf('%.2f %.2f %.2f %.2f', $l, $r, $t, $b).']';
4409                                                         }
4410                                                         //$annots .= ' /LE ';
4411                                                         break;
4412                                                 }
4413                                                 // ... to be completed ...
4414                                                 case 'line': {
4415                                                         break;
4416                                                 }
4417                                                 case 'square': {
4418                                                         break;
4419                                                 }
4420                                                 case 'circle': {
4421                                                         break;
4422                                                 }
4423                                                 case 'polygon': {
4424                                                         break;
4425                                                 }
4426                                                 case 'polyline': {
4427                                                         break;
4428                                                 }
4429                                                 case 'highlight': {
4430                                                         break;
4431                                                 }
4432                                                 case 'underline': {
4433                                                         break;
4434                                                 }
4435                                                 case 'squiggly': {
4436                                                         break;
4437                                                 }
4438                                                 case 'strikeout': {
4439                                                         break;
4440                                                 }
4441                                                 case 'stamp': {
4442                                                         break;
4443                                                 }
4444                                                 case 'caret': {
4445                                                         break;
4446                                                 }
4447                                                 case 'ink': {
4448                                                         break;
4449                                                 }
4450                                                 case 'popup': {
4451                                                         break;
4452                                                 }
4453                                                 case 'fileattachment': {
4454                                                         break;
4455                                                 }
4456                                                 case 'sound': {
4457                                                         break;
4458                                                 }
4459                                                 case 'movie': {
4460                                                         break;
4461                                                 }
4462                                                 case 'widget': {
4463                                                         break;
4464                                                 }
4465                                                 case 'screen': {
4466                                                         break;
4467                                                 }
4468                                                 case 'printermark': {
4469                                                         break;
4470                                                 }
4471                                                 case 'trapnet': {
4472                                                         break;
4473                                                 }
4474                                                 case 'watermark': {
4475                                                         break;
4476                                                 }
4477                                                 case '3d': {
4478                                                         break;
4479                                                 }
4480                                                 default: {
4481                                                         break;
4482                                                 }
4483                                         }
4484                                         
4485                                 $annots .= '>>';
4486                                 }
4487                                 $this->_out($annots.']');
4488                         }
4489                 }
4490
4491                 /**
4492                 * Output fonts.
4493                 * _putfonts
4494                 * @access protected
4495                 */
4496                 function _putfonts() {
4497                         $nf = $this->n;
4498                         foreach($this->diffs as $diff) {
4499                                 //Encodings
4500                                 $this->_newobj();
4501                                 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
4502                                 $this->_out('endobj');
4503                         }
4504                         $mqr = get_magic_quotes_runtime();
4505                         set_magic_quotes_runtime(0);
4506                         foreach($this->FontFiles as $file => $info) {
4507                                 //Font file embedding
4508                                 $this->_newobj();
4509                                 $this->FontFiles[$file]['n'] = $this->n;
4510                                 $font = file_get_contents($this->_getfontpath().strtolower($file));
4511                                 $compressed = (substr($file,-2)=='.z');
4512                                 if ((!$compressed) AND (isset($info['length2']))) {
4513                                         $header = (ord($font{0}) == 128);
4514                                         if ($header) {
4515                                                 //Strip first binary header
4516                                                 $font = substr($font,6);
4517                                         }
4518                                         if ($header AND (ord($font{$info['length1']}) == 128)) {
4519                                                 //Strip second binary header
4520                                                 $font = substr($font, 0, $info['length1']).substr($font, $info['length1']+6);
4521                                         }
4522                                 }
4523                                 $this->_out('<</Length '.strlen($font));
4524                                 if ($compressed) {
4525                                         $this->_out('/Filter /FlateDecode');
4526                                 }
4527                                 $this->_out('/Length1 '.$info['length1']);
4528                                 if (isset($info['length2'])) {
4529                                         $this->_out('/Length2 '.$info['length2'].' /Length3 0');
4530                                 }
4531                                 $this->_out('>>');
4532                                 $this->_putstream($font);
4533                                 $this->_out('endobj');
4534                         }
4535                         set_magic_quotes_runtime($mqr);
4536                         foreach($this->fonts as $k => $font) {
4537                                 //Font objects
4538                                 $this->fonts[$k]['n'] = $this->n + 1;
4539                                 $type = $font['type'];
4540                                 $name = $font['name'];
4541                                 if ($type == 'core') {
4542                                         //Standard font
4543                                         $this->_newobj();
4544                                         $this->_out('<</Type /Font');
4545                                         $this->_out('/BaseFont /'.$name);
4546                                         $this->_out('/Subtype /Type1');
4547                                         if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
4548                                                 $this->_out('/Encoding /WinAnsiEncoding');
4549                                         }
4550                                         $this->_out('>>');
4551                                         $this->_out('endobj');
4552                                 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
4553                                         //Additional Type1 or TrueType font
4554                                         $this->_newobj();
4555                                         $this->_out('<</Type /Font');
4556                                         $this->_out('/BaseFont /'.$name);
4557                                         $this->_out('/Subtype /'.$type);
4558                                         $this->_out('/FirstChar 32 /LastChar 255');
4559                                         $this->_out('/Widths '.($this->n + 1).' 0 R');
4560                                         $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
4561                                         if ($font['enc']) {
4562                                                 if (isset($font['diff'])) {
4563                                                         $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
4564                                                 } else {
4565                                                         $this->_out('/Encoding /WinAnsiEncoding');
4566                                                 }
4567                                         }
4568                                         $this->_out('>>');
4569                                         $this->_out('endobj');
4570                                         //Widths
4571                                         $this->_newobj();
4572                                         $cw = &$font['cw'];
4573                                         $s = '[';
4574                                         for($i=32; $i <= 255; $i++) {
4575                                                 //$s .= $cw[chr($i)].' ';
4576                                                 $s .= $cw[$i].' ';
4577                                         }
4578                                         $this->_out($s.']');
4579                                         $this->_out('endobj');
4580                                         //Descriptor
4581                                         $this->_newobj();
4582                                         $s = '<</Type /FontDescriptor /FontName /'.$name;
4583                                         foreach($font['desc'] as $k => $v) {
4584                                                 $s .= ' /'.$k.' '.$v;
4585                                         }
4586                                         $file = $font['file'];
4587                                         if ($file) {
4588                                                 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
4589                                         }
4590                                         $this->_out($s.'>>');
4591                                         $this->_out('endobj');
4592                                 } else {
4593                                         //Allow for additional types
4594                                         $mtd = '_put'.strtolower($type);
4595                                         if (!method_exists($this, $mtd)) {
4596                                                 $this->Error('Unsupported font type: '.$type);
4597                                         }
4598                                         $this->$mtd($font);
4599                                 }
4600                         }
4601                 }
4602
4603                 /**
4604                  * Output CID-0 fonts.
4605                  * @param array $font font data
4606                  * @access protected
4607                  * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
4608                  * @since 3.2.000 (2008-06-23)
4609                  */
4610                 function _putcidfont0($font) {
4611                         if (isset($font['cidinfo']['uni2cid'])) {
4612                                 // convert unicode to cid.
4613                                 $uni2cid = $font['cidinfo']['uni2cid'];
4614                                 $cw = array();
4615                                 foreach ($font['cw'] as $uni => $width) {
4616                                         if (isset($uni2cid[$uni])) {
4617                                                 $cw[($uni2cid[$uni] + 31)] = $width;
4618                                         } elseif ($uni <= 255) {
4619                                                 $cw[$uni] = $width;
4620                                         } // else unknown character
4621                                 }
4622                                 ksort($cw);
4623                                 $font = array_merge($font, array('cw'=>$cw));
4624                         }
4625                         $longname = $name = $font['name'];
4626                         $enc = $font['enc'];
4627                         if ($enc) {
4628                                 $longname .= "-$enc";
4629                         }
4630                         $this->_newobj();
4631                         $this->_out('<</Type /Font');
4632                         $this->_out('/BaseFont /'.$longname);
4633                         $this->_out('/Subtype /Type0');
4634                         if ($enc) {
4635                                 $this->_out('/Encoding /'.$enc);
4636                         }
4637                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
4638                         $this->_out('>>');
4639                         $this->_out('endobj');
4640                         $this->_newobj();
4641                         $this->_out('<</Type /Font');
4642                         $this->_out('/BaseFont /'.$name);
4643                         $this->_out('/Subtype /CIDFontType0');
4644                         $cidinfo = '/Registry ('.$font['cidinfo']['Registry'].') ';
4645                         $cidinfo .= '/Ordering ('.$font['cidinfo']['Ordering'].') ';
4646                         $cidinfo .= '/Supplement '.$font['cidinfo']['Supplement'];
4647                         $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
4648                         $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
4649                         $codes = array_keys($font['cw']);
4650                         $first = current($codes);
4651                         $last = end($codes);
4652                         $this->_out('/DW '.$font['dw']);
4653                         $w = '/W [';
4654                         $ranges = array();
4655                         $currange = 0;
4656                         for($i = $first; $i <= $last; $i++) {
4657                                 if (isset($font['cw'][$i]) AND (!$currange)) {
4658                                         $currange = $i - 31;
4659                                 } elseif (!isset($font['cw'][$i])) {
4660                                         $currange = 0;
4661                                 }
4662                                 if ($currange) {
4663                                         $ranges[$currange][] = $font['cw'][$i];
4664                                 }
4665                         }
4666                         foreach($ranges as $k => $ws) {
4667                                 $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
4668                         }
4669                         $w .= ' ]';
4670                         $this->_out($w);
4671                         $this->_out('>>');
4672                         $this->_out('endobj');
4673                         $this->_newobj();
4674                         $s = '<</Type /FontDescriptor /FontName /'.$name;
4675                         foreach($font['desc'] as $k => $v) {
4676                                 $s .= ' /'.$k.' '.$v;
4677                         }
4678                         $this->_out($s.'>>');
4679                         $this->_out('endobj');
4680                 }
4681
4682                 /**
4683                  * Output images.
4684                  * @access protected
4685                  */
4686                 function _putimages() {
4687                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4688                         reset($this->images);
4689                         while (list($file, $info) = each($this->images)) {
4690                                 $this->_newobj();
4691                                 $this->images[$file]['n'] = $this->n;
4692                                 $this->_out('<</Type /XObject');
4693                                 $this->_out('/Subtype /Image');
4694                                 $this->_out('/Width '.$info['w']);
4695                                 $this->_out('/Height '.$info['h']);
4696                                 if (isset($info["masked"])) {
4697                                         $this->_out('/SMask '.($this->n-1).' 0 R');
4698                                 }
4699                                 if ($info['cs'] == 'Indexed') {
4700                                         $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal']) / 3 - 1).' '.($this->n + 1).' 0 R]');
4701                                 } else {
4702                                         $this->_out('/ColorSpace /'.$info['cs']);
4703                                         if ($info['cs'] == 'DeviceCMYK') {
4704                                                 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
4705                                         }
4706                                 }
4707                                 $this->_out('/BitsPerComponent '.$info['bpc']);
4708                                 if (isset($info['f'])) {
4709                                         $this->_out('/Filter /'.$info['f']);
4710                                 }
4711                                 if (isset($info['parms'])) {
4712                                         $this->_out($info['parms']);
4713                                 }
4714                                 if (isset($info['trns']) and is_array($info['trns'])) {
4715                                         $trns='';
4716                                         for($i=0; $i < count($info['trns']); $i++) {
4717                                                 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
4718                                         }
4719                                         $this->_out('/Mask ['.$trns.']');
4720                                 }
4721                                 $this->_out('/Length '.strlen($info['data']).'>>');
4722                                 $this->_putstream($info['data']);
4723                                 unset($this->images[$file]['data']);
4724                                 $this->_out('endobj');
4725                                 //Palette
4726                                 if ($info['cs'] == 'Indexed') {
4727                                         $this->_newobj();
4728                                         $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
4729                                         $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
4730                                         $this->_putstream($pal);
4731                                         $this->_out('endobj');
4732                                 }
4733                         }
4734                 }
4735
4736                 /**
4737                 * Output Spot Colors Resources.
4738                 * @access protected
4739                 * @since 4.0.024 (2008-09-12)
4740                 */
4741                 function _putspotcolors() {
4742                         foreach ($this->spot_colors as $name => $color) {
4743                                 $this->_newobj();
4744                                 $this->spot_colors[$name]['n'] = $this->n;
4745                                 $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
4746                                 $this->_out('/DeviceCMYK <<');
4747                                 $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
4748                                 $this->_out(sprintf('/C1 [%.4f %.4f %.4f %.4f] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
4749                                 $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
4750                                 $this->_out('endobj');
4751                         }
4752                 }
4753
4754                 /**
4755                 * Output object dictionary for images.
4756                 * @access protected
4757                 */
4758                 function _putxobjectdict() {
4759                         foreach($this->images as $image) {
4760                                 $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
4761                         }
4762                 }
4763
4764                 /**
4765                 * Output Resources Dictionary.
4766                 * @access protected
4767                 */
4768                 function _putresourcedict(){
4769                         $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
4770                         $this->_out('/Font <<');
4771                         foreach($this->fonts as $font) {
4772                                 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
4773                         }
4774                         $this->_out('>>');
4775                         $this->_out('/XObject <<');
4776                         $this->_putxobjectdict();
4777                         $this->_out('>>');
4778                         // visibility
4779                         $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
4780                         // transparency
4781                         $this->_out('/ExtGState <<');
4782                         foreach($this->extgstates as $k => $extgstate) {
4783                                 $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
4784                         }
4785                         $this->_out('>>');
4786                         // gradients
4787                         if (isset($this->gradients) AND (count($this->gradients) > 0)) {
4788                                 $this->_out('/Shading <<');
4789                                 foreach($this->gradients as $id => $grad) {
4790                                         $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
4791                                 }
4792                                 $this->_out('>>');
4793                         }
4794                         // spot colors
4795                         if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
4796                                 $this->_out('/ColorSpace <<');
4797                                 foreach ($this->spot_colors as $color) {
4798                                         $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
4799                                 }
4800                                 $this->_out('>>');
4801                         }
4802                 }
4803
4804                 /**
4805                 * Output Resources.
4806                 * @access protected
4807                 */
4808                 function _putresources() {
4809                         $this->_putextgstates();
4810                         $this->_putocg();
4811                         $this->_putfonts();
4812                         $this->_putimages();
4813                         $this->_putspotcolors();
4814                         $this->_putshaders();
4815                         //Resource dictionary
4816                         $this->offsets[2] = strlen($this->buffer);
4817                         $this->_out('2 0 obj');
4818                         $this->_out('<<');
4819                         $this->_putresourcedict();
4820                         $this->_out('>>');
4821                         $this->_out('endobj');
4822                         $this->_putjavascript();
4823                         $this->_putbookmarks();
4824                         // encryption
4825                         if ($this->encrypted) {
4826                                 $this->_newobj();
4827                                 $this->enc_obj_id = $this->n;
4828                                 $this->_out('<<');
4829                                 $this->_putencryption();
4830                                 $this->_out('>>');
4831                                 $this->_out('endobj');
4832                         }
4833                 }
4834
4835                 /**
4836                 * Adds some Metadata information
4837                 * (see Chapter 10.2 of PDF Reference)
4838                 * @access protected
4839                 */
4840                 function _putinfo() {
4841                         if (!empty($this->title)) {
4842                                 $this->_out('/Title '.$this->_textstring($this->title));
4843                         }
4844                         if (!empty($this->author)) {
4845                                 $this->_out('/Author '.$this->_textstring($this->author));
4846                         }
4847                         if (!empty($this->subject)) {
4848                                 $this->_out('/Subject '.$this->_textstring($this->subject));
4849                         }
4850                         if (!empty($this->keywords)) {
4851                                 $this->_out('/Keywords '.$this->_textstring($this->keywords));
4852                         }
4853                         if (!empty($this->creator)) {
4854                                 $this->_out('/Creator '.$this->_textstring($this->creator));
4855                         }
4856                         if (defined('PDF_PRODUCER')) {
4857                                 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
4858                         }
4859                         $this->_out('/CreationDate '.$this->_datestring('D:'.date('YmdHis')));
4860                         $this->_out('/ModDate '.$this->_datestring('D:'.date('YmdHis')));
4861                 }
4862
4863                 /**
4864                 * Format a date string for meta information
4865                 * @param string $s date string to escape.
4866                 * @return string escaped string.
4867                 * @access protected
4868                 */
4869                 function _datestring($s) {
4870                         if ($this->encrypted) {
4871                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
4872                         }
4873                         return '('. $this->_escape($s).')';
4874                 }
4875
4876                 /**
4877                 * Output Catalog.
4878                 * @access protected
4879                 */
4880                 function _putcatalog() {
4881                         $this->_out('/Type /Catalog');
4882                         $this->_out('/Pages 1 0 R');
4883
4884                         if ($this->ZoomMode == 'fullpage') {
4885                                 $this->_out('/OpenAction [3 0 R /Fit]');
4886                         } elseif ($this->ZoomMode == 'fullwidth') {
4887                                 $this->_out('/OpenAction [3 0 R /FitH null]');
4888                         } elseif ($this->ZoomMode == 'real') {
4889                                 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
4890                         } elseif (!is_string($this->ZoomMode)) {
4891                                 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
4892                         }
4893                         if (isset($this->LayoutMode) AND (!empty($this->LayoutMode))) {
4894                                 $this->_out('/PageLayout /'.$this->LayoutMode.'');
4895                         }
4896                         if (isset($this->PageMode) AND (!empty($this->PageMode))) {
4897                                 $this->_out('/PageMode /'.$this->PageMode);
4898                         }
4899                         if (isset($this->l['a_meta_language'])) {
4900                                 $this->_out('/Lang /'.$this->l['a_meta_language']);
4901                         }
4902                         if (!empty($this->javascript)) {
4903                                 $this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
4904                         }
4905                         if (count($this->outlines) > 0) {
4906                                 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
4907                                 $this->_out('/PageMode /UseOutlines');
4908                         }
4909                         $this->_putviewerpreferences();
4910                         $p = $this->n_ocg_print.' 0 R';
4911                         $v = $this->n_ocg_view.' 0 R';
4912                         $as = "<</Event /Print /OCGs [".$p." ".$v."] /Category [/Print]>> <</Event /View /OCGs [".$p." ".$v."] /Category [/View]>>";
4913                         $this->_out("/OCProperties <</OCGs [".$p." ".$v."] /D <</ON [".$p."] /OFF [".$v."] /AS [".$as."]>>>>");
4914                         $this->_putuserrights();
4915                 }
4916
4917                 /**
4918                 * Output viewer preferences.
4919                 * @author Nicola asuni
4920                 * @since 3.1.000 (2008-06-09)
4921                 * @access protected
4922                 */
4923                 function _putviewerpreferences() {
4924                         $this->_out('/ViewerPreferences<<');
4925                         if ($this->rtl) {
4926                                 $this->_out('/Direction /R2L');
4927                         } else {
4928                                 $this->_out('/Direction /L2R');
4929                         }
4930                         if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
4931                                 $this->_out('/HideToolbar true');
4932                         }
4933                         if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
4934                                 $this->_out('/HideMenubar true');
4935                         }
4936                         if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
4937                                 $this->_out('/HideWindowUI true');
4938                         }
4939                         if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
4940                                 $this->_out('/FitWindow true');
4941                         }
4942                         if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
4943                                 $this->_out('/CenterWindow true');
4944                         }
4945                         if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
4946                                 $this->_out('/DisplayDocTitle true');
4947                         }
4948                         if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
4949                                 $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
4950                         }
4951                         if (isset($this->viewer_preferences['ViewArea'])) {
4952                                 $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
4953                         }
4954                         if (isset($this->viewer_preferences['ViewClip'])) {
4955                                 $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
4956                         }
4957                         if (isset($this->viewer_preferences['PrintArea'])) {
4958                                 $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
4959                         }
4960                         if (isset($this->viewer_preferences['PrintClip'])) {
4961                                 $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
4962                         }
4963                         if (isset($this->viewer_preferences['PrintScaling'])) {
4964                                 $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
4965                         }
4966                         if (isset($this->viewer_preferences['Duplex']) AND (!empty($this->viewer_preferences['Duplex']))) {
4967                                 $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
4968                         }
4969                         if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
4970                                 if ($this->viewer_preferences['PickTrayByPDFSize']) {
4971                                         $this->_out('/PickTrayByPDFSize true');
4972                                 } else {
4973                                         $this->_out('/PickTrayByPDFSize false');
4974                                 }
4975                         }
4976                         if (isset($this->viewer_preferences['PrintPageRange'])) {
4977                                 $PrintPageRangeNum = "";
4978                                 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
4979                                         $PrintPageRangeNum .= " ".($v-1)."";
4980                                 }
4981                                 $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
4982                         }
4983                         if (isset($this->viewer_preferences['NumCopies'])) {
4984                                 $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
4985                         }
4986                         $this->_out('>>');
4987                 }
4988
4989                 /**
4990                 * Output trailer.
4991                 * @access protected
4992                 */
4993                 function _puttrailer() {
4994                         $this->_out('/Size '.($this->n + 1));
4995                         $this->_out('/Root '.$this->n.' 0 R');
4996                         $this->_out('/Info '.($this->n - 1).' 0 R');
4997                         if ($this->encrypted) {
4998                                 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
4999                                 $this->_out('/ID [()()]');
5000                         }
5001                 }
5002
5003                 /**
5004                 * Output PDF header.
5005                 * @access protected
5006                 */
5007                 function _putheader() {
5008                         $this->_out('%PDF-'.$this->PDFVersion);
5009                 }
5010
5011                 /**
5012                 * Output end of document (EOF).
5013                 * @access protected
5014                 */
5015                 function _enddoc() {
5016                         $this->_putheader();
5017                         $this->_putpages();
5018                         $this->_putresources();
5019                         //Info
5020                         $this->_newobj();
5021                         $this->_out('<<');
5022                         $this->_putinfo();
5023                         $this->_out('>>');
5024                         $this->_out('endobj');
5025                         //Catalog
5026                         $this->_newobj();
5027                         $this->_out('<<');
5028                         $this->_putcatalog();
5029                         $this->_out('>>');
5030                         $this->_out('endobj');
5031                         //Cross-ref
5032                         $o = strlen($this->buffer);
5033                         $this->_out('xref');
5034                         $this->_out('0 '.($this->n + 1));
5035                         $this->_out('0000000000 65535 f ');
5036                         for($i=1; $i <= $this->n; $i++) {
5037                                 $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i]));
5038                         }
5039                         //Trailer
5040                         $this->_out('trailer');
5041                         $this->_out('<<');
5042                         $this->_puttrailer();
5043                         $this->_out('>>');
5044                         $this->_out('startxref');
5045                         $this->_out($o);
5046                         $this->_out('%%EOF');
5047                         $this->state = 3;
5048                 }
5049
5050                 /**
5051                 * Initialize a new page.
5052                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
5053                 * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
5054                 * @access protected
5055                 */
5056                 function _beginpage($orientation='', $format='') {
5057                         $this->page++;
5058                         $this->pages[$this->page] = ""; // this mark should be removed before output
5059                         $this->state = 2;
5060                         if (empty($orientation)) {
5061                                 if (isset($this->CurOrientation)) {
5062                                         $orientation = $this->CurOrientation;
5063                                 } else {
5064                                         $orientation = 'P';
5065                                 }
5066                         }
5067                         if (!empty($format)) {
5068                                 $this->setPageFormat($format, $orientation);
5069                         } else {
5070                                 $this->setPageOrientation($orientation);
5071                         }
5072                         if ($this->rtl) {
5073                                 $this->x = $this->w - $this->rMargin;
5074                         } else {
5075                                 $this->x = $this->lMargin;
5076                         }
5077                         $this->y = $this->tMargin;
5078                         if ($this->newpagegroup){
5079                                 // start a new group
5080                                 $n = sizeof($this->pagegroups) + 1;
5081                                 $alias = "{nb".$n."}";
5082                                 $this->pagegroups[$alias] = 1;
5083                                 $this->currpagegroup = $alias;
5084                                 $this->newpagegroup = false;
5085                         } elseif ($this->currpagegroup) {
5086                                 $this->pagegroups[$this->currpagegroup]++;
5087                         }
5088                 }
5089
5090                 /**
5091                 * Mark end of page.
5092                 * @access protected
5093                 */
5094                 function _endpage() {
5095                         $this->setVisibility("all");
5096                         $this->state = 1;
5097                 }
5098
5099                 /**
5100                 * Begin a new object.
5101                 * @access protected
5102                 */
5103                 function _newobj() {
5104                         $this->n++;
5105                         $this->offsets[$this->n] = strlen($this->buffer);
5106                         $this->_out($this->n.' 0 obj');
5107                 }
5108
5109                 /**
5110                 * Underline text.
5111                 * @param int $x X coordinate
5112                 * @param int $y Y coordinate
5113                 * @param string $txt text to underline
5114                 * @access protected
5115                 */
5116                 function _dounderline($x, $y, $txt) {
5117                         $up = $this->CurrentFont['up'];
5118                         $ut = $this->CurrentFont['ut'];
5119                         $w = $this->GetStringWidth($txt);
5120                         return sprintf('%.2f %.2f %.2f %.2f re f', $x * $this->k, ($this->h - ($y - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
5121                 }
5122
5123                 /**
5124                 * Line through text.
5125                 * @param int $x X coordinate
5126                 * @param int $y Y coordinate
5127                 * @param string $txt text to underline
5128                 * @access protected
5129                 */
5130                 function _dolinethrough($x, $y, $txt) {
5131                         $up = $this->CurrentFont['up'];
5132                         $ut = $this->CurrentFont['ut'];
5133                         $w = $this->GetStringWidth($txt);
5134                         return sprintf('%.2f %.2f %.2f %.2f re f', $x * $this->k, ($this->h - ($y - ($this->FontSize/2) - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt);
5135                 }
5136
5137                 /**
5138                 * Read a 4-byte integer from file.
5139                 * @param string $f file name.
5140                 * @return 4-byte integer
5141                 * @access protected
5142                 */
5143                 function _freadint($f) {
5144                         $a = unpack('Ni', fread($f,4));
5145                         return $a['i'];
5146                 }
5147
5148                 /**
5149                 * Format a text string for meta information
5150                 * @param string $s string to escape.
5151                 * @return string escaped string.
5152                 * @access protected
5153                 */
5154                 function _textstring($s) {
5155                         if ($this->isunicode) {
5156                                 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5157                                         $s = $this->UTF8ToLatin1($s);
5158                                 } else {
5159                                         //Convert string to UTF-16BE
5160                                         $s = $this->UTF8ToUTF16BE($s, true);
5161                                 }
5162                         }
5163                         if ($this->encrypted) {
5164                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
5165                         }
5166                         return '('. $this->_escape($s).')';
5167                 }
5168
5169                 /**
5170                 * Format an URI string
5171                 * @param string $s string to escape.
5172                 * @return string escaped string.
5173                 * @access protected
5174                 */
5175                 function _uristring($s) {
5176                         if ($this->encrypted) {
5177                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
5178                         }
5179                         return '('.$this->_escape($s).')';
5180                 }
5181
5182                 /**
5183                 * Format a text string
5184                 * @param string $s string to escape.
5185                 * @return string escaped string.
5186                 * @access protected
5187                 */
5188                 function _escapetext($s) {
5189                         if ($this->isunicode) {
5190                                 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5191                                         $s = $this->UTF8ToLatin1($s);
5192                                 } else {
5193                                         //Convert string to UTF-16BE and reverse RTL language
5194                                         $s = $this->utf8StrRev($s, false, $this->tmprtl);
5195                                 }
5196                         }
5197                         return $this->_escape($s);
5198                 }
5199
5200                 /**
5201                 * Add "\" before "\", "(" and ")"
5202                 * @param string $s string to escape.
5203                 * @return string escaped string.
5204                 * @access protected
5205                 */
5206                 function _escape($s) {
5207                         // the chr(13) substitution fixes the Bugs item #1421290.
5208                         return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
5209                 }
5210
5211                 /**
5212                 * Output a stream.
5213                 * @param string $s string to output.
5214                 * @access protected
5215                 */
5216                 function _putstream($s) {
5217                         if ($this->encrypted) {
5218                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
5219                         }
5220                         $this->_out('stream');
5221                         $this->_out($s);
5222                         $this->_out('endstream');
5223                 }
5224
5225                 /**
5226                 * Output a string to the document.
5227                 * @param string $s string to output.
5228                 * @access protected
5229                 */
5230                 function _out($s) {
5231                         if ($this->state == 2) {
5232                                 if (isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
5233                                         // puts data before page footer
5234                                         $page = substr($this->pages[$this->page], 0, -$this->footerlen[$this->page]);
5235                                         $footer = substr($this->pages[$this->page], -$this->footerlen[$this->page]);
5236                                         $this->pages[$this->page] = $page." ".$s."\n".$footer;
5237                                 } else {
5238                                         $this->pages[$this->page] .= $s."\n";
5239                                 }
5240                         } else {
5241                                 $this->buffer .= $s."\n";
5242                         }
5243                 }
5244
5245                 /**
5246                 * Adds unicode fonts.<br>
5247                 * Based on PDF Reference 1.3 (section 5)
5248                 * @access protected
5249                 * @author Nicola Asuni
5250                 * @since 1.52.0.TC005 (2005-01-05)
5251                 */
5252                 function _puttruetypeunicode($font) {
5253                         // Type0 Font
5254                         // A composite font composed of other fonts, organized hierarchically
5255                         $this->_newobj();
5256                         $this->_out('<</Type /Font');
5257                         $this->_out('/Subtype /Type0');
5258                         $this->_out('/BaseFont /'.$font['name'].'');
5259                         $this->_out('/Encoding /Identity-H'); //The horizontal identity mapping for 2-byte CIDs; may be used with CIDFonts using any Registry, Ordering, and Supplement values.
5260                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
5261                         $this->_out('/ToUnicode '.($this->n + 2).' 0 R');
5262                         $this->_out('>>');
5263                         $this->_out('endobj');
5264                         // CIDFontType2
5265                         // A CIDFont whose glyph descriptions are based on TrueType font technology
5266                         $this->_newobj();
5267                         $this->_out('<</Type /Font');
5268                         $this->_out('/Subtype /CIDFontType2');
5269                         $this->_out('/BaseFont /'.$font['name'].'');
5270                         $this->_out('/CIDSystemInfo '.($this->n + 2).' 0 R');
5271                         $this->_out('/FontDescriptor '.($this->n + 3).' 0 R');
5272                         if (isset($font['desc']['MissingWidth'])){
5273                                 $this->_out('/DW '.$font['desc']['MissingWidth'].''); // The default width for glyphs in the CIDFont MissingWidth
5274                         }
5275                         $w = "";
5276                         foreach ($font['cw'] as $cid => $width) {
5277                                 $w .= ''.$cid.' ['.$width.'] '; // define a specific width for each individual CID
5278                         }
5279                         $this->_out('/W ['.$w.']'); // A description of the widths for the glyphs in the CIDFont
5280                         $this->_out('/CIDToGIDMap '.($this->n + 4).' 0 R');
5281                         $this->_out('>>');
5282                         $this->_out('endobj');
5283                         // ToUnicode
5284                         // is a stream object that contains the definition of the CMap
5285                         // (PDF Reference 1.3 chap. 5.9)
5286                         $this->_newobj();
5287                         $this->_out('<</Length 345>>');
5288                         $this->_out('stream');
5289                         $this->_out('/CIDInit /ProcSet findresource begin');
5290                         $this->_out('12 dict begin');
5291                         $this->_out('begincmap');
5292                         $this->_out('/CIDSystemInfo');
5293                         $this->_out('<</Registry (Adobe)');
5294                         $this->_out('/Ordering (UCS)');
5295                         $this->_out('/Supplement 0');
5296                         $this->_out('>> def');
5297                         $this->_out('/CMapName /Adobe-Identity-UCS def');
5298                         $this->_out('/CMapType 2 def');
5299                         $this->_out('1 begincodespacerange');
5300                         $this->_out('<0000> <FFFF>');
5301                         $this->_out('endcodespacerange');
5302                         $this->_out('1 beginbfrange');
5303                         $this->_out('<0000> <FFFF> <0000>');
5304                         $this->_out('endbfrange');
5305                         $this->_out('endcmap');
5306                         $this->_out('CMapName currentdict /CMap defineresource pop');
5307                         $this->_out('end');
5308                         $this->_out('end');
5309                         $this->_out('endstream');
5310                         $this->_out('endobj');
5311                         // CIDSystemInfo dictionary
5312                         // A dictionary containing entries that define the character collection of the CIDFont.
5313                         $this->_newobj();
5314                         $this->_out('<</Registry (Adobe)'); // A string identifying an issuer of character collections
5315                         $this->_out('/Ordering (UCS)'); // A string that uniquely names a character collection issued by a specific registry
5316                         $this->_out('/Supplement 0'); // The supplement number of the character collection.
5317                         $this->_out('>>');
5318                         $this->_out('endobj');
5319                         // Font descriptor
5320                         // A font descriptor describing the CIDFont default metrics other than its glyph widths
5321                         $this->_newobj();
5322                         $this->_out('<</Type /FontDescriptor');
5323                         $this->_out('/FontName /'.$font['name']);
5324                         foreach ($font['desc'] as $key => $value) {
5325                                 $this->_out('/'.$key.' '.$value);
5326                         }
5327                         if ($font['file']) {
5328                                 // A stream containing a TrueType font program
5329                                 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
5330                         }
5331                         $this->_out('>>');
5332                         $this->_out('endobj');
5333                         // Embed CIDToGIDMap
5334                         // A specification of the mapping from CIDs to glyph indices
5335                         $this->_newobj();
5336                         $ctgfile = $this->_getfontpath().strtolower($font['ctg']);
5337                         if (!file_exists($ctgfile)) {
5338                                 $this->Error('Font file not found: '.$ctgfile);
5339                         }
5340                         $size = filesize($ctgfile);
5341                         $this->_out('<</Length '.$size.'');
5342                         if (substr($ctgfile, -2) == '.z') { // check file extension
5343                                 /* Decompresses data encoded using the public-domain
5344                                 zlib/deflate compression method, reproducing the
5345                                 original text or binary data */
5346                                 $this->_out('/Filter /FlateDecode');
5347                         }
5348                         $this->_out('>>');
5349                         $this->_putstream(file_get_contents($ctgfile));
5350                         $this->_out('endobj');
5351                 }
5352
5353                  /**
5354                  * Converts UTF-8 strings to codepoints array.<br>
5355                  * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
5356                  * Based on: http://www.faqs.org/rfcs/rfc3629.html
5357                  * <pre>
5358                  *        Char. number range  |        UTF-8 octet sequence
5359                  *       (hexadecimal)    |              (binary)
5360                  *    --------------------+-----------------------------------------------
5361                  *    0000 0000-0000 007F | 0xxxxxxx
5362                  *    0000 0080-0000 07FF | 110xxxxx 10xxxxxx
5363                  *    0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
5364                  *    0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
5365                  *    ---------------------------------------------------------------------
5366                  *
5367                  *   ABFN notation:
5368                  *   ---------------------------------------------------------------------
5369                  *   UTF8-octets = *( UTF8-char )
5370                  *   UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
5371                  *   UTF8-1      = %x00-7F
5372                  *   UTF8-2      = %xC2-DF UTF8-tail
5373                  *
5374                  *   UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
5375                  *                 %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
5376                  *   UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
5377                  *                 %xF4 %x80-8F 2( UTF8-tail )
5378                  *   UTF8-tail   = %x80-BF
5379                  *   ---------------------------------------------------------------------
5380                  * </pre>
5381                  * @param string $str string to process.
5382                  * @return array containing codepoints (UTF-8 characters values)
5383                  * @access protected
5384                  * @author Nicola Asuni
5385                  * @since 1.53.0.TC005 (2005-01-05)
5386                  */
5387                 function UTF8StringToArray($str) {
5388                         if (!$this->isunicode) {
5389                                 // split string into array of equivalent codes
5390                                 $strarr = array();
5391                                 $strlen = strlen($str);
5392                                 for($i=0; $i < $strlen; $i++) {
5393                                         $strarr[] = ord($str{$i});
5394                                 }
5395                                 return $strarr;
5396                         }
5397                         $unicode = array(); // array containing unicode values
5398                         $bytes  = array(); // array containing single character byte sequences
5399                         $numbytes  = 1; // number of octetc needed to represent the UTF-8 character
5400                         $str .= ""; // force $str to be a string
5401                         $length = strlen($str);
5402                         for($i = 0; $i < $length; $i++) {
5403                                 $char = ord($str{$i}); // get one string character at time
5404                                 if (count($bytes) == 0) { // get starting octect
5405                                         if ($char <= 0x7F) {
5406                                                 $unicode[] = $char; // use the character "as is" because is ASCII
5407                                                 $numbytes = 1;
5408                                         } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
5409                                                 $bytes[] = ($char - 0xC0) << 0x06;
5410                                                 $numbytes = 2;
5411                                         } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
5412                                                 $bytes[] = ($char - 0xE0) << 0x0C;
5413                                                 $numbytes = 3;
5414                                         } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
5415                                                 $bytes[] = ($char - 0xF0) << 0x12;
5416                                                 $numbytes = 4;
5417                                         } else {
5418                                                 // use replacement character for other invalid sequences
5419                                                 $unicode[] = 0xFFFD;
5420                                                 $bytes = array();
5421                                                 $numbytes = 1;
5422                                         }
5423                                 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
5424                                         $bytes[] = $char - 0x80;
5425                                         if (count($bytes) == $numbytes) {
5426                                                 // compose UTF-8 bytes to a single unicode value
5427                                                 $char = $bytes[0];
5428                                                 for($j = 1; $j < $numbytes; $j++) {
5429                                                         $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
5430                                                 }
5431                                                 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
5432                                                         /* The definition of UTF-8 prohibits encoding character numbers between
5433                                                         U+D800 and U+DFFF, which are reserved for use with the UTF-16
5434                                                         encoding form (as surrogate pairs) and do not directly represent
5435                                                         characters. */
5436                                                         $unicode[] = 0xFFFD; // use replacement character
5437                                                 } else {
5438                                                         $unicode[] = $char; // add char to array
5439                                                 }
5440                                                 // reset data for next char
5441                                                 $bytes = array();
5442                                                 $numbytes = 1;
5443                                         }
5444                                 } else {
5445                                         // use replacement character for other invalid sequences
5446                                         $unicode[] = 0xFFFD;
5447                                         $bytes = array();
5448                                         $numbytes = 1;
5449                                 }
5450                         }
5451                         return $unicode;
5452                 }
5453
5454                 /**
5455                  * Converts UTF-8 strings to UTF16-BE.<br>
5456                  * @param string $str string to process.
5457                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5458                  * @return string
5459                  * @access protected
5460                  * @author Nicola Asuni
5461                  * @since 1.53.0.TC005 (2005-01-05)
5462                  * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
5463                  */
5464                 function UTF8ToUTF16BE($str, $setbom=true) {
5465                         if (!$this->isunicode) {
5466                                 return $str; // string is not in unicode
5467                         }
5468                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5469                         return $this->arrUTF8ToUTF16BE($unicode, $setbom);
5470                 }
5471
5472                 /**
5473                  * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
5474                  * @param string $str string to process.
5475                  * @return string
5476                  * @author Andrew Whitehead, Nicola Asuni
5477                  * @access protected
5478                  * @since 3.2.000 (2008-06-23)
5479                  */
5480                 function UTF8ToLatin1($str) {
5481                         if (!$this->isunicode) {
5482                                 return $str; // string is not in unicode
5483                         }
5484                         $outstr = ""; // string to be returned
5485                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5486                         foreach ($unicode as $char) {
5487                                 if ($char == 0xFFFD) {
5488                                         // skip
5489                                 } elseif ($char == 0x2022) {
5490                                         // fix for middot
5491                                         $outstr .= chr(183);
5492                                 } elseif ($char < 256) {
5493                                         $outstr .= chr($char);
5494                                 } else {
5495                                         $outstr .= '?';
5496                                 }
5497                         }
5498                         return $outstr;
5499                 }
5500
5501                 /**
5502                  * Converts array of UTF-8 characters to UTF16-BE string.<br>
5503                  * Based on: http://www.faqs.org/rfcs/rfc2781.html
5504                  * <pre>
5505                  *   Encoding UTF-16:
5506                  *
5507                  *   Encoding of a single character from an ISO 10646 character value to
5508                  *    UTF-16 proceeds as follows. Let U be the character number, no greater
5509                  *    than 0x10FFFF.
5510                  *
5511                  *    1) If U < 0x10000, encode U as a 16-bit unsigned integer and
5512                  *       terminate.
5513                  *
5514                  *    2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
5515                  *       U' must be less than or equal to 0xFFFFF. That is, U' can be
5516                  *       represented in 20 bits.
5517                  *
5518                  *    3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
5519                  *       0xDC00, respectively. These integers each have 10 bits free to
5520                  *       encode the character value, for a total of 20 bits.
5521                  *
5522                  *    4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
5523                  *       bits of W1 and the 10 low-order bits of U' to the 10 low-order
5524                  *       bits of W2. Terminate.
5525                  *
5526                  *    Graphically, steps 2 through 4 look like:
5527                  *    U' = yyyyyyyyyyxxxxxxxxxx
5528                  *    W1 = 110110yyyyyyyyyy
5529                  *    W2 = 110111xxxxxxxxxx
5530                  * </pre>
5531                  * @param array $unicode array containing UTF-8 unicode values
5532                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5533                  * @return string
5534                  * @access protected
5535                  * @author Nicola Asuni
5536                  * @since 2.1.000 (2008-01-08)
5537                  * @see UTF8ToUTF16BE()
5538                  */
5539                 function arrUTF8ToUTF16BE($unicode, $setbom=true) {
5540                         $outstr = ""; // string to be returned
5541                         if ($setbom) {
5542                                 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
5543                         }
5544                         foreach($unicode as $char) {
5545                                 if ($char == 0xFFFD) {
5546                                         $outstr .= "\xFF\xFD"; // replacement character
5547                                 } elseif ($char < 0x10000) {
5548                                         $outstr .= chr($char >> 0x08);
5549                                         $outstr .= chr($char & 0xFF);
5550                                 } else {
5551                                         $char -= 0x10000;
5552                                         $w1 = 0xD800 | ($char >> 0x10);
5553                                         $w2 = 0xDC00 | ($char & 0x3FF);
5554                                         $outstr .= chr($w1 >> 0x08);
5555                                         $outstr .= chr($w1 & 0xFF);
5556                                         $outstr .= chr($w2 >> 0x08);
5557                                         $outstr .= chr($w2 & 0xFF);
5558                                 }
5559                         }
5560                         return $outstr;
5561                 }
5562                 // ====================================================
5563
5564                 /**
5565                  * Set header font.
5566                  * @param array $font font
5567                  * @since 1.1
5568                  */
5569                 function setHeaderFont($font) {
5570                         $this->header_font = $font;
5571                 }
5572
5573                 /**
5574                  * Get header font.
5575                  * @return array()
5576                  * @since 4.0.012 (2008-07-24)
5577                  */
5578                 function getHeaderFont() {
5579                         return $this->header_font;
5580                 }
5581
5582                 /**
5583                  * Set footer font.
5584                  * @param array $font font
5585                  * @since 1.1
5586                  */
5587                 function setFooterFont($font) {
5588                         $this->footer_font = $font;
5589                 }
5590
5591                 /**
5592                  * Get Footer font.
5593                  * @return array()
5594                  * @since 4.0.012 (2008-07-24)
5595                  */
5596                 function getFooterFont() {
5597                         return $this->footer_font;
5598                 }
5599
5600                 /**
5601                  * Set language array.
5602                  * @param array $language
5603                  * @since 1.1
5604                  */
5605                 function setLanguageArray($language) {
5606                         $this->l = $language;
5607                         $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
5608                 }
5609
5610                 /**
5611                  * Returns the PDF data.
5612                  */
5613                 function getPDFData() {
5614                         if ($this->state < 3) {
5615                                 $this->Close();
5616                         }
5617                         return $this->buffer;
5618                 }
5619
5620                 /**
5621                  * Sets font style.
5622                  * @param string $tag tag name in lowercase. Supported tags are:<ul>
5623                  * <li>b : bold text</li>
5624                  * <li>i : italic</li>
5625                  * <li>u : underlined</li>
5626                  * <li>d : line-through</li></ul>
5627                  * @param boolean $enable
5628                  * @access protected
5629                  */
5630                 function setStyle($tag, $enable) {
5631                         $this->$tag += ($enable ? 1 : -1);
5632                         $style = '';
5633                         foreach(array('b', 'i', 'u', 'd') as $s) {
5634                                 if ($this->$s > 0) {
5635                                         $style .= $s;
5636                                 }
5637                         }
5638                         $this->SetFont('', $style);
5639                 }
5640
5641                 /**
5642                  * Output anchor link.
5643                  * @param string $url link URL
5644                  * @param string $name link name
5645                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
5646                  * @param boolean $firstline if true prints only the first line and return the remaining string.
5647                  * @return the number of cells used or the remaining text if $firstline = true;
5648                  * @access public
5649                  */
5650                 function addHtmlLink($url, $name, $fill=0, $firstline=false) {
5651                         $prevcolor = $this->fgcolor;
5652                         $this->SetTextColor(0, 0, 255);
5653                         $this->setStyle('u', true);
5654                         $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
5655                         $this->setStyle('u', false);
5656                         $this->SetTextColorArray($prevcolor);
5657                         return $ret;
5658                 }
5659
5660                 /**
5661                  * Returns an associative array (keys: R,G,B) from an html color name or a six-digit or three-digit hexadecimal color representation (i.e. #3FE5AA or #7FF).
5662                  * @param string $color html color
5663                  * @return array
5664                  * @access protected
5665                  */
5666                 function convertHTMLColorToDec($color="#000000") {
5667                         global $webcolor;
5668                         $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
5669                         // set default color to be returned in case of error
5670                         $returncolor = array ('R' => 0, 'G' => 0, 'B' => 0);
5671                         if (empty($color)) {
5672                                 return $returncolor;
5673                         }
5674                         if (substr(strtolower($color), 0, 3) == 'rgb') {
5675                                 $codes = substr($color, 4);
5676                                 $codes = str_replace(')', '', $codes);
5677                                 $returncolor = explode(',', $codes, 3);
5678                                 return $returncolor;    
5679                         }
5680                         if (substr($color, 0, 1) != "#") {
5681                                 // decode color name
5682                                 if (isset($webcolor[strtolower($color)])) {
5683                                         $color_code = $webcolor[strtolower($color)];
5684                                 } else {
5685                                         return $returncolor;
5686                                 }
5687                         } else {
5688                                 $color_code = substr($color, 1);
5689                         }
5690                         switch (strlen($color_code)) {
5691                                 case 3: {
5692                                         // three-digit hexadecimal representation
5693                                         $r = substr($color_code, 0, 1);
5694                                         $g = substr($color_code, 1, 1);
5695                                         $b = substr($color_code, 2, 1);
5696                                         $returncolor['R'] = hexdec($r.$r);
5697                                         $returncolor['G'] = hexdec($g.$g);
5698                                         $returncolor['B'] = hexdec($b.$b);
5699                                         break;
5700                                 }
5701                                 case 6: {
5702                                         // six-digit hexadecimal representation
5703                                         $returncolor['R'] = hexdec(substr($color_code, 0, 2));
5704                                         $returncolor['G'] = hexdec(substr($color_code, 2, 2));
5705                                         $returncolor['B'] = hexdec(substr($color_code, 4, 2));
5706                                         break;
5707                                 }
5708                         }
5709                         return $returncolor;
5710                 }
5711
5712                 /**
5713                  * Converts pixels to Units.
5714                  * @param int $px pixels
5715                  * @return float millimeters
5716                  * @access public
5717                  */
5718                 function pixelsToUnits($px){
5719                         return $px / $this->k;
5720                 }
5721
5722                 /**
5723                  * Reverse function for htmlentities.
5724                  * Convert entities in UTF-8.
5725                  * @param $text_to_convert Text to convert.
5726                  * @return string converted
5727                  */
5728                 function unhtmlentities($text_to_convert) {
5729                         if (!$this->isunicode) {
5730                                 return html_entity_decode($text_to_convert);
5731                         }
5732                         return html_entity_decode_php4($text_to_convert);
5733                 }
5734
5735                 // ENCRYPTION METHODS ----------------------------------
5736                 // SINCE 2.0.000 (2008-01-02)
5737                 /**
5738                 * Compute encryption key depending on object number where the encrypted data is stored
5739                 * @param int $n object number
5740                 * @since 2.0.000 (2008-01-02)
5741                 */
5742                 function _objectkey($n) {
5743                         return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);
5744                 }
5745
5746                 /**
5747                  * Put encryption on PDF document.
5748                  * @since 2.0.000 (2008-01-02)
5749                  */
5750                 function _putencryption() {
5751                         $this->_out('/Filter /Standard');
5752                         $this->_out('/V 1');
5753                         $this->_out('/R 2');
5754                         $this->_out('/O ('.$this->_escape($this->Ovalue).')');
5755                         $this->_out('/U ('.$this->_escape($this->Uvalue).')');
5756                         $this->_out('/P '.$this->Pvalue);
5757                 }
5758
5759                 /**
5760                 * Returns the input text exrypted using RC4 algorithm and the specified key.
5761                 * RC4 is the standard encryption algorithm used in PDF format
5762                 * @param string $key encryption key
5763                 * @param String $text input text to be encrypted
5764                 * @return String encrypted text
5765                 * @since 2.0.000 (2008-01-02)
5766                 * @author Klemen Vodopivec
5767                 */
5768                 function _RC4($key, $text) {
5769                         if ($this->last_rc4_key != $key) {
5770                                 $k = str_repeat($key, 256/strlen($key)+1);
5771                                 $rc4 = range(0,255);
5772                                 $j = 0;
5773                                 for ($i=0; $i < 256; $i++) {
5774                                         $t = $rc4[$i];
5775                                         $j = ($j + $t + ord($k{$i})) % 256;
5776                                         $rc4[$i] = $rc4[$j];
5777                                         $rc4[$j] = $t;
5778                                 }
5779                                 $this->last_rc4_key = $key;
5780                                 $this->last_rc4_key_c = $rc4;
5781                         } else {
5782                                 $rc4 = $this->last_rc4_key_c;
5783                         }
5784                         $len = strlen($text);
5785                         $a = 0;
5786                         $b = 0;
5787                         $out = '';
5788                         for ($i=0; $i < $len; $i++) {
5789                                 $a = ($a + 1) % 256;
5790                                 $t = $rc4[$a];
5791                                 $b = ($b + $t) % 256;
5792                                 $rc4[$a] = $rc4[$b];
5793                                 $rc4[$b] = $t;
5794                                 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
5795                                 $out .= chr(ord($text{$i}) ^ $k);
5796                         }
5797                         return $out;
5798                 }
5799
5800                 /**
5801                 * Encrypts a string using MD5 and returns it's value as a binary string.
5802                 * @param string $str input string
5803                 * @return String MD5 encrypted binary string
5804                 * @since 2.0.000 (2008-01-02)
5805                 * @author Klemen Vodopivec
5806                 */
5807                 function _md5_16($str) {
5808                         return pack('H*',md5($str));
5809                 }
5810
5811                 /**
5812                 * Compute O value (used for RC4 encryption)
5813                 * @param String $user_pass user password
5814                 * @param String $owner_pass user password
5815                 * @return String O value
5816                 * @since 2.0.000 (2008-01-02)
5817                 * @author Klemen Vodopivec
5818                 */
5819                 function _Ovalue($user_pass, $owner_pass) {
5820                         $tmp = $this->_md5_16($owner_pass);
5821                         $owner_RC4_key = substr($tmp,0,5);
5822                         return $this->_RC4($owner_RC4_key, $user_pass);
5823                 }
5824
5825                 /**
5826                 * Compute U value (used for RC4 encryption)
5827                 * @return String U value
5828                 * @since 2.0.000 (2008-01-02)
5829                 * @author Klemen Vodopivec
5830                 */
5831                 function _Uvalue() {
5832                         return $this->_RC4($this->encryption_key, $this->padding);
5833                 }
5834
5835                 /**
5836                 * Compute encryption key
5837                 * @param String $user_pass user password
5838                 * @param String $owner_pass user password
5839                 * @param String $protection protection type
5840                 * @since 2.0.000 (2008-01-02)
5841                 * @author Klemen Vodopivec
5842                 */
5843                 function _generateencryptionkey($user_pass, $owner_pass, $protection) {
5844                         // Pad passwords
5845                         $user_pass = substr($user_pass.$this->padding,0,32);
5846                         $owner_pass = substr($owner_pass.$this->padding,0,32);
5847                         // Compute O value
5848                         $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
5849                         // Compute encyption key
5850                         $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
5851                         $this->encryption_key = substr($tmp,0,5);
5852                         // Compute U value
5853                         $this->Uvalue = $this->_Uvalue();
5854                         // Compute P value
5855                         $this->Pvalue = -(($protection^255)+1);
5856                 }
5857
5858                 /**
5859                 * Set document protection
5860                 * The permission array is composed of values taken from the following ones:
5861                 * - copy: copy text and images to the clipboard
5862                 * - print: print the document
5863                 * - modify: modify it (except for annotations and forms)
5864                 * - annot-forms: add annotations and forms
5865                 * Remark: the protection against modification is for people who have the full Acrobat product.
5866                 * If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access.
5867                 * Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts.
5868                 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
5869                 * @param String $user_pass user password. Empty by default.
5870                 * @param String $owner_pass owner password. If not specified, a random value is used.
5871                 * @since 2.0.000 (2008-01-02)
5872                 * @author Klemen Vodopivec
5873                 */
5874                 function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
5875                         $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
5876                         $protection = 192;
5877                         foreach($permissions as $permission) {
5878                                 if (!isset($options[$permission])) {
5879                                         $this->Error('Incorrect permission: '.$permission);
5880                                 }
5881                                 $protection += $options[$permission];
5882                         }
5883                         if ($owner_pass === null) {
5884                                 $owner_pass = uniqid(rand());
5885                         }
5886                         $this->encrypted = true;
5887                         $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
5888                 }
5889
5890                 // END OF ENCRYPTION FUNCTIONS -------------------------
5891
5892                 // START TRANSFORMATIONS SECTION -----------------------
5893                 // authors: Moritz Wagner, Andreas Wurmser, Nicola Asuni
5894
5895                 /**
5896                 * Starts a 2D tranformation saving current graphic state.
5897                 * This function must be called before scaling, mirroring, translation, rotation and skewing.
5898                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5899                 * @since 2.1.000 (2008-01-07)
5900                 * @see StartTransform(), StopTransform()
5901                 */
5902                 function StartTransform() {
5903                         $this->_out('q');
5904                 }
5905
5906                 /**
5907                 * Stops a 2D tranformation restoring previous graphic state.
5908                 * This function must be called after scaling, mirroring, translation, rotation and skewing.
5909                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5910                 * @since 2.1.000 (2008-01-07)
5911                 * @see StartTransform(), StopTransform()
5912                 */
5913                 function StopTransform() {
5914                         $this->_out('Q');
5915                 }
5916                 /**
5917                 * Horizontal Scaling.
5918                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5919                 * @param int $x abscissa of the scaling center. Default is current x position
5920                 * @param int $y ordinate of the scaling center. Default is current y position
5921                 * @since 2.1.000 (2008-01-07)
5922                 * @see StartTransform(), StopTransform()
5923                 */
5924                 function ScaleX($s_x, $x='', $y=''){
5925                         $this->Scale($s_x, 100, $x, $y);
5926                 }
5927
5928                 /**
5929                 * Vertical Scaling.
5930                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5931                 * @param int $x abscissa of the scaling center. Default is current x position
5932                 * @param int $y ordinate of the scaling center. Default is current y position
5933                 * @since 2.1.000 (2008-01-07)
5934                 * @see StartTransform(), StopTransform()
5935                 */
5936                 function ScaleY($s_y, $x='', $y=''){
5937                         $this->Scale(100, $s_y, $x, $y);
5938                 }
5939
5940                 /**
5941                 * Vertical and horizontal proportional Scaling.
5942                 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
5943                 * @param int $x abscissa of the scaling center. Default is current x position
5944                 * @param int $y ordinate of the scaling center. Default is current y position
5945                 * @since 2.1.000 (2008-01-07)
5946                 * @see StartTransform(), StopTransform()
5947                 */
5948                 function ScaleXY($s, $x='', $y=''){
5949                         $this->Scale($s, $s, $x, $y);
5950                 }
5951
5952                 /**
5953                 * Vertical and horizontal non-proportional Scaling.
5954                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5955                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5956                 * @param int $x abscissa of the scaling center. Default is current x position
5957                 * @param int $y ordinate of the scaling center. Default is current y position
5958                 * @since 2.1.000 (2008-01-07)
5959                 * @see StartTransform(), StopTransform()
5960                 */
5961                 function Scale($s_x, $s_y, $x='', $y=''){
5962                         if ($x === '') {
5963                                 $x=$this->x;
5964                         }
5965                         if ($y === '') {
5966                                 $y=$this->y;
5967                         }
5968                         if ($this->rtl) {
5969                                 $x = $this->w - $x;
5970                         }
5971                         if (($s_x == 0) OR ($s_y == 0)) {
5972                                 $this->Error('Please do not use values equal to zero for scaling');
5973                         }
5974                         $y = ($this->h - $y) * $this->k;
5975                         $x *= $this->k;
5976                         //calculate elements of transformation matrix
5977                         $s_x /= 100;
5978                         $s_y /= 100;
5979                         $tm[0] = $s_x;
5980                         $tm[1] = 0;
5981                         $tm[2] = 0;
5982                         $tm[3] = $s_y;
5983                         $tm[4] = $x * (1 - $s_x);
5984                         $tm[5] = $y * (1 - $s_y);
5985                         //scale the coordinate system
5986                         $this->Transform($tm);
5987                 }
5988
5989                 /**
5990                 * Horizontal Mirroring.
5991                 * @param int $x abscissa of the point. Default is current x position
5992                 * @since 2.1.000 (2008-01-07)
5993                 * @see StartTransform(), StopTransform()
5994                 */
5995                 function MirrorH($x=''){
5996                         $this->Scale(-100, 100, $x);
5997                 }
5998
5999                 /**
6000                 * Verical Mirroring.
6001                 * @param int $y ordinate of the point. Default is current y position
6002                 * @since 2.1.000 (2008-01-07)
6003                 * @see StartTransform(), StopTransform()
6004                 */
6005                 function MirrorV($y=''){
6006                         $this->Scale(100, -100, '', $y);
6007                 }
6008
6009                 /**
6010                 * Point reflection mirroring.
6011                 * @param int $x abscissa of the point. Default is current x position
6012                 * @param int $y ordinate of the point. Default is current y position
6013                 * @since 2.1.000 (2008-01-07)
6014                 * @see StartTransform(), StopTransform()
6015                 */
6016                 function MirrorP($x='',$y=''){
6017                         $this->Scale(-100, -100, $x, $y);
6018                 }
6019
6020                 /**
6021                 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
6022                 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
6023                 * @param int $x abscissa of the point. Default is current x position
6024                 * @param int $y ordinate of the point. Default is current y position
6025                 * @since 2.1.000 (2008-01-07)
6026                 * @see StartTransform(), StopTransform()
6027                 */
6028                 function MirrorL($angle=0, $x='',$y=''){
6029                         $this->Scale(-100, 100, $x, $y);
6030                         $this->Rotate(-2*($angle-90), $x, $y);
6031                 }
6032
6033                 /**
6034                 * Translate graphic object horizontally.
6035                 * @param int $t_x movement to the right (or left for RTL)
6036                 * @since 2.1.000 (2008-01-07)
6037                 * @see StartTransform(), StopTransform()
6038                 */
6039                 function TranslateX($t_x){
6040                         $this->Translate($t_x, 0);
6041                 }
6042
6043                 /**
6044                 * Translate graphic object vertically.
6045                 * @param int $t_y movement to the bottom
6046                 * @since 2.1.000 (2008-01-07)
6047                 * @see StartTransform(), StopTransform()
6048                 */
6049                 function TranslateY($t_y){
6050                         $this->Translate(0, $t_y);
6051                 }
6052
6053                 /**
6054                 * Translate graphic object horizontally and vertically.
6055                 * @param int $t_x movement to the right
6056                 * @param int $t_y movement to the bottom
6057                 * @since 2.1.000 (2008-01-07)
6058                 * @see StartTransform(), StopTransform()
6059                 */
6060                 function Translate($t_x, $t_y){
6061                         if ($this->rtl) {
6062                                 $t_x = -$t_x;
6063                         }
6064                         //calculate elements of transformation matrix
6065                         $tm[0] = 1;
6066                         $tm[1] = 0;
6067                         $tm[2] = 0;
6068                         $tm[3] = 1;
6069                         $tm[4] = $t_x * $this->k;
6070                         $tm[5] = -$t_y * $this->k;
6071                         //translate the coordinate system
6072                         $this->Transform($tm);
6073                 }
6074
6075                 /**
6076                 * Rotate object.
6077                 * @param float $angle angle in degrees for counter-clockwise rotation
6078                 * @param int $x abscissa of the rotation center. Default is current x position
6079                 * @param int $y ordinate of the rotation center. Default is current y position
6080                 * @since 2.1.000 (2008-01-07)
6081                 * @see StartTransform(), StopTransform()
6082                 */
6083                 function Rotate($angle, $x='', $y=''){
6084                         if ($x === '') {
6085                                 $x=$this->x;
6086                         }
6087                         if ($y === '') {
6088                                 $y=$this->y;
6089                         }
6090                         if ($this->rtl) {
6091                                 $x = $this->w - $x;
6092                                 $angle = -$angle;
6093                         }
6094                         $y = ($this->h - $y) * $this->k;
6095                         $x *= $this->k;
6096                         //calculate elements of transformation matrix
6097                         $tm[0] = cos(deg2rad($angle));
6098                         $tm[1] = sin(deg2rad($angle));
6099                         $tm[2] = -$tm[1];
6100                         $tm[3] = $tm[0];
6101                         $tm[4] = $x + $tm[1] * $y - $tm[0] * $x;
6102                         $tm[5] = $y - $tm[0] * $y - $tm[1] * $x;
6103                         //rotate the coordinate system around ($x,$y)
6104                         $this->Transform($tm);
6105                 }
6106
6107                 /**
6108                 * Skew horizontally.
6109                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6110                 * @param int $x abscissa of the skewing center. default is current x position
6111                 * @param int $y ordinate of the skewing center. default is current y position
6112                 * @since 2.1.000 (2008-01-07)
6113                 * @see StartTransform(), StopTransform()
6114                 */
6115                 function SkewX($angle_x, $x='', $y=''){
6116                         $this->Skew($angle_x, 0, $x, $y);
6117                 }
6118
6119                 /**
6120                 * Skew vertically.
6121                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6122                 * @param int $x abscissa of the skewing center. default is current x position
6123                 * @param int $y ordinate of the skewing center. default is current y position
6124                 * @since 2.1.000 (2008-01-07)
6125                 * @see StartTransform(), StopTransform()
6126                 */
6127                 function SkewY($angle_y, $x='', $y=''){
6128                         $this->Skew(0, $angle_y, $x, $y);
6129                 }
6130
6131                 /**
6132                 * Skew.
6133                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6134                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6135                 * @param int $x abscissa of the skewing center. default is current x position
6136                 * @param int $y ordinate of the skewing center. default is current y position
6137                 * @since 2.1.000 (2008-01-07)
6138                 * @see StartTransform(), StopTransform()
6139                 */
6140                 function Skew($angle_x, $angle_y, $x='', $y=''){
6141                         if ($x === '') {
6142                                 $x = $this->x;
6143                         }
6144                         if ($y === '') {
6145                                 $y = $this->y;
6146                         }
6147                         if ($this->rtl) {
6148                                 $x = $this->w - $x;
6149                                 $angle_x = -$angle_x;
6150                         }
6151                         if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
6152                                 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
6153                         }
6154                         $x *= $this->k;
6155                         $y = ($this->h - $y) * $this->k;
6156                         //calculate elements of transformation matrix
6157                         $tm[0] = 1;
6158                         $tm[1] = tan(deg2rad($angle_y));
6159                         $tm[2] = tan(deg2rad($angle_x));
6160                         $tm[3] = 1;
6161                         $tm[4] = -$tm[2] * $y;
6162                         $tm[5] = -$tm[1] * $x;
6163                         //skew the coordinate system
6164                         $this->Transform($tm);
6165                 }
6166
6167                 /**
6168                 * Apply graphic transformations.
6169                 * @since 2.1.000 (2008-01-07)
6170                 * @see StartTransform(), StopTransform()
6171                 */
6172                 function Transform($tm){
6173                         $this->_out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
6174                 }
6175
6176                 // END TRANSFORMATIONS SECTION -------------------------
6177
6178
6179                 // START GRAPHIC FUNCTIONS SECTION ---------------------
6180                 // The following section is based on the code provided by David Hernandez Sanz
6181
6182                 /**
6183                 * Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page.
6184                 * @param float $width The width.
6185                 * @since 1.0
6186                 * @see Line(), Rect(), Cell(), MultiCell()
6187                 */
6188                 function SetLineWidth($width) {
6189                         //Set line width
6190                         $this->LineWidth = $width;
6191                         $this->linestyleWidth = sprintf('%.2f w', ($width * $this->k));
6192                         $this->_out($this->linestyleWidth);
6193                 }
6194
6195                 /**
6196                 * Returns the current the line width.
6197                 * @return int Line width
6198                 * @since 2.1.000 (2008-01-07)
6199                 * @see Line(), SetLineWidth()
6200                 */
6201                 function GetLineWidth() {
6202                         return $this->LineWidth;
6203                 }
6204
6205                 /**
6206                 * Set line style.
6207                 * @param array $style Line style. Array with keys among the following:
6208                 * <ul>
6209                 *        <li>width (float): Width of the line in user units.</li>
6210                 *        <li>cap (string): Type of cap to put on the line. Possible values are:
6211                 * butt, round, square. The difference between "square" and "butt" is that
6212                 * "square" projects a flat end past the end of the line.</li>
6213                 *        <li>join (string): Type of join. Possible values are: miter, round,
6214                 * bevel.</li>
6215                 *        <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
6216                 * series of length values, which are the lengths of the on and off dashes.
6217                 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
6218                 * 1 off, 2 on, 1 off, ...</li>
6219                 *        <li>phase (integer): Modifier on the dash pattern which is used to shift
6220                 * the point at which the pattern starts.</li>
6221                 *        <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
6222                 * </ul>
6223                 * @access public
6224                 * @since 2.1.000 (2008-01-08)
6225                 */
6226                 function SetLineStyle($style) {
6227                         extract($style);
6228                         if (isset($width)) {
6229                                 $width_prev = $this->LineWidth;
6230                                 $this->SetLineWidth($width);
6231                                 $this->LineWidth = $width_prev;
6232                         }
6233                         if (isset($cap)) {
6234                                 $ca = array("butt" => 0, "round"=> 1, "square" => 2);
6235                                 if (isset($ca[$cap])) {
6236                                         $this->linestyleCap = $ca[$cap]." J";
6237                                         $this->_out($this->linestyleCap);
6238                                 }
6239                         }
6240                         if (isset($join)) {
6241                                 $ja = array("miter" => 0, "round" => 1, "bevel" => 2);
6242                                 if (isset($ja[$join])) {
6243                                         $this->linestyleJoin = $ja[$join]." j";
6244                                         $this->_out($this->linestyleJoin);
6245                                 }
6246                         }
6247                         if (isset($dash)) {
6248                                 $dash_string = "";
6249                                 if ($dash) {
6250                                         if (ereg("^.+,", $dash)) {
6251                                                 $tab = explode(",", $dash);
6252                                         } else {
6253                                                 $tab = array($dash);
6254                                         }
6255                                         $dash_string = "";
6256                                         foreach ($tab as $i => $v) {
6257                                                 if ($i) {
6258                                                         $dash_string .= " ";
6259                                                 }
6260                                                 $dash_string .= sprintf("%.2f", $v);
6261                                         }
6262                                 }
6263                                 if (!isset($phase) OR !$dash) {
6264                                         $phase = 0;
6265                                 }
6266                                 $this->linestyleDash = sprintf("[%s] %.2f d", $dash_string, $phase);
6267                                 $this->_out($this->linestyleDash);
6268                         }
6269                         if (isset($color)) {
6270                                 $this->SetDrawColorArray($color);
6271                         }
6272                 }
6273
6274                 /*
6275                 * Set a draw point.
6276                 * @param float $x Abscissa of point.
6277                 * @param float $y Ordinate of point.
6278                 * @access protected
6279                 * @since 2.1.000 (2008-01-08)
6280                 */
6281                 function _outPoint($x, $y) {
6282                         if ($this->rtl) {
6283                                 $x = $this->w - $x;
6284                         }
6285                         $this->_out(sprintf("%.2f %.2f m", $x * $this->k, ($this->h - $y) * $this->k));
6286                 }
6287
6288                 /*
6289                 * Draws a line from last draw point.
6290                 * @param float $x Abscissa of end point.
6291                 * @param float $y Ordinate of end point.
6292                 * @access protected
6293                 * @since 2.1.000 (2008-01-08)
6294                 */
6295                 function _outLine($x, $y) {
6296                         if ($this->rtl) {
6297                                 $x = $this->w - $x;
6298                         }
6299                         $this->_out(sprintf("%.2f %.2f l", $x * $this->k, ($this->h - $y) * $this->k));
6300                 }
6301
6302                 /**
6303                 * Draws a rectangle.
6304                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6305                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6306                 * @param float $w Width.
6307                 * @param float $h Height.
6308                 * @param string $op options
6309                 * @access protected
6310                 * @since 2.1.000 (2008-01-08)
6311                 */
6312                 function _outRect($x, $y, $w, $h, $op) {
6313                         if ($this->rtl) {
6314                                 $x = $this->w - $x - $w;
6315                         }
6316                         $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
6317                 }
6318
6319                 /*
6320                 * Draws a Bezier curve from last draw point.
6321                 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
6322                 * @param float $x1 Abscissa of control point 1.
6323                 * @param float $y1 Ordinate of control point 1.
6324                 * @param float $x2 Abscissa of control point 2.
6325                 * @param float $y2 Ordinate of control point 2.
6326                 * @param float $x3 Abscissa of end point.
6327                 * @param float $y3 Ordinate of end point.
6328                 * @access protected
6329                 * @since 2.1.000 (2008-01-08)
6330                 */
6331                 function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
6332                         if ($this->rtl) {
6333                                 $x1 = $this->w - $x1;
6334                                 $x2 = $this->w - $x2;
6335                                 $x3 = $this->w - $x3;
6336                         }
6337                         $this->_out(sprintf("%.2f %.2f %.2f %.2f %.2f %.2f c", $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
6338                 }
6339
6340                 /**
6341                 * Draws a line between two points.
6342                 * @param float $x1 Abscissa of first point.
6343                 * @param float $y1 Ordinate of first point.
6344                 * @param float $x2 Abscissa of second point.
6345                 * @param float $y2 Ordinate of second point.
6346                 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6347                 * @access public
6348                 * @since 1.0
6349                 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
6350                 */
6351                 function Line($x1, $y1, $x2, $y2, $style=array()) {
6352                         if ($style) {
6353                                 $this->SetLineStyle($style);
6354                         }
6355                         $this->_outPoint($x1, $y1);
6356                         $this->_outLine($x2, $y2);
6357                         $this->_out(" S");
6358                 }
6359
6360                 /**
6361                 * Draws a rectangle.
6362                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6363                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6364                 * @param float $w Width.
6365                 * @param float $h Height.
6366                 * @param string $style Style of rendering. Possible values are:
6367                 * <ul>
6368                 *        <li>D or empty string: Draw (default).</li>
6369                 *        <li>F: Fill.</li>
6370                 *        <li>DF or FD: Draw and fill.</li>
6371                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6372                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6373                 * </ul>
6374                 * @param array $border_style Border style of rectangle. Array with keys among the following:
6375                 * <ul>
6376                 *        <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
6377                 *        <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
6378                 * </ul>
6379                 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
6380                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6381                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
6382                 * @access public
6383                 * @since 1.0
6384                 * @see SetLineStyle()
6385                 */
6386                 function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
6387                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6388                                 $this->SetFillColorArray($fill_color);
6389                         }
6390                         switch ($style) {
6391                                 case "F": {
6392                                         $op = 'f';
6393                                         $border_style = array();
6394                                         $this->_outRect($x, $y, $w, $h, $op);
6395                                         break;
6396                                 }
6397                                 case "DF":
6398                                 case "FD": {
6399                                         if ((!$border_style) OR (isset($border_style["all"]))) {
6400                                                 $op = 'B';
6401                                                 if (isset($border_style["all"])) {
6402                                                         $this->SetLineStyle($border_style["all"]);
6403                                                         $border_style = array();
6404                                                 }
6405                                         } else {
6406                                                 $op = 'f';
6407                                         }
6408                                         $this->_outRect($x, $y, $w, $h, $op);
6409                                         break;
6410                                 }
6411                                 case "CNZ": {
6412                                         $op = "W n";
6413                                         break;
6414                                 }
6415                                 case "CEO": {
6416                                         $op = "W* n";
6417                                         break;
6418                                 }
6419                                 default: {
6420                                         $op = 'S';
6421                                         if ((!$border_style) OR (isset($border_style["all"]))) {
6422                                                 if (isset($border_style["all"]) AND $border_style["all"]) {
6423                                                         $this->SetLineStyle($border_style["all"]);
6424                                                         $border_style = array();
6425                                                 }
6426                                                 $this->_outRect($x, $y, $w, $h, $op);
6427                                         }
6428                                         break;
6429                                 }
6430                         }
6431                         if ($border_style) {
6432                                 $border_style2 = array();
6433                                 foreach ($border_style as $line => $value) {
6434                                         $lenght = strlen($line);
6435                                         for ($i = 0; $i < $lenght; $i++) {
6436                                                 $border_style2[$line[$i]] = $value;
6437                                         }
6438                                 }
6439                                 $border_style = $border_style2;
6440                                 if (isset($border_style["L"]) AND $border_style["L"]) {
6441                                         $this->Line($x, $y, $x, $y + $h, $border_style["L"]);
6442                                 }
6443                                 if (isset($border_style["T"]) AND $border_style["T"]) {
6444                                         $this->Line($x, $y, $x + $w, $y, $border_style["T"]);
6445                                 }
6446                                 if (isset($border_style["R"]) AND $border_style["R"]) {
6447                                         $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style["R"]);
6448                                 }
6449                                 if (isset($border_style["B"]) AND $border_style["B"]) {
6450                                         $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style["B"]);
6451                                 }
6452                         }
6453                 }
6454
6455
6456                 /**
6457                 * Draws a Bezier curve.
6458                 * The Bezier curve is a tangent to the line between the control points at
6459                 * either end of the curve.
6460                 * @param float $x0 Abscissa of start point.
6461                 * @param float $y0 Ordinate of start point.
6462                 * @param float $x1 Abscissa of control point 1.
6463                 * @param float $y1 Ordinate of control point 1.
6464                 * @param float $x2 Abscissa of control point 2.
6465                 * @param float $y2 Ordinate of control point 2.
6466                 * @param float $x3 Abscissa of end point.
6467                 * @param float $y3 Ordinate of end point.
6468                 * @param string $style Style of rendering. Possible values are:
6469                 * <ul>
6470                 *        <li>D or empty string: Draw (default).</li>
6471                 *        <li>F: Fill.</li>
6472                 *        <li>DF or FD: Draw and fill.</li>
6473                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6474                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6475                 * </ul>
6476                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6477                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
6478                 * @access public
6479                 * @see SetLineStyle()
6480                 * @since 2.1.000 (2008-01-08)
6481                 */
6482                 function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style="", $line_style=array(), $fill_color=array()) {
6483                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6484                                 $this->SetFillColorArray($fill_color);
6485                         }
6486                         switch ($style) {
6487                                 case "F": {
6488                                         $op = "f";
6489                                         $line_style = array();
6490                                         break;
6491                                 }
6492                                 case "FD":
6493                                 case "DF": {
6494                                         $op = "B";
6495                                         break;
6496                                 }
6497                                 case "CNZ": {
6498                                         $op = "W n";
6499                                         break;
6500                                 }
6501                                 case "CEO": {
6502                                         $op = "W* n";
6503                                         break;
6504                                 }
6505                                 default: {
6506                                         $op = "S";
6507                                         break;
6508                                 }
6509                         }
6510                         if ($line_style) {
6511                                 $this->SetLineStyle($line_style);
6512                         }
6513                         $this->_outPoint($x0, $y0);
6514                         $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6515                         $this->_out($op);
6516                 }
6517
6518                 /**
6519                 * Draws a poly-Bezier curve.
6520                 * Each Bezier curve segment is a tangent to the line between the control points at
6521                 * either end of the curve.
6522                 * @param float $x0 Abscissa of start point.
6523                 * @param float $y0 Ordinate of start point.
6524                 * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
6525                 * @param string $style Style of rendering. Possible values are:
6526                 * <ul>
6527                 *        <li>D or empty string: Draw (default).</li>
6528                 *        <li>F: Fill.</li>
6529                 *        <li>DF or FD: Draw and fill.</li>
6530                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6531                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6532                 * </ul>
6533                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6534                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
6535                 * @access public
6536                 * @see SetLineStyle()
6537                 * @since 3.0008 (2008-05-12)
6538                 */
6539                 function Polycurve($x0, $y0, $segments, $style="", $line_style=array(), $fill_color=array()) {
6540                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6541                                 $this->SetFillColorArray($fill_color);
6542                         }
6543                         switch ($style) {
6544                                 case "F": {
6545                                         $op = "f";
6546                                         $line_style = array();
6547                                         break;
6548                                 }
6549                                 case "FD":
6550                                 case "DF": {
6551                                         $op = "B";
6552                                         break;
6553                                 }
6554                                 case "CNZ": {
6555                                         $op = "W n";
6556                                         break;
6557                                 }
6558                                 case "CEO": {
6559                                         $op = "W* n";
6560                                         break;
6561                                 }
6562                                 default: {
6563                                         $op = "S";
6564                                         break;
6565                                 }
6566                         }
6567                         if ($line_style) {
6568                                 $this->SetLineStyle($line_style);
6569                         }
6570                         $this->_outPoint($x0, $y0);
6571                         foreach ($segments as $segment) {
6572                                 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
6573                                 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6574                         }
6575                         $this->_out($op);
6576                 }
6577
6578                 /**
6579                 * Draws an ellipse.
6580                 * An ellipse is formed from n Bezier curves.
6581                 * @param float $x0 Abscissa of center point.
6582                 * @param float $y0 Ordinate of center point.
6583                 * @param float $rx Horizontal radius.
6584                 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
6585                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6586                 * @param float $astart: Angle start of draw line. Default value: 0.
6587                 * @param float $afinish: Angle finish of draw line. Default value: 360.
6588                 * @param string $style Style of rendering. Possible values are:
6589                 * <ul>
6590                 *        <li>D or empty string: Draw (default).</li>
6591                 *        <li>F: Fill.</li>
6592                 *        <li>DF or FD: Draw and fill.</li>
6593                 *        <li>C: Draw close.</li>
6594                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6595                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6596                 * </ul>
6597                 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6598                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
6599                 * @param integer $nc Number of curves used in ellipse. Default value: 8.
6600                 * @access public
6601                 * @since 2.1.000 (2008-01-08)
6602                 */
6603                 function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6604                         if ($angle) {
6605                                 $this->StartTransform();
6606                                 $this->Rotate($angle, $x0, $y0);
6607                                 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6608                                 $this->StopTransform();
6609                                 return;
6610                         }
6611                         if ($rx) {
6612                                 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6613                                         $this->SetFillColorArray($fill_color);
6614                                 }
6615                                 switch ($style) {
6616                                         case "F": {
6617                                                 $op = "f";
6618                                                 $line_style = array();
6619                                                 break;
6620                                         }
6621                                         case "FD":
6622                                         case "DF": {
6623                                                 $op = "B";
6624                                                 break;
6625                                         }
6626                                         case "C": {
6627                                                 $op = "s"; // Small "s" signifies closing the path as well
6628                                                 break;
6629                                         }
6630                                         case "CNZ": {
6631                                                 $op = "W n";
6632                                                 break;
6633                                         }
6634                                         case "CEO": {
6635                                                 $op = "W* n";
6636                                                 break;
6637                                         }
6638                                         default: {
6639                                                 $op = "S";
6640                                                 break;
6641                                         }
6642                                 }
6643                                 if ($line_style) {
6644                                         $this->SetLineStyle($line_style);
6645                                 }
6646                                 if (!$ry) {
6647                                         $ry = $rx;
6648                                 }
6649                                 $rx *= $this->k;
6650                                 $ry *= $this->k;
6651                                 if ($nc < 2){
6652                                         $nc = 2;
6653                                 }
6654                                 $astart = deg2rad((float) $astart);
6655                                 $afinish = deg2rad((float) $afinish);
6656                                 $total_angle = $afinish - $astart;
6657                                 $dt = $total_angle / $nc;
6658                                 $dtm = $dt / 3;
6659                                 $x0 *= $this->k;
6660                                 $y0 = ($this->h - $y0) * $this->k;
6661                                 $t1 = $astart;
6662                                 $a0 = $x0 + ($rx * cos($t1));
6663                                 $b0 = $y0 + ($ry * sin($t1));
6664                                 $c0 = -$rx * sin($t1);
6665                                 $d0 = $ry * cos($t1);
6666                                 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
6667                                 for ($i = 1; $i <= $nc; $i++) {
6668                                         // Draw this bit of the total curve
6669                                         $t1 = ($i * $dt) + $astart;
6670                                         $a1 = $x0 + ($rx * cos($t1));
6671                                         $b1 = $y0 + ($ry * sin($t1));
6672                                         $c1 = -$rx * sin($t1);
6673                                         $d1 = $ry * cos($t1);
6674                                         $this->_outCurve(($a0 + ($c0 * $dtm)) / $this->k, $this->h - (($b0 + ($d0 * $dtm)) / $this->k), ($a1 - ($c1 * $dtm)) / $this->k, $this->h - (($b1 - ($d1 * $dtm)) / $this->k), $a1 / $this->k, $this->h - ($b1 / $this->k));
6675                                         $a0 = $a1;
6676                                         $b0 = $b1;
6677                                         $c0 = $c1;
6678                                         $d0 = $d1;
6679                                 }
6680                                 $this->_out($op);
6681                         }
6682                 }
6683
6684                 /**
6685                 * Draws a circle.
6686                 * A circle is formed from n Bezier curves.
6687                 * @param float $x0 Abscissa of center point.
6688                 * @param float $y0 Ordinate of center point.
6689                 * @param float $r Radius.
6690                 * @param float $astart: Angle start of draw line. Default value: 0.
6691                 * @param float $afinish: Angle finish of draw line. Default value: 360.
6692                 * @param string $style Style of rendering. Possible values are:
6693                 * <ul>
6694                 *        <li>D or empty string: Draw (default).</li>
6695                 *        <li>F: Fill.</li>
6696                 *        <li>DF or FD: Draw and fill.</li>
6697                 *        <li>C: Draw close.</li>
6698                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6699                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6700                 * </ul>
6701                 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6702                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6703                 * @param integer $nc Number of curves used in circle. Default value: 8.
6704                 * @access public
6705                 * @since 2.1.000 (2008-01-08)
6706                 */
6707                 function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6708                         $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6709                 }
6710
6711                 /**
6712                 * Draws a polygon.
6713                 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
6714                 * @param string $style Style of rendering. Possible values are:
6715                 * <ul>
6716                 *        <li>D or empty string: Draw (default).</li>
6717                 *        <li>F: Fill.</li>
6718                 *        <li>DF or FD: Draw and fill.</li>
6719                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6720                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6721                 * </ul>
6722                 * @param array $line_style Line style of polygon. Array with keys among the following:
6723                 * <ul>
6724                 *        <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
6725                 *        <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
6726                 * </ul>
6727                 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
6728                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
6729                 * @access public
6730                 * @since 2.1.000 (2008-01-08)
6731                 */
6732                 function Polygon($p, $style="", $line_style=array(), $fill_color=array()) {
6733                         $np = count($p) / 2;
6734                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6735                                 $this->SetFillColorArray($fill_color);
6736                         }
6737                         switch ($style) {
6738                                 case "F": {
6739                                         $line_style = array();
6740                                         $op = "f";
6741                                         break;
6742                                 }
6743                                 case "FD":
6744                                 case "DF": {
6745                                         $op = "B";
6746                                         break;
6747                                 }
6748                                 case "CNZ": {
6749                                         $op = "W n";
6750                                         break;
6751                                 }
6752                                 case "CEO": {
6753                                         $op = "W* n";
6754                                         break;
6755                                 }
6756                                 default: {
6757                                         $op = "S";
6758                                         break;
6759                                 }
6760                         }
6761                         $draw = true;
6762                         if ($line_style) {
6763                                 if (isset($line_style["all"])) {
6764                                         $this->SetLineStyle($line_style["all"]);
6765                                 } else { // 0 .. (np - 1), op = {B, S}
6766                                         $draw = false;
6767                                         if ("B" == $op) {
6768                                                 $op = "f";
6769                                                 $this->_outPoint($p[0], $p[1]);
6770                                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6771                                                         $this->_outLine($p[$i], $p[$i + 1]);
6772                                                 }
6773                                                 $this->_outLine($p[0], $p[1]);
6774                                                 $this->_out($op);
6775                                         }
6776                                         $p[($np * 2)] = $p[0];
6777                                         $p[(($np * 2) + 1)] = $p[1];
6778                                         for ($i = 0; $i < $np; $i++) {
6779                                                 if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
6780                                                         $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
6781                                                 }
6782                                         }
6783                                 }
6784                         }
6785                         if ($draw) {
6786                                 $this->_outPoint($p[0], $p[1]);
6787                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6788                                         $this->_outLine($p[$i], $p[$i + 1]);
6789                                 }
6790                                 $this->_outLine($p[0], $p[1]);
6791                                 $this->_out($op);
6792                         }
6793                 }
6794
6795                 /**
6796                 * Draws a regular polygon.
6797                 * @param float $x0 Abscissa of center point.
6798                 * @param float $y0 Ordinate of center point.
6799                 * @param float $r: Radius of inscribed circle.
6800                 * @param integer $ns Number of sides.
6801                 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
6802                 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
6803                 * @param string $style Style of rendering. Possible values are:
6804                 * <ul>
6805                 *        <li>D or empty string: Draw (default).</li>
6806                 *        <li>F: Fill.</li>
6807                 *        <li>DF or FD: Draw and fill.</li>
6808                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6809                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6810                 * </ul>
6811                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6812                 * <ul>
6813                 *        <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
6814                 *        <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6815                 * </ul>
6816                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6817                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6818                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6819                 * <ul>
6820                 *        <li>D or empty string: Draw (default).</li>
6821                 *        <li>F: Fill.</li>
6822                 *        <li>DF or FD: Draw and fill.</li>
6823                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6824                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6825                 * </ul>
6826                 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6827                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6828                 * @access public
6829                 * @since 2.1.000 (2008-01-08)
6830                 */
6831                 function RegularPolygon($x0, $y0, $r, $ns, $angle=0, $draw_circle=false, $style="", $line_style=array(), $fill_color=array(), $circle_style="", $circle_outLine_style=array(), $circle_fill_color=array()) {
6832                         if (3 > $ns) {
6833                                 $ns = 3;
6834                         }
6835                         if ($draw_circle) {
6836                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6837                         }
6838                         $p = array();
6839                         for ($i = 0; $i < $ns; $i++) {
6840                                 $a = $angle + ($i * 360 / $ns);
6841                                 $a_rad = deg2rad((float) $a);
6842                                 $p[] = $x0 + ($r * sin($a_rad));
6843                                 $p[] = $y0 + ($r * cos($a_rad));
6844                         }
6845                         $this->Polygon($p, $style, $line_style, $fill_color);
6846                 }
6847
6848                 /**
6849                 * Draws a star polygon
6850                 * @param float $x0 Abscissa of center point.
6851                 * @param float $y0 Ordinate of center point.
6852                 * @param float $r Radius of inscribed circle.
6853                 * @param integer $nv Number of vertices.
6854                 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
6855                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6856                 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
6857                 * @param string $style Style of rendering. Possible values are:
6858                 * <ul>
6859                 *        <li>D or empty string: Draw (default).</li>
6860                 *        <li>F: Fill.</li>
6861                 *        <li>DF or FD: Draw and fill.</li>
6862                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6863                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6864                 * </ul>
6865                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6866                 * <ul>
6867                 *        <li>all: Line style of all sides. Array like for
6868                 * {@link SetLineStyle SetLineStyle}.</li>
6869                 *        <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6870                 * </ul>
6871                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6872                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6873                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6874                 * <ul>
6875                 *        <li>D or empty string: Draw (default).</li>
6876                 *        <li>F: Fill.</li>
6877                 *        <li>DF or FD: Draw and fill.</li>
6878                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6879                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6880                 * </ul>
6881                 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6882                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6883                 * @access public
6884                 * @since 2.1.000 (2008-01-08)
6885                 */
6886                 function StarPolygon($x0, $y0, $r, $nv, $ng, $angle=0, $draw_circle=false, $style="", $line_style=array(), $fill_color=array(), $circle_style="", $circle_outLine_style=array(), $circle_fill_color=array()) {
6887                         if (2 > $nv) {
6888                                 $nv = 2;
6889                         }
6890                         if ($draw_circle) {
6891                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6892                         }
6893                         $p2 = array();
6894                         $visited = array();
6895                         for ($i = 0; $i < $nv; $i++) {
6896                                 $a = $angle + ($i * 360 / $nv);
6897                                 $a_rad = deg2rad((float) $a);
6898                                 $p2[] = $x0 + ($r * sin($a_rad));
6899                                 $p2[] = $y0 + ($r * cos($a_rad));
6900                                 $visited[] = false;
6901                         }
6902                         $p = array();
6903                         $i = 0;
6904                         do {
6905                                 $p[] = $p2[$i * 2];
6906                                 $p[] = $p2[($i * 2) + 1];
6907                                 $visited[$i] = true;
6908                                 $i += $ng;
6909                                 $i %= $nv;
6910                         } while (!$visited[$i]);
6911                         $this->Polygon($p, $style, $line_style, $fill_color);
6912                 }
6913
6914                 /**
6915                 * Draws a rounded rectangle.
6916                 * @param float $x Abscissa of upper-left corner.
6917                 * @param float $y Ordinate of upper-left corner.
6918                 * @param float $w Width.
6919                 * @param float $h Height.
6920                 * @param float $r Radius of the rounded corners.
6921                 * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111").
6922                 * @param string $style Style of rendering. Possible values are:
6923                 * <ul>
6924                 *        <li>D or empty string: Draw (default).</li>
6925                 *        <li>F: Fill.</li>
6926                 *        <li>DF or FD: Draw and fill.</li>
6927                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6928                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6929                 * </ul>
6930                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6931                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
6932                 * @access public
6933                 * @since 2.1.000 (2008-01-08)
6934                 */
6935                 function RoundedRect($x, $y, $w, $h, $r, $round_corner="1111", $style="", $border_style=array(), $fill_color=array()) {
6936                         if ("0000" == $round_corner) { // Not rounded
6937                                 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
6938                         } else { // Rounded
6939                                 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6940                                         $this->SetFillColorArray($fill_color);
6941                                 }
6942                                 switch ($style) {
6943                                         case "F": {
6944                                                 $border_style = array();
6945                                                 $op = "f";
6946                                                 break;
6947                                         }
6948                                         case "FD":
6949                                         case "DF": {
6950                                                 $op = "B";
6951                                                 break;
6952                                         }
6953                                         case "CNZ": {
6954                                                 $op = "W n";
6955                                                 break;
6956                                         }
6957                                         case "CEO": {
6958                                                 $op = "W* n";
6959                                                 break;
6960                                         }
6961                                         default: {
6962                                                 $op = "S";
6963                                                 break;
6964                                         }
6965                                 }
6966                                 if ($border_style) {
6967                                         $this->SetLineStyle($border_style);
6968                                 }
6969                                 $MyArc = 4 / 3 * (sqrt(2) - 1);
6970                                 $this->_outPoint($x + $r, $y);
6971                                 $xc = $x + $w - $r;
6972                                 $yc = $y + $r;
6973                                 $this->_outLine($xc, $y);
6974                                 if ($round_corner[0]) {
6975                                         $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
6976                                 } else {
6977                                         $this->_outLine($x + $w, $y);
6978                                 }
6979                                 $xc = $x + $w - $r;
6980                                 $yc = $y + $h - $r;
6981                                 $this->_outLine($x + $w, $yc);
6982                                 if ($round_corner[1]) {
6983                                         $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
6984                                 } else {
6985                                         $this->_outLine($x + $w, $y + $h);
6986                                 }
6987                                 $xc = $x + $r;
6988                                 $yc = $y + $h - $r;
6989                                 $this->_outLine($xc, $y + $h);
6990                                 if ($round_corner[2]) {
6991                                         $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
6992                                 } else {
6993                                         $this->_outLine($x, $y + $h);
6994                                 }
6995                                 $xc = $x + $r;
6996                                 $yc = $y + $r;
6997                                 $this->_outLine($x, $yc);
6998                                 if ($round_corner[3]) {
6999                                         $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
7000                                 } else {
7001                                         $this->_outLine($x, $y);
7002                                         $this->_outLine($x + $r, $y);
7003                                 }
7004                                 $this->_out($op);
7005                         }
7006                 }
7007
7008                 // END GRAPHIC FUNCTIONS SECTION -----------------------
7009
7010                 // BIDIRECTIONAL TEXT SECTION --------------------------
7011                 /**
7012                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7013                  * @param string $str string to manipulate.
7014                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7015                  * @return string
7016                  * @author Nicola Asuni
7017                  * @since 2.1.000 (2008-01-08)
7018                 */
7019                 function utf8StrRev($str, $setbom=false, $forcertl=false) {
7020                         return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $forcertl), $setbom);
7021                 }
7022
7023                 /**
7024                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7025                  * @param array $ta array of characters composing the string.
7026                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7027                  * @return string
7028                  * @author Nicola Asuni
7029                  * @since 2.4.000 (2008-03-06)
7030                 */
7031                 function utf8Bidi($ta, $forcertl=false) {
7032                         global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
7033                         // paragraph embedding level
7034                         $pel = 0;
7035                         // max level
7036                         $maxlevel = 0;
7037                         // create string from array
7038                         $str = $this->UTF8ArrSubString($ta);
7039                         // check if string contains arabic text
7040                         if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
7041                                 $arabic = true;
7042                         } else {
7043                                 $arabic = false;
7044                         }
7045                         // check if string contains RTL text
7046                         if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
7047                                 return $ta;
7048                         }
7049                         
7050                         // get number of chars
7051                         $numchars = count($ta);
7052                         
7053                         if ($forcertl == 'R') {
7054                                         $pel = 1;
7055                         } elseif ($forcertl == 'L') {
7056                                         $pel = 0;
7057                         } else {
7058                                 // P2. In each paragraph, find the first character of type L, AL, or R.
7059                                 // P3. If a character is found in P2 and it is of type AL or R, then set the paragraph embedding level to one; otherwise, set it to zero.
7060                                 for ($i=0; $i < $numchars; $i++) {
7061                                         $type = $unicode[$ta[$i]];
7062                                         if ($type == 'L') {
7063                                                 $pel = 0;
7064                                                 break;
7065                                         } elseif (($type == 'AL') OR ($type == 'R')) {
7066                                                 $pel = 1;
7067                                                 break;
7068                                         }
7069                                 }
7070                         }
7071                         
7072                         // Current Embedding Level
7073                         $cel = $pel;
7074                         // directional override status
7075                         $dos = 'N';
7076                         $remember = array();
7077                         // start-of-level-run
7078                         $sor = $pel % 2 ? 'R' : 'L';
7079                         $eor = $sor;
7080
7081                         //$levels = array(array('level' => $cel, 'sor' => $sor, 'eor' => '', 'chars' => array()));
7082                         //$current_level = &$levels[count( $levels )-1];
7083
7084                         // Array of characters data
7085                         $chardata = Array();
7086
7087                         // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase.
7088                         //      In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
7089                         for ($i=0; $i < $numchars; $i++) {
7090                                 if ($ta[$i] == K_RLE) {
7091                                         // X2. With each RLE, compute the least greater odd embedding level.
7092                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
7093                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7094                                         $next_level = $cel + ($cel % 2) + 1;
7095                                         if ($next_level < 62) {
7096                                                 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
7097                                                 $cel = $next_level;
7098                                                 $dos = 'N';
7099                                                 $sor = $eor;
7100                                                 $eor = $cel % 2 ? 'R' : 'L';
7101                                         }
7102                                 } elseif ($ta[$i] == K_LRE) {
7103                                         // X3. With each LRE, compute the least greater even embedding level.
7104                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
7105                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7106                                         $next_level = $cel + 2 - ($cel % 2);
7107                                         if ( $next_level < 62 ) {
7108                                                 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
7109                                                 $cel = $next_level;
7110                                                 $dos = 'N';
7111                                                 $sor = $eor;
7112                                                 $eor = $cel % 2 ? 'R' : 'L';
7113                                         }
7114                                 } elseif ($ta[$i] == K_RLO) {
7115                                         // X4. With each RLO, compute the least greater odd embedding level.
7116                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left.
7117                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7118                                         $next_level = $cel + ($cel % 2) + 1;
7119                                         if ($next_level < 62) {
7120                                                 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
7121                                                 $cel = $next_level;
7122                                                 $dos = 'R';
7123                                                 $sor = $eor;
7124                                                 $eor = $cel % 2 ? 'R' : 'L';
7125                                         }
7126                                 } elseif ($ta[$i] == K_LRO) {
7127                                         // X5. With each LRO, compute the least greater even embedding level.
7128                                         //      a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right.
7129                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7130                                         $next_level = $cel + 2 - ($cel % 2);
7131                                         if ( $next_level < 62 ) {
7132                                                 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
7133                                                 $cel = $next_level;
7134                                                 $dos = 'L';
7135                                                 $sor = $eor;
7136                                                 $eor = $cel % 2 ? 'R' : 'L';
7137                                         }
7138                                 } elseif ($ta[$i] == K_PDF) {
7139                                         // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override.
7140                                         if (count($remember)) {
7141                                                 $last = count($remember ) - 1;
7142                                                 if (($remember[$last]['num'] == K_RLE) OR
7143                                                           ($remember[$last]['num'] == K_LRE) OR
7144                                                           ($remember[$last]['num'] == K_RLO) OR
7145                                                           ($remember[$last]['num'] == K_LRO)) {
7146                                                         $match = array_pop($remember);
7147                                                         $cel = $match['cel'];
7148                                                         $dos = $match['dos'];
7149                                                         $sor = $eor;
7150                                                         $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
7151                                                 }
7152                                         }
7153                                 } elseif (($ta[$i] != K_RLE) AND
7154                                                                  ($ta[$i] != K_LRE) AND
7155                                                                  ($ta[$i] != K_RLO) AND
7156                                                                  ($ta[$i] != K_LRO) AND
7157                                                                  ($ta[$i] != K_PDF)) {
7158                                         // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
7159                                         //      a. Set the level of the current character to the current embedding level.
7160                                         //      b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
7161                                         if ($dos != 'N') {
7162                                                 $chardir = $dos;
7163                                         } else {
7164                                                 $chardir = $unicode[$ta[$i]];
7165                                         }
7166                                         // stores string characters and other information
7167                                         $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
7168                                 }
7169                         } // end for each char
7170
7171                         // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
7172                         // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
7173                         // X10. The remaining rules are applied to each run of characters at the same level. For each run, determine the start-of-level-run (sor) and end-of-level-run (eor) type, either L or R. This depends on the higher of the two levels on either side of the boundary (at the start or end of the paragraph, the level of the 'other' run is the base embedding level). If the higher level is odd, the type is R; otherwise, it is L.
7174
7175                         // 3.3.3 Resolving Weak Types
7176                         // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used.
7177                         // Nonspacing marks are now resolved based on the previous characters.
7178                         $numchars = count($chardata);
7179
7180                         // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor.
7181                         $prevlevel = -1; // track level changes
7182                         $levcount = 0; // counts consecutive chars at the same level
7183                         for ($i=0; $i < $numchars; $i++) {
7184                                 if ($chardata[$i]['type'] == 'NSM') {
7185                                         if ($levcount) {
7186                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7187                                         } elseif ($i > 0) {
7188                                                 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
7189                                         }
7190                                 }
7191                                 if ($chardata[$i]['level'] != $prevlevel) {
7192                                         $levcount = 0;
7193                                 } else {
7194                                         $levcount++;
7195                                 }
7196                                 $prevlevel = $chardata[$i]['level'];
7197                         }
7198
7199                         // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number.
7200                         $prevlevel = -1;
7201                         $levcount = 0;
7202                         for ($i=0; $i < $numchars; $i++) {
7203                                 if ($chardata[$i]['char'] == 'EN') {
7204                                         for ($j=$levcount; $j >= 0; $j--) {
7205                                                 if ($chardata[$j]['type'] == 'AL') {
7206                                                         $chardata[$i]['type'] = 'AN';
7207                                                 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
7208                                                         break;
7209                                                 }
7210                                         }
7211                                 }
7212                                 if ($chardata[$i]['level'] != $prevlevel) {
7213                                         $levcount = 0;
7214                                 } else {
7215                                         $levcount++;
7216                                 }
7217                                 $prevlevel = $chardata[$i]['level'];
7218                         }
7219
7220                         // W3. Change all ALs to R.
7221                         for ($i=0; $i < $numchars; $i++) {
7222                                 if ($chardata[$i]['type'] == 'AL') {
7223                                         $chardata[$i]['type'] = 'R';
7224                                 }
7225                         }
7226
7227                         // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type.
7228                         $prevlevel = -1;
7229                         $levcount = 0;
7230                         for ($i=0; $i < $numchars; $i++) {
7231                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7232                                         if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7233                                                 $chardata[$i]['type'] = 'EN';
7234                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7235                                                 $chardata[$i]['type'] = 'EN';
7236                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
7237                                                 $chardata[$i]['type'] = 'AN';
7238                                         }
7239                                 }
7240                                 if ($chardata[$i]['level'] != $prevlevel) {
7241                                         $levcount = 0;
7242                                 } else {
7243                                         $levcount++;
7244                                 }
7245                                 $prevlevel = $chardata[$i]['level'];
7246                         }
7247
7248                         // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
7249                         $prevlevel = -1;
7250                         $levcount = 0;
7251                         for ($i=0; $i < $numchars; $i++) {
7252                                 if ($chardata[$i]['type'] == 'ET') {
7253                                         if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
7254                                                 $chardata[$i]['type'] = 'EN';
7255                                         } else {
7256                                                 $j = $i+1;
7257                                                 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
7258                                                         if ($chardata[$j]['type'] == 'EN') {
7259                                                                 $chardata[$i]['type'] = 'EN';
7260                                                                 break;
7261                                                         } elseif ($chardata[$j]['type'] != 'ET') {
7262                                                                 break;
7263                                                         }
7264                                                         $j++;
7265                                                 }
7266                                         }
7267                                 }
7268                                 if ($chardata[$i]['level'] != $prevlevel) {
7269                                         $levcount = 0;
7270                                 } else {
7271                                         $levcount++;
7272                                 }
7273                                 $prevlevel = $chardata[$i]['level'];
7274                         }
7275
7276                         // W6. Otherwise, separators and terminators change to Other Neutral.
7277                         $prevlevel = -1;
7278                         $levcount = 0;
7279                         for ($i=0; $i < $numchars; $i++) {
7280                                 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
7281                                         $chardata[$i]['type'] = 'ON';
7282                                 }
7283                                 if ($chardata[$i]['level'] != $prevlevel) {
7284                                         $levcount = 0;
7285                                 } else {
7286                                         $levcount++;
7287                                 }
7288                                 $prevlevel = $chardata[$i]['level'];
7289                         }
7290
7291                         //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L.
7292                         $prevlevel = -1;
7293                         $levcount = 0;
7294                         for ($i=0; $i < $numchars; $i++) {
7295                                 if ($chardata[$i]['char'] == 'EN') {
7296                                         for ($j=$levcount; $j >= 0; $j--) {
7297                                                 if ($chardata[$j]['type'] == 'L') {
7298                                                         $chardata[$i]['type'] = 'L';
7299                                                 } elseif ($chardata[$j]['type'] == 'R') {
7300                                                         break;
7301                                                 }
7302                                         }
7303                                 }
7304                                 if ($chardata[$i]['level'] != $prevlevel) {
7305                                         $levcount = 0;
7306                                 } else {
7307                                         $levcount++;
7308                                 }
7309                                 $prevlevel = $chardata[$i]['level'];
7310                         }
7311
7312                         // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries.
7313                         $prevlevel = -1;
7314                         $levcount = 0;
7315                         for ($i=0; $i < $numchars; $i++) {
7316                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7317                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7318                                                 $chardata[$i]['type'] = 'L';
7319                                         } elseif (($chardata[$i]['type'] == 'N') AND
7320                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7321                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7322                                                 $chardata[$i]['type'] = 'R';
7323                                         } elseif ($chardata[$i]['type'] == 'N') {
7324                                                 // N2. Any remaining neutrals take the embedding direction
7325                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7326                                         }
7327                                 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7328                                         // first char
7329                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7330                                                 $chardata[$i]['type'] = 'L';
7331                                         } elseif (($chardata[$i]['type'] == 'N') AND
7332                                          (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
7333                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7334                                                 $chardata[$i]['type'] = 'R';
7335                                         } elseif ($chardata[$i]['type'] == 'N') {
7336                                                 // N2. Any remaining neutrals take the embedding direction
7337                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7338                                         }
7339                                 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
7340                                         //last char
7341                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
7342                                                 $chardata[$i]['type'] = 'L';
7343                                         } elseif (($chardata[$i]['type'] == 'N') AND
7344                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7345                                          (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
7346                                                 $chardata[$i]['type'] = 'R';
7347                                         } elseif ($chardata[$i]['type'] == 'N') {
7348                                                 // N2. Any remaining neutrals take the embedding direction
7349                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7350                                         }
7351                                 } elseif ($chardata[$i]['type'] == 'N') {
7352                                         // N2. Any remaining neutrals take the embedding direction
7353                                         $chardata[$i]['type'] = $chardata[$i]['sor'];
7354                                 }
7355                                 if ($chardata[$i]['level'] != $prevlevel) {
7356                                         $levcount = 0;
7357                                 } else {
7358                                         $levcount++;
7359                                 }
7360                                 $prevlevel = $chardata[$i]['level'];
7361                         }
7362
7363                         // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels.
7364                         // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
7365                         for ($i=0; $i < $numchars; $i++) {
7366                                 $odd = $chardata[$i]['level'] % 2;
7367                                 if ($odd) {
7368                                         if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7369                                                 $chardata[$i]['level'] += 1;
7370                                         }
7371                                 } else {
7372                                         if ($chardata[$i]['type'] == 'R') {
7373                                                 $chardata[$i]['level'] += 1;
7374                                         } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7375                                                 $chardata[$i]['level'] += 2;
7376                                         }
7377                                 }
7378                                 $maxlevel = max($chardata[$i]['level'],$maxlevel);
7379                         }
7380
7381                         // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
7382                         //      1. Segment separators,
7383                         //      2. Paragraph separators,
7384                         //      3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
7385                         //      4. Any sequence of white space characters at the end of the line.
7386                         for ($i=0; $i < $numchars; $i++) {
7387                                 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
7388                                         $chardata[$i]['level'] = $pel;
7389                                 } elseif ($chardata[$i]['type'] == 'WS') {
7390                                         $j = $i+1;
7391                                         while ($j < $numchars) {
7392                                                 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
7393                                                         (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
7394                                                         $chardata[$i]['level'] = $pel;
7395                                                         break;
7396                                                 } elseif ($chardata[$j]['type'] != 'WS') {
7397                                                         break;
7398                                                 }
7399                                                 $j++;
7400                                         }
7401                                 }
7402                         }
7403
7404                         // Arabic Shaping
7405                         // Cursively connected scripts, such as Arabic or Syriac, require the selection of positional character shapes that depend on adjacent characters. Shaping is logically applied after the Bidirectional Algorithm is used and is limited to characters within the same directional run.
7406                         if ($arabic) {
7407                                 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
7408                                 $alfletter = array(1570,1571,1573,1575);
7409                                 $chardata2 = $chardata;
7410                                 $laaletter = false;
7411                                 $charAL = array();
7412                                 $x = 0;
7413                                 for ($i=0; $i < $numchars; $i++) {
7414                                         if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
7415                                                 $charAL[$x] = $chardata[$i];
7416                                                 $charAL[$x]['i'] = $i;
7417                                                 $chardata[$i]['x'] = $x;
7418                                                 $x++;
7419                                         }
7420                                 }
7421                                 $numAL = $x;
7422                                 for ($i=0; $i < $numchars; $i++) {
7423                                         $thischar = $chardata[$i];
7424                                         if ($i > 0) {
7425                                                 $prevchar = $chardata[($i-1)];
7426                                         } else {
7427                                                 $prevchar = false;
7428                                         }
7429                                         if (($i+1) < $numchars) {
7430                                                 $nextchar = $chardata[($i+1)];
7431                                         } else {
7432                                                 $nextchar = false;
7433                                         }
7434                                         if ($unicode[$thischar['char']] == 'AL') {
7435                                                 $x = $thischar['x'];
7436                                                 if ($x > 0) {
7437                                                         $prevchar = $charAL[($x-1)];
7438                                                 } else {
7439                                                         $prevchar = false;
7440                                                 }
7441                                                 if (($x+1) < $numAL) {
7442                                                         $nextchar = $charAL[($x+1)];
7443                                                 } else {
7444                                                         $nextchar = false;
7445                                                 }
7446                                                 // if laa letter
7447                                                 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
7448                                                         $arabicarr = $laa_array;
7449                                                         $laaletter = true;
7450                                                         if ($x > 1) {
7451                                                                 $prevchar = $charAL[($x-2)];
7452                                                         } else {
7453                                                                 $prevchar = false;
7454                                                         }
7455                                                 } else {
7456                                                         $arabicarr = $unicode_arlet;
7457                                                         $laaletter = false;
7458                                                 }
7459                                                 if (($prevchar !== false) AND ($nextchar !== false) AND
7460                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7461                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7462                                                         ($prevchar['type'] == $thischar['type']) AND
7463                                                         ($nextchar['type'] == $thischar['type']) AND
7464                                                         ($nextchar['char'] != 1567)) {
7465                                                         if (in_array($prevchar['char'], $endedletter)) {
7466                                                                 if (isset($arabicarr[$thischar['char']][2])) {
7467                                                                         // initial
7468                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7469                                                                 }
7470                                                         } else {
7471                                                                 if (isset($arabicarr[$thischar['char']][3])) {
7472                                                                         // medial
7473                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
7474                                                                 }
7475                                                         }
7476                                                 } elseif (($nextchar !== false) AND
7477                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7478                                                         ($nextchar['type'] == $thischar['type']) AND
7479                                                         ($nextchar['char'] != 1567)) {
7480                                                         if (isset($arabicarr[$chardata[$i]['char']][2])) {
7481                                                                 // initial
7482                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7483                                                         }
7484                                                 } elseif ((($prevchar !== false) AND
7485                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7486                                                         ($prevchar['type'] == $thischar['type'])) OR
7487                                                         (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
7488                                                         // final
7489                                                         if (($i > 1) AND ($thischar['char'] == 1607) AND
7490                                                                 ($chardata[$i-1]['char'] == 1604) AND
7491                                                                 ($chardata[$i-2]['char'] == 1604)) {
7492                                                                 //Allah Word
7493                                                                 // mark characters to delete with false
7494                                                                 $chardata2[$i-2]['char'] = false;
7495                                                                 $chardata2[$i-1]['char'] = false;
7496                                                                 $chardata2[$i]['char'] = 65010;
7497                                                         } else {
7498                                                                 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
7499                                                                         if (isset($arabicarr[$thischar['char']][0])) {
7500                                                                                 // isolated
7501                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7502                                                                         }
7503                                                                 } else {
7504                                                                         if (isset($arabicarr[$thischar['char']][1])) {
7505                                                                                 // final
7506                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
7507                                                                         }
7508                                                                 }
7509                                                         }
7510                                                 } elseif (isset($arabicarr[$thischar['char']][0])) {
7511                                                         // isolated
7512                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7513                                                 }
7514                                                 // if laa letter
7515                                                 if ($laaletter) {
7516                                                         // mark characters to delete with false
7517                                                         $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
7518                                                 }
7519                                         } // end if AL (Arabic Letter)
7520                                 } // end for each char
7521                                 /*
7522                                  * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
7523                                  * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
7524                                  */
7525                                 $cw = &$this->CurrentFont['cw'];
7526                                 for ($i=0; $i < ($numchars-1); $i++) {
7527                                         if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
7528                                                 // check if the subtitution font is defined on current font
7529                                                 if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
7530                                                         $chardata2[$i]['char'] = false;
7531                                                         $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
7532                                                 }
7533                                         }
7534                                 }
7535                                 // remove marked characters
7536                                 foreach($chardata2 as $key => $value) {
7537                                         if ($value['char'] === false) {
7538                                                 unset($chardata2[$key]);
7539                                         }
7540                                 }
7541                                 $chardata = array_values($chardata2);
7542                                 $numchars = count($chardata);
7543                                 unset($chardata2);
7544                                 unset($arabicarr);
7545                                 unset($laaletter);
7546                                 unset($charAL);
7547                         }
7548
7549                         // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher.
7550                         for ($j=$maxlevel; $j > 0; $j--) {
7551                                 $ordarray = Array();
7552                                 $revarr = Array();
7553                                 $onlevel = false;
7554                                 for ($i=0; $i < $numchars; $i++) {
7555                                         if ($chardata[$i]['level'] >= $j) {
7556                                                 $onlevel = true;
7557                                                 if (isset($unicode_mirror[$chardata[$i]['char']])) {
7558                                                         // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true.
7559                                                         $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
7560                                                 }
7561                                                 $revarr[] = $chardata[$i];
7562                                         } else {
7563                                                 if ($onlevel) {
7564                                                         $revarr = array_reverse($revarr);
7565                                                         $ordarray = array_merge($ordarray, $revarr);
7566                                                         $revarr = Array();
7567                                                         $onlevel = false;
7568                                                 }
7569                                                 $ordarray[] = $chardata[$i];
7570                                         }
7571                                 }
7572                                 if ($onlevel) {
7573                                         $revarr = array_reverse($revarr);
7574                                         $ordarray = array_merge($ordarray, $revarr);
7575                                 }
7576                                 $chardata = $ordarray;
7577                         }
7578
7579                         $ordarray = array();
7580                         for ($i=0; $i < $numchars; $i++) {
7581                                 $ordarray[] = $chardata[$i]['char'];
7582                         }
7583
7584                         return $ordarray;
7585                 }
7586
7587                 // END OF BIDIRECTIONAL TEXT SECTION -------------------
7588
7589                 /*
7590                 * Adds a bookmark.
7591                 * @param string $txt bookmark description.
7592                 * @param int $level bookmark level (minimum value is 0).
7593                 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
7594                 * @access public
7595                 * @author Olivier Plathey, Nicola Asuni
7596                 * @since 2.1.002 (2008-02-12)
7597                 */
7598                 function Bookmark($txt, $level=0, $y=-1) {
7599                         if ($level < 0) {
7600                                 $level = 0;
7601                         }
7602                         if (isset($this->outlines[0])) {
7603                                 $lastoutline = end($this->outlines);
7604                                 $maxlevel = $lastoutline['l'] + 1;
7605                         } else {
7606                                 $maxlevel = 0;
7607                         }
7608                         if ($level > $maxlevel) {
7609                                 $level = $maxlevel;
7610                         }
7611                         if ($y == -1) {
7612                                 $y = $this->GetY();
7613                         }
7614                         $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $this->PageNo());
7615                 }
7616
7617                 /*
7618                 * Create a bookmark PDF string.
7619                 * @access protected
7620                 * @author Olivier Plathey, Nicola Asuni
7621                 * @since 2.1.002 (2008-02-12)
7622                 */
7623                 function _putbookmarks() {
7624                         $nb = count($this->outlines);
7625                         if ($nb == 0) {
7626                                 return;
7627                         }
7628                         $lru = array();
7629                         $level = 0;
7630                         foreach($this->outlines as $i => $o) {
7631                                 if ($o['l'] > 0) {
7632                                         $parent = $lru[($o['l'] - 1)];
7633                                         //Set parent and last pointers
7634                                         $this->outlines[$i]['parent'] = $parent;
7635                                         $this->outlines[$parent]['last'] = $i;
7636                                         if ($o['l'] > $level) {
7637                                                 //Level increasing: set first pointer
7638                                                 $this->outlines[$parent]['first'] = $i;
7639                                         }
7640                                 } else {
7641                                         $this->outlines[$i]['parent'] = $nb;
7642                                 }
7643                                 if (($o['l'] <= $level) AND ($i > 0)) {
7644                                         //Set prev and next pointers
7645                                         $prev = $lru[$o['l']];
7646                                         $this->outlines[$prev]['next'] = $i;
7647                                         $this->outlines[$i]['prev'] = $prev;
7648                                 }
7649                                 $lru[$o['l']] = $i;
7650                                 $level = $o['l'];
7651                         }
7652                         //Outline items
7653                         $n = $this->n + 1;
7654                         foreach($this->outlines as $i => $o) {
7655                                 $this->_newobj();
7656                                 $this->_out('<</Title '.$this->_textstring($o['t']));
7657                                 $this->_out('/Parent '.($n+$o['parent']).' 0 R');
7658                                 if (isset($o['prev']))
7659                                 $this->_out('/Prev '.($n+$o['prev']).' 0 R');
7660                                 if (isset($o['next']))
7661                                 $this->_out('/Next '.($n+$o['next']).' 0 R');
7662                                 if (isset($o['first']))
7663                                 $this->_out('/First '.($n+$o['first']).' 0 R');
7664                                 if (isset($o['last']))
7665                                 $this->_out('/Last '.($n+$o['last']).' 0 R');
7666                                 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]', 1+2*$o['p'], ($this->h-$o['y'])*$this->k));
7667                                 $this->_out('/Count 0>>');
7668                                 $this->_out('endobj');
7669                         }
7670                         //Outline root
7671                         $this->_newobj();
7672                         $this->OutlineRoot=$this->n;
7673                         $this->_out('<</Type /Outlines /First '.$n.' 0 R');
7674                         $this->_out('/Last '.($n+$lru[0]).' 0 R>>');
7675                         $this->_out('endobj');
7676                 }
7677
7678
7679                 // --- JAVASCRIPT - FORMS ------------------------------
7680
7681                 /*
7682                 * Adds a javascript
7683                 * @access public
7684                 * @author Johannes Güntert, Nicola Asuni
7685                 * @since 2.1.002 (2008-02-12)
7686                 */
7687                 function IncludeJS($script) {
7688                         $this->javascript .= $script;
7689                 }
7690
7691                 /*
7692                 * Create a javascript PDF string.
7693                 * @access protected
7694                 * @author Johannes Güntert, Nicola Asuni
7695                 * @since 2.1.002 (2008-02-12)
7696                 */
7697                 function _putjavascript() {
7698                         if (empty($this->javascript)) {
7699                                 return;
7700                         }
7701                         // the following two lines are uded to avoid form fields duplication after saving
7702                         $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2f,%.2f,%.2f,%.2f]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
7703                         $js2 = "getField('tcpdfdocsaved').value = 'saved';";
7704                         $this->_newobj();
7705                         $this->n_js = $this->n;
7706                         $this->_out('<<');
7707                         $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
7708                         $this->_out('>>');
7709                         $this->_out('endobj');
7710                         $this->_newobj();
7711                         $this->_out('<<');
7712                         $this->_out('/S /JavaScript');
7713                         $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
7714                         $this->_out('>>');
7715                         $this->_out('endobj');
7716                 }
7717
7718                 /*
7719                 * Convert color to javascript color.
7720                 * @param string $color color name or #RRGGBB
7721                 * @access protected
7722                 * @author Denis Van Nuffelen, Nicola Asuni
7723                 * @since 2.1.002 (2008-02-12)
7724                 */
7725                 function _JScolor($color) {
7726                         static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
7727                         if (substr($color,0,1) == '#') {
7728                                 return sprintf("['RGB',%.3f,%.3f,%.3f]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
7729                         }
7730                         if (!in_array($color,$aColors)) {
7731                                 $this->Error('Invalid color: '.$color);
7732                         }
7733                         return 'color.'.$color;
7734                 }
7735
7736                 /*
7737                 * Adds a javascript form field.
7738                 * @param string $type field type
7739                 * @param string $name field name
7740                 * @param int $x horizontal position
7741                 * @param int $y vertical position
7742                 * @param int $w width
7743                 * @param int $h height
7744                 * @param array $prop array of properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
7745                 * @access protected
7746                 * @author Denis Van Nuffelen, Nicola Asuni
7747                 * @since 2.1.002 (2008-02-12)
7748                 */
7749                 function _addfield($type, $name, $x, $y, $w, $h, $prop) {
7750                         // the followind avoid fields duplication after saving the document
7751                         $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
7752                         $k = $this->k;
7753                         $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%d,[%.2f,%.2f,%.2f,%.2f]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
7754                         $this->javascript .= "f".$name.".textSize=".$this->FontSizePt.";\n";
7755                         while (list($key, $val) = each($prop)) {
7756                                 if (strcmp(substr($key,-5),"Color") == 0) {
7757                                         $val = $this->_JScolor($val);
7758                                 } else {
7759                                         $val = "'".$val."'";
7760                                 }
7761                                 $this->javascript .= "f".$name.".".$key."=".$val.";\n";
7762                         }
7763                         $this->x += $w;
7764                         $this->javascript .= "}";
7765                 }
7766
7767                 /*
7768                 * Creates a text field
7769                 * @param string $name field name
7770                 * @param int $w width
7771                 * @param int $h height
7772                 * @param string $prop properties. The value property allows to set the initial value. The multiline property allows to define the field as multiline. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
7773                 * @access public
7774                 * @author Denis Van Nuffelen, Nicola Asuni
7775                 * @since 2.1.002 (2008-02-12)
7776                 */
7777                 function TextField($name, $w, $h, $prop=array()) {
7778                         $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
7779                 }
7780
7781                 /*
7782                 * Creates a RadioButton field
7783                 * @param string $name field name
7784                 * @param int $w width
7785                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
7786                 * @access public
7787                 * @author Nicola Asuni
7788                 * @since 2.2.003 (2008-03-03)
7789                 */
7790                 function RadioButton($name, $w, $prop=array()) {
7791                         if (!isset($prop['strokeColor'])) {
7792                                 $prop['strokeColor']='black';
7793                         }
7794                         $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
7795                 }
7796
7797                 /*
7798                 * Creates a List-box field
7799                 * @param string $name field name
7800                 * @param int $w width
7801                 * @param int $h height
7802                 * @param array $values array containing the list of values.
7803                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
7804                 * @access public
7805                 * @author Nicola Asuni
7806                 * @since 2.2.003 (2008-03-03)
7807                 */
7808                 function ListBox($name, $w, $h, $values, $prop=array()) {
7809                         if (!isset($prop['strokeColor'])) {
7810                                 $prop['strokeColor'] = 'ltGray';
7811                         }
7812                         $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
7813                         $s = '';
7814                         foreach($values as $value) {
7815                                 $s .= "'".addslashes($value)."',";
7816                         }
7817                         $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7818                 }
7819
7820                 /*
7821                 * Creates a Combo-box field
7822                 * @param string $name field name
7823                 * @param int $w width
7824                 * @param int $h height
7825                 * @param array $values array containing the list of values.
7826                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
7827                 * @access public
7828                 * @author Denis Van Nuffelen, Nicola Asuni
7829                 * @since 2.1.002 (2008-02-12)
7830                 */
7831                 function ComboBox($name, $w, $h, $values, $prop=array()) {
7832                         $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
7833                         $s = '';
7834                         foreach($values as $value) {
7835                                 $s .= "'".addslashes($value)."',";
7836                         }
7837                         $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7838                 }
7839
7840                 /*
7841                 * Creates a CheckBox field
7842                 * @param string $name field name
7843                 * @param int $w width
7844                 * @param boolean $checked define the initial state (default = false).
7845                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
7846                 * @access public
7847                 * @author Denis Van Nuffelen, Nicola Asuni
7848                 * @since 2.1.002 (2008-02-12)
7849                 */
7850                 function CheckBox($name, $w, $checked=false, $prop=array()) {
7851                         $prop['value'] = ($checked ? 'Yes' : 'Off');
7852                         if (!isset($prop['strokeColor'])) {
7853                                 $prop['strokeColor'] = 'black';
7854                         }
7855                         $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
7856                 }
7857
7858                 /*
7859                 * Creates a button field
7860                 * @param string $name field name
7861                 * @param int $w width
7862                 * @param int $h height
7863                 * @param string $caption caption.
7864                 * @param string $action action triggered by the button (JavaScript code).
7865                 * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf): <ul><li>rect: Position and size of field on page.</li><li>borderStyle: Rectangle border appearance.</li><li>strokeColor: Color of bounding rectangle.</li><li>lineWidth: Width of the edge of the surrounding rectangle.</li><li>rotation: Rotation of field in 90-degree increments.</li><li>fillColor: Background color of field (gray, transparent, RGB, or CMYK).</li><li>userName: Short description of field that appears on mouse-over.</li><li>readonly: Whether the user may change the field contents.</li><li>doNotScroll: Whether text fields may scroll.</li><li>display: Whether visible or hidden on screen or in print.</li><li>textFont: Text font.</li><li>textColor: Text color.</li><li>textSize: Text size.</li><li>richText: Rich text.</li><li>richValue: Text.</li><li>comb: Text comb format.</li><li>multiline: Text multiline.</li><li>charLimit: Text limit to number of characters.</li><li>fileSelect: Text file selection format.</li><li>password: Text password format.</li><li>alignment: Text layout in text fields.</li><li>buttonAlignX: X alignment of icon on button face.</li><li>buttonAlignY: Y alignment of icon on button face.</li><li>buttonFitBounds: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleHow: Relative scaling of an icon to fit inside a button face.</li><li>buttonScaleWhen: Relative scaling of an icon to fit inside a button face.</li><li>highlight: Appearance of a button when pushed.</li><li>style: Glyph style for checkbox and radio buttons.</li><li>numItems: Number of items in a combo box or list box.</li><li>editable: Whether the user can type in a combo box.</li><li>multipleSelection: Whether multiple list box items may be selected.</li></ul>
7866                 * @access public
7867                 * @author Denis Van Nuffelen, Nicola Asuni
7868                 * @since 2.1.002 (2008-02-12)
7869                 */
7870                 function Button($name, $w, $h, $caption, $action, $prop=array()) {
7871                         if (!isset($prop['strokeColor'])) {
7872                                 $prop['strokeColor'] = 'black';
7873                         }
7874                         if (!isset($prop['borderStyle'])) {
7875                                 $prop['borderStyle'] = 'beveled';
7876                         }
7877                         $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
7878                         $this->javascript .= "f".$name.".buttonSetCaption('".addslashes($caption)."');\n";
7879                         $this->javascript .= "f".$name.".setAction('MouseUp','".addslashes($action)."');\n";
7880                         $this->javascript .= "f".$name.".highlight='push';\n";
7881                         $this->javascript .= "f".$name.".print=false;\n";
7882                 }
7883
7884                 // END JAVASCRIPT - FORMS ------------------------------
7885
7886                 /*
7887                 * Enable Write permissions for PDF Reader.
7888                 * @access protected
7889                 * @author Nicola Asuni
7890                 * @since 2.9.000 (2008-03-26)
7891                 */
7892                 function _putuserrights() {
7893                         if (!$this->ur) {
7894                                 return;
7895                         }
7896                         $this->_out('/Perms');
7897                         $this->_out('<<');
7898                         $this->_out('/UR3');
7899                         $this->_out('<<');
7900                         //$this->_out('/SubFilter/adbe.pkcs7.detached/Filter/Adobe.PPKLite/Contents');
7901                         //$this->_out('<0>');
7902                         //$this->_out('/ByteRange[0 3]');
7903                         $this->_out('/M '.$this->_datestring('D:'.date('YmdHis')));
7904                         $this->_out('/Name(TCPDF)');
7905                         $this->_out('/Reference[');
7906                         $this->_out('<<');
7907                         $this->_out('/TransformParams');
7908                         $this->_out('<<');
7909                         $this->_out('/Type/TransformParams');
7910                         $this->_out('/V/2.2');
7911                         if (!empty($this->ur_document)) {
7912                                 $this->_out('/Document['.$this->ur_document.']');
7913                         }
7914                         if (!empty($this->ur_annots)) {
7915                                 $this->_out('/Annots['.$this->ur_annots.']');
7916                         }
7917                         if (!empty($this->ur_form)) {
7918                                 $this->_out('/Form['.$this->ur_form.']');
7919                         }
7920                         if (!empty($this->ur_signature)) {
7921                                 $this->_out('/Signature['.$this->ur_signature.']');
7922                         }
7923                         $this->_out('>>');
7924                         $this->_out('/TransformMethod/UR3');
7925                         $this->_out('/Type/SigRef');
7926                         $this->_out('>>');
7927                         $this->_out(']');
7928                         $this->_out('/Type/Sig');
7929                         $this->_out('>>');
7930                         $this->_out('>>');
7931                 }
7932
7933                 /*
7934                 * Set User's Rights for PDF Reader
7935                 * Check the PDF Reference 8.7.1 Transform Methods,
7936                 * Table 8.105 Entries in the UR transform parameters dictionary
7937                 * @param boolean $enable if true enable user's rights on PDF reader
7938                 * @param string $document Names specifying additional document-wide usage rights for the document. The only defined value is "/FullSave", which permits a user to save the document along with modified form and/or annotation data.
7939                 * @param string $annots Names specifying additional annotation-related usage rights for the document. Valid names in PDF 1.5 and later are /Create/Delete/Modify/Copy/Import/Export, which permit the user to perform the named operation on annotations.
7940                 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
7941                 * @param string $signature Names specifying additional signature-related usage rights for the document. The only defined value is /Modify, which permits a user to apply a digital signature to an existing signature form field or clear a signed signature form field.
7942                 * @access public
7943                 * @author Nicola Asuni
7944                 * @since 2.9.000 (2008-03-26)
7945                 */
7946                 function setUserRights(
7947                                 $enable=true,
7948                                 $document="/FullSave",
7949                                 $annots="/Create/Delete/Modify/Copy/Import/Export",
7950                                 $form="/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate",
7951                                 $signature="/Modify") {
7952                         $this->ur = $enable;
7953                         $this->ur_document = $document;
7954                         $this->ur_annots = $annots;
7955                         $this->ur_form = $form;
7956                         $this->ur_signature = $signature;
7957                 }
7958
7959                 /*
7960                 * Create a new page group.
7961                 * NOTE: call this function before calling AddPage()
7962                 * @access public
7963                 * @since 3.0.000 (2008-03-27)
7964                 */
7965                 function startPageGroup() {
7966                         $this->newpagegroup = true;
7967                 }
7968
7969                 /*
7970                 * Return the current page in the group.
7971                 * @return current page in the group
7972                 * @access public
7973                 * @since 3.0.000 (2008-03-27)
7974                 */
7975                 function getGroupPageNo() {
7976                         return $this->pagegroups[$this->currpagegroup];
7977                 }
7978
7979                 /*
7980                 * Return the alias of the current page group
7981         * If the current font is unicode type, the returned string is surrounded by additional curly braces.
7982                 * (will be replaced by the total number of pages in this group).
7983                 * @return alias of the current page group
7984                 * @access public
7985                 * @since 3.0.000 (2008-03-27)
7986                 */
7987                 function getPageGroupAlias() {
7988                         if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
7989                                 return "{".$this->currpagegroup."}";
7990             }
7991                         return $this->currpagegroup;
7992                 }
7993
7994                 /*
7995                 * Put visibility settings.
7996                 * @access protected
7997                 * @since 3.0.000 (2008-03-27)
7998                 */
7999                 function _putocg() {
8000                         $this->_newobj();
8001                         $this->n_ocg_print = $this->n;
8002                         $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
8003                         $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
8004                         $this->_out('endobj');
8005                         $this->_newobj();
8006                         $this->n_ocg_view=$this->n;
8007                         $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
8008                         $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
8009                         $this->_out('endobj');
8010                 }
8011
8012                 /*
8013                 * Set the visibility of the successive elements.
8014                 * This can be useful, for instance, to put a background
8015                 * image or color that will show on screen but won't print.
8016                 * @param string $v visibility mode. Legal values are: all, print, screen.
8017                 * @access public
8018                 * @since 3.0.000 (2008-03-27)
8019                 */
8020                 function setVisibility($v) {
8021                         if ($this->openMarkedContent) {
8022                                 // close existing open marked-content
8023                                 $this->_out('EMC');
8024                                 $this->openMarkedContent = false;
8025                         }
8026                         switch($v) {
8027                                 case "print": {
8028                                         $this->_out('/OC /OC1 BDC');
8029                                         $this->openMarkedContent = true;
8030                                         break;
8031                                 }
8032                                 case "screen": {
8033                                         $this->_out('/OC /OC2 BDC');
8034                                         $this->openMarkedContent = true;
8035                                         break;
8036                                 }
8037                                 case "all": {
8038                                         $this->_out('');
8039                                         break;
8040                                 }
8041                                 default: {
8042                                         $this->Error('Incorrect visibility: '.$v);
8043                                         break;
8044                                 }
8045                         }
8046                         $this->visibility = $v;
8047                 }
8048
8049                 /*
8050                 * Add transparency parameters to the current extgstate
8051                 * @param array $params parameters
8052                 * @return the number of extgstates
8053                 * @access protected
8054                 * @since 3.0.000 (2008-03-27)
8055                 */
8056                 function addExtGState($parms) {
8057                         $n = count($this->extgstates) + 1;
8058                         $this->extgstates[$n]['parms'] = $parms;
8059                         return $n;
8060                 }
8061
8062                 /*
8063                 * Add an extgstate
8064                 * @param array $gs extgstate
8065                 * @access protected
8066                 * @since 3.0.000 (2008-03-27)
8067                 */
8068                 function setExtGState($gs) {
8069                         $this->_out(sprintf('/GS%d gs', $gs));
8070                 }
8071
8072                 /*
8073                 * Put extgstates for object transparency
8074                 * @param array $gs extgstate
8075                 * @access protected
8076                 * @since 3.0.000 (2008-03-27)
8077                 */
8078                 function _putextgstates() {
8079                         $ne = count($this->extgstates);
8080                         for ($i = 1; $i <= $ne; $i++) {
8081                                 $this->_newobj();
8082                                 $this->extgstates[$i]['n'] = $this->n;
8083                                 $this->_out('<</Type /ExtGState');
8084                                 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
8085                                         $this->_out('/'.$k.' '.$v);
8086                                 }
8087                                 $this->_out('>>');
8088                                 $this->_out('endobj');
8089                         }
8090                 }
8091
8092                 /*
8093                 * Set alpha for stroking (CA) and non-stroking (ca) operations.
8094                 * @param float $alpha real value from 0 (transparent) to 1 (opaque)
8095                 * @param string $bm blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
8096                 * @access public
8097                 * @since 3.0.000 (2008-03-27)
8098                 */
8099                 function setAlpha($alpha, $bm='Normal') {
8100                         $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
8101                         $this->setExtGState($gs);
8102                 }
8103
8104                 /*
8105                 * Set the default JPEG compression quality (1-100)
8106                 * @param int $quality JPEG quality, integer between 1 and 100
8107                 * @access public
8108                 * @since 3.0.000 (2008-03-27)
8109                 */
8110                 function setJPEGQuality($quality) {
8111                         if (($quality < 1) OR ($quality > 100)) {
8112                                 $quality = 75;
8113                         }
8114                         $this->jpeg_quality = intval($quality);
8115                 }
8116
8117                 /*
8118                 * Set the default number of columns in a row for HTML tables.
8119                 * @param int $cols number of columns
8120                 * @access public
8121                 * @since 3.0.014 (2008-06-04)
8122                 */
8123                 function setDefaultTableColumns($cols=4) {
8124                         $this->default_table_columns = intval($cols);
8125                 }
8126
8127                 /*
8128                 * Set the height of cell repect font height.
8129                 * @param int $h cell proportion respect font height (typical value = 1.25).
8130                 * @access public
8131                 * @since 3.0.014 (2008-06-04)
8132                 */
8133                 function setCellHeightRatio($h) {
8134                         $this->cell_height_ratio = $h;
8135                 }
8136
8137                 /*
8138                 * return the height of cell repect font height.
8139                 * @access public
8140                 * @since 4.0.012 (2008-07-24)
8141                 */
8142                 function getCellHeightRatio() {
8143                         return $this->cell_height_ratio;
8144                 }
8145
8146                 /*
8147                 * Set the PDF version (check PDF reference for valid values).
8148                 * Default value is 1.t
8149                 * @access public
8150                 * @since 3.1.000 (2008-06-09)
8151                 */
8152                 function setPDFVersion($version="1.7") {
8153                         $this->PDFVersion = $version;
8154                 }
8155
8156                 /*
8157                 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
8158                 * (see Section 8.1 of PDF reference, "Viewer Preferences").
8159                 * <ul>
8160                 * <li>HideToolbar boolean (Optional) A flag specifying whether to hide the viewer application's tool bars when the document is active. Default value: false.</li>
8161                 * <li>HideMenubar boolean (Optional) A flag specifying whether to hide the viewer application's menu bar when the document is active. Default value: false.</li>
8162                 * <li>HideWindowUI boolean (Optional) A flag specifying whether to hide user interface elements in the document's window (such as scroll bars and navigation controls), leaving only the document's contents displayed. Default value: false.</li>
8163                 * <li>FitWindow boolean (Optional) A flag specifying whether to resize the document's window to fit the size of the first displayed page. Default value: false.</li>
8164                 * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
8165                 * <li>DisplayDocTitle boolean (Optional; PDF 1.4) A flag specifying whether the window's title bar should display the document title taken from the Title entry of the document information dictionary (see Section 10.2.1, "Document Information Dictionary"). If false, the title bar should instead display the name of the PDF file containing the document. Default value: false.</li>
8166                 * <li>NonFullScreenPageMode name (Optional) The document's page mode, specifying how to display the document on exiting full-screen mode:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>UseOC Optional content group panel visible</li><ul>This entry is meaningful only if the value of the PageMode entry in the catalog dictionary (see Section 3.6.1, "Document Catalog") is FullScreen; it is ignored otherwise. Default value: UseNone.</li>
8167                 * <li>ViewArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be displayed when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
8168                 * <li>ViewClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
8169                 * <li>PrintArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be rendered when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
8170                 * <li>PrintClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li>
8171                 * <li>PrintScaling name (Optional; PDF 1.6) The page scaling option to be selected when a print dialog is displayed for this document. Valid values are: <ul><li>None, which indicates that the print dialog should reflect no page scaling</li><li>AppDefault (default), which indicates that applications should use the current print scaling</li><ul></li>
8172                 * <li>Duplex name (Optional; PDF 1.7) The paper handling option to use when printing the file from the print dialog. The following values are valid:<ul><li>Simplex - Print single-sided</li><li>DuplexFlipShortEdge - Duplex and flip on the short edge of the sheet</li><li>DuplexFlipLongEdge - Duplex and flip on the long edge of the sheet</li></ul>Default value: none</li>
8173                 * <li>PickTrayByPDFSize boolean (Optional; PDF 1.7) A flag specifying whether the PDF page size is used to select the input paper tray. This setting influences only the preset values used to populate the print dialog presented by a PDF viewer application. If PickTrayByPDFSize is true, the check box in the print dialog associated with input paper tray is checked. Note: This setting has no effect on Mac OS systems, which do not provide the ability to pick the input tray by size.</li>
8174                 * <li>PrintPageRange array (Optional; PDF 1.7) The page numbers used to initialize the print dialog box when the file is printed. The first page of the PDF file is denoted by 1. Each pair consists of the first and last pages in the sub-range. An odd number of integers causes this entry to be ignored. Negative numbers cause the entire array to be ignored. Default value: as defined by PDF viewer application</li>
8175                 * <li>NumCopies integer (Optional; PDF 1.7) The number of copies to be printed when the print dialog is opened for this file. Supported values are the integers 2 through 5. Values outside this range are ignored. Default value: as defined by PDF viewer application, but typically 1</li>
8176                 * </ul>
8177                 * @param array $preferences array of options.
8178                 * @author Nicola Asuni
8179                 * @access public
8180                 * @since 3.1.000 (2008-06-09)
8181                 */
8182                 function setViewerPreferences($preferences) {
8183                         $this->viewer_preferences = $preferences;
8184                 }
8185
8186                 /**
8187                 * Paints a linear colour gradient.
8188                 * @param float $x abscissa of the top left corner of the rectangle.
8189                 * @param float $y ordinate of the top left corner of the rectangle.
8190                 * @param float $w width of the rectangle.
8191                 * @param float $h height of the rectangle.
8192                 * @param array $col1 first color (RGB components).
8193                 * @param array $col2 second color (RGB components).
8194                 * @param array $coords array of the form (x1, y1, x2, y2) which defines the gradient vector (see linear_gradient_coords.jpg). The default value is from left to right (x1=0, y1=0, x2=1, y2=0).
8195                 * @author Andreas Würmser, Nicola Asuni
8196                 * @since 3.1.000 (2008-06-09)
8197                 * @access public
8198                 */
8199                 function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
8200                         $this->Clip($x, $y, $w, $h);
8201                         $this->Gradient(2, $col1, $col2, $coords);
8202                 }
8203
8204                 /**
8205                 * Paints a radial colour gradient.
8206                 * @param float $x abscissa of the top left corner of the rectangle.
8207                 * @param float $y ordinate of the top left corner of the rectangle.
8208                 * @param float $w width of the rectangle.
8209                 * @param float $h height of the rectangle.
8210                 * @param array $col1 first color (RGB components).
8211                 * @param array $col2 second color (RGB components).
8212                 * @param array $coords array of the form (fx, fy, cx, cy, r) where (fx, fy) is the starting point of the gradient with color1, (cx, cy) is the center of the circle with color2, and r is the radius of the circle (see radial_gradient_coords.jpg). (fx, fy) should be inside the circle, otherwise some areas will not be defined.
8213                 * @author Andreas Würmser, Nicola Asuni
8214                 * @since 3.1.000 (2008-06-09)
8215                 * @access public
8216                 */
8217                 function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
8218                         $this->Clip($x, $y, $w, $h);
8219                         $this->Gradient(3, $col1, $col2, $coords);
8220                 }
8221
8222                 /**
8223                 * Paints a coons patch mesh.
8224                 * @param float $x abscissa of the top left corner of the rectangle.
8225                 * @param float $y ordinate of the top left corner of the rectangle.
8226                 * @param float $w width of the rectangle.
8227                 * @param float $h height of the rectangle.
8228                 * @param array $col1 first color (lower left corner) (RGB components).
8229                 * @param array $col2 second color (lower right corner) (RGB components).
8230                 * @param array $col3 third color (upper right corner) (RGB components).
8231                 * @param array $col4 fourth color (upper left corner) (RGB components).
8232                 * @param array $coords <ul><li>for one patch mesh: array(float x1, float y1, .... float x12, float y12): 12 pairs of coordinates (normally from 0 to 1) which specify the Bezier control points that define the patch. First pair is the lower left edge point, next is its right control point (control point 2). Then the other points are defined in the order: control point 1, edge point, control point 2 going counter-clockwise around the patch. Last (x12, y12) is the first edge point's left control point (control point 1).</li><li>for two or more patch meshes: array[number of patches]: arrays with the following keys for each patch: f: where to put that patch (0 = first patch, 1, 2, 3 = right, top and left of precedent patch - I didn't figure this out completely - just try and error ;-) points: 12 pairs of coordinates of the Bezier control points as above for the first patch, 8 pairs of coordinates for the following patches, ignoring the coordinates already defined by the precedent patch (I also didn't figure out the order of these - also: try and see what's happening) colors: must be 4 colors for the first patch, 2 colors for the following patches</li></ul>
8233                 * @param array $coords_min minimum value used by the coordinates. If a coordinate's value is smaller than this it will be cut to coords_min. default: 0
8234                 * @param array $coords_max maximum value used by the coordinates. If a coordinate's value is greater than this it will be cut to coords_max. default: 1
8235                 * @author Andreas Würmser, Nicola Asuni
8236                 * @since 3.1.000 (2008-06-09)
8237                 * @access public
8238                 */
8239                 function CoonsPatchMesh($x, $y, $w, $h, $col1=array(), $col2=array(), $col3=array(), $col4=array(), $coords=array(0.00,0.0,0.33,0.00,0.67,0.00,1.00,0.00,1.00,0.33,1.00,0.67,1.00,1.00,0.67,1.00,0.33,1.00,0.00,1.00,0.00,0.67,0.00,0.33), $coords_min=0, $coords_max=1) {
8240                         $this->Clip($x, $y, $w, $h);
8241                         $n = count($this->gradients) + 1;
8242                         $this->gradients[$n]['type'] = 6; //coons patch mesh
8243                         //check the coords array if it is the simple array or the multi patch array
8244                         if (!isset($coords[0]['f'])){
8245                                 //simple array -> convert to multi patch array
8246                                 if (!isset($col1[1])) {
8247                                         $col1[1] = $col1[2] = $col1[0];
8248                                 }
8249                                 if (!isset($col2[1])) {
8250                                         $col2[1] = $col2[2] = $col2[0];
8251                                 }
8252                                 if (!isset($col3[1])) {
8253                                         $col3[1] = $col3[2] = $col3[0];
8254                                 }
8255                                 if (!isset($col4[1])) {
8256                                         $col4[1] = $col4[2] = $col4[0];
8257                                 }
8258                                 $patch_array[0]['f'] = 0;
8259                                 $patch_array[0]['points'] = $coords;
8260                                 $patch_array[0]['colors'][0]['r'] = $col1[0];
8261                                 $patch_array[0]['colors'][0]['g'] = $col1[1];
8262                                 $patch_array[0]['colors'][0]['b'] = $col1[2];
8263                                 $patch_array[0]['colors'][1]['r'] = $col2[0];
8264                                 $patch_array[0]['colors'][1]['g'] = $col2[1];
8265                                 $patch_array[0]['colors'][1]['b'] = $col2[2];
8266                                 $patch_array[0]['colors'][2]['r'] = $col3[0];
8267                                 $patch_array[0]['colors'][2]['g'] = $col3[1];
8268                                 $patch_array[0]['colors'][2]['b'] = $col3[2];
8269                                 $patch_array[0]['colors'][3]['r'] = $col4[0];
8270                                 $patch_array[0]['colors'][3]['g'] = $col4[1];
8271                                 $patch_array[0]['colors'][3]['b'] = $col4[2];
8272                         } else {
8273                                 //multi patch array
8274                                 $patch_array = $coords;
8275                         }
8276                         $bpcd = 65535; //16 BitsPerCoordinate
8277                         //build the data stream
8278                         $this->gradients[$n]['stream'] = "";
8279                         for($i=0; $i < count($patch_array); $i++) {
8280                                 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
8281                                 for($j=0; $j < count($patch_array[$i]['points']); $j++) {
8282                                         //each point as 16 bit
8283                                         $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j]-$coords_min)/($coords_max-$coords_min))*$bpcd;
8284                                         if ($patch_array[$i]['points'][$j] < 0) {
8285                                                 $patch_array[$i]['points'][$j] = 0;
8286                                         }
8287                                         if ($patch_array[$i]['points'][$j] > $bpcd) {
8288                                                 $patch_array[$i]['points'][$j] = $bpcd;
8289                                         }
8290                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]/256));
8291                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]%256));
8292                                 }
8293                                 for($j=0; $j < count($patch_array[$i]['colors']); $j++) {
8294                                         //each color component as 8 bit
8295                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
8296                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
8297                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
8298                                 }
8299                         }
8300                         //paint the gradient
8301                         $this->_out('/Sh'.$n.' sh');
8302                         //restore previous Graphic State
8303                         $this->_out('Q');
8304                 }
8305
8306                 /**
8307                 * Set a rectangular clipping area.
8308                 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
8309                 * @param float $y ordinate of the top left corner of the rectangle.
8310                 * @param float $w width of the rectangle.
8311                 * @param float $h height of the rectangle.
8312                 * @author Andreas Würmser, Nicola Asuni
8313                 * @since 3.1.000 (2008-06-09)
8314                 * @access protected
8315                 */
8316                 function Clip($x, $y, $w, $h){
8317                         if ($this->rtl) {
8318                                 $x = $this->w - $x - $w;
8319                         }
8320                         //save current Graphic State
8321                         $s = 'q';
8322                         //set clipping area
8323                         $s .= sprintf(' %.2f %.2f %.2f %.2f re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
8324                         //set up transformation matrix for gradient
8325                         $s .= sprintf(' %.3f 0 0 %.3f %.3f %.3f cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
8326                         $this->_out($s);
8327                 }
8328
8329                 /**
8330                 * Output gradient.
8331                 * @param int $type type of gradient.
8332                 * @param array $col1 first color (RGB components).
8333                 * @param array $col2 second color (RGB components).
8334                 * @param array $coords array of coordinates.
8335                 * @author Andreas Würmser, Nicola Asuni
8336                 * @since 3.1.000 (2008-06-09)
8337                 * @access protected
8338                 */
8339                 function Gradient($type, $col1, $col2, $coords){
8340                         $n = count($this->gradients) + 1;
8341                         $this->gradients[$n]['type'] = $type;
8342                         if (!isset($col1[1])) {
8343                                 $col1[1]=$col1[2]=$col1[0];
8344                         }
8345                         $this->gradients[$n]['col1'] = sprintf('%.3f %.3f %.3f', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
8346                         if (!isset($col2[1])) {
8347                                 $col2[1] = $col2[2] = $col2[0];
8348                         }
8349                         $this->gradients[$n]['col2'] = sprintf('%.3f %.3f %.3f', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
8350                         $this->gradients[$n]['coords'] = $coords;
8351                         //paint the gradient
8352                         $this->_out('/Sh'.$n.' sh');
8353                         //restore previous Graphic State
8354                         $this->_out('Q');
8355                 }
8356
8357                 /**
8358                 * Output shaders.
8359                 * @author Andreas Würmser, Nicola Asuni
8360                 * @since 3.1.000 (2008-06-09)
8361                 * @access protected
8362                 */
8363                 function _putshaders() {
8364                         foreach($this->gradients as $id => $grad) {
8365                                 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
8366                                         $this->_newobj();
8367                                         $this->_out('<<');
8368                                         $this->_out('/FunctionType 2');
8369                                         $this->_out('/Domain [0.0 1.0]');
8370                                         $this->_out('/C0 ['.$grad['col1'].']');
8371                                         $this->_out('/C1 ['.$grad['col2'].']');
8372                                         $this->_out('/N 1');
8373                                         $this->_out('>>');
8374                                         $this->_out('endobj');
8375                                         $f1 = $this->n;
8376                                 }
8377                                 $this->_newobj();
8378                                 $this->_out('<<');
8379                                 $this->_out('/ShadingType '.$grad['type']);
8380                                 $this->_out('/ColorSpace /DeviceRGB');
8381                                 if ($grad['type'] == 2) {
8382                                         $this->_out(sprintf('/Coords [%.3f %.3f %.3f %.3f]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
8383                                         $this->_out('/Function '.$f1.' 0 R');
8384                                         $this->_out('/Extend [true true] ');
8385                                         $this->_out('>>');
8386                                 } elseif ($grad['type'] == 3) {
8387                                         //x0, y0, r0, x1, y1, r1
8388                                         //at this this time radius of inner circle is 0
8389                                         $this->_out(sprintf('/Coords [%.3f %.3f 0 %.3f %.3f %.3f]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]));
8390                                         $this->_out('/Function '.$f1.' 0 R');
8391                                         $this->_out('/Extend [true true] ');
8392                                         $this->_out('>>');
8393                                 } elseif ($grad['type'] == 6) {
8394                                         $this->_out('/BitsPerCoordinate 16');
8395                                         $this->_out('/BitsPerComponent 8');
8396                                         $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
8397                                         $this->_out('/BitsPerFlag 8');
8398                                         $this->_out('/Length '.strlen($grad['stream']));
8399                                         $this->_out('>>');
8400                                         $this->_putstream($grad['stream']);
8401                                 }
8402                                 $this->_out('endobj');
8403                                 $this->gradients[$id]['id'] = $this->n;
8404                         }
8405                 }
8406
8407                 /**
8408                 * Output an arc
8409                 * @author Maxime Delorme, Nicola Asuni
8410                 * @since 3.1.000 (2008-06-09)
8411                 * @access protected
8412                 */
8413                 function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
8414                         $h = $this->h;
8415                         $this->_out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c', $x1*$this->k, ($h-$y1)*$this->k, $x2*$this->k, ($h-$y2)*$this->k, $x3*$this->k, ($h-$y3)*$this->k));
8416                 }
8417
8418                 /**
8419                 * Draw the sector of a circle.
8420                 * It can be used for instance to render pie charts.
8421                 * @param float $xc abscissa of the center.
8422                 * @param float $yc ordinate of the center.
8423                 * @param float $r radius.
8424                 * @param float $a start angle (in degrees).
8425                 * @param float $b end angle (in degrees).
8426                 * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
8427                 * @param float $cw: indicates whether to go clockwise (default: true).
8428                 * @param float $o: origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). Default: 90.
8429                 * @author Maxime Delorme, Nicola Asuni
8430                 * @since 3.1.000 (2008-06-09)
8431                 * @access public
8432                 */
8433                 function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
8434                         if ($this->rtl) {
8435                                 $xc = $this->w - $xc - $w;
8436                         }
8437                         if ($cw) {
8438                                 $d = $b;
8439                                 $b = $o - $a;
8440                                 $a = $o - $d;
8441                         } else {
8442                                 $b += $o;
8443                                 $a += $o;
8444                         }
8445                         $a = ($a % 360) + 360;
8446                         $b = ($b % 360) + 360;
8447                         if ($a > $b) {
8448                                 $b +=360;
8449                         }
8450                         $b = $b / 360 * 2 * M_PI;
8451                         $a = $a / 360 * 2 * M_PI;
8452                         $d = $b - $a;
8453                         if ($d == 0 ) {
8454                                 $d = 2 * M_PI;
8455                         }
8456                         $k = $this->k;
8457                         $hp = $this->h;
8458                         if ($style=='F') {
8459                                 $op = 'f';
8460                         } elseif ($style=='FD' or $style=='DF') {
8461                                 $op = 'b';
8462                         } else {
8463                                 $op = 's';
8464                         }
8465                         if (sin($d/2)) {
8466                                 $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
8467                         }
8468                         //first put the center
8469                         $this->_out(sprintf('%.2f %.2f m', ($xc)*$k, ($hp-$yc)*$k));
8470                         //put the first point
8471                         $this->_out(sprintf('%.2f %.2f l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
8472                         //draw the arc
8473                         if ($d < (M_PI/2)) {
8474                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
8475                         } else {
8476                                 $b = $a + $d/4;
8477                                 $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
8478                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
8479                                 $a = $b;
8480                                 $b = $a + $d/4;
8481                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
8482                                 $a = $b;
8483                                 $b = $a + $d/4;
8484                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b) );
8485                                 $a = $b;
8486                                 $b = $a + $d/4;
8487                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
8488                         }
8489                         //terminate drawing
8490                         $this->_out($op);
8491                 }
8492
8493                 /**
8494                 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
8495                 * Only vector drawing is supported, not text or bitmap.
8496                 * Although the script was successfully tested with various AI format versions, best results are probably achieved with files that were exported in the AI3 format (tested with Illustrator CS2, Freehand MX and Photoshop CS2).
8497                 * @param string $file Name of the file containing the image.
8498                 * @param float $x Abscissa of the upper-left corner.
8499                 * @param float $y Ordinate of the upper-left corner.
8500                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
8501                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
8502                 * @param mixed $link URL or identifier returned by AddLink().
8503                 * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
8504                 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
8505                 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
8506                 * @author Valentin Schmidt, Nicola Asuni
8507                 * @since 3.1.000 (2008-06-09)
8508                 * @access public
8509                 */
8510                 function ImageEps($file, $x, $y, $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='') {
8511                         $data = file_get_contents($file);
8512                         if ($data === false) {
8513                                 $this->Error('EPS file not found: '.$file);
8514                         }
8515                         $regs = array();
8516                         // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
8517                         preg_match ('/%%Creator:([^\r\n]+)/', $data, $regs); # find Creator
8518                         if (count($regs) > 1) {
8519                                 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
8520                                 if (strpos($version_str, 'Adobe Illustrator') !== false) {
8521                                         $versexp = explode(' ', $version_str);
8522                                         $version = (float)array_pop($versexp);
8523                                         if ($version >= 9) {
8524                                                 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
8525                                         }
8526                                 }
8527                         }
8528                         // strip binary bytes in front of PS-header
8529                         $start = strpos($data, '%!PS-Adobe');
8530                         if ($start > 0) {
8531                                 $data = substr($data, $start);
8532                         }
8533                         // find BoundingBox params
8534                         preg_match ("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
8535                         if (count($regs) > 1) {
8536                                 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
8537                         } else {
8538                                 $this->Error('No BoundingBox found in EPS file: '.$file);
8539                         }
8540                         $start = strpos($data, '%%EndSetup');
8541                         if ($start === false) {
8542                                 $start = strpos($data, '%%EndProlog');
8543                         }
8544                         if ($start === false) {
8545                                 $start = strpos($data, '%%BoundingBox');
8546                         }
8547                         $data = substr($data, $start);
8548                         $end = strpos($data, '%%PageTrailer');
8549                         if ($end===false) {
8550                                 $end = strpos($data, 'showpage');
8551                         }
8552                         if ($end) {
8553                                 $data = substr($data, 0, $end);
8554                         }
8555                         $k = $this->k;
8556                         if ($w > 0) {
8557                                 $scale_x = $w/(($x2-$x1)/$k);
8558                                 if ($h > 0) {
8559                                         $scale_y = $h/(($y2-$y1)/$k);
8560                                 } else {
8561                                         $scale_y = $scale_x;
8562                                         $h = ($y2-$y1)/$k * $scale_y;
8563                                 }
8564                         } else {
8565                                 if ($h > 0) {
8566                                         $scale_y = $h/(($y2-$y1)/$k);
8567                                         $scale_x = $scale_y;
8568                                         $w = ($x2-$x1)/$k * $scale_x;
8569                                 } else {
8570                                         $w = ($x2 - $x1) / $k;
8571                                         $h = ($y2 - $y1) / $k;
8572                                 }
8573                         }
8574                         // Check whether we need a new page first as this does not fit
8575                         if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
8576                                 // Automatic page break
8577                                 $this->AddPage($this->CurOrientation);
8578                                 // Reset coordinates to top fo next page
8579                                 //$x = $this->GetX();
8580                                 $y = $this->GetY() + $this->cMargin;
8581                         }
8582                         // set bottomcoordinates
8583                         $this->img_rb_y = $y + $h;
8584                         // set alignment
8585                         if ($this->rtl) {
8586                                 if ($palign == 'L') {
8587                                         $ximg = $this->lMargin;
8588                                         // set right side coordinate
8589                                         $this->img_rb_x = $ximg + $w;
8590                                 } elseif ($palign == 'C') {
8591                                         $ximg = ($this->w - $x - $w) / 2;
8592                                         // set right side coordinate
8593                                         $this->img_rb_x = $ximg + $w;
8594                                 } else {
8595                                         $ximg = $this->w - $x - $w;
8596                                         // set left side coordinate
8597                                         $this->img_rb_x = $ximg;
8598                                 }
8599                         } else {
8600                                 if ($palign == 'R') {
8601                                         $ximg = $this->w - $this->rMargin - $w;
8602                                         // set left side coordinate
8603                                         $this->img_rb_x = $ximg;
8604                                 } elseif ($palign == 'C') {
8605                                         $ximg = ($this->w - $x - $w) / 2;
8606                                         // set right side coordinate
8607                                         $this->img_rb_x = $ximg + $w;
8608                                 } else {
8609                                         $ximg = $x;
8610                                         // set right side coordinate
8611                                         $this->img_rb_x = $ximg + $w;
8612                                 }
8613                         }
8614                         if ($useBoundingBox){
8615                                 $dx = $ximg * $k - $x1;
8616                                 $dy = $y * $k - $y1;
8617                         } else {
8618                                 $dx = $ximg * $k;
8619                                 $dy = $y * $k;
8620                         }
8621                         // save the current graphic state
8622                         $this->_out('q');
8623                         // translate
8624                         $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy+($this->hPt - 2*$y*$k - ($y2-$y1))));
8625                         // scale
8626                         if (isset($scale_x)) {
8627                                 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1*(1-$scale_x), $y2*(1-$scale_y)));
8628                         }
8629                         // handle pc/unix/mac line endings
8630                         $lines = split("\r\n|[\r\n]", $data);
8631                         $u=0;
8632                         $cnt = count($lines);
8633                         for ($i=0; $i < $cnt; $i++) {
8634                                 $line = $lines[$i];
8635                                 if (($line == '') OR ($line{0} == '%')) {
8636                                         continue;
8637                                 }
8638                                 $len = strlen($line);
8639                                 $chunks = explode(' ', $line);
8640                                 $cmd = array_pop($chunks);
8641                                 // RGB
8642                                 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
8643                                         $b = array_pop($chunks);
8644                                         $g = array_pop($chunks);
8645                                         $r = array_pop($chunks);
8646                                         $this->_out("$r $g $b ". ($cmd=='Xa'?'rg':'RG') ); //substr($line, 0, -2).'rg' -> in EPS (AI8): c m y k r g b rg!
8647                                         continue;
8648                                 }
8649                                 switch ($cmd) {
8650                                         case 'm':
8651                                         case 'l':
8652                                         case 'v':
8653                                         case 'y':
8654                                         case 'c':
8655                                         case 'k':
8656                                         case 'K':
8657                                         case 'g':
8658                                         case 'G':
8659                                         case 's':
8660                                         case 'S':
8661                                         case 'J':
8662                                         case 'j':
8663                                         case 'w':
8664                                         case 'M':
8665                                         case 'd':
8666                                         case 'n':
8667                                         case 'v': {
8668                                                 $this->_out($line);
8669                                                 break;
8670                                         }
8671                                         case 'x': {// custom fill color
8672                                                 list($c,$m,$y,$k) = $chunks;
8673                                                 $this->_out("$c $m $y $k k");
8674                                                 break;
8675                                         }
8676                                         case 'X': { // custom stroke color
8677                                                 list($c,$m,$y,$k) = $chunks;
8678                                                 $this->_out("$c $m $y $k K");
8679                                                 break;
8680                                         }
8681                                         case 'Y':
8682                                         case 'N':
8683                                         case 'V':
8684                                         case 'L':
8685                                         case 'C': {
8686                                                 $line{$len-1} = strtolower($cmd);
8687                                                 $this->_out($line);
8688                                                 break;
8689                                         }
8690                                         case 'b':
8691                                         case 'B': {
8692                                                 $this->_out($cmd . '*');
8693                                                 break;
8694                                         }
8695                                         case 'f':
8696                                         case 'F': {
8697                                                 if ($u > 0) {
8698                                                         $isU = false;
8699                                                         $max = min($i+5, $cnt);
8700                                                         for ($j=$i+1; $j < $max; $j++)
8701                                                           $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
8702                                                         if ($isU) {
8703                                                                 $this->_out("f*");
8704                                                         }
8705                                                 } else {
8706                                                         $this->_out("f*");
8707                                                 }
8708                                                 break;
8709                                         }
8710                                         case '*u': {
8711                                                 $u++;
8712                                                 break;
8713                                         }
8714                                         case '*U': {
8715                                                 $u--;
8716                                                 break;
8717                                         }
8718                                 }
8719                         }
8720                         // restore previous graphic state
8721                         $this->_out('Q');
8722                         if ($link) {
8723                                 $this->Link($ximg, $y, $w, $h, $link);
8724                         }
8725                         // set pointer to align the successive text/objects
8726                         switch($align) {
8727                                 case 'T':{
8728                                         $this->y = $y;
8729                                         $this->x = $this->img_rb_x;
8730                                         break;
8731                                 }
8732                                 case 'M':{
8733                                         $this->y = $y + round($h/2);
8734                                         $this->x = $this->img_rb_x;
8735                                         break;
8736                                 }
8737                                 case 'B':{
8738                                         $this->y = $this->img_rb_y;
8739                                         $this->x = $this->img_rb_x;
8740                                         break;
8741                                 }
8742                                 case 'N':{
8743                                         $this->SetY($this->img_rb_y);
8744                                         break;
8745                                 }
8746                                 default:{
8747                                         break;
8748                                 }
8749                         }
8750                         $this->endlinex = $this->img_rb_x;
8751                 }
8752
8753                 /**
8754                  * Set document barcode.
8755                  * @param string $bc barcode
8756                  */
8757                 function setBarcode($bc="") {
8758                         $this->barcode = $bc;
8759                 }
8760
8761                 /**
8762                  * Get current barcode.
8763                  * @return string
8764                  * @since 4.0.012 (2008-07-24)
8765                  */
8766                 function getBarcode() {
8767                         return $this->barcode;
8768                 }
8769
8770                 /**
8771                  * Print Barcode.
8772                  * @param string $code code to print
8773                  * @param string $type type of barcode.
8774                  * @param int $x x position in user units
8775                  * @param int $y y position in user units
8776                  * @param int $w width in user units
8777                  * @param int $h height position in user units
8778                  * @param float $xres width of the smallest bar in user units
8779                  * @param array $style array of options:<ul><li>string $style["position"] barcode position inside the specified width: L = left (default for LTR); C = center; R = right (default for RTL); S = stretch</li><li>boolean $style["border"] if true prints a border around the barcode</li><li>int $style["padding"] padding to leave around the barcode in user units</li><li>array $style["fgcolor"] color array for bars and text</li><li>mixed $style["bgcolor"] color array for background or false for transparent</li><li>boolean $style["text"] boolean if true prints text below the barcode</li><li>string $style["font"] font name for text</li><li>int $style["fontsize"] font size for text</li><li>int $style["stretchtext"]: 0 = disabled; 1 = horizontal scaling only if necessary; 2 = forced horizontal scaling; 3 = character spacing only if necessary; 4 = forced character spacing</li></ul>
8780                  * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
8781                  * @author Nicola Asuni
8782                  * @since 3.1.000 (2008-06-09)
8783                  * @access public
8784                  */
8785                 function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
8786                         if (empty($code)) {
8787                                 return;
8788                         }
8789                         $barcodeobj = new TCPDFbarcode($code, $type);
8790                         $arrcode = $barcodeobj->getBarcodeArray();
8791                         if ($arrcode === false) {
8792                                 $this->Error('Error in barcode string');
8793                         }
8794                         // set default values
8795                         if (!isset($style["position"])) {
8796                                 if ($this->rtl) {
8797                                         $style["position"] = "R";
8798                                 } else {
8799                                         $style["position"] = "L";
8800                                 }
8801                         }
8802                         if (!isset($style["padding"])) {
8803                                 $style["padding"] = 0;
8804                         }
8805                         if (!isset($style["fgcolor"])) {
8806                                 $style["fgcolor"] = array(0,0,0); // default black
8807                         }
8808                         if (!isset($style["bgcolor"])) {
8809                                 $style["bgcolor"] = false; // default transparent
8810                         }
8811                         if (!isset($style["border"])) {
8812                                 $style["border"] = false;
8813                         }
8814                         if (!isset($style["text"])) {
8815                                 $style["text"] = false;
8816                                 $fontsize = 0;
8817                         }
8818                         if ($style["text"] AND isset($style["font"])) {
8819                                 $prevFontFamily = $this->FontFamily;
8820                                 $prevFontStyle = $this->FontStyle;
8821                                 $prevFontSizePt = $this->FontSizePt;
8822                                 if (isset($style["fontsize"])) {
8823                                         $fontsize = $style["fontsize"];
8824                                 } else {
8825                                         $fontsize = 0;
8826                                 }
8827                                 $this->SetFont($style["font"], '', $fontsize);
8828                         }
8829                         if (!isset($style["stretchtext"])) {
8830                                 $style["stretchtext"] = 4;
8831                         }
8832                         // set foreground color
8833                         $prevDrawColor = $this->DrawColor;
8834                         $prevTextColor = $this->TextColor;
8835                         $this->SetDrawColorArray($style["fgcolor"]);
8836                         $this->SetTextColorArray($style["fgcolor"]);
8837                         if (empty($w) OR ($w <= 0)) {
8838                                 if ($this->rtl) {
8839                                         $w = $this->x - $this->lMargin;
8840                                 } else {
8841                                         $w = $this->w - $this->rMargin - $this->x;
8842                                 }
8843                         }
8844                         if (empty($x)) {
8845                                 $x = $this->GetX();
8846                         }
8847                         if ($this->rtl) {
8848                                 $x = $this->w - $x;
8849                         }
8850                         if (empty($y)) {
8851                                 $y = $this->GetY();
8852                         }
8853                         if (empty($xres)) {
8854                                 $xres = 0.4;
8855                         }
8856                         $fbw = ($arrcode["maxw"] * $xres) + (2 * $style["padding"]);
8857                         $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style["padding"]);
8858                         if (empty($h)) {
8859                                 $h = 10 + $extraspace;
8860                         }
8861                         if ((($y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
8862                                 //Automatic page break
8863                                 $x = $this->x;
8864                                 $ws = $this->ws;
8865                                 if ($ws > 0) {
8866                                         $this->ws = 0;
8867                                         $this->_out('0 Tw');
8868                                 }
8869                                 $this->AddPage($this->CurOrientation);
8870                                 if ($ws > 0) {
8871                                         $this->ws = $ws;
8872                                         $this->_out(sprintf('%.3f Tw',$ws * $k));
8873                                 }
8874                                 $this->x = $x;
8875                                 $y = $this->y;
8876                         }
8877                         // maximum bar heigth
8878                         $barh = $h - $extraspace;
8879                         switch ($style["position"]) {
8880                                 case "L": { // left
8881                                         if ($this->rtl) {
8882                                                 $xpos = $x - $w;
8883                                         } else {
8884                                                 $xpos = $x;
8885                                         }
8886                                         break;
8887                                 }
8888                                 case "C": { // center
8889                                         $xdiff = (($w - $fbw) / 2);
8890                                         if ($this->rtl) {
8891                                                 $xpos = $x - $w + $xdiff;
8892                                         } else {
8893                                                 $xpos = $x + $xdiff;
8894                                         }
8895                                         break;
8896                                 }
8897                                 case "R": { // right
8898                                         if ($this->rtl) {
8899                                                 $xpos = $x - $fbw;
8900                                         } else {
8901                                                 $xpos = $x + $w - $fbw;
8902                                         }
8903                                         break;
8904                                 }
8905                                 case "S": { // stretch
8906                                         $fbw = $w;
8907                                         $xres = ($w - (2 * $style["padding"])) / $arrcode["maxw"];
8908                                         if ($this->rtl) {
8909                                                 $xpos = $x - $w;
8910                                         } else {
8911                                                 $xpos = $x;
8912                                         }
8913                                         break;
8914                                 }
8915                         }
8916                         $xpos_rect = $xpos;
8917                         $xpos = $xpos_rect + $style["padding"];
8918                         $xpos_text = $xpos;
8919                         // barcode is always printed in LTR direction
8920                         $tempRTL = $this->rtl;
8921                         $this->rtl = false;
8922                         // print background color
8923                         if ($style["bgcolor"]) {
8924                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style["bgcolor"]);
8925                         } elseif ($style["border"]) {
8926                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
8927                         }
8928                         // print bars
8929                         if ($arrcode !== false) {
8930                                 foreach ($arrcode["bcode"] as $k => $v) {
8931                                         $bw = ($v["w"] * $xres);
8932                                         if ($v["t"]) {
8933                                                 // braw a vertical bar
8934                                                 $ypos = $y + $style["padding"] + ($v["p"] * $barh / $arrcode["maxh"]);
8935                                                 $this->Rect($xpos, $ypos, $bw, ($v["h"] * $barh  / $arrcode["maxh"]), 'DF', array("L"=>0,"T"=>0,"R"=>0,"B"=>0), $style["fgcolor"]);
8936                                         }
8937                                         $xpos += $bw;
8938                                 }
8939                         }
8940                         // print text
8941                         if ($style["text"]) {
8942                                 // print text
8943                                 $this->x = $xpos_text;
8944                                 $this->y = $y + $style["padding"] + $barh;
8945                                 $this->Cell(($arrcode["maxw"] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style["stretchtext"]);
8946                         }
8947                         // restore original direction
8948                         $this->rtl = $tempRTL;
8949                         // restore previous font
8950                         if ($style["text"] AND isset($style["font"])) {
8951                                 $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
8952                         }
8953                         // restore colors
8954                         $this->DrawColor = $prevDrawColor;
8955                         $this->TextColor = $prevTextColor;
8956                         // set bottomcoordinates
8957                         $this->img_rb_y = $y + $h;
8958                         if ($this->rtl) {
8959                                 // set left side coordinate
8960                                 $this->img_rb_x = ($this->w - $x - $w);
8961                         } else {
8962                                 // set right side coordinate
8963                                 $this->img_rb_x = $x + $w;
8964                         }
8965                         // set pointer to align the successive text/objects
8966                         switch($align) {
8967                                 case 'T':{
8968                                         $this->y = $y;
8969                                         $this->x = $this->img_rb_x;
8970                                         break;
8971                                 }
8972                                 case 'M':{
8973                                         $this->y = $y + round($h/2);
8974                                         $this->x = $this->img_rb_x;
8975                                         break;
8976                                 }
8977                                 case 'B':{
8978                                         $this->y = $this->img_rb_y;
8979                                         $this->x = $this->img_rb_x;
8980                                         break;
8981                                 }
8982                                 case 'N':{
8983                                         $this->SetY($this->img_rb_y);
8984                                         break;
8985                                 }
8986                                 default:{
8987                                         break;
8988                                 }
8989                         }
8990                 }
8991
8992                 /**
8993                  * This function is DEPRECATED, please use the new write1DBarcode() function.
8994                  * @param int $x x position in user units
8995                  * @param int $y y position in user units
8996                  * @param int $w width in user units
8997                  * @param int $h height position in user units
8998                  * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
8999                  * @param string $style barcode style
9000                  * @param string $font font for text
9001                  * @param int $xres x resolution
9002                  * @param string $code code to print
9003                  * @deprecated deprecated since version 3.1.000 (2008-06-10)
9004                  * @see write1DBarcode()
9005                  */
9006                 function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
9007                         // convert old settings for the new write1DBarcode() function.
9008                         $xres = 1 / $xres;
9009                         $newstyle = array(
9010                                 "position" => "L",
9011                                 "border" => false,
9012                                 "padding" => 0,
9013                                 "fgcolor" => array(0,0,0),
9014                                 "bgcolor" => false,
9015                                 "text" => true,
9016                                 "font" => $font,
9017                                 "fontsize" => 8,
9018                                 "stretchtext" => 4
9019                         );
9020                         if ($style & 1) {
9021                                 $newstyle["border"] = true;
9022                         }
9023                         if ($style & 2) {
9024                                 $newstyle["bgcolor"] = false;
9025                         }
9026                         if ($style & 4) {
9027                                 $newstyle["position"] = "C";
9028                         } elseif ($style & 8) {
9029                                 $newstyle["position"] = "L";
9030                         } elseif ($style & 16) {
9031                                 $newstyle["position"] = "R";
9032                         }
9033                         if ($style & 128) {
9034                                 $newstyle["text"] = true;
9035                         }
9036                         if ($style & 256) {
9037                                 $newstyle["stretchtext"] = 4;
9038                         }
9039                         $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
9040                 }
9041
9042                 /**
9043                  * Returns an array containing current margins:
9044                  * <ul>
9045                                 <li>$ret['left'] = left  margin</li>
9046                                 <li>$ret['right'] = right margin</li>
9047                                 <li>$ret['top'] = top margin</li>
9048                                 <li>$ret['bottom'] = bottom margin</li>
9049                                 <li>$ret['header'] = header margin</li>
9050                                 <li>$ret['footer'] = footer margin</li>
9051                                 <li>$ret['cell'] = cell margin</li>
9052                  * </ul>
9053                  * @return array containing all margins measures
9054                  * @since 3.2.000 (2008-06-23)
9055                  */
9056                 function getMargins() {
9057                         $ret = array(
9058                                 'left' => $this->lMargin,
9059                                 'right' => $this->rMargin,
9060                                 'top' => $this->tMargin,
9061                                 'bottom' => $this->bMargin,
9062                                 'header' => $this->header_margin,
9063                                 'footer' => $this->footer_margin,
9064                                 'cell' => $this->cMargin,
9065                         );
9066                         return $ret;
9067                 }
9068
9069                 /**
9070                  * Returns an array containing original margins:
9071                  * <ul>
9072                                 <li>$ret['left'] = left  margin</li>
9073                                 <li>$ret['right'] = right margin</li>
9074                  * </ul>
9075                  * @return array containing all margins measures
9076                  * @since 4.0.012 (2008-07-24)
9077                  */
9078                 function getOriginalMargins() {
9079                         $ret = array(
9080                                 'left' => $this->original_lMargin,
9081                                 'right' => $this->original_rMargin
9082                         );
9083                         return $ret;
9084                 }
9085
9086                 /**
9087                  * Returns the current font size.
9088                  * @return current font size
9089                  * @since 3.2.000 (2008-06-23)
9090                  */
9091                 function getFontSize() {
9092                         return $this->FontSize;
9093                 }
9094
9095                 /**
9096                  * Returns the current font size in points unit.
9097                  * @return current font size in points unit
9098                  * @since 3.2.000 (2008-06-23)
9099                  */
9100                 function getFontSizePt() {
9101                         return $this->FontSizePt;
9102                 }
9103
9104                 /**
9105                  * Prints a cell (rectangular area) with optional borders, background color and html text string.
9106                  * The upper-left corner of the cell corresponds to the current position. After the call, the current position moves to the right or to the next line.<br />
9107                  * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
9108                  * @param float $w Cell width. If 0, the cell extends up to the right margin.
9109                  * @param float $h Cell minimum height. The cell extends automatically if needed.
9110                  * @param float $x upper-left corner X coordinate
9111                  * @param float $y upper-left corner Y coordinate
9112                  * @param string $html html text to print. Default value: empty string.
9113                  * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
9114                  * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL language)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
9115         Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
9116                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
9117                  * @param boolean $reseth if true reset the last cell height (default true).
9118                  * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
9119                  * @uses MultiCell()
9120                  * @see Multicell(), writeHTML()
9121                  */
9122                 function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='') {
9123                         return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true);
9124                 }
9125
9126                 /**
9127                  * Returns the HTML DOM array.
9128                  * <ul><li>$dom[$key]['tag'] = true if tag, false otherwise;</li><li>$dom[$key]['value'] = tag name or text;</li><li>$dom[$key]['opening'] = true if opening tag, false otherwise;</li><li>$dom[$key]['attribute'] = array of attributes (attribute name is the key);</li><li>$dom[$key]['style'] = array of style attributes (attribute name is the key);</li><li>$dom[$key]['parent'] = id of parent element;</li><li>$dom[$key]['fontname'] = font family name;</li><li>$dom[$key]['fontstyle'] = font style;</li><li>$dom[$key]['fontsize'] = font size in points;</li><li>$dom[$key]['bgcolor'] = RGB array of background color;</li><li>$dom[$key]['fgcolor'] = RGB array of foreground color;</li><li>$dom[$key]['width'] = width in pixels;</li><li>$dom[$key]['height'] = height in pixels;</li><li>$dom[$key]['align'] = text alignment;</li><li>$dom[$key]['cols'] = number of colums in table;</li><li>$dom[$key]['rows'] = number of rows in table;</li></ul>
9129                  * @param string $html html code
9130                  * @return array
9131                  * @since 3.2.000 (2008-06-20)
9132                  */
9133                 function getHtmlDomArray($html) {
9134                         // remove all unsupported tags (the line below lists all supported tags)
9135                         $html = strip_tags($html, "<a><b><blockquote><br><br/><dd><del><div><dl><dt><em><font><h1><h2><h3><h4><h5><h6><hr><i><img><li><ol><p><small><span><strong><sub><sup><table><td><th><tr><u><ul>");
9136                         //replace carriage returns, newlines and tabs
9137                         $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ", "\\" => "\\\\");
9138                         $html = strtr($html, $repTable);
9139                         // remove extra spaces from tables
9140                         $html = preg_replace('/[\s]*<\/table>[\s]*/', '</table>', $html);
9141                         $html = preg_replace('/[\s]*<\/tr>[\s]*/', '</tr>', $html);
9142                         $html = preg_replace('/[\s]*<tr/', '<tr', $html);
9143                         $html = preg_replace('/[\s]*<\/th>[\s]*/', '</th>', $html);
9144                         $html = preg_replace('/[\s]*<th/', '<th', $html);
9145                         $html = preg_replace('/[\s]*<\/td>[\s]*/', '</td>', $html);
9146                         $html = preg_replace('/[\s]*<td/', '<td', $html);
9147                         $html = preg_replace('/<\/th>/', '<span></span></th>', $html);
9148                         $html = preg_replace('/<\/td>/', '<span></span></td>', $html);
9149                         // pattern for generic tag
9150                         $tagpattern = '/(<[^>]+>)/Uu';
9151                         // explodes the string
9152                         $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
9153                         // count elements
9154                         $maxel = count($a);
9155                         $key = 0;
9156                         // create an array of elements
9157                         $dom = array();
9158                         $dom[$key] = array();
9159                         // set first void element
9160                         $dom[$key]['tag'] = false;
9161                         $dom[$key]['value'] = "";
9162                         $dom[$key]['parent'] = 0;
9163                         $dom[$key]['fontname'] = $this->FontFamily;
9164                         $dom[$key]['fontstyle'] = $this->FontStyle;
9165                         $dom[$key]['fontsize'] = $this->FontSizePt;
9166                         $dom[$key]['bgcolor'] = false;
9167                         $dom[$key]['fgcolor'] = $this->fgcolor;
9168                         $dom[$key]['align'] = '';
9169                         $key++;
9170                         $level = array();
9171                         array_push($level, 0); // root
9172                         while ($key <= $maxel) {
9173                                 if ($key > 0) {
9174                                         $dom[$key] = array();
9175                                 }
9176                                 $element = $a[($key-1)];
9177                                 if (preg_match($tagpattern, $element)) {
9178                                         // html tag
9179                                         $dom[$key]['tag'] = true;
9180                                         $element = substr($element, 1, -1);
9181                                         // get tag name
9182                                         preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
9183                                         $dom[$key]['value'] = strtolower($tag[1]);
9184                                         if ($element{0} == '/') {
9185                                                 // closing html tag
9186                                                 $dom[$key]['opening'] = false;
9187                                                 $dom[$key]['parent'] = end($level);
9188                                                 array_pop($level);
9189                                                 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
9190                                                 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
9191                                                 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
9192                                                 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
9193                                                 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
9194                                                 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
9195                                                 // set the number of columns in table tag
9196                                                 if (($dom[$key]['value'] == "tr") AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
9197                                                         $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
9198                                                 }
9199                                                 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9200                                                         $dom[($dom[$key]['parent'])]['content'] = "";
9201                                                         for ($i = ($dom[$key]['parent'] + 1); $i < $key; $i++) {
9202                                                                 $dom[($dom[$key]['parent'])]['content'] .= $a[($i-1)];
9203                                                         }
9204                                                         $key = $i;
9205                                                 }
9206                                         } else {
9207                                                 // opening html tag
9208                                                 $dom[$key]['opening'] = true;
9209                                                 $dom[$key]['parent'] = end($level);
9210                                                 if (substr($element, -1, 1) != '/') {
9211                                                         // not self-closing tag
9212                                                         array_push($level, $key);
9213                                                         $dom[$key]['self'] = false;
9214                                                 } else {
9215                                                         $dom[$key]['self'] = true;
9216                                                 }
9217                                                 // copy some values from parent
9218                                                 if ($key > 0) {
9219                                                         $dom[$key]['fontname'] = $dom[($dom[$key]['parent'])]['fontname'];
9220                                                         $dom[$key]['fontstyle'] = $dom[($dom[$key]['parent'])]['fontstyle'];
9221                                                         $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'];
9222                                                         $dom[$key]['bgcolor'] = $dom[($dom[$key]['parent'])]['bgcolor'];
9223                                                         $dom[$key]['fgcolor'] = $dom[($dom[$key]['parent'])]['fgcolor'];
9224                                                         $dom[$key]['align'] = $dom[($dom[$key]['parent'])]['align'];
9225                                                 }
9226                                                 // get attributes
9227                                                 preg_match_all('/([^=\s]*)=["\']?([^"\']*)["\']?/', $element, $attr_array, PREG_PATTERN_ORDER);
9228                                                 $dom[$key]['attribute'] = array(); // reset attribute array
9229                                                 while (list($id, $name) = each($attr_array[1])) {
9230                                                         $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
9231                                                 }
9232                                                 // split style attributes
9233                                                 if (isset($dom[$key]['attribute']['style'])) {
9234                                                         // get style attributes
9235                                                         preg_match_all('/([^:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
9236                                                         $dom[$key]['style'] = array(); // reset style attribute array
9237                                                         while (list($id, $name) = each($style_array[1])) {
9238                                                                 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
9239                                                         }
9240                                                         // --- get some style attributes ---
9241                                                         if (isset($dom[$key]['style']['font-family'])) {
9242                                                                 // font family
9243                                                                 if (isset($dom[$key]['style']['font-family'])) {
9244                                                                         $fontslist = split(",", strtolower($dom[$key]['style']['font-family']));
9245                                                                         foreach($fontslist as $font) {
9246                                                                                 $font = trim(strtolower($font));
9247                                                                                 if (in_array($font, $this->fontlist)){
9248                                                                                         $dom[$key]['fontname'] = $font;
9249                                                                                         break;
9250                                                                                 }
9251                                                                         }
9252                                                                 }
9253                                                         }
9254                                                         // font size
9255                                                         if (isset($dom[$key]['style']['font-size'])) {
9256                                                                 $fsize = trim($dom[$key]['style']['font-size']);
9257                                                                 switch ($fsize) {
9258                                                                         case 'xx-small': {
9259                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
9260                                                                                 break;
9261                                                                         }
9262                                                                         case 'x-small': {
9263                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
9264                                                                                 break;
9265                                                                         }
9266                                                                         case 'small': {
9267                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
9268                                                                                 break;
9269                                                                         }
9270                                                                         case 'medium': {
9271                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
9272                                                                                 break;
9273                                                                         }
9274                                                                         case 'large': {
9275                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
9276                                                                                 break;
9277                                                                         }
9278                                                                         case 'x-large': {
9279                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
9280                                                                                 break;
9281                                                                         }
9282                                                                         case 'xx-large': {
9283                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
9284                                                                                 break;
9285                                                                         }
9286                                                                         default: {
9287                                                                                 $dom[$key]['fontsize'] = intval($fsize);
9288                                                                         }
9289                                                                 }
9290                                                         }
9291                                                         // font style
9292                                                         $dom[$key]['fontstyle'] = "";
9293                                                         if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == "b")) {
9294                                                                 $dom[$key]['fontstyle'] .= "B";
9295                                                         }
9296                                                         if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == "i")) {
9297                                                                 $dom[$key]['fontstyle'] .= "I";
9298                                                         }
9299                                                         // font color
9300                                                         if (isset($dom[$key]['style']['color']) AND (!empty($dom[$key]['style']['color']))) {
9301                                                                 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
9302                                                         }
9303                                                         // background color
9304                                                         if (isset($dom[$key]['style']['background-color']) AND (!empty($dom[$key]['style']['background-color']))) {
9305                                                                 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
9306                                                         }
9307                                                         // text-decoration
9308                                                         if (isset($dom[$key]['style']['text-decoration'])) {
9309                                                                 $decors = explode(" ", strtolower($dom[$key]['style']['text-decoration']));
9310                                                                 foreach ($decors as $dec) {
9311                                                                         $dec = trim($dec);
9312                                                                         if ($dec{0} == "u") {
9313                                                                                 $dom[$key]['fontstyle'] .= "U";
9314                                                                         } elseif ($dec{0} == "l") {
9315                                                                                 $dom[$key]['fontstyle'] .= "D";
9316                                                                         }
9317                                                                 }
9318                                                         }
9319                                                         // check for width attribute
9320                                                         if (isset($dom[$key]['style']['width'])) {
9321                                                                 $dom[$key]['width'] = intval($dom[$key]['style']['width']);
9322                                                         }
9323                                                         // check for height attribute
9324                                                         if (isset($dom[$key]['style']['height'])) {
9325                                                                 $dom[$key]['height'] = intval($dom[$key]['style']['height']);
9326                                                         }
9327                                                         // check for text alignment
9328                                                         if (isset($dom[$key]['style']['text-align'])) {
9329                                                                 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
9330                                                         }
9331                                                 }
9332                                                 // check for font tag
9333                                                 if ($dom[$key]['value'] == "font") {
9334                                                         // font family
9335                                                         if (isset($dom[$key]['attribute']['face'])) {
9336                                                                 $fontslist = split(",", strtolower($dom[$key]['attribute']['face']));
9337                                                                 foreach($fontslist as $font) {
9338                                                                         $font = trim(strtolower($font));
9339                                                                         if (in_array($font, $this->fontlist)){
9340                                                                                 $dom[$key]['fontname'] = $font;
9341                                                                                 break;
9342                                                                         }
9343                                                                 }
9344                                                         }
9345                                                         // font size
9346                                                         if (isset($dom[$key]['attribute']['size'])) {
9347                                                                 if ($key > 0) {
9348                                                                         if ($dom[$key]['attribute']['size']{0} == "+") {
9349                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
9350                                                                         } elseif ($dom[$key]['attribute']['size']{0} == "-") {
9351                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
9352                                                                         } else {
9353                                                                                 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9354                                                                         }
9355                                                                 } else {
9356                                                                         $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9357                                                                 }
9358                                                         }
9359                                                 }
9360                                                 if (($dom[$key]['value'] == "ul") OR ($dom[$key]['value'] == "ol") OR ($dom[$key]['value'] == "dl")) {
9361                                                         // force natural alignment for lists
9362                                                         if ($this->rtl) {
9363                                                                 $dom[$key]['align'] = "R";
9364                                                         } else {
9365                                                                 $dom[$key]['align'] = "L";
9366                                                         }
9367                                                 }
9368                                                 if (($dom[$key]['value'] == "small") OR ($dom[$key]['value'] == "sup") OR ($dom[$key]['value'] == "sub")) {
9369                                                         $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
9370                                                 }
9371                                                 if (($dom[$key]['value'] == "strong") OR ($dom[$key]['value'] == "b")) {
9372                                                         $dom[$key]['fontstyle'] .= "B";
9373                                                 }
9374                                                 if (($dom[$key]['value'] == "em") OR ($dom[$key]['value'] == "i")) {
9375                                                         $dom[$key]['fontstyle'] .= "I";
9376                                                 }
9377                                                 if (($dom[$key]['value']{0} == "h") AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
9378                                                         $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
9379                                                         $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
9380                                                         $dom[$key]['fontstyle'] .= "B";
9381                                                 }
9382                                                 if (($dom[$key]['value'] == "table")) {
9383                                                         $dom[$key]['rows'] = 0; // number of rows
9384                                                         $dom[$key]['trids'] = array(); // IDs of TR elements
9385                                                 }
9386                                                 if (($dom[$key]['value'] == "tr")) {
9387                                                         $dom[$key]['cols'] = 0;
9388                                                         // store the number of rows on table element
9389                                                         $dom[($dom[$key]['parent'])]['rows']++;
9390                                                         // store the TR elements IDs on table element
9391                                                         array_push($dom[($dom[$key]['parent'])]['trids'], $key);
9392                                                 }
9393                                                 if (($dom[$key]['value'] == "th") OR ($dom[$key]['value'] == "td")) {
9394                                                         if (isset($dom[$key]['attribute']['colspan'])) {
9395                                                                 $colspan = intval($dom[$key]['attribute']['colspan']);
9396                                                         } else {
9397                                                                 $colspan = 1;
9398                                                         }
9399                                                         $dom[$key]['attribute']['colspan'] = $colspan;
9400                                                         $dom[($dom[$key]['parent'])]['cols'] += $colspan;
9401                                                 }
9402                                                 // set foreground color attribute
9403                                                 if (isset($dom[$key]['attribute']['color']) AND (!empty($dom[$key]['attribute']['color']))) {
9404                                                         $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
9405                                                 }
9406                                                 // set background color attribute
9407                                                 if (isset($dom[$key]['attribute']['bgcolor']) AND (!empty($dom[$key]['attribute']['bgcolor']))) {
9408                                                         $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
9409                                                 }
9410                                                 // check for width attribute
9411                                                 if (isset($dom[$key]['attribute']['width'])) {
9412                                                         $dom[$key]['width'] = intval($dom[$key]['attribute']['width']);
9413                                                 }
9414                                                 // check for height attribute
9415                                                 if (isset($dom[$key]['attribute']['height'])) {
9416                                                         $dom[$key]['height'] = intval($dom[$key]['attribute']['height']);
9417                                                 }
9418                                                 // check for text alignment
9419                                                 if (isset($dom[$key]['attribute']['align']) AND (!empty($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
9420                                                         $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
9421                                                 }
9422                                         } // end opening tag
9423                                 } else {
9424                                         // text
9425                                         $dom[$key]['tag'] = false;
9426                                         $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
9427                                         $dom[$key]['parent'] = end($level);
9428                                         // calculate text width
9429                                         //$dom[$key]['width'] = $this->GetStringWidth($dom[$key]['value'], $dom[($dom[$key]['parent'])]['fontname'], $dom[($dom[$key]['parent'])]['fontstyle'], $dom[($dom[$key]['parent'])]['fontsize']);
9430                                 }
9431                                 $key++;
9432                         }
9433                         return $dom;
9434                 }
9435
9436                 /**
9437                  * Allows to preserve some HTML formatting (limited support).<br />
9438                  * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
9439                  * Supported tags are: a, b, blockquote, br, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, li, ol, p, small, span, strong, sub, sup, table, td, th, tr, u, ul,
9440                  * @param string $html text to display
9441                  * @param boolean $ln if true add a new line after text (default = true)
9442                  * @param int $fill Indicates if the background must be painted (true) or transparent (false).
9443                  * @param boolean $reseth if true reset the last cell height (default false).
9444                  * @param boolean $cell if true add the default cMargin space to each Write (default false).
9445                  * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
9446                  */
9447                 function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
9448                         // store current values
9449                         $prevlMargin = $this->lMargin;
9450                         $prevrMargin = $this->rMargin;
9451                         $prevcMargin = $this->cMargin;
9452                         $prevFontFamily = $this->FontFamily;
9453                         $prevFontStyle = $this->FontStyle;
9454                         $prevFontSizePt = $this->FontSizePt;
9455                         $curfontname = $prevFontFamily;
9456                         $curfontstyle = $prevFontStyle;
9457                         $curfontsize = $prevFontSizePt;
9458                         $prevbgcolor = $this->bgcolor;
9459                         $prevfgcolor = $this->fgcolor;
9460                         $this->newline = true;
9461                         $minstartliney = $this->y;
9462                         $yshift = 0;
9463                         $startlinepage = $this->page;
9464                         $newline = true;
9465                         if (isset($this->footerlen[$this->page])) {
9466                                 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9467                         } else {
9468                                 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9469                         }
9470                         $startlinepos = $this->footerpos[$this->page];
9471                         $lalign = $align;
9472                         $plalign = $align;
9473                         if ($this->rtl) {
9474                                 $w = $this->x - $this->lMargin;
9475                         } else {
9476                                 $w = $this->w - $this->rMargin - $this->x;
9477                         }
9478                         $w -= (2 * $this->cMargin);
9479                         if ($cell) {
9480                                 if ($this->rtl) {
9481                                         $this->x -= $this->cMargin;
9482                                 } else {
9483                                         $this->x += $this->cMargin;
9484                                 }
9485                         }
9486                         $this->listindent = $this->GetStringWidth("0000");
9487                         $this->listnum = 0;
9488                         if ((empty($this->lasth))OR ($reseth)) {
9489                                 //set row height
9490                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9491                         }
9492                         $dom = $this->getHtmlDomArray($html);
9493                         $maxel = count($dom);
9494                         $key = 0;
9495                         while ($key < $maxel) {
9496                                 if ($dom[$key]['tag'] OR ($key == 0)) {
9497                                         if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
9498                                                 $dom[$key]['align'] = ($this->rtl)?'R':'L';
9499                                         }
9500                                         // vertically align image in line
9501                                         if ((!$this->newline) AND ($dom[$key]['value'] == 'img') 
9502                                                 AND (isset($dom[$key]['attribute']['height']))
9503                                                 AND ($dom[$key]['attribute']['height'] > 0)
9504                                                 ) {
9505                                                 $this->y += (($curfontsize / $this->k) - $this->pixelsToUnits($dom[$key]['attribute']['height']));
9506                                                 $minstartliney = min($this->y, $minstartliney);
9507                                         } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
9508                                                 // account for different font size
9509                                                 $pfontname = $curfontname;
9510                                                 $pfontstyle = $curfontstyle;
9511                                                 $pfontsize = $curfontsize;
9512                                                 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
9513                                                 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
9514                                                 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
9515                                                 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
9516                                                         $this->SetFont($fontname, $fontstyle, $fontsize);
9517                                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
9518                                                         if (is_numeric($fontsize) AND ($fontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($fontsize != $curfontsize) AND (!$this->newline)) {
9519                                                                 $this->y += (($curfontsize - $fontsize) / $this->k);
9520                                                                 $minstartliney = min($this->y, $minstartliney);
9521                                                         }
9522                                                         $curfontname = $fontname;
9523                                                         $curfontstyle = $fontstyle;
9524                                                         $curfontsize = $fontsize;
9525                                                 }
9526                                         }
9527                                         if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
9528                                                 $this->SetFillColorArray($dom[$key]['bgcolor']);
9529                                                 $wfill = true;
9530                                         } else {
9531                                                 $wfill = $fill | false;
9532                                         }
9533                                         if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
9534                                                 $this->SetTextColorArray($dom[$key]['fgcolor']);
9535                                         }
9536                                         if (isset($dom[$key]['align'])) {
9537                                                 $lalign = $dom[$key]['align'];
9538                                         }
9539                                         if (empty($lalign)) {
9540                                                 $lalign = $align;
9541                                         }
9542                                 }
9543                                 // align lines
9544                                 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
9545                                         $newline = true;
9546                                         // we are at the beginning of a new line
9547                                         if (isset($startlinex)) {
9548                                                 $yshift = $minstartliney - $startliney;
9549                                                 if ($yshift > 0) {
9550                                                         $yshift = 0;
9551                                                 }
9552                                                 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9553                                                         // the last line must be shifted to be aligned as requested
9554                                                         $linew = abs($this->endlinex - $startlinex);
9555                                                         $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9556                                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9557                                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9558                                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9559                                                         } elseif (isset($opentagpos)) {
9560                                                                 $midpos = $opentagpos;
9561                                                         } elseif (isset($this->footerlen[$startlinepage])) {
9562                                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9563                                                                 $midpos = $this->footerpos[$startlinepage];
9564                                                         } else {
9565                                                                 $midpos = 0;
9566                                                         }
9567                                                         if ($midpos > 0) {
9568                                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9569                                                                 $pend = substr($this->pages[$startlinepage], $midpos);
9570                                                         } else {
9571                                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9572                                                                 $pend = "";
9573                                                         }
9574                                                         // calculate shifting amount
9575                                                         $mdiff = abs($w - $linew);
9576                                                         if ($plalign == "C") {
9577                                                                 if ($this->rtl) {
9578                                                                         $t_x = -($mdiff / 2);
9579                                                                 } else {
9580                                                                         $t_x = ($mdiff / 2);
9581                                                                 }
9582                                                         }       elseif (($plalign == "R") AND (!$this->rtl)) {
9583                                                                 // right alignment on LTR document
9584                                                                 $t_x = $mdiff;
9585                                                         }       elseif (($plalign == "L") AND ($this->rtl)) {
9586                                                                 // left alignment on RTL document
9587                                                                 $t_x = -$mdiff;
9588                                                         } else {
9589                                                                 $t_x = 0;
9590                                                         }
9591                                                         if (($t_x != 0) OR ($yshift < 0)) {
9592                                                                 // shift the line
9593                                                                 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9594                                                                 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9595                                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9596                                                                 // shift the annotations and links
9597                                                                 if (isset($this->PageAnnots[$this->page])) {
9598                                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9599                                                                                 if ($pac['y'] >= $minstartliney) {
9600                                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9601                                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9602                                                                                 }
9603                                                                         }
9604                                                                 }
9605                                                                 $this->y -= $yshift;
9606                                                         }
9607                                                 }
9608                                         }
9609                                         $this->checkPageBreak($this->lasth);
9610                                         $this->SetFont($fontname, $fontstyle, $fontsize);
9611                                         if ($wfill) {
9612                                                 $this->SetFillColorArray($this->bgcolor);
9613                                         }
9614                                         $startlinex = $this->x;
9615                                         $startliney = $this->y;
9616                                         $minstartliney = $this->y;
9617                                         $startlinepage = $this->page;
9618                                         if (isset($endlinepos)) {
9619                                                 $startlinepos = $endlinepos;
9620                                                 unset($endlinepos);
9621                                         } else {
9622                                                 if (isset($this->footerlen[$this->page])) {
9623                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9624                                                 } else {
9625                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9626                                                 }
9627                                                 $startlinepos = $this->footerpos[$this->page];
9628                                         }
9629                                         $plalign = $lalign;
9630                                         $this->newline = false;
9631                                 }
9632                                 if (isset($opentagpos)) {
9633                                         unset($opentagpos);
9634                                 }
9635                                 if ($dom[$key]['tag']) {
9636                                         if ($dom[$key]['opening']) {
9637                                                 // table content is handled in a special way
9638                                                 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9639                                                         $trid = $dom[$key]['parent'];
9640                                                         $table_el = $dom[$trid]['parent'];
9641                                                         if (!isset($dom[$table_el]['cols'])) {
9642                                                                 $dom[$table_el]['cols'] = $trid['cols'];
9643                                                         }
9644                                                         // calculate cell width
9645                                                         if (isset($dom[($dom[$key]['parent'])]['width'])) {
9646                                                                 $table_width = $this->pixelsToUnits($dom[($dom[$key]['parent'])]['width']);
9647                                                         } else {
9648                                                                 $table_width = $w;
9649                                                         }
9650                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
9651                                                                 $currentcmargin = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding']);
9652                                                         } else {
9653                                                                 $currentcmargin = 0;
9654                                                         }
9655                                                         $this->cMargin = $currentcmargin;
9656                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
9657                                                                 $cellspacing = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing']);
9658                                                         } else {
9659                                                                 $cellspacing = 0;
9660                                                         }
9661                                                         if ($this->rtl) {
9662                                                                 $cellspacingx = -$cellspacing;
9663                                                         } else {
9664                                                                 $cellspacingx = $cellspacing;
9665                                                         }
9666                                                         $colspan = $dom[$key]['attribute']['colspan'];
9667                                                         if (isset($dom[$key]['width'])) {
9668                                                                 $cellw = $this->pixelsToUnits($dom[$key]['width']);
9669                                                         } else {
9670                                                                 $cellw = ($colspan * ($table_width / $dom[$table_el]['cols']));
9671                                                         }
9672                                                         $cellw -= $cellspacing;
9673                                                         if (isset($dom[$key]['content'])) {
9674                                                                 $cell_content = $dom[$key]['content'];
9675                                                         } else {
9676                                                                 $cell_content = "&nbsp;";
9677                                                         }
9678                                                         $tagtype = $dom[$key]['value'];
9679                                                         $parentid = $key;
9680                                                         while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
9681                                                                 // move $key index forward
9682                                                                 $key++;
9683                                                         }
9684                                                         if (!isset($dom[$trid]['startpage'])) {
9685                                                                 $dom[$trid]['startpage'] = $this->page;
9686                                                         } else {
9687                                                                 $this->setPage($dom[$trid]['startpage']);
9688                                                         }
9689                                                         if (!isset($dom[$trid]['starty'])) {
9690                                                                 $dom[$trid]['starty'] = $this->y;
9691                                                         } else {
9692                                                                 $this->y = $dom[$trid]['starty'];
9693                                                         }
9694                                                         if (!isset($dom[$trid]['startx'])) {
9695                                                                 $dom[$trid]['startx'] = $this->x;
9696                                                         }
9697                                                         $this->x += ($cellspacingx / 2);
9698                                                         if (isset($dom[$parentid]['attribute']['rowspan'])) {
9699                                                                 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
9700                                                         }       else {
9701                                                                 $rowspan = 1;
9702                                                         }
9703                                                         // skip row-spanned cells started on the previous rows
9704                                                         if (isset($dom[$table_el]['rowspans'])) {
9705                                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9706                                                                         if  (($trwsp['startx'] == $this->x) AND (($trwsp['starty'] < $this->y) OR ($trwsp['startpage'] < $this->page)) AND ($trwsp['rowspan'] > 0)) {
9707                                                                                 $this->x = $trwsp['endx'] + $cellspacingx;
9708                                                                         }
9709                                                                 }
9710                                                         }
9711                                                         // add rowspan information to table element
9712                                                         if ($rowspan > 1) {
9713                                                                 if (isset($this->footerlen[$this->page])) {
9714                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9715                                                                 } else {
9716                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9717                                                                 }
9718                                                                 $trintmrkpos = $this->footerpos[$this->page];
9719                                                                 $trsid = array_push($dom[$table_el]['rowspans'], array('rowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startx' => $this->x, 'starty' => $this->y, 'intmrkpos' => $trintmrkpos));
9720                                                         }
9721                                                         $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
9722                                                         if ($rowspan > 1) {
9723                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
9724                                                         }
9725                                                         // push background colors
9726                                                         if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
9727                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
9728                                                         }
9729
9730                                                         // write the cell content
9731                                                         $this->MultiCell($cellw, 0, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
9732
9733                                                         $this->cMargin = $currentcmargin;
9734                                                         $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
9735                                                         
9736                                                         // update the end of row position
9737                                                         if ($rowspan <= 1) {
9738                                                                 if (isset($dom[$trid]['endy'])) {
9739                                                                         if ($this->page == $dom[$trid]['endpage']) {
9740                                                                                 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
9741                                                                         } elseif ($this->page > $dom[$trid]['endpage']) {
9742                                                                                 $dom[$trid]['endy'] = $this->y;
9743                                                                         }
9744                                                                 } else {
9745                                                                         $dom[$trid]['endy'] = $this->y;
9746                                                                 }
9747                                                                 if (isset($dom[$trid]['endpage'])) {
9748                                                                         $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
9749                                                                 } else {
9750                                                                         $dom[$trid]['endpage'] = $this->page;
9751                                                                 }
9752                                                         } else {
9753                                                         // account for row-spanned cells
9754                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
9755                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
9756                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
9757                                                         }
9758                                                         if (isset($dom[$table_el]['rowspans'])) {
9759                                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9760                                                                         if ($trwsp['rowspan'] > 0) {
9761                                                                                 if (isset($dom[$trid]['endpage'])) {
9762                                                                                         if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
9763                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
9764                                                                                         } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[$trid]['endpage']) {
9765                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $trwsp['endy'];
9766                                                                                         } else {
9767                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
9768                                                                                                 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
9769                                                                                         }
9770                                                                                 }
9771                                                                         }
9772                                                                 }
9773                                                         }
9774                                                         $this->x += ($cellspacingx / 2);
9775                                                 } else {
9776                                                         // opening tag (or self-closing tag)
9777                                                         if (!isset($opentagpos)) {
9778                                                                 if (isset($this->footerlen[$this->page])) {
9779                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9780                                                                 } else {
9781                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9782                                                                 }
9783                                                                 $opentagpos = $this->footerpos[$this->page];
9784                                                         }
9785                                                         $this->openHTMLTagHandler($dom, $key, $cell);
9786                                                 }
9787                                         } else {
9788                                                 // closing tag
9789                                                 $this->closeHTMLTagHandler($dom, $key, $cell);
9790                                         }
9791                                 } elseif (strlen($dom[$key]['value']) > 0) {
9792                                         // print list-item
9793                                         if (!empty($this->lispacer)) {
9794                                                 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
9795                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9796                                                 $minstartliney = $this->y;
9797                                                 $tmpx = $this->x;
9798                                                 $lspace = $this->GetStringWidth($this->lispacer."  ");
9799                                                 if ($this->rtl) {
9800                                                         $this->x += $lspace;
9801                                                 } else {
9802                                                         $this->x -= $lspace;
9803                                                 }
9804                                                 $this->Write($this->lasth, $this->lispacer, '', false, '', false, 0, false);
9805                                                 $this->x = $tmpx;
9806                                                 $this->lispacer = "";
9807                                                 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
9808                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9809                                                 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
9810                                                         $this->y += (($pfontsize - $curfontsize) / $this->k);
9811                                                         $minstartliney = min($this->y, $minstartliney);
9812                                                 }
9813                                         }
9814                                         // text
9815                                         $this->htmlvspace = 0;
9816                                         if ($newline) {
9817                                                 if ($this->rtl OR $this->tmprtl) {
9818                                                         $dom[$key]['value'] = rtrim($dom[$key]['value']);
9819                                                 } else {
9820                                                         $dom[$key]['value'] = ltrim($dom[$key]['value']);
9821                                                 }
9822                                                 $newline = false;
9823                                         }
9824                                         if ($this->HREF) {
9825                                                 // HTML <a> Link
9826                                                 $strrest = $this->addHtmlLink($this->HREF, $dom[$key]['value'], $wfill, true);
9827                                         } else {
9828                                                 $ctmpmargin = $this->cMargin;
9829                                                 $this->cMargin = 0;
9830                                                 // write only until the end of the line and get the rest
9831                                                 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, "", false, 0, true);
9832                                                 $this->cMargin = $ctmpmargin;
9833                                         }
9834                                         if (strlen($strrest) > 0) {
9835                                                 // store the remaining string on the previous $key position
9836                                                 $this->newline = true;
9837                                                 if ($cell) {
9838                                                         if ($this->rtl) {
9839                                                                 $this->x -= $this->cMargin;
9840                                                         } else {
9841                                                                 $this->x += $this->cMargin;
9842                                                         }
9843                                                 }
9844                                                 $dom[$key]['value'] = ltrim($strrest);
9845                                                 $key--;
9846                                         }
9847                                 }
9848                                 $key++;
9849                         } // end for each $key
9850                         // align the last line
9851                         if (isset($startlinex)) {
9852                                 $yshift = $minstartliney - $startliney;
9853                                 if ($yshift > 0) {
9854                                         $yshift = 0;
9855                                 }
9856                                 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9857                                         // the last line must be shifted to be aligned as requested
9858                                         $linew = abs($this->endlinex - $startlinex);
9859                                         $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9860                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9861                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9862                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9863                                         } elseif (isset($opentagpos)) {
9864                                                 $midpos = $opentagpos;
9865                                         } elseif (isset($this->footerlen[$startlinepage])) {
9866                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9867                                                 $midpos = $this->footerpos[$startlinepage];
9868                                         } else {
9869                                                 $midpos = 0;
9870                                         }
9871                                         if ($midpos > 0) {
9872                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9873                                                 $pend = substr($this->pages[$startlinepage], $midpos);
9874                                         } else {
9875                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9876                                                 $pend = "";
9877                                         }
9878                                         // calculate shifting amount
9879                                         $mdiff = abs($w - $linew);
9880                                         if ($plalign == "C") {
9881                                                 if ($this->rtl) {
9882                                                         $t_x = -($mdiff / 2);
9883                                                 } else {
9884                                                         $t_x = ($mdiff / 2);
9885                                                 }
9886                                         }       elseif (($plalign == "R") AND (!$this->rtl)) {
9887                                                 // right alignment on LTR document
9888                                                 $t_x = $mdiff;
9889                                         }       elseif (($plalign == "L") AND ($this->rtl)) {
9890                                                 // left alignment on RTL document
9891                                                 $t_x = -$mdiff;
9892                                         } else {
9893                                                 $t_x = 0;
9894                                         }
9895                                         if (($t_x != 0) OR ($yshift < 0)) {
9896                                                 // shift the line
9897                                                 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9898                                                 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9899                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9900                                                 // shift the annotations and links
9901                                                 if (isset($this->PageAnnots[$this->page])) {
9902                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9903                                                                 if ($pac['y'] >= $minstartliney) {
9904                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9905                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9906                                                                 }
9907                                                         }
9908                                                 }
9909                                                 $this->y -= $yshift;
9910                                         }
9911                                 }
9912                         }
9913                         if ($ln AND (!($cell AND ($dom[$key-1]['value'] == "table")))) {
9914                                 $this->Ln($this->lasth);
9915                         }
9916                         // restore previous values
9917                         $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
9918                         $this->SetFillColorArray($prevbgcolor);
9919                         $this->SetTextColorArray($prevfgcolor);
9920                         $this->lMargin = $prevlMargin;
9921                         $this->rMargin = $prevrMargin;
9922                         $this->cMargin = $prevcMargin;
9923                         unset($dom);
9924                 }
9925
9926                 /**
9927                  * Process opening tags.
9928                  * @param array $dom html dom array
9929                  * @param int $key current element id
9930                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
9931                  * @access protected
9932                  */
9933                 function openHTMLTagHandler(&$dom, $key, $cell=false) {
9934                         $tag = $dom[$key];
9935                         $parent = $dom[($dom[$key]['parent'])];
9936                         // check for text direction attribute
9937                         if (isset($tag['attribute']['dir'])) {
9938                                 $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
9939                         } else {
9940                                 $this->tmprtl = false;
9941                         }
9942                         //Opening tag
9943                         switch($tag['value']) {
9944                                 case 'table': {
9945                                         $dom[$key]['rowspans'] = array();
9946                                         if (isset($tag['attribute']['cellpadding'])) {
9947                                                 $this->oldcMargin = $this->cMargin;
9948                                                 $this->cMargin = $this->pixelsToUnits($tag['attribute']['cellpadding']);
9949                                         }
9950                                         break;
9951                                 }
9952                                 case 'tr': {
9953                                         // array of columns positions
9954                                         $dom[$key]['cellpos'] = array();
9955                                         break;
9956                                 }
9957                                 case 'td':
9958                                 case 'th': {
9959                                         break;
9960                                 }
9961                                 case 'hr': {
9962                                         $this->addHTMLVertSpace(1, $cell);
9963                                         $this->htmlvspace = 0;
9964                                         if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
9965                                                 $hrWidth = $this->pixelsToUnits($tag['attribute']['width']);
9966                                         } else {
9967                                                 $hrWidth = $this->w - $this->lMargin - $this->rMargin;
9968                                         }
9969                                         $x = $this->GetX();
9970                                         $y = $this->GetY();
9971                                         $prevlinewidth = $this->GetLineWidth();
9972                                         $this->Line($x, $y, $x + $hrWidth, $y);
9973                                         $this->SetLineWidth($prevlinewidth);
9974                                         $this->addHTMLVertSpace(1, $cell);
9975                                         break;
9976                                 }
9977                                 case 'b': {
9978                                         $this->setStyle('b', true);
9979                                         break;
9980                                 }
9981                                 case 'i': {
9982                                         $this->setStyle('i', true);
9983                                         break;
9984                                 }
9985                                 case 'u': {
9986                                         $this->setStyle('u', true);
9987                                         break;
9988                                 }
9989                                 case 'del': {
9990                                         $this->setStyle('d', true);
9991                                         break;
9992                                 }
9993                                 case 'a': {
9994                                         if (array_key_exists('href', $tag['attribute'])) {
9995                                                 $this->HREF = $tag['attribute']['href'];
9996                                         }
9997                                         break;
9998                                 }
9999                                 case 'img': {
10000                                         if (isset($tag['attribute']['src'])) {
10001                                                 // replace relative path with real server path
10002                                                 if ($tag['attribute']['src'][0] == '/') {
10003                                                         $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
10004                                                 }
10005                                                 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
10006                                                 if (!isset($tag['attribute']['width'])) {
10007                                                         $tag['attribute']['width'] = 0;
10008                                                 }
10009                                                 if (!isset($tag['attribute']['height'])) {
10010                                                         $tag['attribute']['height'] = 0;
10011                                                 }
10012                                                 //if (!isset($tag['attribute']['align'])) {
10013                                                         // the only alignment supported is "bottom"
10014                                                         // further development is required for other modes.
10015                                                         $tag['attribute']['align'] = 'bottom';
10016                                                 //} 
10017                                                 switch($tag['attribute']['align']) {
10018                                                         case 'top': {
10019                                                                 $align = 'T';
10020                                                                 break;
10021                                                         }
10022                                                         case 'middle': {
10023                                                                 $align = 'M';
10024                                                                 break;
10025                                                         }
10026                                                         case 'bottom': {
10027                                                                 $align = 'B';
10028                                                                 break;
10029                                                         }
10030                                                         default: {
10031                                                                 $align = 'B';
10032                                                                 break;
10033                                                         }
10034                                                 }
10035                                                 $fileinfo = pathinfo($tag['attribute']['src']);
10036                                                 if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
10037                                                         $type = strtolower($fileinfo['extension']);
10038                                                 }
10039                                                 $prevy = $this->y;
10040                                                 if (($type == "eps") OR ($type == "ai")) {
10041                                                         $this->ImageEps($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', true, $align);
10042                                                 } else {
10043                                                         $this->Image($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', '', $align);
10044                                                 }
10045                                                 switch($align) {
10046                                                         case 'T': {
10047                                                                 $this->y = $prevy;
10048                                                                 break;
10049                                                         }
10050                                                         case 'M': {
10051                                                                 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
10052                                                                 break;
10053                                                         }
10054                                                         case 'B': {
10055                                                                 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
10056                                                                 break;
10057                                                         }
10058                                                 }
10059                                         }
10060                                         break;
10061                                 }
10062                                 case 'dl': {
10063                                         $this->listnum++;
10064                                         break;
10065                                 }
10066                                 case 'dt': {
10067                                         $this->addHTMLVertSpace(1, $cell);
10068                                         break;
10069                                 }
10070                                 case 'dd': {
10071                                         if ($this->rtl) {
10072                                                 $this->rMargin += $this->listindent;
10073                                         } else {
10074                                                 $this->lMargin += $this->listindent;
10075                                         }
10076                                         $this->addHTMLVertSpace(1, $cell);
10077                                         break;
10078                                 }
10079                                 case 'ul':
10080                                 case 'ol': {
10081                                         $this->listnum++;
10082                                         if ($tag['value'] == "ol") {
10083                                                 $this->listordered[$this->listnum] = true;
10084                                         } else {
10085                                                 $this->listordered[$this->listnum] = false;
10086                                         }
10087                                         $this->listcount[$this->listnum] = 0;
10088                                         if ($this->rtl) {
10089                                                 $this->rMargin += $this->listindent;
10090                                         } else {
10091                                                 $this->lMargin += $this->listindent;
10092                                         }
10093                                         break;
10094                                 }
10095                                 case 'li': {
10096                                         $this->Ln('', $cell);
10097                                         if ($tag['value'] == 'li') {
10098                                                 if ($this->listordered[$this->listnum]) {
10099                                                         if (isset($tag['attribute']['value'])) {
10100                                                                 $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
10101                                                         }
10102                                                         $this->listcount[$this->listnum]++;
10103                                                         if ($this->rtl) {
10104                                                                 $this->lispacer = ".".($this->listcount[$this->listnum]);
10105                                                         } else {
10106                                                                 $this->lispacer = ($this->listcount[$this->listnum]).".";
10107                                                         }
10108                                                 } else {
10109                                                         //unordered list symbol
10110                                                         $this->lispacer = "-";
10111                                                 }
10112                                         } else {
10113                                                 $this->lispacer = "";
10114                                         }
10115                                         break;
10116                                 }
10117                                 case 'blockquote': {
10118                                         if ($this->rtl) {
10119                                                 $this->rMargin += $this->listindent;
10120                                         } else {
10121                                                 $this->lMargin += $this->listindent;
10122                                         }
10123                                         $this->addHTMLVertSpace(2, $cell);
10124                                         break;
10125                                 }
10126                                 case 'br': {
10127                                         $this->Ln('', $cell);
10128                                         break;
10129                                 }
10130                                 case 'div': {
10131                                         $this->addHTMLVertSpace(2, $cell);
10132                                         break;
10133                                 }
10134                                 case 'p': {
10135                                         $this->addHTMLVertSpace(2, $cell);
10136                                         break;
10137                                 }
10138                                 case 'sup': {
10139                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
10140                                         break;
10141                                 }
10142                                 case 'sub': {
10143                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
10144                                         break;
10145                                 }
10146                                 case 'h1':
10147                                 case 'h2':
10148                                 case 'h3':
10149                                 case 'h4':
10150                                 case 'h5':
10151                                 case 'h6': {
10152                                         $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k);
10153                                         break;
10154                                 }
10155                                 default: {
10156                                         break;
10157                                 }
10158                         }
10159                 }
10160
10161                 /**
10162                  * Process closing tags.
10163                  * @param array $dom html dom array
10164                  * @param int $key current element id
10165                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
10166                  * @access protected
10167                  */
10168                 function closeHTMLTagHandler(&$dom, $key, $cell=false) {
10169                         $tag = $dom[$key];
10170                         $parent = $dom[($dom[$key]['parent'])];
10171                         //Closing tag
10172                         switch($tag['value']) {
10173                                 case 'td':
10174                                 case 'th': {
10175                                         break;
10176                                 }
10177                                 case 'tr': {
10178                                         $table_el = $dom[($dom[$key]['parent'])]['parent'];
10179                                         // update row-spanned cells
10180                                         if (isset($dom[$table_el]['rowspans'])) {
10181                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
10182                                                         $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
10183                                                         if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
10184                                                                 if ($dom[$table_el]['rowspans'][$k]['endpage'] == $dom[($dom[$key]['parent'])]['endpage']) {
10185                                                                         $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
10186                                                                 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[($dom[$key]['parent'])]['endpage']) {
10187                                                                         $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
10188                                                                         $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
10189                                                                 }
10190                                                         }
10191                                                 }
10192                                         }
10193                                         $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
10194                                         $this->y = $dom[($dom[$key]['parent'])]['endy'];
10195                                         if (isset($dom[$table_el]['attribute']['cellspacing'])) {
10196                                                 $cellspacing = $this->pixelsToUnits($dom[$table_el]['attribute']['cellspacing']);
10197                                                 $this->y += $cellspacing;
10198                                         }                               
10199                                         $this->Ln(0, $cell);
10200                                         $this->x = $dom[($dom[$key]['parent'])]['startx'];
10201                                         break;
10202                                 }
10203                                 case 'table': {
10204                                         // draw borders
10205                                         $table_el = $parent;
10206                                         if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
10207                                                 OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
10208                                                         $border = 1;
10209                                         } else {
10210                                                 $border = 0;
10211                                         }
10212                                         // for each row
10213                                         foreach ($table_el['trids'] as $j => $trkey) {
10214                                                 $parent = $dom[$trkey];
10215                                                 $restspace = $this->getPageHeight() - $this->y - $this->getBreakMargin();
10216                                                 // for each cell on the row
10217                                                 foreach ($parent['cellpos'] as $k => $cellpos) {
10218                                                         if (isset($cellpos['rowspanid'])) {
10219                                                                 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
10220                                                                 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
10221                                                                 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
10222                                                                 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
10223                                                                 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
10224                                                         } else {
10225                                                                 $endy = $parent['endy'];
10226                                                                 $startpage = $parent['startpage'];
10227                                                                 $endpage = $parent['endpage'];
10228                                                         }
10229                                                         $this->setPage($startpage);
10230                                                         $this->y = $parent['starty'];
10231                                                         if ($endpage > $startpage) {
10232                                                                 // design borders around HTML cells.
10233                                                                 for ($page=$startpage; $page <= $endpage; $page++) {
10234                                                                         $this->setPage($page);
10235                                                                         if ($page == $startpage) {
10236                                                                                 $this->y = $this->getPageHeight() - $restspace - $this->getBreakMargin();
10237                                                                                 $ch = $restspace;
10238                                                                         } elseif ($page == $endpage) {
10239                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of text
10240                                                                                 $ch = $endy - $this->tMargin;
10241                                                                         } else {
10242                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of text
10243                                                                                 $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
10244                                                                         }
10245
10246                                                                         if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10247                                                                                 $this->SetFillColorArray($cellpos['bgcolor']);
10248                                                                                 $fill = true;
10249                                                                         } else {
10250                                                                                 $fill = false;
10251                                                                         }
10252                                                                         $cw = abs($cellpos['endx'] - $cellpos['startx']);
10253                                                                         $this->x = $cellpos['startx'];
10254                                                                         // design a cell around the text
10255                                                                         $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10256                                                                         $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10257                                                                         $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10258                                                                         $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10259                                                                         $this->intmrk[$this->page] += strlen($ccode."\n");
10260                                                                 }
10261                                                         } else {
10262                                                                 $ch = $endy - $parent['starty'];
10263                                                                 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10264                                                                         $this->SetFillColorArray($cellpos['bgcolor']);
10265                                                                         $fill = true;
10266                                                                 } else {
10267                                                                         $fill = false;
10268                                                                 }
10269                                                                 $cw = abs($cellpos['endx'] - $cellpos['startx']);
10270                                                                 $this->x = $cellpos['startx'];
10271                                                                 $this->y = $parent['starty'];
10272                                                                 // design a cell around the text
10273                                                                 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10274                                                                 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10275                                                                 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10276                                                                 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10277                                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
10278                                                         }
10279                                                 }
10280                                                 if (isset($table_el['attribute']['cellspacing'])) {
10281                                                         $cellspacing = $this->pixelsToUnits($table_el['attribute']['cellspacing']);
10282                                                         $this->y += $cellspacing;
10283                                                 }
10284                                                 $this->Ln(0, $cell);
10285                                                 $this->x = $parent['startx'];
10286                                         }
10287                                         if (isset($parent['cellpadding'])) {
10288                                                 $this->cMargin = $this->oldcMargin;
10289                                         }
10290                                         //set row height
10291                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
10292                                         break;
10293                                 }
10294                                 case 'b': {
10295                                         $this->setStyle('b', false);
10296                                         break;
10297                                 }
10298                                 case 'i': {
10299                                         $this->setStyle('i', false);
10300                                         break;
10301                                 }
10302                                 case 'u': {
10303                                         $this->setStyle('u', false);
10304                                         break;
10305                                 }
10306                                 case 'del': {
10307                                         $this->setStyle('d', false);
10308                                         break;
10309                                 }
10310                                 case 'a': {
10311                                         $this->HREF = '';
10312                                         break;
10313                                 }
10314                                 case 'sup': {
10315                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
10316                                         break;
10317                                 }
10318                                 case 'sub': {
10319                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
10320                                         break;
10321                                 }
10322                                 case 'div': {
10323                                         $this->addHTMLVertSpace(1, $cell);
10324                                         break;
10325                                 }
10326                                 case 'blockquote': {
10327                                         if ($this->rtl) {
10328                                                 $this->rMargin -= $this->listindent;
10329                                         } else {
10330                                                 $this->lMargin -= $this->listindent;
10331                                         }
10332                                         $this->addHTMLVertSpace(2, $cell);
10333                                         break;
10334                                 }
10335                                 case 'p': {
10336                                         $this->addHTMLVertSpace(2, $cell);
10337                                         break;
10338                                 }
10339                                 case 'dl': {
10340                                         $this->listnum--;
10341                                         if ($this->listnum <= 0) {
10342                                                 $this->listnum = 0;
10343                                                 $this->addHTMLVertSpace(2, $cell);
10344                                         }
10345                                         break;
10346                                 }
10347                                 case 'dt': {
10348                                         $this->lispacer = "";
10349                                         break;
10350                                 }
10351                                 case 'dd': {
10352                                         $this->lispacer = "";
10353                                         if ($this->rtl) {
10354                                                 $this->rMargin -= $this->listindent;
10355                                         } else {
10356                                                 $this->lMargin -= $this->listindent;
10357                                         }
10358                                         break;
10359                                 }
10360                                 case 'ul':
10361                                 case 'ol': {
10362                                         $this->listnum--;
10363                                         $this->lispacer = "";
10364                                         if ($this->rtl) {
10365                                                 $this->rMargin -= $this->listindent;
10366                                         } else {
10367                                                 $this->lMargin -= $this->listindent;
10368                                         }
10369                                         if ($this->listnum <= 0) {
10370                                                 $this->listnum = 0;
10371                                                 $this->addHTMLVertSpace(2, $cell);
10372                                         }
10373                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
10374                                         break;
10375                                 }
10376                                 case 'li': {
10377                                         $this->lispacer = "";
10378                                         break;
10379                                 }
10380                                 case 'h1':
10381                                 case 'h2':
10382                                 case 'h3':
10383                                 case 'h4':
10384                                 case 'h5':
10385                                 case 'h6': {
10386                                         $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k);
10387                                         break;
10388                                 }
10389                                 default : {
10390                                         break;
10391                                 }
10392                         }
10393                         $this->tmprtl = false;
10394                 }
10395                 
10396                 /**
10397                  * Add vertical spaces if needed.
10398                  * @param int $n number of spaces to add
10399                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
10400                  * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
10401                  * @access protected
10402                  */
10403                 function addHTMLVertSpace($n, $cell=false, $h='') {
10404                         if (is_string($h)) {
10405                                 $vsize = $n * $this->lasth;
10406                         } else {
10407                                 $vsize = $n * $h;
10408                         }
10409                         if ($vsize > $this->htmlvspace) {
10410                                 $this->Ln(($vsize - $this->htmlvspace), $cell);
10411                                 $this->htmlvspace = $vsize;
10412             }
10413         }
10414                 
10415         } // END OF TCPDF CLASS
10416 }
10417 //============================================================+
10418 // END OF FILE
10419 //============================================================+
10420 ?>