01d15527f598cb1bd827d563cc2af5180ebdee6f
[fa-stable.git] / reporting / includes / tcpdf.php
1 4527<?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   * 5. Header function renamed to Header1 (due to conflict with FrontReport Header)
145   * 6. Line 6190, SetLineWidth (cast of values to avoid problem in PHP 5.2.6
146   * 7. Line 6261. ereg replaced by preg_match (with start and end delimiter)
147   * 8. Lines 8642,9256 and 9348. split replaced by preg_split.
148   * -------------------------------------------------------------------------------
149   */
150 if (!defined("K_PATH_FONTS"))
151         define ("K_PATH_FONTS", dirname(__FILE__)."/../fonts/");
152 define ("K_PATH_CACHE", dirname(__FILE__)."/../fonts/");
153 define("K_CELL_HEIGHT_RATIO", 1.25);
154
155 //require_once(dirname(__FILE__).'/config/tcpdf_config.php');
156
157 // includes some support files
158
159 /**
160  * unicode data
161  */
162 // only included if unicode
163 //include_once(dirname(__FILE__)."/unicode_data2.php");
164
165 /**
166  * html colors table
167  */
168 require_once(dirname(__FILE__).'/htmlcolors.php');
169
170 /**
171  * barcode class
172  */
173 require_once(dirname(__FILE__)."/barcodes.php");
174
175 /**
176  * HTML entity decode functions
177  */
178 require_once(dirname(__FILE__)."/html_entity_decode_php4.php");
179
180 if (!class_exists('TCPDF')) {
181         /**
182          * define default PDF document producer
183          */
184         define('PDF_PRODUCER','TCPDF 4.0.027_PHP4 (http://www.tcpdf.org)');
185
186         /**
187         * This is a PHP class for generating PDF documents without requiring external extensions.<br>
188         * 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>
189         * @name TCPDF
190         * @package com.tecnick.tcpdf
191         * @version 4.0.027_PHP4
192         * @author Nicola Asuni - info@tecnick.com
193         * @link http://www.tcpdf.org
194         * @license http://www.gnu.org/copyleft/lesser.html LGPL
195         */
196         class TCPDF {
197                 
198                 // protected or Protected properties
199
200                 /**
201                 * @var current page number
202                 * @access protected
203                 */
204                 var $page;
205
206                 /**
207                 * @var current object number
208                 * @access protected
209                 */
210                 var $n;
211
212                 /**
213                 * @var array of object offsets
214                 * @access protected
215                 */
216                 var $offsets;
217
218                 /**
219                 * @var buffer holding in-memory PDF
220                 * @access protected
221                 */
222                 var $buffer;
223
224                 /**
225                 * @var array containing pages
226                 * @access protected
227                 */
228                 var $pages = array();
229
230                 /**
231                 * @var current document state
232                 * @access protected
233                 */
234                 var $state;
235
236                 /**
237                 * @var compression flag
238                 * @access protected
239                 */
240                 var $compress;
241
242                 /**
243                 * @var current page orientation (P = Portrait, L = Landscape)
244                 * @access protected
245                 */
246                 var $CurOrientation;
247
248                 /**
249                 * @var array that stores page dimensions.<ul><li>$this->pagedim[$this->page]['w'] => page_width_in_points</li><li>$this->pagedim[$this->page]['h'] => height</li><li>$this->pagedim[$this->page]['tm'] => top_margin</li><li>$this->pagedim[$this->page]['bm'] => bottom_margin</li><li>$this->pagedim[$this->page]['lm'] => left_margin</li><li>$this->pagedim[$this->page]['rm'] => right_margin</li><li>$this->pagedim[$this->page]['pb'] => auto_page_break</li><li>$this->pagedim[$this->page]['or'] => page_orientation</li></ul>
250                 * @access protected
251                 */
252                 var $pagedim = array();
253
254                 /**
255                 * @var scale factor (number of points in user unit)
256                 * @access protected
257                 */
258                 var $k;
259
260                 /**
261                 * @var width of page format in points
262                 * @access protected
263                 */
264                 var $fwPt;
265
266                 /**
267                 * @var height of page format in points
268                 * @access protected
269                 */
270                 var $fhPt;
271
272                 /**
273                 * @var current width of page in points
274                 * @access protected
275                 */
276                 var $wPt;
277
278                 /**
279                 * @var current height of page in points
280                 * @access protected
281                 */
282                 var $hPt;
283
284                 /**
285                 * @var current width of page in user unit
286                 * @access protected
287                 */
288                 var $w;
289
290                 /**
291                 * @var current height of page in user unit
292                 * @access protected
293                 */
294                 var $h;
295
296                 /**
297                 * @var left margin
298                 * @access protected
299                 */
300                 var $lMargin;
301
302                 /**
303                 * @var top margin
304                 * @access protected
305                 */
306                 var $tMargin;
307
308                 /**
309                 * @var right margin
310                 * @access protected
311                 */
312                 var $rMargin;
313
314                 /**
315                 * @var page break margin
316                 * @access protected
317                 */
318                 var $bMargin;
319
320                 /**
321                 * @var cell internal padding
322                 * @access protected
323                 */
324                 var $cMargin;
325
326                 /**
327                 * @var cell internal padding (previous value)
328                 * @access protected
329                 */
330                 var $oldcMargin;
331
332                 /**
333                 * @var current horizontal position in user unit for cell positioning
334                 * @access protected
335                 */
336                 var $x;
337
338                 /**
339                 * @var current vertical position in user unit for cell positioning
340                 * @access protected
341                 */
342                 var $y;
343
344                 /**
345                 * @var height of last cell printed
346                 * @access protected
347                 */
348                 var $lasth;
349
350                 /**
351                 * @var line width in user unit
352                 * @access protected
353                 */
354                 var $LineWidth;
355
356                 /**
357                 * @var array of standard font names
358                 * @access protected
359                 */
360                 var $CoreFonts;
361
362                 /**
363                 * @var array of used fonts
364                 * @access protected
365                 */
366                 var $fonts = array();
367
368                 /**
369                 * @var array of font files
370                 * @access protected
371                 */
372                 var $FontFiles = array();
373
374                 /**
375                 * @var array of encoding differences
376                 * @access protected
377                 */
378                 var $diffs = array();
379
380                 /**
381                 * @var array of used images
382                 * @access protected
383                 */
384                 var $images = array();
385
386                 /**
387                 * @var array of Annotations in pages
388                 * @access protected
389                 */
390                 var $PageAnnots = array();
391
392                 /**
393                 * @var array of internal links
394                 * @access protected
395                 */
396                 var $links = array();
397
398                 /**
399                 * @var current font family
400                 * @access protected
401                 */
402                 var $FontFamily;
403
404                 /**
405                 * @var current font style
406                 * @access protected
407                 */
408                 var $FontStyle;
409
410                 /**
411                 * @var current font ascent (distance between font top and baseline)
412                 * @access protected
413                 * @since 2.8.000 (2007-03-29)
414                 */
415                 var $FontAscent;
416
417                 /**
418                 * @var current font descent (distance between font bottom and baseline)
419                 * @access protected
420                 * @since 2.8.000 (2007-03-29)
421                 */
422                 var $FontDescent;
423
424                 /**
425                 * @var underlining flag
426                 * @access protected
427                 */
428                 var $underline;
429
430                 /**
431                 * @var current font info
432                 * @access protected
433                 */
434                 var $CurrentFont;
435
436                 /**
437                 * @var current font size in points
438                 * @access protected
439                 */
440                 var $FontSizePt;
441
442                 /**
443                 * @var current font size in user unit
444                 * @access protected
445                 */
446                 var $FontSize;
447
448                 /**
449                 * @var commands for drawing color
450                 * @access protected
451                 */
452                 var $DrawColor;
453
454                 /**
455                 * @var commands for filling color
456                 * @access protected
457                 */
458                 var $FillColor;
459
460                 /**
461                 * @var commands for text color
462                 * @access protected
463                 */
464                 var $TextColor;
465
466                 /**
467                 * @var indicates whether fill and text colors are different
468                 * @access protected
469                 */
470                 var $ColorFlag;
471
472                 /**
473                 * @var word spacing
474                 * @access protected
475                 */
476                 var $ws;
477
478                 /**
479                 * @var automatic page breaking
480                 * @access protected
481                 */
482                 var $AutoPageBreak;
483
484                 /**
485                 * @var threshold used to trigger page breaks
486                 * @access protected
487                 */
488                 var $PageBreakTrigger;
489
490                 /**
491                 * @var flag set when processing footer
492                 * @access protected
493                 */
494                 var $InFooter;
495
496                 /**
497                 * @var zoom display mode
498                 * @access protected
499                 */
500                 var $ZoomMode;
501
502                 /**
503                 * @var layout display mode
504                 * @access protected
505                 */
506                 var $LayoutMode;
507
508                 /**
509                 * @var title
510                 * @access protected
511                 */
512                 var $title;
513
514                 /**
515                 * @var subject
516                 * @access protected
517                 */
518                 var $subject;
519
520                 /**
521                 * @var author
522                 * @access protected
523                 */
524                 var $author;
525
526                 /**
527                 * @var keywords
528                 * @access protected
529                 */
530                 var $keywords;
531
532                 /**
533                 * @var creator
534                 * @access protected
535                 */
536                 var $creator;
537
538                 /**
539                 * @var alias for total number of pages
540                 * @access protected
541                 */
542                 var $AliasNbPages;
543
544                 /**
545                 * @var right-bottom corner X coordinate of inserted image
546                 * @since 2002-07-31
547                 * @author Nicola Asuni
548                 * @access protected
549                 */
550                 var $img_rb_x;
551
552                 /**
553                 * @var right-bottom corner Y coordinate of inserted image
554                 * @since 2002-07-31
555                 * @author Nicola Asuni
556                 * @access protected
557                 */
558                 var $img_rb_y;
559
560                 /**
561                 * @var image scale factor
562                 * @since 2004-06-14
563                 * @author Nicola Asuni
564                 * @access protected
565                 */
566                 var $imgscale = 1;
567
568                 /**
569                 * @var boolean set to true when the input text is unicode (require unicode fonts)
570                 * @since 2005-01-02
571                 * @author Nicola Asuni
572                 * @access protected
573                 */
574                 var $isunicode = false;
575
576                 /**
577                 * @var PDF version
578                 * @since 1.5.3
579                 * @access protected
580                 */
581                 var $PDFVersion = "1.7";
582
583
584                 // ----------------------
585
586                 /**
587                  * @var Minimum distance between header and top page margin.
588                  * @access protected
589                  */
590                 var $header_margin;
591
592                 /**
593                  * @var Minimum distance between footer and bottom page margin.
594                  * @access protected
595                  */
596                 var $footer_margin;
597
598                 /**
599                  * @var original left margin value
600                  * @access protected
601                  * @since 1.53.0.TC013
602                  */
603                 var $original_lMargin;
604
605                 /**
606                  * @var original right margin value
607                  * @access protected
608                  * @since 1.53.0.TC013
609                  */
610                 var $original_rMargin;
611
612                 /**
613                  * @var Header font.
614                  * @access protected
615                  */
616                 var $header_font;
617
618                 /**
619                  * @var Footer font.
620                  * @access protected
621                  */
622                 var $footer_font;
623
624                 /**
625                  * @var Language templates.
626                  * @access protected
627                  */
628                 var $l;
629
630                 /**
631                  * @var Barcode to print on page footer (only if set).
632                  * @access protected
633                  */
634                 var $barcode = false;
635
636                 /**
637                  * @var If true prints header
638                  * @access protected
639                  */
640                 var $print_header = true;
641
642                 /**
643                  * @var If true prints footer.
644                  * @access protected
645                  */
646                 var $print_footer = true;
647
648                 /**
649                  * @var Header image logo.
650                  * @access protected
651                  */
652                 var $header_logo = "";
653
654                 /**
655                  * @var Header image logo width in mm.
656                  * @access protected
657                  */
658                 var $header_logo_width = 30;
659
660                 /**
661                  * @var String to print as title on document header.
662                  * @access protected
663                  */
664                 var $header_title = "";
665
666                 /**
667                  * @var String to print on document header.
668                  * @access protected
669                  */
670                 var $header_string = "";
671
672                 /**
673                  * @var Default number of columns for html table.
674                  * @access protected
675                  */
676                 var $default_table_columns = 4;
677
678
679                 // variables for html parser
680
681                 /**
682                  * @var HTML PARSER: store current link.
683                  * @access protected
684                  */
685                 var $HREF;
686
687                 /**
688                  * @var store available fonts list.
689                  * @access protected
690                  */
691                 var $fontlist = array();
692
693                 /**
694                  * @var current foreground color
695                  * @access protected
696                  */
697                 var $fgcolor;
698
699                 /**
700                  * @var HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
701                  * @access protected
702                  */
703                 var $listordered = array();
704
705                 /**
706                  * @var HTML PARSER: array count list items on nested lists.
707                  * @access protected
708                  */
709                 var $listcount = array();
710
711                 /**
712                  * @var HTML PARSER: current list nesting level.
713                  * @access protected
714                  */
715                 var $listnum = 0;
716
717                 /**
718                  * @var HTML PARSER: indent amount for lists.
719                  * @access protected
720                  */
721                 var $listindent;
722
723                 /**
724                  * @var current background color
725                  * @access protected
726                  */
727                 var $bgcolor;
728
729                 /**
730                  * @var Store temporary font size in points.
731                  * @access protected
732                  */
733                 var $tempfontsize = 10;
734
735                 /**
736                  * @var Bold font style status.
737                  * @access protected
738                  */
739                 var $b;
740
741                 /**
742                  * @var Underlined font style status.
743                  * @access protected
744                  */
745                 var $u;
746
747                 /**
748                  * @var Italic font style status.
749                  * @access protected
750                  */
751                 var $i;
752
753                 /**
754                  * @var Line through font style status.
755                  * @access protected
756                  * @since 2.8.000 (2008-03-19)
757                  */
758                 var $d;
759
760                 /**
761                  * @var spacer for LI tags.
762                  * @access protected
763                  */
764                 var $lispacer = "";
765
766                 /**
767                  * @var default encoding
768                  * @access protected
769                  * @since 1.53.0.TC010
770                  */
771                 var $encoding = "UTF-8";
772
773                 /**
774                  * @var PHP internal encoding
775                  * @access protected
776                  * @since 1.53.0.TC016
777                  */
778                 var $internal_encoding;
779
780                 /**
781                  * @var indicates if the document language is Right-To-Left
782                  * @access protected
783                  * @since 2.0.000
784                  */
785                 var $rtl = false;
786
787                 /**
788                  * @var used to force RTL or LTR string inversion
789                  * @access protected
790                  * @since 2.0.000
791                  */
792                 var $tmprtl = false;
793
794                 // --- Variables used for document encryption:
795
796                 /**
797                  * Indicates whether document is protected
798                  * @access protected
799                  * @since 2.0.000 (2008-01-02)
800                  */
801                 var $encrypted;
802
803                 /**
804                  * U entry in pdf document
805                  * @access protected
806                  * @since 2.0.000 (2008-01-02)
807                  */
808                 var $Uvalue;
809
810                 /**
811                  * O entry in pdf document
812                  * @access protected
813                  * @since 2.0.000 (2008-01-02)
814                  */
815                 var $Ovalue;
816
817                 /**
818                  * P entry in pdf document
819                  * @access protected
820                  * @since 2.0.000 (2008-01-02)
821                  */
822                 var $Pvalue;
823
824                 /**
825                  * encryption object id
826                  * @access protected
827                  * @since 2.0.000 (2008-01-02)
828                  */
829                 var $enc_obj_id;
830
831                 /**
832                  * last RC4 key encrypted (cached for optimisation)
833                  * @access protected
834                  * @since 2.0.000 (2008-01-02)
835                  */
836                 var $last_rc4_key;
837
838                 /**
839                  * last RC4 computed key
840                  * @access protected
841                  * @since 2.0.000 (2008-01-02)
842                  */
843                 var $last_rc4_key_c;
844
845                 // --- bookmark ---
846
847                 /**
848                  * Outlines for bookmark
849                  * @access protected
850                  * @since 2.1.002 (2008-02-12)
851                  */
852                 var $outlines = array();
853
854                 /**
855                  * Outline root for bookmark
856                  * @access protected
857                  * @since 2.1.002 (2008-02-12)
858                  */
859                 var $OutlineRoot;
860
861
862                 // --- javascript and form ---
863
864                 /**
865                  * javascript code
866                  * @access protected
867                  * @since 2.1.002 (2008-02-12)
868                  */
869                 var $javascript = "";
870
871                 /**
872                  * javascript counter
873                  * @access protected
874                  * @since 2.1.002 (2008-02-12)
875                  */
876                 var $n_js;
877
878                 /**
879                  * line trough state
880                  * @access protected
881                  * @since 2.8.000 (2008-03-19)
882                  */
883                 var $linethrough;
884
885                 // --- Variables used for User's Rights ---
886                 // See PDF reference chapter 8.7 Digital Signatures
887
888                 /**
889                  * If true enables user's rights on PDF reader
890                  * @access protected
891                  * @since 2.9.000 (2008-03-26)
892                  */
893                 var $ur;
894
895                 /**
896                  * Names specifying additional document-wide usage rights for the document.
897                  * @access protected
898                  * @since 2.9.000 (2008-03-26)
899                  */
900                 var $ur_document;
901
902                 /**
903                  * Names specifying additional annotation-related usage rights for the document.
904                  * @access protected
905                  * @since 2.9.000 (2008-03-26)
906                  */
907                 var $ur_annots;
908
909                 /**
910                  * Names specifying additional form-field-related usage rights for the document.
911                  * @access protected
912                  * @since 2.9.000 (2008-03-26)
913                  */
914                 var $ur_form;
915
916                 /**
917                  * Names specifying additional signature-related usage rights for the document.
918                  * @access protected
919                  * @since 2.9.000 (2008-03-26)
920                  */
921                 var $ur_signature;
922
923                 /**
924                  * Dot Per Inch Document Resolution (do not change)
925                  * @access protected
926                  * @since 3.0.000 (2008-03-27)
927                  */
928                 var $dpi = 72;
929
930                 /**
931                  * Indicates whether a new page group was requested
932                  * @access protected
933                  * @since 3.0.000 (2008-03-27)
934                  */
935                 var $newpagegroup;
936
937                 /**
938                  * Contains the number of pages of the groups
939                  * @access protected
940                  * @since 3.0.000 (2008-03-27)
941                  */
942                 var $pagegroups;
943
944                 /**
945                  * Contains the alias of the current page group
946                  * @access protected
947                  * @since 3.0.000 (2008-03-27)
948                  */
949                 var $currpagegroup;
950
951                 /**
952                  * Restrict the rendering of some elements to screen or printout.
953                  * @access protected
954                  * @since 3.0.000 (2008-03-27)
955                  */
956                 var $visibility="all";
957
958                 /**
959                  * Print visibility.
960                  * @access protected
961                  * @since 3.0.000 (2008-03-27)
962                  */
963                 var $n_ocg_print;
964
965                 /**
966                  * View visibility.
967                  * @access protected
968                  * @since 3.0.000 (2008-03-27)
969                  */
970                 var $n_ocg_view;
971
972                 /**
973                  * Array of transparency objects and parameters.
974                  * @access protected
975                  * @since 3.0.000 (2008-03-27)
976                  */
977                 var $extgstates;
978
979                 /**
980                  * Set the default JPEG compression quality (1-100)
981                  * @access protected
982                  * @since 3.0.000 (2008-03-27)
983                  */
984                 var $jpeg_quality;
985
986                 /**
987                  * Default cell height ratio.
988                  * @access protected
989                  * @since 3.0.014 (2008-05-23)
990                  */
991                 var $cell_height_ratio = K_CELL_HEIGHT_RATIO;
992
993                 /**
994                  * PDF viewer preferences.
995                  * @access protected
996                  * @since 3.1.000 (2008-06-09)
997                  */
998                 var $viewer_preferences;
999
1000                 /**
1001                  * A name object specifying how the document should be displayed when opened.
1002                  * @access protected
1003                  * @since 3.1.000 (2008-06-09)
1004                  */
1005                 var $PageMode;
1006
1007                 /**
1008                  * Array for storing gradient information.
1009                  * @access protected
1010                  * @since 3.1.000 (2008-06-09)
1011                  */
1012                 var $gradients = array();
1013
1014                 /**
1015                  * Array used to store positions inside the pages buffer.
1016                  * keys are the page numbers
1017                  * @access protected
1018                  * @since 3.2.000 (2008-06-26)
1019                  */
1020                 var $intmrk = array();
1021
1022                 /**
1023                  * Array used to store footer positions of each page.
1024                  * @access protected
1025                  * @since 3.2.000 (2008-07-01)
1026                  */
1027                 var $footerpos = array();
1028
1029
1030                 /**
1031                  * Array used to store footer lenght of each page.
1032                  * @access protected
1033                  * @since 4.0.014 (2008-07-29)
1034                  */
1035                 var $footerlen = array();
1036
1037                 /**
1038                  * True if a newline is created.
1039                  * @access protected
1040                  * @since 3.2.000 (2008-07-01)
1041                  */
1042                 var $newline = true;
1043
1044                 /**
1045                  * End position of the latest inserted line
1046                  * @access protected
1047                  * @since 3.2.000 (2008-07-01)
1048                  */
1049                 var $endlinex = 0;
1050
1051                 /**
1052                  * PDF string for last line width
1053                  * @access protected
1054                  * @since 4.0.006 (2008-07-16)
1055                  */
1056                 var $linestyleWidth = "";
1057
1058                 /**
1059                  * PDF string for last line width
1060                  * @access protected
1061                  * @since 4.0.006 (2008-07-16)
1062                  */
1063                 var $linestyleCap = "0 J";
1064
1065                 /**
1066                  * PDF string for last line width
1067                  * @access protected
1068                  * @since 4.0.006 (2008-07-16)
1069                  */
1070                 var $linestyleJoin = "0 j";
1071
1072                 /**
1073                  * PDF string for last line width
1074                  * @access protected
1075                  * @since 4.0.006 (2008-07-16)
1076                  */
1077                 var $linestyleDash = "[] 0 d";
1078
1079                 /**
1080                  * True if marked-content sequence is open
1081                  * @access protected
1082                  * @since 4.0.013 (2008-07-28)
1083                  */
1084                 var $openMarkedContent = false;
1085
1086                 /**
1087                  * Count the latest inserted vertical spaces on HTML.
1088                  * @access protected
1089                  * @since 4.0.021 (2008-08-24)
1090                  */
1091                 var $htmlvspace = 0;
1092                 
1093                 /**
1094                  * Array of Spot colors
1095                  * @access protected
1096                  * @since 4.0.024 (2008-09-12)
1097                  */
1098                 var $spot_colors = array();
1099
1100                 //------------------------------------------------------------
1101                 // METHODS
1102                 //------------------------------------------------------------
1103
1104                 /**
1105                  * This is the class constructor.
1106                  * It allows to set up the page format, the orientation and
1107                  * the measure unit used in all the methods (except for the font sizes).
1108                  * @since 1.0
1109                  * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
1110                  * @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.
1111                  * @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>
1112                  * @param boolean $unicode TRUE means that the input text is unicode (default = true)
1113                  * @param String $encoding charset encoding; default is UTF-8
1114                  */
1115                 function __construct($orientation='P', $unit='mm', $format='A4', $uni=true, $encoding="UTF-8") {
1116                         if ($uni) // Fix for FrontAccounting
1117                         {
1118                                 global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
1119                                 include_once(dirname(__FILE__)."/unicode_data2.php");
1120                         }
1121                         /* Set internal character encoding to ASCII */
1122                         if (function_exists("mb_internal_encoding") AND mb_internal_encoding()) {
1123                                 $this->internal_encoding = mb_internal_encoding();
1124                                 mb_internal_encoding("ASCII");
1125                         }
1126                         // set language direction
1127
1128                         $this->rtl = @$this->l['a_meta_dir']=='rtl' ? true : false;
1129                         $this->tmprtl = false;
1130                         //Some checks
1131                         $this->_dochecks();
1132                         //Initialization of properties
1133                         $this->isunicode = $uni;
1134                         $this->page = 0;
1135                         $this->pagedim = array();
1136                         $this->n = 2;
1137                         $this->buffer = '';
1138                         $this->pages = array();
1139                         $this->state = 0;
1140                         $this->fonts = array();
1141                         $this->FontFiles = array();
1142                         $this->diffs = array();
1143                         $this->images = array();
1144                         $this->links = array();
1145                         $this->gradients = array();
1146                         $this->InFooter = false;
1147                         $this->lasth = 0;
1148                         $this->FontFamily = 'helvetica';
1149                         $this->FontStyle = '';
1150                         $this->FontSizePt = 12;
1151                         $this->underline = false;
1152                         $this->linethrough = false;
1153                         $this->DrawColor = '0 G';
1154                         $this->FillColor = '0 g';
1155                         $this->TextColor = '0 g';
1156                         $this->ColorFlag = false;
1157                         $this->ws = 0;
1158                         // encryption values
1159                         $this->encrypted = false;
1160                         $this->last_rc4_key = '';
1161                         $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";
1162                         //Standard Unicode fonts
1163                         $this->CoreFonts = array(
1164                                 'courier'=>'Courier',
1165                                 'courierB'=>'Courier-Bold',
1166                                 'courierI'=>'Courier-Oblique',
1167                                 'courierBI'=>'Courier-BoldOblique',
1168                                 'helvetica'=>'Helvetica',
1169                                 'helveticaB'=>'Helvetica-Bold',
1170                                 'helveticaI'=>'Helvetica-Oblique',
1171                                 'helveticaBI'=>'Helvetica-BoldOblique',
1172                                 'times'=>'Times-Roman',
1173                                 'timesB'=>'Times-Bold',
1174                                 'timesI'=>'Times-Italic',
1175                                 'timesBI'=>'Times-BoldItalic',
1176                                 'symbol'=>'Symbol',
1177                                 'zapfdingbats'=>'ZapfDingbats'
1178                         );
1179                         //Set scale factor
1180                         $this->setPageUnit($unit);
1181                         // set page format and orientation
1182                         $this->setPageFormat($format, $orientation);
1183                         //Page margins (1 cm)
1184                         $margin = 28.35 / $this->k;
1185                         $this->SetMargins($margin,$margin);
1186                         //Interior cell margin (1 mm)
1187                         $this->cMargin = $margin / 10;
1188                         //Line width (0.2 mm)
1189                         $this->LineWidth = 0.57 / $this->k;
1190                         $this->linestyleWidth = sprintf('%.2f w', ($this->LineWidth * $this->k));
1191                         $this->linestyleCap = "0 J";
1192                         $this->linestyleJoin = "0 j";
1193                         $this->linestyleDash = "[] 0 d";
1194                         //Automatic page break
1195                         $this->SetAutoPageBreak(true, 2*$margin);
1196                         //Full width display mode
1197                         $this->SetDisplayMode('fullwidth');
1198                         //Compression
1199                         $this->SetCompression(true);
1200                         //Set default PDF version number
1201                         $this->PDFVersion = "1.7";
1202                         $this->encoding = $encoding;
1203                         $this->HREF = '';
1204                         $this->getFontsList();
1205                         $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
1206                         $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
1207                         $this->extgstates = array();
1208                         // user's rights
1209                         $this->ur = false;
1210                         $this->ur_document = "/FullSave";
1211                         $this->ur_annots = "/Create/Delete/Modify/Copy/Import/Export";
1212                         $this->ur_form = "/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate";
1213                         $this->ur_signature = "/Modify";
1214                         // set default JPEG quality
1215                         $this->jpeg_quality = 75;
1216                         // initialize some settings
1217                         $this->utf8Bidi(array(""));
1218                 }
1219
1220                 /**
1221                  * Default destructor.
1222                  * @since 1.53.0.TC016
1223                  */
1224                 function TCPDFDestruct() {
1225                         // restore internal encoding
1226                         if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
1227                                 mb_internal_encoding($this->internal_encoding);
1228                         }
1229                 }
1230
1231                 /**
1232                 * Set the units of measure for the document.
1233                 * @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.
1234                 * @since 3.0.015 (2008-06-06)
1235                 */
1236                 function setPageUnit($unit) {
1237                 //Set scale factor
1238                         switch (strtolower($unit)) {
1239                                 // points
1240                                 case 'pt': {
1241                                         $this->k = 1;
1242                                         break;
1243                                 }
1244                                 // millimeters
1245                                 case 'mm': {
1246                                         $this->k = $this->dpi / 25.4;
1247                                         break;
1248                                 }
1249                                 // centimeters
1250                                 case 'cm': {
1251                                         $this->k = $this->dpi / 2.54;
1252                                         break;
1253                                 }
1254                                 // inches
1255                                 case 'in': {
1256                                         $this->k = $this->dpi;
1257                                         break;
1258                                 }
1259                                 // unsupported unit
1260                                 default : {
1261                                         $this->Error('Incorrect unit: '.$unit);
1262                                         break;
1263                                 }
1264                         }
1265                         if (isset($this->CurOrientation)) {
1266                                         $this->setPageOrientation($this->CurOrientation);
1267                         }
1268                 }
1269
1270                 /**
1271                 * Set the page format
1272                 * @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>
1273                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1274                 * @since 3.0.015 (2008-06-06)
1275                 */
1276                 function setPageFormat($format, $orientation="P") {
1277                         //Page format
1278                         if (is_string($format)) {
1279                                 // Page formats (45 standard ISO paper formats and 4 american common formats).
1280                                 // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm)
1281                                 switch (strtoupper($format)){
1282                                         case '4A0': {$format = array(4767.87,6740.79); break;}
1283                                         case '2A0': {$format = array(3370.39,4767.87); break;}
1284                                         case 'A0': {$format = array(2383.94,3370.39); break;}
1285                                         case 'A1': {$format = array(1683.78,2383.94); break;}
1286                                         case 'A2': {$format = array(1190.55,1683.78); break;}
1287                                         case 'A3': {$format = array(841.89,1190.55); break;}
1288                                         case 'A4': default: {$format = array(595.28,841.89); break;}
1289                                         case 'A5': {$format = array(419.53,595.28); break;}
1290                                         case 'A6': {$format = array(297.64,419.53); break;}
1291                                         case 'A7': {$format = array(209.76,297.64); break;}
1292                                         case 'A8': {$format = array(147.40,209.76); break;}
1293                                         case 'A9': {$format = array(104.88,147.40); break;}
1294                                         case 'A10': {$format = array(73.70,104.88); break;}
1295                                         case 'B0': {$format = array(2834.65,4008.19); break;}
1296                                         case 'B1': {$format = array(2004.09,2834.65); break;}
1297                                         case 'B2': {$format = array(1417.32,2004.09); break;}
1298                                         case 'B3': {$format = array(1000.63,1417.32); break;}
1299                                         case 'B4': {$format = array(708.66,1000.63); break;}
1300                                         case 'B5': {$format = array(498.90,708.66); break;}
1301                                         case 'B6': {$format = array(354.33,498.90); break;}
1302                                         case 'B7': {$format = array(249.45,354.33); break;}
1303                                         case 'B8': {$format = array(175.75,249.45); break;}
1304                                         case 'B9': {$format = array(124.72,175.75); break;}
1305                                         case 'B10': {$format = array(87.87,124.72); break;}
1306                                         case 'C0': {$format = array(2599.37,3676.54); break;}
1307                                         case 'C1': {$format = array(1836.85,2599.37); break;}
1308                                         case 'C2': {$format = array(1298.27,1836.85); break;}
1309                                         case 'C3': {$format = array(918.43,1298.27); break;}
1310                                         case 'C4': {$format = array(649.13,918.43); break;}
1311                                         case 'C5': {$format = array(459.21,649.13); break;}
1312                                         case 'C6': {$format = array(323.15,459.21); break;}
1313                                         case 'C7': {$format = array(229.61,323.15); break;}
1314                                         case 'C8': {$format = array(161.57,229.61); break;}
1315                                         case 'C9': {$format = array(113.39,161.57); break;}
1316                                         case 'C10': {$format = array(79.37,113.39); break;}
1317                                         case 'RA0': {$format = array(2437.80,3458.27); break;}
1318                                         case 'RA1': {$format = array(1729.13,2437.80); break;}
1319                                         case 'RA2': {$format = array(1218.90,1729.13); break;}
1320                                         case 'RA3': {$format = array(864.57,1218.90); break;}
1321                                         case 'RA4': {$format = array(609.45,864.57); break;}
1322                                         case 'SRA0': {$format = array(2551.18,3628.35); break;}
1323                                         case 'SRA1': {$format = array(1814.17,2551.18); break;}
1324                                         case 'SRA2': {$format = array(1275.59,1814.17); break;}
1325                                         case 'SRA3': {$format = array(907.09,1275.59); break;}
1326                                         case 'SRA4': {$format = array(637.80,907.09); break;}
1327                                         case 'LETTER': {$format = array(612.00,792.00); break;}
1328                                         case 'LEGAL': {$format = array(612.00,1008.00); break;}
1329                                         case 'EXECUTIVE': {$format = array(521.86,756.00); break;}
1330                                         case 'FOLIO': {$format = array(612.00,936.00); break;}
1331                                 }
1332                                 $this->fwPt = $format[0];
1333                                 $this->fhPt = $format[1];
1334                         }
1335                         else {
1336                                 $this->fwPt = $format[0] * $this->k;
1337                                 $this->fhPt = $format[1] * $this->k;
1338                         }
1339                         $this->setPageOrientation($orientation);
1340                 }
1341
1342
1343                 /**
1344                 * Set page orientation.
1345                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1346                 * @param boolean $autopagebreak Boolean indicating if auto-page-break mode should be on or off.
1347                 * @param float $bottommargin bottom margin of the page.
1348                 * @since 3.0.015 (2008-06-06)
1349                 */
1350                 function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
1351                         $orientation = strtoupper($orientation);
1352                         if (($orientation == 'P') OR ($orientation == 'PORTRAIT')) {
1353                                 $this->CurOrientation = 'P';
1354                                 $this->wPt = $this->fwPt;
1355                                 $this->hPt = $this->fhPt;
1356                         } elseif (($orientation == 'L') OR ($orientation == 'LANDSCAPE')) {
1357                                 $this->CurOrientation = 'L';
1358                                 $this->wPt = $this->fhPt;
1359                                 $this->hPt = $this->fwPt;
1360                         }
1361                         else {
1362                                 $this->Error('Incorrect orientation: '.$orientation);
1363                         }
1364                         $this->w = $this->wPt / $this->k;
1365                         $this->h = $this->hPt / $this->k;
1366                         if (empty($autopagebreak)) {
1367                                 if (isset($this->AutoPageBreak)) {
1368                                         $autopagebreak = $this->AutoPageBreak;
1369                                 } else {
1370                                         $autopagebreak = true;
1371                                 }
1372                         }
1373                         if (empty($bottommargin)) {
1374                                 if (isset($this->bMargin)) {
1375                                         $bottommargin = $this->bMargin;
1376                                 } else {
1377                                         // default value = 2 cm
1378                                         $bottommargin = 2 * 28.35 / $this->k;
1379                                 }
1380                         }
1381                         $this->SetAutoPageBreak($autopagebreak, $bottommargin);
1382                         // store page dimensions
1383                         $this->pagedim[$this->page] = array('w' => $this->wPt, 'h' => $this->hPt, 'tm' => $this->tMargin, 'bm' => $bottommargin, 'lm' => $this->lMargin, 'rm' => $this->rMargin, 'pb' => $autopagebreak, 'or' => $this->CurOrientation);
1384                 }
1385
1386                 /**
1387                  * Enable or disable Right-To-Left language mode
1388                  * @param Boolean $enable if true enable Right-To-Left language mode.
1389                  * @since 2.0.000 (2008-01-03)
1390                  */
1391                 function setRTL($enable) {
1392                         $this->rtl = $enable ? true : false;
1393                         $this->tmprtl = false;
1394                 }
1395
1396                 /**
1397                  * Return the RTL status
1398                  * @return boolean
1399                  * @since 4.0.012 (2008-07-24)
1400                  */
1401                 function getRTL() {
1402                         return $this->rtl;
1403                 }
1404
1405                 /**
1406                 * Force temporary RTL language direction
1407                 * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL
1408                 * @since 2.1.000 (2008-01-09)
1409                 */
1410                 function setTempRTL($mode) {
1411                         switch ($mode) {
1412                                 case false:
1413                                 case 'L':
1414                                 case 'R': {
1415                                         $this->tmprtl = $mode;
1416                                 }
1417                         }
1418                 }
1419
1420                 /**
1421                 * Set the last cell height.
1422                 * @param float $h cell height.
1423                 * @author Nicola Asuni
1424                 * @since 1.53.0.TC034
1425                 */
1426                 function setLastH($h) {
1427                         $this->lasth = $h;
1428                 }
1429
1430                 /**
1431                 * Get the last cell height.
1432                 * @return last cell height
1433                 * @since 4.0.017 (2008-08-05)
1434                 */
1435                 function getLastH() {
1436                         return $this->lasth;
1437                 }
1438
1439                 /**
1440                 * Set the image scale.
1441                 * @param float $scale image scale.
1442                 * @author Nicola Asuni
1443                 * @since 1.5.2
1444                 */
1445                 function setImageScale($scale) {
1446                         $this->imgscale = $scale;
1447                 }
1448
1449                 /**
1450                 * Returns the image scale.
1451                 * @return float image scale.
1452                 * @author Nicola Asuni
1453                 * @since 1.5.2
1454                 */
1455                 function getImageScale() {
1456                         return $this->imgscale;
1457                 }
1458
1459                 /**
1460                 * Returns the page width in units.
1461                 * @return int page width.
1462                 * @author Nicola Asuni
1463                 * @since 1.5.2
1464                 */
1465                 function getPageWidth() {
1466                         return $this->w;
1467                 }
1468
1469                 /**
1470                 * Returns the page height in units.
1471                 * @return int page height.
1472                 * @author Nicola Asuni
1473                 * @since 1.5.2
1474                 */
1475                 function getPageHeight() {
1476                         return $this->h;
1477                 }
1478
1479                 /**
1480                 * Returns the page break margin.
1481                 * @return int page break margin.
1482                 * @author Nicola Asuni
1483                 * @since 1.5.2
1484                 */
1485                 function getBreakMargin() {
1486                         return $this->bMargin;
1487                 }
1488
1489                 /**
1490                 * Returns the scale factor (number of points in user unit).
1491                 * @return int scale factor.
1492                 * @author Nicola Asuni
1493                 * @since 1.5.2
1494                 */
1495                 function getScaleFactor() {
1496                         return $this->k;
1497                 }
1498
1499                 /**
1500                 * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
1501                 * @param float $left Left margin.
1502                 * @param float $top Top margin.
1503                 * @param float $right Right margin. Default value is the left one.
1504                 * @since 1.0
1505                 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
1506                 */
1507                 function SetMargins($left, $top, $right=-1) {
1508                         //Set left, top and right margins
1509                         $this->lMargin = $left;
1510                         $this->tMargin = $top;
1511                         if ($right == -1) {
1512                                 $right = $left;
1513                         }
1514                         $this->rMargin = $right;
1515                 }
1516
1517                 /**
1518                 * 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.
1519                 * @param float $margin The margin.
1520                 * @since 1.4
1521                 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1522                 */
1523                 function SetLeftMargin($margin) {
1524                         //Set left margin
1525                         $this->lMargin=$margin;
1526                         if (($this->page > 0) AND ($this->x < $margin)) {
1527                                 $this->x = $margin;
1528                         }
1529                 }
1530
1531                 /**
1532                 * Defines the top margin. The method can be called before creating the first page.
1533                 * @param float $margin The margin.
1534                 * @since 1.5
1535                 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1536                 */
1537                 function SetTopMargin($margin) {
1538                         //Set top margin
1539                         $this->tMargin=$margin;
1540                         if (($this->page > 0) AND ($this->y < $margin)) {
1541                                 $this->y = $margin;
1542                         }
1543                 }
1544
1545                 /**
1546                 * Defines the right margin. The method can be called before creating the first page.
1547                 * @param float $margin The margin.
1548                 * @since 1.5
1549                 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1550                 */
1551                 function SetRightMargin($margin) {
1552                         $this->rMargin=$margin;
1553                         if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
1554                                 $this->x = $this->w - $margin;
1555                         }
1556                 }
1557
1558                 /**
1559                 * Set the internal Cell padding.
1560                 * @param float $pad internal padding.
1561                 * @since 2.1.000 (2008-01-09)
1562                 * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1563                 */
1564                 function SetCellPadding($pad) {
1565                         $this->cMargin = $pad;
1566                 }
1567
1568                 /**
1569                 * 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.
1570                 * @param boolean $auto Boolean indicating if mode should be on or off.
1571                 * @param float $margin Distance from the bottom of the page.
1572                 * @since 1.0
1573                 * @see Cell(), MultiCell(), AcceptPageBreak()
1574                 */
1575                 function SetAutoPageBreak($auto, $margin=0) {
1576                         //Set auto page break mode and triggering margin
1577                         $this->AutoPageBreak = $auto;
1578                         $this->bMargin = $margin;
1579                         $this->PageBreakTrigger = $this->h - $margin;
1580                 }
1581
1582                 /**
1583                 * Defines the way the document is to be displayed by the viewer.
1584                 * @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>
1585                 * @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>
1586                 * @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>
1587                 * @since 1.2
1588                 */
1589                 function SetDisplayMode($zoom, $layout='SinglePage', $mode="UseNone") {
1590                         //Set display mode in viewer
1591                         if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
1592                                 $this->ZoomMode = $zoom;
1593                         } else {
1594                                 $this->Error('Incorrect zoom display mode: '.$zoom);
1595                         }
1596                         switch ($layout) {
1597                                 case "default":
1598                                 case "single":
1599                                 case "SinglePage": {
1600                                         $this->LayoutMode = "SinglePage";
1601                                         break;
1602                                 }
1603                                 case "continuous":
1604                                 case "OneColumn": {
1605                                         $this->LayoutMode = "OneColumn";
1606                                         break;
1607                                 }
1608                                 case "two":
1609                                 case "TwoColumnLeft": {
1610                                         $this->LayoutMode = "TwoColumnLeft";
1611                                         break;
1612                                 }
1613                                 case "TwoColumnRight": {
1614                                         $this->LayoutMode = "TwoColumnRight";
1615                                         break;
1616                                 }
1617                                 case "TwoPageLeft": {
1618                                         $this->LayoutMode = "TwoPageLeft";
1619                                         break;
1620                                 }
1621                                 case "TwoPageRight": {
1622                                         $this->LayoutMode = "TwoPageRight";
1623                                         break;
1624                                 }
1625                                 default: {
1626                                         $this->LayoutMode = "SinglePage";
1627                                 }
1628                         }
1629                         switch ($mode) {
1630                                 case "UseNone": {
1631                                         $this->PageMode = "UseNone";
1632                                         break;
1633                                 }
1634                                 case "UseOutlines": {
1635                                         $this->PageMode = "UseOutlines";
1636                                         break;
1637                                 }
1638                                 case "UseThumbs": {
1639                                         $this->PageMode = "UseThumbs";
1640                                         break;
1641                                 }
1642                                 case "FullScreen": {
1643                                         $this->PageMode = "FullScreen";
1644                                         break;
1645                                 }
1646                                 case "UseOC": {
1647                                         $this->PageMode = "UseOC";
1648                                         break;
1649                                 }
1650                                 case "": {
1651                                         $this->PageMode = "UseAttachments";
1652                                         break;
1653                                 }
1654                                 default: {
1655                                         $this->PageMode = "UseNone";
1656                                 }
1657                         }
1658                 }
1659
1660                 /**
1661                 * 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.
1662                 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
1663                 * @param boolean $compress Boolean indicating if compression must be enabled.
1664                 * @since 1.4
1665                 */
1666                 function SetCompression($compress) {
1667                         //Set page compression
1668                         if (function_exists('gzcompress')) {
1669                                 $this->compress = $compress;
1670                         } else {
1671                                 $this->compress = false;
1672                         }
1673                 }
1674
1675                 /**
1676                 * Defines the title of the document.
1677                 * @param string $title The title.
1678                 * @since 1.2
1679                 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
1680                 */
1681                 function SetTitle($title) {
1682                         //Title of document
1683                         $this->title = $title;
1684                 }
1685
1686                 /**
1687                 * Defines the subject of the document.
1688                 * @param string $subject The subject.
1689                 * @since 1.2
1690                 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
1691                 */
1692                 function SetSubject($subject) {
1693                         //Subject of document
1694                         $this->subject = $subject;
1695                 }
1696
1697                 /**
1698                 * Defines the author of the document.
1699                 * @param string $author The name of the author.
1700                 * @since 1.2
1701                 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
1702                 */
1703                 function SetAuthor($author) {
1704                         //Author of document
1705                         $this->author = $author;
1706                 }
1707
1708                 /**
1709                 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
1710                 * @param string $keywords The list of keywords.
1711                 * @since 1.2
1712                 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
1713                 */
1714                 function SetKeywords($keywords) {
1715                         //Keywords of document
1716                         $this->keywords = $keywords;
1717                 }
1718
1719                 /**
1720                 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
1721                 * @param string $creator The name of the creator.
1722                 * @since 1.2
1723                 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
1724                 */
1725                 function SetCreator($creator) {
1726                         //Creator of document
1727                         $this->creator = $creator;
1728                 }
1729
1730                 /**
1731                 * Defines an alias for the total number of pages. It will be substituted as the document is closed.<br />
1732                 * @param string $alias The alias. Default value: {nb}.
1733                 * @since 1.4
1734                 * @see getAliasNbPages(), PageNo(), Footer()
1735                 */
1736                 function AliasNbPages($alias='{nb}') {
1737                         //Define an alias for total number of pages
1738                         $this->AliasNbPages = $alias;
1739                 }
1740                 
1741                 /**
1742                  * Returns the string alias used for the total number of pages.
1743          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
1744                  * @return string
1745                  * @since 4.0.018 (2008-08-08)
1746                  * @see AliasNbPages(), PageNo(), Footer()
1747                 */
1748                 function getAliasNbPages() {
1749                         if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
1750                                 return "{".$this->AliasNbPages."}";
1751             }
1752                         return $this->AliasNbPages;
1753                 }
1754
1755                 /**
1756                 * 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.
1757                 * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
1758                 * @param string $msg The error message
1759                 * @since 1.0
1760                 */
1761                 function Error($msg) {
1762                         //Fatal error
1763                         display_error('<strong>TCPDF error: </strong>'.$msg);
1764                         exit;
1765                 }
1766
1767                 /**
1768                 * This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.
1769                 * Note: no page is created by this method
1770                 * @since 1.0
1771                 * @see AddPage(), Close()
1772                 */
1773                 function Open() {
1774                         //Begin document
1775                         $this->state = 1;
1776                 }
1777
1778                 /**
1779                 * 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.
1780                 * @since 1.0
1781                 * @see Open(), Output()
1782                 */
1783                 function Close() {
1784                         //Terminate document
1785                         if ($this->state == 3) {
1786                                 return;
1787                         }
1788                         if ($this->page == 0) {
1789                                 $this->AddPage();
1790                         }
1791                         //Page footer
1792                         $this->setFooter();
1793                         //Close page
1794                         $this->_endpage();
1795                         //Close document
1796                         $this->_enddoc();
1797                 }
1798
1799                 /**
1800                 * Move pointer at the specified document page and update page dimensions.
1801                 * @param int $pnum page number
1802                 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
1803                 * @since 2.1.000 (2008-01-07)
1804                 * @see getPage(), lastpage(), getNumPages()
1805                 */
1806                 function setPage($pnum, $resetmargins=false) {
1807                         if (($pnum > 0) AND ($pnum <= count($this->pages))) {
1808                                 $this->page = $pnum;
1809                                 $this->wPt = $this->pagedim[$this->page]['w'];
1810                                 $this->hPt = $this->pagedim[$this->page]['h'];
1811                                 $this->w = $this->wPt / $this->k;
1812                                 $this->h = $this->hPt / $this->k;
1813                                 $this->tMargin = $this->pagedim[$this->page]['tm'];
1814                                 $this->bMargin = $this->pagedim[$this->page]['bm'];
1815                                 $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
1816                                 $this->CurOrientation = $this->pagedim[$this->page]['or'];
1817                                 $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
1818                                 if ($resetmargins) {
1819                                         $this->lMargin = $this->pagedim[$this->page]['lm'];
1820                                         $this->rMargin = $this->pagedim[$this->page]['rm'];
1821                                         $this->SetY($this->tMargin);
1822                                 }
1823                         } else {
1824                                 $this->Error('Wrong page number on setPage() function.');
1825                         }
1826                 }
1827
1828                 /**
1829                 * Reset pointer to the last document page.
1830                 * @since 2.0.000 (2008-01-04)
1831                 * @see setPage(), getPage(), getNumPages()
1832                 */
1833                 function lastPage() {
1834                         $this->setPage($this->getNumPages());
1835                 }
1836
1837                 /**
1838                 * Get current document page number.
1839                 * @return int page number
1840                 * @since 2.1.000 (2008-01-07)
1841                 * @see setPage(), lastpage(), getNumPages()
1842                 */
1843                 function getPage() {
1844                         return $this->page;
1845                 }
1846
1847
1848                 /**
1849                 * Get the total number of insered pages.
1850                 * @return int number of pages
1851                 * @since 2.1.000 (2008-01-07)
1852                 * @see setPage(), getPage(), lastpage()
1853                 */
1854                 function getNumPages() {
1855                         return count($this->pages);
1856                 }
1857
1858                 /**
1859                 * 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.
1860                 * 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.
1861                 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
1862                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1863                 * @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>
1864                 * @since 1.0
1865                 * @see TCPDF(), Header(), Footer(), SetMargins()
1866                 */
1867                 function AddPage($orientation='', $format='') {
1868                         if (!isset($this->original_lMargin)) {
1869                                 $this->original_lMargin = $this->lMargin;
1870                         }
1871                         if (!isset($this->original_rMargin)) {
1872                                 $this->original_rMargin = $this->rMargin;
1873                         }
1874                         if (count($this->pages) > $this->page) {
1875                                 // this page has been already added
1876                                 $this->setPage(($this->page + 1));
1877                                 $this->SetY($this->tMargin);
1878                                 return;
1879                         }
1880                         //Start a new page
1881                         if ($this->state == 0) {
1882                                 $this->Open();
1883                         }
1884                         // save current settings
1885                         $font_family = $this->FontFamily;
1886                         $font_style = $this->FontStyle.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '');
1887                         $font_size = $this->FontSizePt;
1888                         $prev_rMargin = $this->rMargin;
1889                         $prev_lMargin = $this->lMargin;
1890                         $prev_cMargin = $this->cMargin;
1891                         $prev_linestyleWidth = $this->linestyleWidth;
1892                         $prev_linestyleCap = $this->linestyleCap;
1893                         $prev_linestyleJoin = $this->linestyleJoin;
1894                         $prev_linestyleDash = $this->linestyleDash;
1895                         $prev_DrawColor = $this->DrawColor;
1896                         $prev_FillColor = $this->FillColor;
1897                         $prev_TextColor = $this->TextColor;
1898                         $prev_ColorFlag = $this->ColorFlag;
1899                         if ($this->page > 0) {
1900                                 //Page footer
1901                                 $this->setFooter();
1902                                 //Close page
1903                                 $this->_endpage();
1904                         }
1905                         //Start new page
1906                         $this->_beginpage($orientation, $format);
1907                         // restore graphic styles
1908                         $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1909                         if (!empty($font_family)) {
1910                                 $this->SetFont($font_family, $font_style, $font_size);
1911                         }
1912                         //Page header
1913                         $this->setHeader();
1914                         // restore graphic styles
1915                         $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1916                         if (!empty($font_family)) {
1917                                 $this->SetFont($font_family, $font_style, $font_size);
1918                         }
1919                         // restore settings
1920                         $this->FontFamily = $font_family;
1921                         $this->FontStyle = $font_style;
1922                         $this->FontSizePt = $font_size;
1923                         $this->rMargin = $prev_rMargin;
1924                         $this->lMargin = $prev_lMargin;
1925                         $this->cMargin = $prev_cMargin;
1926                         $this->linestyleWidth = $prev_linestyleWidth;
1927                         $this->linestyleCap = $prev_linestyleCap;
1928                         $this->linestyleJoin = $prev_linestyleJoin;
1929                         $this->linestyleDash = $prev_linestyleDash;
1930                         $this->DrawColor = $prev_DrawColor;
1931                         $this->FillColor = $prev_FillColor;
1932                         $this->TextColor = $prev_TextColor;
1933                         $this->ColorFlag = $prev_ColorFlag;
1934                         // mark this point
1935                         $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1936                 }
1937
1938                 /**
1939                  * Set start-writing mark on current page for multicell borders and fills.
1940                  * This function must be called after calling Image() function for a background image.
1941                  * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
1942                  * @access public
1943                  * @since 4.0.016 (2008-07-30)
1944                  */
1945                 function setPageMark() {
1946                         $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1947                 }
1948
1949                 /**
1950                  * Set header data.
1951                  * @param string $ln header image logo
1952                  * @param string $lw header image logo width in mm
1953                  * @param string $ht string to print as title on document header
1954                  * @param string $hs string to print on document header
1955                 */
1956                 function setHeaderData($ln="", $lw=0, $ht="", $hs="") {
1957                         $this->header_logo = $ln;
1958                         $this->header_logo_width = $lw;
1959                         $this->header_title = $ht;
1960                         $this->header_string = $hs;
1961                 }
1962
1963                 /**
1964                  * Returns header data:
1965                  * <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>
1966                  * @return array()
1967                  * @since 4.0.012 (2008-07-24)
1968                  */
1969                 function getHeaderData() {
1970                         $ret = array();
1971                         $ret['logo'] = $this->header_logo;
1972                         $ret['logo_width'] = $this->header_logo_width;
1973                         $ret['title'] = $this->header_title;
1974                         $ret['string'] = $this->header_string;
1975                         return $ret;
1976                 }
1977
1978                 /**
1979                  * Set header margin.
1980                  * (minimum distance between header and top page margin)
1981                  * @param int $hm distance in user units
1982                 */
1983                 function setHeaderMargin($hm=10) {
1984                         $this->header_margin = $hm;
1985                 }
1986
1987                 /**
1988                  * Returns header margin in user units.
1989                  * @return float
1990                  * @since 4.0.012 (2008-07-24)
1991                 */
1992                 function getHeaderMargin() {
1993                         return $this->header_margin;
1994                 }
1995
1996                 /**
1997                  * Set footer margin.
1998                  * (minimum distance between footer and bottom page margin)
1999                  * @param int $fm distance in user units
2000                 */
2001                 function setFooterMargin($fm=10) {
2002                         $this->footer_margin = $fm;
2003                 }
2004
2005                 /**
2006                  * Returns footer margin in user units.
2007                  * @return float
2008                  * @since 4.0.012 (2008-07-24)
2009                 */
2010                 function getFooterMargin() {
2011                         return $this->footer_margin;
2012                 }
2013                 /**
2014                  * Set a flag to print page header.
2015                  * @param boolean $val set to true to print the page header (default), false otherwise.
2016                  */
2017                 function setPrintHeader($val=true) {
2018                         $this->print_header = $val;
2019                 }
2020
2021                 /**
2022                  * Set a flag to print page footer.
2023                  * @param boolean $value set to true to print the page footer (default), false otherwise.
2024                  */
2025                 function setPrintFooter($val=true) {
2026                         $this->print_footer = $val;
2027                 }
2028
2029                 /**
2030                  * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
2031                  * @return float
2032                  */
2033                 function getImageRBX() {
2034                         return $this->img_rb_x;
2035                 }
2036
2037                 /**
2038                  * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
2039                  * @return float
2040                  */
2041                 function getImageRBY() {
2042                         return $this->img_rb_y;
2043                 }
2044
2045                 /**
2046                  * This method is used to render the page header.
2047                  * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2048                  */
2049                 function Header1() {
2050                         $ormargins = $this->getOriginalMargins();
2051                         $headerfont = $this->getHeaderFont();
2052                         $headerdata = $this->getHeaderData();
2053                         if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
2054                                 $this->Image(K_PATH_IMAGES.$headerdata['logo'], $this->GetX(), $this->getHeaderMargin(), $headerdata['logo_width']);
2055                                 $imgy = $this->getImageRBY();
2056                         } else {
2057                                 $imgy = $this->GetY();
2058                         }
2059                         $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2);
2060                         // set starting margin for text data cell
2061                         if ($this->getRTL()) {
2062                                 $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1);
2063                         } else {
2064                                 $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1);
2065                         }
2066                         $this->SetTextColor(0, 0, 0);
2067                         // header title
2068                         $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
2069                         $this->SetX($header_x);
2070                         $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '');
2071                         // header string
2072                         $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
2073                         $this->SetX($header_x);
2074                         $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, 0, 0, true, 0);
2075                         // print an ending header line
2076                         $this->SetLineStyle(array("width" => 0.85 / $this->getScaleFactor(), "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2077                         $this->SetY(1 + max($imgy, $this->GetY()));
2078                         if ($this->getRTL()) {
2079                                 $this->SetX($ormargins['right']);
2080                         } else {
2081                                 $this->SetX($ormargins['left']);
2082                         }
2083                         $this->Cell(0, 0, '', 'T', 0, 'C');
2084                 }
2085
2086                 /**
2087                  * This method is used to render the page footer.
2088                  * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2089                  */
2090                 function Footer() {
2091                         $cur_y = $this->GetY();
2092                         $ormargins = $this->getOriginalMargins();
2093                         $this->SetTextColor(0, 0, 0);
2094                         //set style for cell border
2095                         $line_width = 0.85 / $this->getScaleFactor();
2096                         $this->SetLineStyle(array("width" => $line_width, "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2097                         //print document barcode
2098                         $barcode = $this->getBarcode();
2099                         if (!empty($barcode)) {
2100                                 $this->Ln();
2101                                 $barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right'])/3);
2102                                 $this->write1DBarcode($barcode, "C128B", $this->GetX(), $cur_y + $line_width, $barcode_width, (($this->getFooterMargin() / 3) - $line_width), 0.3, '', '');
2103                         }
2104                         $pagenumtxt = $this->l['w_page']." ".$this->PageNo().' / '.$this->getAliasNbPages();
2105                         $this->SetY($cur_y);
2106                         //Print page number
2107                         if ($this->getRTL()) {
2108                                 $this->SetX($ormargins['right']);
2109                                 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
2110                         } else {
2111                                 $this->SetX($ormargins['left']);
2112                                 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R');
2113                         }
2114                 }
2115
2116                 /**
2117                  * This method is used to render the page header.
2118                  * @access protected
2119                  * @since 4.0.012 (2008-07-24)
2120                  */
2121                 function setHeader() {
2122                         if ($this->print_header) {
2123                                 $lasth = $this->lasth;
2124                                 $this->_out("q");
2125                                 $this->rMargin = $this->original_rMargin;
2126                                 $this->lMargin = $this->original_lMargin;
2127                                 //set current position
2128                                 if ($this->rtl) {
2129                                         $this->SetXY($this->original_rMargin, $this->header_margin);
2130                                 } else {
2131                                         $this->SetXY($this->original_lMargin, $this->header_margin);
2132                                 }
2133                                 $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
2134                                 $this->Header1();
2135                                 //restore position
2136                                 if ($this->rtl) {
2137                                         $this->SetXY($this->original_rMargin, $this->tMargin);
2138                                 } else {
2139                                         $this->SetXY($this->original_lMargin, $this->tMargin);
2140                                 }
2141                                 $this->_out("Q");
2142                                 $this->lasth = $lasth;
2143                         }
2144                 }
2145
2146                 /**
2147                  * This method is used to render the page footer.
2148                  * @access protected
2149                  * @since 4.0.012 (2008-07-24)
2150                  */
2151                 function setFooter() {
2152                         //Page footer
2153                         $this->InFooter = true;
2154                         // mark this point
2155                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
2156                         if ($this->print_footer) {
2157                                 $lasth = $this->lasth;
2158                                 $this->_out("q");
2159                                 $this->rMargin = $this->original_rMargin;
2160                                 $this->lMargin = $this->original_lMargin;
2161                                 //set current position
2162                                 $footer_y = $this->h - $this->footer_margin;
2163                                 if ($this->rtl) {
2164                                         $this->SetXY($this->original_rMargin, $footer_y);
2165                                 } else {
2166                                         $this->SetXY($this->original_lMargin, $footer_y);
2167                                 }
2168                                 $this->SetFont($this->footer_font[0], $this->footer_font[1] , $this->footer_font[2]);
2169                                 $this->Footer();
2170                                 //restore position
2171                                 if ($this->rtl) {
2172                                         $this->SetXY($this->original_rMargin, $this->tMargin);
2173                                 } else {
2174                                         $this->SetXY($this->original_lMargin, $this->tMargin);
2175                                 }
2176                                 $this->_out("Q");
2177                                 $this->lasth = $lasth;
2178                         }
2179                         $this->footerlen[$this->page] = strlen($this->pages[$this->page]) - $this->footerpos[$this->page];
2180                         $this->InFooter = false;
2181                 }
2182
2183                 /**
2184                 * Returns the current page number.
2185                 * @return int page number
2186                 * @since 1.0
2187                 * @see AliasNbPages(), getAliasNbPages()
2188                 */
2189                 function PageNo() {
2190                         return $this->page;
2191                 }
2192
2193                 /**
2194                 * Defines a new spot color. 
2195                 * It can be expressed in RGB components or gray scale. 
2196                 * The method can be called before the first page is created and the value is retained from page to page.
2197                 * @param int $c Cyan color for CMYK. Value between 0 and 255
2198                 * @param int $m Magenta color for CMYK. Value between 0 and 255
2199                 * @param int $y Yellow color for CMYK. Value between 0 and 255
2200                 * @param int $k Key (Black) color for CMYK. Value between 0 and 255
2201                 * @since 4.0.024 (2008-09-12)
2202                 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2203                 */
2204                 function AddSpotColor($name, $c, $m, $y, $k) {
2205                         if (!isset($this->spot_colors[$name])) {
2206                                 $i = 1 + count($this->spot_colors);
2207                                 $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k);
2208                         }
2209                 }
2210
2211                 /**
2212                 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
2213                 * It can be expressed in RGB components or gray scale.
2214                 * The method can be called before the first page is created and the value is retained from page to page.
2215                 * @param array $color array of colors
2216                 * @since 3.1.000 (2008-06-11)
2217                 * @see SetDrawColor()
2218                 */
2219                 function SetDrawColorArray($color) {
2220                         if (isset($color)) {
2221                                 $color = array_values($color);
2222                                 $r = isset($color[0]) ? $color[0] : -1;
2223                                 $g = isset($color[1]) ? $color[1] : -1;
2224                                 $b = isset($color[2]) ? $color[2] : -1;
2225                                 $k = isset($color[3]) ? $color[3] : -1;
2226                                 if ($r >= 0) {
2227                                         $this->SetDrawColor($r, $g, $b, $k);
2228                                 }
2229                         }
2230                 }
2231
2232                 /**
2233                 * 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.
2234                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2235                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2236                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2237                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2238                 * @since 1.3
2239                 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
2240                 */
2241                 function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2242                         // set default values
2243                         if (!is_numeric($col1)) {
2244                                 $col1 = 0;
2245                         }
2246                         if (!is_numeric($col2)) {
2247                                 $col2 = -1;
2248                         }
2249                         if (!is_numeric($col3)) {
2250                                 $col3 = -1;
2251                         }
2252                         if (!is_numeric($col4)) {
2253                                 $col4 = -1;
2254                         }
2255                         //Set color for all stroking operations
2256                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2257                                 // Grey scale
2258                                 $this->DrawColor = sprintf('%.3f G', $col1/255);
2259                         } elseif ($col4 == -1) {
2260                                 // RGB
2261                                 $this->DrawColor = sprintf('%.3f %.3f %.3f RG', $col1/255, $col2/255, $col3/255);
2262                         } else {
2263                                 // CMYK
2264                                 $this->DrawColor = sprintf('%.3f %.3f %.3f %.3f K', $col1/100, $col2/100, $col3/100, $col4/100);
2265                         }
2266                         if ($this->page > 0) {
2267                                 $this->_out($this->DrawColor);
2268                         }
2269                 }
2270                 
2271                 /**
2272                 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
2273                 * @param string $name name of the spot color
2274                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2275                 * @since 4.0.024 (2008-09-12)
2276                 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2277                 */
2278                 function SetDrawSpotColor($name, $tint=100) {
2279                         if (!isset($this->spot_colors[$name])) {
2280                                 $this->Error('Undefined spot color: '.$name);
2281                         }
2282                         $this->DrawColor = sprintf('/CS%d CS %.3f SCN', $this->spot_colors[$name]['i'], $tint/100);
2283                         if ($this->page > 0) {
2284                                 $this->_out($this->DrawColor);
2285                         }
2286                 }
2287
2288                 /**
2289                 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
2290                 * It can be expressed in RGB components or gray scale.
2291                 * The method can be called before the first page is created and the value is retained from page to page.
2292                 * @param array $color array of colors
2293                 * @since 3.1.000 (2008-6-11)
2294                 * @see SetFillColor()
2295                 */
2296                 function SetFillColorArray($color) {
2297                         if (isset($color)) {
2298                                 $color = array_values($color);
2299                                 $r = isset($color[0]) ? $color[0] : -1;
2300                                 $g = isset($color[1]) ? $color[1] : -1;
2301                                 $b = isset($color[2]) ? $color[2] : -1;
2302                                 $k = isset($color[3]) ? $color[3] : -1;
2303                                 if ($r >= 0) {
2304                                         $this->SetFillColor($r, $g, $b, $k);
2305                                 }
2306                         }
2307                 }
2308
2309                 /**
2310                 * 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.
2311                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2312                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2313                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2314                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2315                 * @since 1.3
2316                 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
2317                 */
2318                 function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2319                         // set default values
2320                         if (!is_numeric($col1)) {
2321                                 $col1 = 0;
2322                         }
2323                         if (!is_numeric($col2)) {
2324                                 $col2 = -1;
2325                         }
2326                         if (!is_numeric($col3)) {
2327                                 $col3 = -1;
2328                         }
2329                         if (!is_numeric($col4)) {
2330                                 $col4 = -1;
2331                         }
2332                         //Set color for all filling operations
2333                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2334                                 // Grey scale
2335                                 $this->FillColor = sprintf('%.3f g', $col1/255);
2336                                 $this->bgcolor = array('G' => $col1);
2337                         } elseif ($col4 == -1) {
2338                                 // RGB
2339                                 $this->FillColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2340                                 $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2341                         } else {
2342                                 // CMYK
2343                                 $this->FillColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2344                                 $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2345                         }
2346                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2347                         if ($this->page > 0) {
2348                                 $this->_out($this->FillColor);
2349                         }
2350                 }
2351                 
2352                 /**
2353                 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
2354                 * @param string $name name of the spot color
2355                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2356                 * @since 4.0.024 (2008-09-12)
2357                 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
2358                 */
2359                 function SetFillSpotColor($name, $tint=100) {
2360                         if (!isset($this->spot_colors[$name])) {
2361                                 $this->Error('Undefined spot color: '.$name);
2362                         }
2363                         $this->FillColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2364                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2365                         if ($this->page > 0) {
2366                                 $this->_out($this->FillColor);
2367                         }
2368                 }
2369
2370                 /**
2371                 * Defines the color used for text. It can be expressed in RGB components or gray scale.
2372                 * The method can be called before the first page is created and the value is retained from page to page.
2373                 * @param array $color array of colors
2374                 * @since 3.1.000 (2008-6-11)
2375                 * @see SetFillColor()
2376                 */
2377                 function SetTextColorArray($color) {
2378                         if (isset($color)) {
2379                                 $color = array_values($color);
2380                                 $r = isset($color[0]) ? $color[0] : -1;
2381                                 $g = isset($color[1]) ? $color[1] : -1;
2382                                 $b = isset($color[2]) ? $color[2] : -1;
2383                                 $k = isset($color[3]) ? $color[3] : -1;
2384                                 if ($r >= 0) {
2385                                         $this->SetTextColor($r, $g, $b, $k);
2386                                 }
2387                         }
2388                 }
2389
2390                 /**
2391                 * 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.
2392                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2393                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2394                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2395                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2396                 * @since 1.3
2397                 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
2398                 */
2399                 function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2400                         // set default values
2401                         if (!is_numeric($col1)) {
2402                                 $col1 = 0;
2403                         }
2404                         if (!is_numeric($col2)) {
2405                                 $col2 = -1;
2406                         }
2407                         if (!is_numeric($col3)) {
2408                                 $col3 = -1;
2409                         }
2410                         if (!is_numeric($col4)) {
2411                                 $col4 = -1;
2412                         }
2413                         //Set color for text
2414                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2415                                 // Grey scale
2416                                 $this->TextColor = sprintf('%.3f g', $col1/255);
2417                                 $this->fgcolor = array('G' => $col1);
2418                         } elseif ($col4 == -1) {
2419                                 // RGB
2420                                 $this->TextColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2421                                 $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2422                         } else {
2423                                 // CMYK
2424                                 $this->TextColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2425                                 $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2426                         }
2427                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2428                 }
2429
2430                 /**
2431                 * Defines the spot color used for text.
2432                 * @param string $name name of the spot color
2433                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2434                 * @since 4.0.024 (2008-09-12)
2435                 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
2436                 */
2437                 function SetTextSpotColor($name, $tint=100) {
2438                         if (!isset($this->spot_colors[$name])) {
2439                                 $this->Error('Undefined spot color: '.$name);
2440                         }
2441                         $this->TextColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2442                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2443                         if ($this->page > 0) {
2444                                 $this->_out($this->TextColor);
2445                         }
2446                 }
2447
2448                 /**
2449                 * Returns the length of a string in user unit. A font must be selected.<br>
2450                 * @param string $s The string whose length is to be computed
2451                 * @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.
2452                 * @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.
2453                 * @param float $fontsize Font size in points. The default value is the current size.
2454                 * @return int string length
2455                 * @author Nicola Asuni
2456                 * @since 1.2
2457                 */
2458                 function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0) {
2459                         return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $this->tmprtl), $fontname, $fontstyle, $fontsize);
2460                 }
2461
2462                 /**
2463                 * Returns the string length of an array of chars in user unit. A font must be selected.<br>
2464                 * @param string $arr The array of chars whose total length is to be computed
2465                 * @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.
2466                 * @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.
2467                 * @param float $fontsize Font size in points. The default value is the current size.
2468                 * @return int string length
2469                 * @author Nicola Asuni
2470                 * @since 2.4.000 (2008-03-06)
2471                 */
2472                 function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0) {
2473                         // store current values
2474                         if (!empty($fontname)) {
2475                                 $prev_FontFamily = $this->FontFamily;
2476                                 $prev_FontStyle = $this->FontStyle;
2477                                 $prev_FontSizePt = $this->FontSizePt;
2478                                 $this->SetFont($fontname, $fontstyle, $fontsize);
2479                         }
2480                         $w = 0;
2481                         foreach($sa as $char) {
2482                                 $w += $this->GetCharWidth($char);
2483                         }
2484                         // restore previous values
2485                         if (!empty($fontname)) {
2486                                 $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt);
2487                         }
2488                         return $w;
2489                 }
2490
2491                 /**
2492                 * Returns the length of the char in user unit for the current font.<br>
2493                 * @param int $char The char code whose length is to be returned
2494                 * @return int char width
2495                 * @author Nicola Asuni
2496                 * @since 2.4.000 (2008-03-06)
2497                 */
2498                 function GetCharWidth($char) {
2499                         $cw = &$this->CurrentFont['cw'];
2500                         if (isset($cw[$char])) {
2501                                 $w = $cw[$char];
2502                                 /*
2503                         } elseif (isset($cw[ord($char)])) {
2504                                 $w = $cw[ord($char)];
2505                         } elseif (isset($cw[chr($char)])) {
2506                                 $w = $cw[chr($char)];
2507                                 */
2508                         } elseif (isset($this->CurrentFont['dw'])) {
2509                                 $w = $this->CurrentFont['dw'];
2510                         } elseif (isset($this->CurrentFont['desc']['MissingWidth'])) {
2511                                 $w = $this->CurrentFont['desc']['MissingWidth']; // set default size
2512                         } else {
2513                                 $w = 500; // default width
2514                         }
2515                         return ($w * $this->FontSize / 1000);
2516                 }
2517
2518                 /**
2519                 * Returns the numbero of characters in a string.
2520                 * @param string $s The input string.
2521                 * @return int number of characters
2522                 * @since 2.0.0001 (2008-01-07)
2523                 */
2524                 function GetNumChars($s) {
2525                         if ($this->isunicode) {
2526                                 return count($this->UTF8StringToArray($s));
2527                         }
2528                         return strlen($s);
2529                 }
2530
2531                 /**
2532                 * Fill the list of available fonts ($this->fontlist).
2533                 * @access protected
2534                 * @since 4.0.013 (2008-07-28)
2535                 */
2536                 function getFontsList() {
2537                         $fontsdir = opendir($this->_getfontpath());
2538                         while (($file = readdir($fontsdir)) !== false) {
2539                                 if (substr($file, -4) == ".php") {
2540                                                 array_push($this->fontlist, strtolower(basename($file, ".php")));
2541                                 }
2542                         }
2543                         closedir($fontsdir);
2544                 }
2545
2546                 /**
2547                 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
2548                 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
2549                 * 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.
2550                 * Changed to support UTF-8 Unicode [Nicola Asuni, 2005-01-02].
2551                 * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
2552                 * @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>
2553                 * @param string $file The font definition file. By default, the name is built from the family and style, in lower case with no space.
2554                 * @return array containing the font data, or false in case of error.
2555                 * @since 1.5
2556                 * @see SetFont()
2557                 */
2558                 function AddFont($family, $style='', $file='') {
2559                         if (empty($family)) {
2560                                 if (!empty($this->FontFamily)) {
2561                                         $family = $this->FontFamily;
2562                                 } else {
2563                                         $this->Error('Empty font family');
2564                                 }
2565                         }
2566                         $family = strtolower($family);
2567                         if ((!$this->isunicode) AND ($family == 'arial')) {
2568                                 $family = 'helvetica';
2569                         }
2570                         if (($family == "symbol") OR ($family == "zapfdingbats")) {
2571                                 $style = '';
2572                         }
2573                         $style = strtoupper($style);
2574                         // underline
2575                         if (strpos($style,'U') !== false) {
2576                                 $this->underline = true;
2577                                 $style = str_replace('U', '', $style);
2578                         } else {
2579                                 $this->underline = false;
2580                         }
2581                         //line through (deleted)
2582                         if (strpos($style,'D') !== false) {
2583                                 $this->linethrough = true;
2584                                 $style = str_replace('D', '', $style);
2585                         } else {
2586                                 $this->linethrough = false;
2587                         }
2588                         if ($style == 'IB') {
2589                                 $style = 'BI';
2590                         }
2591                         $fontkey = $family.$style;
2592                         $fontdata = array("fontkey" => $fontkey, "family" => $family, "style" => $style);
2593                         // check if the font has been already added
2594                         if (isset($this->fonts[$fontkey])) {
2595                                 return $fontdata;
2596                         }
2597                         if ($file == '') {
2598                                 $file = str_replace(' ', '', $family).strtolower($style).'.php';
2599                         }
2600                         if (!file_exists($this->_getfontpath().$file)) {
2601                                 // try to load the basic file without styles
2602                                 $file = str_replace(' ', '', $family).'.php';
2603                         }
2604                         if (isset($type)) {
2605                                 unset($type);
2606                         }
2607                         if (isset($cw)) {
2608                                 unset($cw);
2609                         }
2610                         @include($this->_getfontpath().$file);
2611                         if ((!isset($type)) OR (!isset($cw))) {
2612                                 $this->Error("Could not include font definition file: ".$file);
2613                         }
2614                         $i = count($this->fonts) + 1;
2615                         // register CID font (all styles at once)
2616                         if ($type == 'cidfont0') {
2617                                 $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
2618                                 foreach ($styles as $skey => $qual) {
2619                                         $sname = $name.$qual;
2620                                         $sfontkey = $family.$skey;
2621                                         $this->fonts[$sfontkey] = array('i' => $i, 'type' => $type, 'name' => $sname, 'desc' => $desc, 'cidinfo' => $cidinfo, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc);
2622                                         $i = count($this->fonts) + 1;
2623                                 }
2624                                 $file = '';
2625                         } elseif ($type == 'core') {
2626                                 $def_width = $cw[ord('?')];
2627                                 $this->fonts[$fontkey] = array('i' => $i, 'type' => 'core', 'name' => $this->CoreFonts[$fontkey], 'up' => -100, 'ut' => 50, 'cw' => $cw, 'dw' => $def_width);
2628                         } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
2629                                 if (!isset($file)) {
2630                                         $file = '';
2631                                 }
2632                                 if (!isset($enc)) {
2633                                         $enc = '';
2634                                 }
2635                                 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'file' => $file, 'enc' => $enc, 'desc' => $desc);
2636                         } elseif ($type == 'TrueTypeUnicode') {
2637                                 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'enc' => $enc, 'file' => $file, 'ctg' => $ctg);
2638                         } else {
2639                                 $this->Error('Unknow font type');
2640                         }
2641                         if (isset($diff) AND (!empty($diff))) {
2642                                 //Search existing encodings
2643                                 $d = 0;
2644                                 $nb = count($this->diffs);
2645                                 for($i=1; $i <= $nb; $i++) {
2646                                         if ($this->diffs[$i] == $diff) {
2647                                                 $d = $i;
2648                                                 break;
2649                                         }
2650                                 }
2651                                 if ($d == 0) {
2652                                         $d = $nb + 1;
2653                                         $this->diffs[$d] = $diff;
2654                                 }
2655                                 $this->fonts[$fontkey]['diff'] = $d;
2656                         }
2657                         if (!empty($file)) {
2658                                 if ((strcasecmp($type,"TrueType") == 0) OR (strcasecmp($type,"TrueTypeUnicode") == 0)) {
2659                                         $this->FontFiles[$file] = array('length1' => $originalsize);
2660                                 } elseif ($type != 'core') {
2661                                         $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2);
2662                                 }
2663                         }
2664                         return $fontdata;
2665                 }
2666
2667                 /**
2668                 * Sets the font used to print character strings.
2669                 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
2670                 * The method can be called before the first page is created and the font is retained from page to page.
2671                 * If you just wish to change the current font size, it is simpler to call SetFontSize().
2672                 * 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 />
2673                 * @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.
2674                 * @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.
2675                 * @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
2676                 * @since 1.0
2677                 * @see AddFont(), SetFontSize()
2678                 */
2679                 function SetFont($family, $style='', $size=0) {
2680                         //Select a font; size given in points
2681                         if ($size == 0) {
2682                                 $size = $this->FontSizePt;
2683                         }
2684                         // try to add font (if not already added)
2685                         $fontdata =  $this->AddFont($family, $style);
2686                         $this->FontFamily = $fontdata['family'];
2687                         $this->FontStyle = $fontdata['style'];
2688                         $this->CurrentFont = &$this->fonts[$fontdata['fontkey']];
2689                         $this->SetFontSize($size);
2690                 }
2691
2692                 /**
2693                 * Defines the size of the current font.
2694                 * @param float $size The size (in points)
2695                 * @since 1.0
2696                 * @see SetFont()
2697                 */
2698                 function SetFontSize($size) {
2699                         //Set font size in points
2700                         $this->FontSizePt = $size;
2701                         $this->FontSize = $size / $this->k;
2702                         if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
2703                                 $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000;
2704                         } else {
2705                                 $this->FontAscent = 0.8 * $this->FontSize;
2706                         }
2707                         if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] > 0)) {
2708                                 $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000;
2709                         } else {
2710                                 $this->FontDescent = 0.2 * $this->FontSize;
2711                         }
2712                         if (($this->page > 0) AND (isset($this->CurrentFont['i']))) {
2713                                 $this->_out(sprintf('BT /F%d %.2f Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
2714                         }
2715                 }
2716
2717                 /**
2718                 * 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 />
2719                 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
2720                 * @since 1.5
2721                 * @see Cell(), Write(), Image(), Link(), SetLink()
2722                 */
2723                 function AddLink() {
2724                         //Create a new internal link
2725                         $n = count($this->links) + 1;
2726                         $this->links[$n] = array(0, 0);
2727                         return $n;
2728                 }
2729
2730                 /**
2731                 * Defines the page and position a link points to.
2732                 * @param int $link The link identifier returned by AddLink()
2733                 * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
2734                 * @param int $page Number of target page; -1 indicates the current page. This is the default value
2735                 * @since 1.5
2736                 * @see AddLink()
2737                 */
2738                 function SetLink($link, $y=0, $page=-1) {
2739                         if ($y == -1) {
2740                                 $y = $this->y;
2741                         }
2742                         if ($page == -1) {
2743                                 $page = $this->page;
2744                         }
2745                         $this->links[$link] = array($page, $y);
2746                 }
2747
2748                 /**
2749                 * Puts a link on a rectangular area of the page.
2750                 * 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.
2751                 * @param float $x Abscissa of the upper-left corner of the rectangle
2752                 * @param float $y Ordinate of the upper-left corner of the rectangle
2753                 * @param float $w Width of the rectangle
2754                 * @param float $h Height of the rectangle
2755                 * @param mixed $link URL or identifier returned by AddLink()
2756                 * @since 1.5
2757                 * @see AddLink(), Annotation(), Cell(), Write(), Image()
2758                 */
2759                 function Link($x, $y, $w, $h, $link) {
2760                         $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'));
2761                 }
2762                 
2763                 /**
2764                 * Puts a text annotation on a rectangular area of the page.
2765                 * !!!! THIS FUNCTION IS NOT YET FULLY IMPLEMENTED !!!!
2766                 * @param float $x Abscissa of the upper-left corner of the rectangle
2767                 * @param float $y Ordinate of the upper-left corner of the rectangle
2768                 * @param float $w Width of the rectangle
2769                 * @param float $h Height of the rectangle
2770                 * @param string $text annotation text
2771                 * @param array $opt array of options (see section 8.4 of PDF reference 1.7).
2772                 * @since 4.0.018 (2008-08-06)
2773                 */
2774                 function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text')) {
2775                         $this->PageAnnots[$this->page][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt);
2776                 }
2777
2778                 /**
2779                 * 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.
2780                 * @param float $x Abscissa of the origin
2781                 * @param float $y Ordinate of the origin
2782                 * @param string $txt String to print
2783                 * @param int $stroke outline size in points (0 = disable)
2784                 * @param boolean $clip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
2785                 * @since 1.0
2786                 * @see SetFont(), SetTextColor(), Cell(), MultiCell(), Write()
2787                 */
2788                 function Text($x, $y, $txt, $stroke=0, $clip=false) {
2789                         //Output a string
2790                         if ($this->rtl) {
2791                                 // bidirectional algorithm (some chars may be changed affecting the line length)
2792                                 $s = $this->utf8Bidi($this->UTF8StringToArray($txt), $this->tmprtl);
2793                                 $l = $this->GetArrStringWidth($s);
2794                                 $xr = $this->w - $x - $this->GetArrStringWidth($s);
2795                         } else {
2796                                 $xr = $x;
2797                         }
2798                         $opt = "";
2799                         if (($stroke > 0) AND (!$clip)) {
2800                                 $opt .= "1 Tr ".intval($stroke)." w ";
2801                         } elseif (($stroke > 0) AND $clip) {
2802                                 $opt .= "5 Tr ".intval($stroke)." w ";
2803                         } elseif ($clip) {
2804                                 $opt .= "7 Tr ";
2805                         }
2806                         $s = sprintf('BT %.2f %.2f Td %s(%s) Tj ET 0 Tr', $xr * $this->k, ($this->h-$y) * $this->k, $opt, $this->_escapetext($txt));
2807                         if ($this->underline AND ($txt!='')) {
2808                                 $s .= ' '.$this->_dounderline($xr, $y, $txt);
2809                         }
2810                         if ($this->linethrough AND ($txt!='')) {
2811                                 $s .= ' '.$this->_dolinethrough($xr, $y, $txt);
2812                         }
2813                         if ($this->ColorFlag AND (!$clip)) {
2814                                 $s='q '.$this->TextColor.' '.$s.' Q';
2815                         }
2816                         $this->_out($s);
2817                 }
2818
2819                 /**
2820                 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
2821                 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
2822                 * This method is called automatically and should not be called directly by the application.
2823                 * @return boolean
2824                 * @since 1.4
2825                 * @see SetAutoPageBreak()
2826                 */
2827                 function AcceptPageBreak() {
2828                         return $this->AutoPageBreak;
2829                 }
2830
2831                 /**
2832                 * Add page if needed.
2833                 * @param float $h Cell height. Default value: 0.
2834                 * @since 3.2.000 (2008-07-01)
2835                 * @access protected
2836                 */
2837                 function checkPageBreak($h) {
2838                         if ((($this->y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
2839                                 $rs = "";
2840                                 //Automatic page break
2841                                 $x = $this->x;
2842                                 $ws = $this->ws;
2843                                 if ($ws > 0) {
2844                                         $this->ws = 0;
2845                                         $rs .= '0 Tw';
2846                                 }
2847                                 $this->AddPage($this->CurOrientation);
2848                                 if ($ws > 0) {
2849                                         $this->ws = $ws;
2850                                         $rs .= sprintf('%.3f Tw', $ws * $k);
2851                                 }
2852                                 $this->_out($rs);
2853                                 $this->y = $this->tMargin;
2854                                 $this->x = $x;
2855                         }
2856                 }
2857
2858                 /**
2859                 * 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 />
2860                 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2861                 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2862                 * @param float $h Cell height. Default value: 0.
2863                 * @param string $txt String to print. Default value: empty string.
2864                 * @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>
2865                 * @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>
2866                 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
2867                 * @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>
2868                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2869                 * @param mixed $link URL or identifier returned by AddLink().
2870                 * @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>
2871                 * @since 1.0
2872                 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
2873                 */
2874                 function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2875                         //$min_cell_height = $this->FontAscent + $this->FontDescent;
2876                         $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2877                         if ($h < $min_cell_height) {
2878                                 $h = $min_cell_height;
2879                         }
2880                         $this->checkPageBreak($h);
2881                         $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch));
2882                 }
2883
2884                 /**
2885                 * 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 />
2886                 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2887                 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2888                 * @param float $h Cell height. Default value: 0.
2889                 * @param string $txt String to print. Default value: empty string.
2890                 * @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>
2891                 * @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.
2892                 * @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>
2893                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2894                 * @param mixed $link URL or identifier returned by AddLink().
2895                 * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
2896                 * @since 1.0
2897                 * @see Cell()
2898                 */
2899                 function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2900                         $rs = ""; //string to be returned
2901                         $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2902                         if ($h < $min_cell_height) {
2903                                 $h = $min_cell_height;
2904                         }
2905                         $k = $this->k;
2906                         if (empty($w) OR ($w <= 0)) {
2907                                 if ($this->rtl) {
2908                                         $w = $this->x - $this->lMargin;
2909                                 } else {
2910                                         $w = $this->w - $this->rMargin - $this->x;
2911                                 }
2912                         }
2913                         $s = '';
2914                         if (($fill == 1) OR ($border == 1)) {
2915                                 if ($fill == 1) {
2916                                         $op = ($border == 1) ? 'B' : 'f';
2917                                 } else {
2918                                         $op = 'S';
2919                                 }
2920                                 if ($this->rtl) {
2921                                         $xk = (($this->x  - $w) * $k);
2922                                 } else {
2923                                         $xk = ($this->x * $k);
2924                                 }
2925                                 $s .= sprintf('%.2f %.2f %.2f %.2f re %s ', $xk, (($this->h - $this->y) * $k), ($w * $k), (-$h * $k), $op);
2926                         }
2927
2928                         if (is_string($border)) {
2929                                 $x = $this->x;
2930                                 $y = $this->y;
2931                                 if (strpos($border,'L') !== false) {
2932                                         if ($this->rtl) {
2933                                                 $xk = ($x - $w) * $k;
2934                                         } else {
2935                                                 $xk = $x * $k;
2936                                         }
2937                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h)) * $k));
2938                                 }
2939                                 if (strpos($border,'T') !== false) {
2940                                         if ($this->rtl) {
2941                                                 $xk = ($x - $w) * $k;
2942                                                 $xwk = $x * $k;
2943                                         } else {
2944                                                 $xk = $x * $k;
2945                                                 $xwk = ($x + $w) * $k;
2946                                         }
2947                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xwk, (($this->h - $y) * $k));
2948                                 }
2949                                 if (strpos($border,'R') !== false) {
2950                                         if ($this->rtl) {
2951                                                 $xk = $x * $k;
2952                                         } else {
2953                                                 $xk = ($x + $w) * $k;
2954                                         }
2955                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h))* $k));
2956                                 }
2957                                 if (strpos($border,'B') !== false) {
2958                                         if ($this->rtl) {
2959                                                 $xk = ($x - $w) * $k;
2960                                                 $xwk = $x * $k;
2961                                         } else {
2962                                                 $xk = $x * $k;
2963                                                 $xwk = ($x + $w) * $k;
2964                                         }
2965                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - ($y + $h)) * $k), $xwk, (($this->h - ($y + $h)) * $k));
2966                                 }
2967                         }
2968                         if ($txt != '') {
2969                                 // text lenght
2970                                 $width = $this->GetStringWidth($txt);
2971                                 // ratio between cell lenght and text lenght
2972                                 $ratio = ($w - (2 * $this->cMargin)) / $width;
2973
2974                                 // stretch text if required
2975                                 if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) {
2976                                         if ($stretch > 2) {
2977                                                 // spacing
2978                                                 //Calculate character spacing in points
2979                                                 $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1);
2980                                                 //Set character spacing
2981                                                 $rs .= sprintf('BT %.2f Tc ET ', $char_space);
2982                                         } else {
2983                                                 // scaling
2984                                                 //Calculate horizontal scaling
2985                                                 $horiz_scale = $ratio * 100.0;
2986                                                 //Set horizontal scaling
2987                                                 $rs .= sprintf('BT %.2f Tz ET ', $horiz_scale);
2988                                         }
2989                                         $align = '';
2990                                         $width = $w - (2 * $this->cMargin);
2991                                 } else {
2992                                         $stretch == 0;
2993                                 }
2994                                 if ($align == 'L') {
2995                                         if ($this->rtl) {
2996                                                 $dx = $w - $width - $this->cMargin;
2997                                         } else {
2998                                                 $dx = $this->cMargin;
2999                                         }
3000                                 } elseif ($align == 'R') {
3001                                         if ($this->rtl) {
3002                                                 $dx = $this->cMargin;
3003                                         } else {
3004                                                 $dx = $w - $width - $this->cMargin;
3005                                         }
3006                                 } elseif ($align == 'C') {
3007                                         $dx = ($w - $width) / 2;
3008                                 } elseif ($align == 'J') {
3009                                         if ($this->rtl) {
3010                                                 $dx = $w - $width - $this->cMargin;
3011                                         } else {
3012                                                 $dx = $this->cMargin;
3013                                         }
3014                                 } else {
3015                                         $dx = $this->cMargin;
3016                                 }
3017                                 if ($this->ColorFlag) {
3018                                         $s .= 'q '.$this->TextColor.' ';
3019                                 }
3020                                 $txt2 = $this->_escapetext($txt);
3021                                 if ($this->rtl) {
3022                                         $xdk = ($this->x - $dx - $width) * $k;
3023                                 } else {
3024                                         $xdk = ($this->x + $dx) * $k;
3025                                 }
3026                                 // Justification
3027                                 if ($align == 'J') {
3028                                         // count number of spaces
3029                                         $ns = substr_count($txt, ' ');
3030                                         //if ($this->isunicode) {
3031                                         if (($this->CurrentFont['type'] == "TrueTypeUnicode") OR ($this->CurrentFont['type'] == "cidfont0")) {
3032                                                 // get string width without spaces
3033                                                 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
3034                                                 // calculate average space width
3035                                                 $spacewidth = ($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1) / $this->FontSize / $this->k;
3036                                                 // set word position to be used with TJ operator
3037                                                 $txt2 = str_replace(chr(0).' ', ') '.(-2830 * $spacewidth).' (', $txt2);
3038                                         } else {
3039                                                 // get string width
3040                                                 $width = $this->GetStringWidth($txt);
3041                                                 $spacewidth = (($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1)) * $this->k;
3042                                                 $rs .= sprintf('BT %.3f Tw ET ', $spacewidth);
3043                                         }
3044                                 }
3045                                 // calculate approximate position of the font base line
3046                                 //$basefonty = $this->y + (($h + $this->FontAscent - $this->FontDescent)/2);
3047                                 $basefonty = $this->y + ($h/2) + ($this->FontSize/3);
3048                                 // print text
3049                                 $s .= sprintf('BT %.2f %.2f Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
3050                                 if ($this->rtl) {
3051                                         $xdx = $this->x - $dx - $width;
3052                                 } else {
3053                                         $xdx = $this->x + $dx;
3054                                 }
3055                                 if ($this->underline)  {
3056                                         $s .= ' '.$this->_dounderline($xdx, $basefonty, $txt);
3057                                 }
3058                                 if ($this->linethrough) {
3059                                         $s .= ' '.$this->_dolinethrough($xdx, $basefonty, $txt);
3060                                 }
3061                                 if ($this->ColorFlag) {
3062                                         $s .= ' Q';
3063                                 }
3064                                 if ($link) {
3065                                         $this->Link($xdx, $this->y + (($h - $this->FontSize)/2), $width, $this->FontSize, $link);
3066                                 }
3067                         }
3068                         // output cell
3069                         if ($s) {
3070                                 // output cell
3071                                 $rs .= $s;
3072                                 // reset text stretching
3073                                 if ($stretch > 2) {
3074                                         //Reset character horizontal spacing
3075                                         $rs .= ' BT 0 Tc ET';
3076                                 } elseif ($stretch > 0) {
3077                                         //Reset character horizontal scaling
3078                                         $rs .= ' BT 100 Tz ET';
3079                                 }
3080                         }
3081                         // reset word spacing
3082                         if ((!$this->isunicode) AND ($align == 'J')) {
3083                                 $rs .= ' BT 0 Tw ET';
3084                         }
3085                         $this->lasth = $h;
3086                         if ($ln > 0) {
3087                                 //Go to the beginning of the next line
3088                                 $this->y += $h;
3089                                 if ($ln == 1) {
3090                                         if ($this->rtl) {
3091                                                 $this->x = $this->w - $this->rMargin;
3092                                         } else {
3093                                                 $this->x = $this->lMargin;
3094                                         }
3095                                 }
3096                         } else {
3097                                 // go left or right by case
3098                                 if ($this->rtl) {
3099                                         $this->x -= $w;
3100                                 } else {
3101                                         $this->x += $w;
3102                                 }
3103                         }
3104                         $gstyles = $this->linestyleWidth." ".$this->linestyleCap." ".$this->linestyleJoin." ".$this->linestyleDash." ".$this->DrawColor." ".$this->FillColor."\n";
3105                         $rs = $gstyles.$rs;
3106                         return $rs;
3107                 }
3108
3109                 /**
3110                 * This method allows printing text with line breaks.
3111                 * 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 />
3112                 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
3113                 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
3114                 * @param float $h Cell minimum height. The cell extends automatically if needed.
3115                 * @param string $txt String to print
3116                 * @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>
3117                 * @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>
3118                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3119                 * @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>
3120                 * @param int $x x position in user units
3121                 * @param int $y y position in user units
3122                 * @param boolean $reseth if true reset the last cell height (default true).
3123                 * @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>
3124                 * @param boolean $ishtml se to true if $txt is HTML content (default = false).
3125                 * @return int Return the number of cells or 1 for html mode.
3126                 * @since 1.3
3127                 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
3128                 */
3129                 function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false) {
3130                         if ((empty($this->lasth))OR ($reseth)) {
3131                                 //set row height
3132                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
3133                         }
3134                         if (!empty($y)) {
3135                                 $this->SetY($y);
3136                         } else {
3137                                 $y = $this->GetY();
3138                         }
3139                         // check for page break
3140                         $this->checkPageBreak($h);
3141                         $y = $this->GetY();
3142                         // get current page number
3143                         $startpage = $this->page;
3144                         if (!empty($x)) {
3145                                 $this->SetX($x);
3146                         } else {
3147                                 $x = $this->GetX();
3148                         }
3149                         if (empty($w) OR ($w <= 0)) {
3150                                 if ($this->rtl) {
3151                                         $w = $this->x - $this->lMargin;
3152                                 } else {
3153                                         $w = $this->w - $this->rMargin - $this->x;
3154                                 }
3155                         }
3156                         // store original margin values
3157                         $lMargin = $this->lMargin;
3158                         $rMargin = $this->rMargin;
3159                         if ($this->rtl) {
3160                                 $this->SetRightMargin($this->w - $this->x);
3161                                 $this->SetLeftMargin($this->x - $w);
3162                         } else {
3163                                 $this->SetLeftMargin($this->x);
3164                                 $this->SetRightMargin($this->w - $this->x - $w);
3165                         }
3166                         // calculate remaining vertical space on first page ($startpage)
3167                         $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin();
3168                         // Adjust internal padding
3169                         if ($this->cMargin < ($this->LineWidth / 2)) {
3170                                 $this->cMargin = ($this->LineWidth / 2);
3171                         }
3172                         // Add top space if needed
3173                         if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3174                                 $this->y += $this->LineWidth / 2;
3175                         }
3176                         // add top padding
3177                         $this->y += $this->cMargin;
3178                         if ($ishtml) {
3179                                 // Write HTML text
3180                                 $this->writeHTML($txt, true, 0, $reseth, true, $align);
3181                                 $nl = 1;
3182                         } else {
3183                                 // Write text
3184                                 $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false);
3185                         }
3186                         // add bottom padding
3187                         $this->y += $this->cMargin;
3188                         // Add bottom space if needed
3189                         if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3190                                 $this->y += $this->LineWidth / 2;
3191                         }
3192                         // Get end-of-text Y position
3193                         $currentY = $this->GetY();
3194                         // get latest page number
3195                         $endpage = $this->page;
3196                         // check if a new page has been created
3197                         if ($endpage > $startpage) {
3198                                 // design borders around HTML cells.
3199                                 for ($page=$startpage; $page <= $endpage; $page++) {
3200                                         $this->setPage($page);
3201                                         if ($page == $startpage) {
3202                                                 $this->SetY($this->getPageHeight() - $restspace - $this->getBreakMargin());
3203                                                 $h = $restspace;
3204                                         } elseif ($page == $endpage) {
3205                                                 $this->SetY($this->tMargin); // put cursor at the beginning of text
3206                                                 $h = $currentY - $this->tMargin;
3207                                         } else {
3208                                                 $this->SetY($this->tMargin); // put cursor at the beginning of text
3209                                                 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
3210                                         }
3211                                         $this->SetX($x);
3212                                         $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3213                                         if ($border OR $fill) {
3214                                                 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3215                                                 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3216                                                 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3217                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
3218                                         }
3219                                 }
3220                         } else {
3221                                 $h = max($h, ($currentY - $y));
3222                                 // put cursor at the beginning of text
3223                                 $this->SetY($y);
3224                                 $this->SetX($x);
3225                                 $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3226                                 if ($border OR $fill) {
3227                                         // design a cell around the text
3228                                         $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3229                                         $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3230                                         $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3231                                         $this->intmrk[$this->page] += strlen($ccode."\n");
3232                                 }
3233                         }
3234                         // Get end-of-cell Y position
3235                         $currentY = $this->GetY();
3236                         // restore original margin values
3237                         $this->SetLeftMargin($lMargin);
3238                         $this->SetRightMargin($rMargin);
3239                         if ($ln > 0) {
3240                                 //Go to the beginning of the next line
3241                                 $this->SetY($currentY);
3242                                 if ($ln == 2) {
3243                                         $this->SetX($x + $w);
3244                                 }
3245                         } else {
3246                                 // go left or right by case
3247                                 $this->setPage($startpage);
3248                                 $this->y = $y;
3249                                 $this->SetX($x + $w);
3250                         }
3251                         return $nl;
3252                 }
3253
3254                 /**
3255                 * This method prints text from the current position.<br />
3256                 * @param float $h Line height
3257                 * @param string $txt String to print
3258                 * @param mixed $link URL or identifier returned by AddLink()
3259                 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
3260                 * @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>
3261                 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
3262                 * @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>
3263                 * @param boolean $firstline if true prints only the first line and return the remaining string.
3264                 * @return mixed Return the number of cells or the remaining string if $firstline = true.
3265                 * @since 1.5
3266                 */
3267                 function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false) {
3268                         // remove carriage returns
3269                         $s = str_replace("\r", '', $txt);
3270                         // check if string contains arabic text
3271                         if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
3272                                 $arabic = true;
3273                         } else {
3274                                 $arabic = false;
3275                         }
3276                         // get array of chars
3277                         $chars = $this->UTF8StringToArray($s);
3278                         // get the number of characters
3279                         $nb = count($chars);
3280                         // handle single space character
3281                         if (($nb == 1) AND preg_match("/[\s]/u", $s)) {
3282                                 if ($this->rtl) {
3283                                         $this->x -= $this->GetStringWidth($s);
3284                                 } else {
3285                                         $this->x += $this->GetStringWidth($s);
3286                                 }
3287                                 return;
3288                         }
3289                         // store current position
3290                         $prevx = $this->x;
3291                         $prevy = $this->y;
3292                         // calculate remaining line width ($w)
3293                         if ($this->rtl) {
3294                                 $w = $this->x - $this->lMargin;
3295                         } else {
3296                                 $w = $this->w - $this->rMargin - $this->x;
3297                         }
3298                         // max column width
3299                         $wmax = $w - (2 * $this->cMargin);
3300                         $i = 0; // character position
3301                         $j = 0; // current starting position
3302                         $sep = -1; // position of the last blank space
3303                         $l = 0; // current string lenght
3304                         $nl = 0; //number of lines
3305                         $linebreak = false;
3306                         // for each character
3307                         while ($i < $nb) {
3308                                 //Get the current character
3309                                 $c = $chars[$i];
3310                                 if ($c == 10) { // 10 = "\n" = new line
3311                                         //Explicit line break
3312                                         if ($align == "J") {
3313                                                 if ($this->rtl) {
3314                                                         $talign = "R";
3315                                                 } else {
3316                                                         $talign = "L";
3317                                                 }
3318                                         } else {
3319                                                 $talign = $align;
3320                                         }
3321                                         if ($firstline) {
3322                                                 $startx = $this->x;
3323                                                 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3324                                                 if ($this->rtl) {
3325                                                         $this->endlinex = $startx - $linew;
3326                                                 } else {
3327                                                         $this->endlinex = $startx + $linew;
3328                                                 }
3329                                                 $w = $linew;
3330                                                 $tmpcmargin = $this->cMargin;
3331                                                 $this->cMargin = 0;
3332                                         }
3333                                         $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $talign, $fill, $link, $stretch);
3334                                         if ($firstline) {
3335                                                 $this->cMargin = $tmpcmargin;
3336                                                 return ($this->UTF8ArrSubString($chars, $i));
3337                                         }
3338                                         $nl++;
3339                                         $j = $i + 1;
3340                                         $l = 0;
3341                                         $sep = -1;
3342                                         $w = $this->getRemainingWidth();
3343                                         $wmax = $w - (2 * $this->cMargin);
3344                                 } else {
3345                                         if (preg_match("/[\s]/u", $this->unichr($c))) {
3346                                                 // update last blank space position
3347                                                 $sep = $i;
3348                                         }
3349                                         // update string length
3350                                         if (($this->isunicode) AND ($arabic)) {
3351                                                 // with bidirectional algorithm some chars may be changed affecting the line length
3352                                                 // *** very slow ***
3353                                                 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), $this->tmprtl));
3354                                         } else {
3355                                                 $l += $this->GetCharWidth($c);
3356                                         }
3357                                         if ($l > $wmax) {
3358                                                 // we have reached the end of column
3359                                                 if ($sep == -1) {
3360                                                         // check if the line was already started
3361                                                         if (($this->rtl AND ($this->x < ($this->w - $this->rMargin)))
3362                                                                 OR ((!$this->rtl) AND ($this->x > $this->lMargin))) {
3363                                                                 // print a void cell and go to next line
3364                                                                 $this->Cell($w, $h, "", 0, 1);
3365                                                                 $linebreak = true;
3366                                                                 if ($firstline) {
3367                                                                         return ($this->UTF8ArrSubString($chars, $j));
3368                                                                 }
3369                                                         } else {
3370                                                                 // truncate the word because do not fit on column
3371                                                                 if ($firstline) {
3372                                                                         $startx = $this->x;
3373                                                                         $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3374                                                                         if ($this->rtl) {
3375                                                                                 $this->endlinex = $startx - $linew;
3376                                                                         } else {
3377                                                                                 $this->endlinex = $startx + $linew;
3378                                                                         }
3379                                                                         $w = $linew;
3380                                                                         $tmpcmargin = $this->cMargin;
3381                                                                         $this->cMargin = 0;
3382                                                                 }
3383                                                                 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $align, $fill, $link, $stretch);
3384                                                                 if ($firstline) {
3385                                                                         $this->cMargin = $tmpcmargin;
3386                                                                         return ($this->UTF8ArrSubString($chars, $i));
3387                                                                 }
3388                                                                 $j = $i;
3389                                                                 $i--;
3390                                                         }
3391                                                 } else {
3392                                                         // word wrapping
3393                                                         if ($firstline) {
3394                                                                 $startx = $this->x;
3395                                                                 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $sep), $this->tmprtl));
3396                                                                 if ($this->rtl) {
3397                                                                         $this->endlinex = $startx - $linew;
3398                                                                 } else {
3399                                                                         $this->endlinex = $startx + $linew;
3400                                                                 }
3401                                                                 $w = $linew;
3402                                                                 $tmpcmargin = $this->cMargin;
3403                                                                 $this->cMargin = 0;
3404                                                         }
3405                                                         $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $sep), 0, 1, $align, $fill, $link, $stretch);
3406                                                         if ($firstline) {
3407                                                                 $this->cMargin = $tmpcmargin;
3408                                                                 return ($this->UTF8ArrSubString($chars, $sep));
3409                                                         }
3410                                                         $i = $sep;
3411                                                         $sep = -1;
3412                                                         $j = ($i+1);
3413                                                 }
3414                                                 $w = $this->getRemainingWidth();
3415                                                 $wmax = $w - (2 * $this->cMargin);
3416                                                 if ($linebreak) {
3417                                                         $linebreak = false;
3418                                                 } else {
3419                                                         $nl++;
3420                                                         $l = 0;
3421                                                 }
3422                                         }
3423                                 }
3424                                 $i++;
3425                         } // end while i < nb
3426                         // print last substring (if any)
3427                         if ($l > 0) {
3428                                 switch ($align) {
3429                                         case "J":
3430                                         case "C": {
3431                                                 $w = $w;
3432                                                 break;
3433                                         }
3434                                         case "L": {
3435                                                 if ($this->rtl) {
3436                                                         $w = $w;
3437                                                 } else {
3438                                                         $w = $l;
3439                                                 }
3440                                                 break;
3441                                         }
3442                                         case "R": {
3443                                                 if ($this->rtl) {
3444                                                         $w = $l;
3445                                                 } else {
3446                                                         $w = $w;
3447                                                 }
3448                                                 break;
3449                                         }
3450                                         default: {
3451                                                 $w = $l;
3452                                                 break;
3453                                         }
3454                                 }
3455                                 if ($firstline) {
3456                                         $startx = $this->x;
3457                                         $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $nb), $this->tmprtl));
3458                                         if ($this->rtl) {
3459                                                 $this->endlinex = $startx - $linew;
3460                                         } else {
3461                                                 $this->endlinex = $startx + $linew;
3462                                         }
3463                                         $w = $linew;
3464                                         $tmpcmargin = $this->cMargin;
3465                                         $this->cMargin = 0;
3466                                 }
3467                                 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $nb), 0, $ln, $align, $fill, $link, $stretch);
3468                                 if ($firstline) {
3469                                         $this->cMargin = $tmpcmargin;
3470                                         return ($this->UTF8ArrSubString($chars, $nb));
3471                                 }
3472                                 $nl++;
3473                         }
3474                         if ($firstline) {
3475                                 return "";
3476                         }
3477                         return $nl;
3478                 }
3479
3480                 /**
3481                 * Returns the remaining width between the current position and margins.
3482                 * @return int Return the remaining width
3483                 * @access protected
3484                 */
3485                 function getRemainingWidth() {
3486                         if ($this->rtl) {
3487                                 return ($this->x - $this->lMargin);
3488                         } else {
3489                                 return ($this->w - $this->rMargin - $this->x);
3490                         }
3491                 }
3492
3493          /**
3494                 * Extract a slice of the $strarr array and return it as string.
3495                 * @param string $strarr The input array of characters.
3496                 * @param int $start the starting element of $strarr.
3497                 * @param int $end first element that will not be returned.
3498                 * @return Return part of a string
3499                 */
3500                 function UTF8ArrSubString($strarr, $start='', $end='') {
3501                         if (strlen($start) == 0) {
3502                                 $start = 0;
3503                         }
3504                         if (strlen($end) == 0) {
3505                                 $end = count($strarr);
3506                         }
3507                         $string = "";
3508                         for ($i=$start; $i < $end; $i++) {
3509                                 $string .= $this->unichr($strarr[$i]);
3510                         }
3511                         return $string;
3512                 }
3513
3514                 /**
3515                 * Returns the unicode caracter specified by UTF-8 code
3516                 * @param int $c UTF-8 code
3517                 * @return Returns the specified character.
3518                 * @author Miguel Perez, Nicola Asuni
3519                 * @since 2.3.000 (2008-03-05)
3520                 */
3521                 function unichr($c) {
3522                         if (!$this->isunicode) {
3523                                 return chr($c);
3524                         } elseif ($c == '') {
3525                                 return '';
3526                         } elseif ($c <= 0x7F) {
3527                                 // one byte
3528                                 return chr($c);
3529                         } elseif ($c <= 0x7FF) {
3530                                 // two bytes
3531                                 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
3532                         } elseif ($c <= 0xFFFF) {
3533                                 // three bytes
3534                                 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3535                         } elseif ($c <= 0x10FFFF) {
3536                                 // four bytes
3537                                 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3538                         } else {
3539                                 return "";
3540                         }
3541                 }
3542
3543                 /**
3544                 * Puts an image in the page.
3545                 * The upper-left corner must be given.
3546                 * The dimensions can be specified in different ways:<ul>
3547                 * <li>explicit width and height (expressed in user unit)</li>
3548                 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
3549                 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
3550                 * 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;
3551                 * The format can be specified explicitly or inferred from the file extension.<br />
3552                 * It is possible to put a link on the image.<br />
3553                 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
3554                 * @param string $file Name of the file containing the image.
3555                 * @param float $x Abscissa of the upper-left corner.
3556                 * @param float $y Ordinate of the upper-left corner.
3557                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
3558                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
3559                 * @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.
3560                 * @param mixed $link URL or identifier returned by AddLink().
3561                 * @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>
3562                 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
3563                 * @param int $dpi dot-per-inch resolution used on resize
3564                 * @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>
3565                 * @since 1.1
3566                 * @see AddLink()
3567                 */
3568                 function Image($file, $x, $y, $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
3569                         // get image size
3570                         list($pixw, $pixh) = getimagesize($file);
3571                         // calculate image width and height on document
3572                         if (($w <= 0) AND ($h <= 0)) {
3573                                 // convert image size to document unit
3574                                 $w = $pixw / ($this->imgscale * $this->k);
3575                                 $h = $pixh / ($this->imgscale * $this->k);
3576                         } elseif ($w <= 0) {
3577                                 $w = $h * $pixw / $pixh;
3578                         } elseif ($h <= 0) {
3579                                 $h = $w * $pixh / $pixw;
3580                         }
3581                         // calculate new minimum dimensions in pixels
3582                         $neww = round($w * $this->k * $dpi / $this->dpi);
3583                         $newh = round($h * $this->k * $dpi / $this->dpi);
3584                         // check if resize is necessary (resize is used only to reduce the image)
3585                         if (($neww * $newh) >= ($pixw * $pixh)) {
3586                                 $resize = false;
3587                         }
3588                         // check if image has been already added on document
3589                         if (!isset($this->images[$file])) {
3590                                 //First use of image, get info
3591                                 if ($type == '') {
3592                                         $fileinfo = pathinfo($file);
3593                                         if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
3594                                                 $type = $fileinfo['extension'];
3595                                         } else {
3596                                                 $this->Error('Image file has no extension and no type was specified: '.$file);
3597                                         }
3598                                 }
3599                                 $type = strtolower($type);
3600                                 if ($type == "jpg") {
3601                                         $type = "jpeg";
3602                                 }
3603                                 $mqr = ini_get('magic_quotes_runtime');
3604                                 ini_set('magic_quotes_runtime', 0);
3605                                 // Specific image handlers
3606                                 $mtd = '_parse'.$type;
3607                                 // GD image handler function
3608                                 $gdfunction = "imagecreatefrom".$type;
3609                                 $info = false;
3610                                 if ((method_exists($this,$mtd)) AND (!($resize AND function_exists($gdfunction)))) {
3611                                         $info = $this->$mtd($file);
3612                                 }
3613                                 if (!$info) {
3614                                         if (function_exists($gdfunction)) {
3615                                                 $img = $gdfunction($file);
3616                                                 if ($resize) {
3617                                                         $imgr = imagecreatetruecolor($neww, $newh);
3618                                                         imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
3619                                                         $info = $this->_toJPEG($imgr);
3620                                                 } else {
3621                                                         $info = $this->_toJPEG($img);
3622                                                 }
3623                                         } else {
3624                                                 return;
3625                                         }
3626                                 }
3627                                 if ($info === false) {
3628                                         //If false, we cannot process image
3629                                         return;
3630                                 }
3631                                 ini_set('magic_quotes_runtime', $mqr);
3632                                 $info['i'] = count($this->images) + 1;
3633                                 // add image to document
3634                                 $this->images[$file] = $info;
3635                         } else {
3636                                 $info = $this->images[$file];
3637                         }
3638                         // Check whether we need a new page first as this does not fit
3639                         if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
3640                                 // Automatic page break
3641                                 $this->AddPage($this->CurOrientation);
3642                                 // Reset coordinates to top fo next page
3643                                 //$x = $this->GetX();
3644                                 $y = $this->GetY() + $this->cMargin;
3645                         }
3646                         // 2007-10-19 Warren Sherliker: End Edit
3647                         // set bottomcoordinates
3648                         $this->img_rb_y = $y + $h;
3649                         // set alignment
3650                         if ($this->rtl) {
3651                                 if ($palign == 'L') {
3652                                         $ximg = $this->lMargin;
3653                                         // set right side coordinate
3654                                         $this->img_rb_x = $ximg + $w;
3655                                 } elseif ($palign == 'C') {
3656                                         $ximg = ($this->w - $x - $w) / 2;
3657                                         // set right side coordinate
3658                                         $this->img_rb_x = $ximg + $w;
3659                                 } else {
3660                                         $ximg = $this->w - $x - $w;
3661                                         // set left side coordinate
3662                                         $this->img_rb_x = $ximg;
3663                                 }
3664                         } else {
3665                                 if ($palign == 'R') {
3666                                         $ximg = $this->w - $this->rMargin - $w;
3667                                         // set left side coordinate
3668                                         $this->img_rb_x = $ximg;
3669                                 } elseif ($palign == 'C') {
3670                                         $ximg = ($this->w - $x - $w) / 2;
3671                                         // set right side coordinate
3672                                         $this->img_rb_x = $ximg + $w;
3673                                 } else {
3674                                         $ximg = $x;
3675                                         // set right side coordinate
3676                                         $this->img_rb_x = $ximg + $w;
3677                                 }
3678                         }
3679                         $xkimg = $ximg * $this->k;
3680                         $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']));
3681                         if ($link) {
3682                                 $this->Link($ximg, $y, $w, $h, $link);
3683                         }
3684                         // set pointer to align the successive text/objects
3685                         switch($align) {
3686                                 case 'T': {
3687                                         $this->y = $y;
3688                                         $this->x = $this->img_rb_x;
3689                                         break;
3690                                 }
3691                                 case 'M': {
3692                                         $this->y = $y + round($h/2);
3693                                         $this->x = $this->img_rb_x;
3694                                         break;
3695                                 }
3696                                 case 'B': {
3697                                         $this->y = $this->img_rb_y;
3698                                         $this->x = $this->img_rb_x;
3699                                         break;
3700                                 }
3701                                 case 'N': {
3702                                         $this->SetY($this->img_rb_y);
3703                                         break;
3704                                 }
3705                                 default:{
3706                                         break;
3707                                 }
3708                         }
3709                         $this->endlinex = $this->img_rb_x;
3710                 }
3711
3712                 /**
3713                 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
3714                 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
3715                 * @param string $file Image file name.
3716                 * @param image $image Image object.
3717                 * return image JPEG image object.
3718                 * @access protected
3719                 */
3720                 function _toJPEG($image) {
3721                         $tempname = tempnam(K_PATH_CACHE,'jpg');
3722                         imagejpeg($image, $tempname, $this->jpeg_quality);
3723                         imagedestroy($image);
3724                         $retvars = $this->_parsejpeg($tempname);
3725                         // tidy up by removing temporary image
3726                         unlink($tempname);
3727                         return $retvars;
3728                 }
3729
3730                 /**
3731                 * Extract info from a JPEG file without using the GD library.
3732                 * @param string $file image file to parse
3733                 * @return array structure containing the image data
3734                 * @access protected
3735                 */
3736                 function _parsejpeg($file) {
3737                         $a = getimagesize($file);
3738                         if (empty($a)) {
3739                                 $this->Error('Missing or incorrect image file: '.$file);
3740                         }
3741                         if ($a[2] != 2) {
3742                                 $this->Error('Not a JPEG file: '.$file);
3743                         }
3744                         if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
3745                                 $colspace = 'DeviceRGB';
3746                         } elseif ($a['channels'] == 4) {
3747                                 $colspace = 'DeviceCMYK';
3748                         }       else {
3749                                 $colspace = 'DeviceGray';
3750                         }
3751                         $bpc = isset($a['bits']) ? $a['bits'] : 8;
3752                         $data = file_get_contents($file);
3753                         return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
3754                 }
3755
3756                 /**
3757                 * Extract info from a PNG file without using the GD library.
3758                 * @param string $file image file to parse
3759                 * @return array structure containing the image data
3760                 * @access protected
3761                 */
3762                 function _parsepng($file) {
3763                         $f = fopen($file,'rb');
3764                         if (empty($f)) {
3765                                 $this->Error('Can\'t open image file: '.$file);
3766                         }
3767                         //Check signature
3768                         if (fread($f,8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3769                                 $this->Error('Not a PNG file: '.$file);
3770                         }
3771                         //Read header chunk
3772                         fread($f,4);
3773                         if (fread($f,4) != 'IHDR') {
3774                                 $this->Error('Incorrect PNG file: '.$file);
3775                         }
3776                         $w = $this->_freadint($f);
3777                         $h = $this->_freadint($f);
3778                         $bpc = ord(fread($f,1));
3779                         if ($bpc > 8) {
3780                                 //$this->Error('16-bit depth not supported: '.$file);
3781                                 return false;
3782                         }
3783                         $ct = ord(fread($f,1));
3784                         if ($ct == 0) {
3785                                 $colspace = 'DeviceGray';
3786                         } elseif ($ct == 2) {
3787                                 $colspace = 'DeviceRGB';
3788                         } elseif ($ct == 3) {
3789                                 $colspace = 'Indexed';
3790                         } else {
3791                                 //$this->Error('Alpha channel not supported: '.$file);
3792                                 return false;
3793                         }
3794                         if (ord(fread($f,1)) != 0) {
3795                                 //$this->Error('Unknown compression method: '.$file);
3796                                 return false;
3797                         }
3798                         if (ord(fread($f,1)) != 0) {
3799                                 //$this->Error('Unknown filter method: '.$file);
3800                                 return false;
3801                         }
3802                         if (ord(fread($f,1)) != 0) {
3803                                 //$this->Error('Interlacing not supported: '.$file);
3804                                 return false;
3805                         }
3806                         fread($f,4);
3807                         $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
3808                         //Scan chunks looking for palette, transparency and image data
3809                         $pal = '';
3810                         $trns = '';
3811                         $data = '';
3812                         do {
3813                                 $n = $this->_freadint($f);
3814                                 $type = fread($f,4);
3815                                 if ($type == 'PLTE') {
3816                                         //Read palette
3817                                         $pal = fread($f,$n);
3818                                         fread($f,4);
3819                                 } elseif ($type == 'tRNS') {
3820                                         //Read transparency info
3821                                         $t = fread($f,$n);
3822                                         if ($ct == 0) {
3823                                                 $trns = array(ord(substr($t,1,1)));
3824                                         }
3825                                         elseif ($ct == 2) {
3826                                                 $trns = array(ord(substr($t,1,1)), ord(substr($t,3,1)), ord(substr($t,5,1)));
3827                                         } else {
3828                                                 $pos = strpos($t,chr(0));
3829                                                 if ($pos !== false) {
3830                                                         $trns = array($pos);
3831                                                 }
3832                                         }
3833                                         fread($f, 4);
3834                                 } elseif ($type == 'IDAT') {
3835                                         //Read image data block
3836                                         $data .= fread($f,$n);
3837                                         fread($f, 4);
3838                                 } elseif ($type == 'IEND') {
3839                                         break;
3840                                 } else {
3841                                         fread($f, $n+4);
3842                                 }
3843                         }
3844                         while ($n);
3845                         if (($colspace == 'Indexed') AND (empty($pal))) {
3846                                 //$this->Error('Missing palette in '.$file);
3847                                 return false;
3848                         }
3849                         fclose($f);
3850                         return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
3851                 }
3852
3853                 /**
3854                 * Performs a line break.
3855                 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
3856                 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
3857                 * @param boolean $cell if true add a cMargin to the x coordinate
3858                 * @since 1.0
3859                 * @see Cell()
3860                 */
3861                 function Ln($h='', $cell=false) {
3862                         //Line feed; default value is last cell height
3863                         if ($cell) {
3864                                 $cellmargin = $this->cMargin;
3865                         } else {
3866                                 $cellmargin = 0;
3867                         }
3868                         if ($this->rtl) {
3869                                 $this->x = $this->w - $this->rMargin - $cellmargin;
3870                         } else {
3871                                 $this->x = $this->lMargin + $cellmargin;
3872                         }
3873                         if (is_string($h)) {
3874                                 $this->y += $this->lasth;
3875                         } else {
3876                                 $this->y += $h;
3877                         }
3878                         $this->newline = true;
3879                 }
3880
3881                 /**
3882                 * Returns the relative X value of current position.
3883                 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
3884                 * @return float
3885                 * @since 1.2
3886                 * @see SetX(), GetY(), SetY()
3887                 */
3888                 function GetX() {
3889                         //Get x position
3890                         if ($this->rtl) {
3891                                 return ($this->w - $this->x);
3892                         } else {
3893                                 return $this->x;
3894                         }
3895                 }
3896
3897                 /**
3898                 * Returns the absolute X value of current position.
3899                 * @return float
3900                 * @since 1.2
3901                 * @see SetX(), GetY(), SetY()
3902                 */
3903                 function GetAbsX() {
3904                         return $this->x;
3905                 }
3906
3907                 /**
3908                 * Returns the ordinate of the current position.
3909                 * @return float
3910                 * @since 1.0
3911                 * @see SetY(), GetX(), SetX()
3912                 */
3913                 function GetY() {
3914                         //Get y position
3915                         return $this->y;
3916                 }
3917
3918                 /**
3919                 * Defines the abscissa of the current position.
3920                 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
3921                 * @param float $x The value of the abscissa.
3922                 * @since 1.2
3923                 * @see GetX(), GetY(), SetY(), SetXY()
3924                 */
3925                 function SetX($x) {
3926                         //Set x position
3927                         if ($this->rtl) {
3928                                 if ($x >= 0) {
3929                                         $this->x = $this->w - $x;
3930                                 } else {
3931                                         $this->x = abs($x);
3932                                 }
3933                         } else {
3934                                 if ($x >= 0) {
3935                                         $this->x = $x;
3936                                 } else {
3937                                         $this->x = $this->w + $x;
3938                                 }
3939                         }
3940                 }
3941
3942                 /**
3943                 * Moves the current abscissa back to the left margin and sets the ordinate.
3944                 * If the passed value is negative, it is relative to the bottom of the page.
3945                 * @param float $y The value of the ordinate.
3946                 * @since 1.0
3947                 * @see GetX(), GetY(), SetY(), SetXY()
3948                 */
3949                 function SetY($y) {
3950                         //Set y position and reset x
3951                         if ($this->rtl) {
3952                                 $this->x = $this->w - $this->rMargin;
3953                         } else {
3954                                 $this->x = $this->lMargin;
3955                         }
3956                         if ($y >= 0) {
3957                                 $this->y = $y;
3958                         } else {
3959                                 $this->y = $this->h + $y;
3960                         }
3961                 }
3962
3963                 /**
3964                 * Defines the abscissa and ordinate of the current position.
3965                 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
3966                 * @param float $x The value of the abscissa
3967                 * @param float $y The value of the ordinate
3968                 * @since 1.2
3969                 * @see SetX(), SetY()
3970                 */
3971                 function SetXY($x, $y) {
3972                         //Set x and y positions
3973                         $this->SetY($y);
3974                         $this->SetX($x);
3975                 }
3976
3977                 /**
3978                 * Send the document to a given destination: string, local file or browser.
3979                 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
3980                 * The method first calls Close() if necessary to terminate the document.
3981                 * @param string $name The name of the file when saved.
3982                 * @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>
3983                 * @since 1.0
3984                 * @see Close()
3985                 */
3986                 function Output($name='doc.pdf', $dest='I') {
3987                         //Output PDF to some destination
3988                         //Finish document if necessary
3989                         if ($this->state < 3) {
3990                                 $this->Close();
3991                         }
3992                         //Normalize parameters
3993                         if (is_bool($dest)) {
3994                                 $dest = $dest ? 'D' : 'F';
3995                         }
3996                         $dest = strtoupper($dest);
3997                         if ($dest != 'F') {
3998                                 $name = str_replace("+", "%20", urlencode($name));
3999                                 $name = preg_replace('/[\r\n]+\s*/', '' , $name);
4000                         }
4001                         switch($dest) {
4002                                 case 'I': {
4003                                         //Send to standard output
4004                                         if (ob_get_contents()) {
4005                                                 $this->Error('Some data has already been output, can\'t send PDF file');
4006                                         }
4007                                         if (php_sapi_name() != 'cli') {
4008                                                 //We send to a browser
4009                                                 header('Content-Type: application/pdf');
4010                                                 if (headers_sent()) {
4011                                                         $this->Error('Some data has already been output to browser, can\'t send PDF file');
4012                                                 }
4013                                                 header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4014                                                 header("Pragma: public");
4015                                                 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4016                                                 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");      
4017                                                 header('Content-Length: '.strlen($this->buffer));
4018                                                 header('Content-Disposition: inline; filename="'.basename($name).'";');
4019                                         }
4020                                         echo $this->buffer;
4021                                         break;
4022                                 }
4023                                 case 'D': {
4024                                         //Download file
4025                                         if (ob_get_contents()) {
4026                                                 $this->Error('Some data has already been output, can\'t send PDF file');
4027                                         }
4028                                         header('Content-Description: File Transfer');
4029                                         if (headers_sent()) {
4030                                                 $this->Error('Some data has already been output to browser, can\'t send PDF file');
4031                                         }
4032                                         header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4033                                         header("Pragma: public");
4034                                         header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4035                                         header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
4036                                         // force download dialog
4037                                         header("Content-Type: application/force-download");
4038                                         header("Content-Type: application/octet-stream", false);
4039                                         header("Content-Type: application/download", false);
4040                                         // use the Content-Disposition header to supply a recommended filename
4041                                         header('Content-Disposition: attachment; filename="'.basename($name).'";');
4042                                         header("Content-Transfer-Encoding: binary");
4043                                         header("Content-Length: ".strlen($this->buffer));
4044                                         echo $this->buffer;
4045                                         break;
4046                                 }
4047                                 case 'F': {
4048                                         //Save to local file
4049                                         $f = fopen($name, 'wb');
4050                                         if (!$f) {
4051                                                 $this->Error('Unable to create output file: '.$name);
4052                                         }
4053                                         fwrite($f, $this->buffer,strlen($this->buffer));
4054                                         fclose($f);
4055                                         break;
4056                                 }
4057                                 case 'S': {
4058                                         //Return as a string
4059                                         return $this->buffer;
4060                                 }
4061                                 default: {
4062                                         $this->Error('Incorrect output destination: '.$dest);
4063                                 }
4064                         }
4065                         return '';
4066                 }
4067
4068                 /**
4069                 * Check for locale-related bug
4070                 * @access protected
4071                 */
4072                 function _dochecks() {
4073                         //Check for locale-related bug
4074                         if (1.1 == 1) {
4075                                 $this->Error('Don\'t alter the locale before including class file');
4076                         }
4077                         //Check for decimal separator
4078                         if (sprintf('%.1f', 1.0) != '1.0') {
4079                                 setlocale(LC_NUMERIC, 'C');
4080                         }
4081                 }
4082
4083                 /**
4084                 * Return fonts path
4085                 * @return string
4086                 * @access protected
4087                 */
4088                 function _getfontpath() {
4089                         if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
4090                                 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
4091                         }
4092                         return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
4093                 }
4094
4095                 /**
4096                 * Output pages.
4097                 * @access protected
4098                 */
4099                 function _putpages() {
4100                         $nb = count($this->pages);
4101                         if (!empty($this->pagegroups)) {
4102                                 // do page number replacement
4103                                 foreach ($this->pagegroups as $k => $v) {
4104                                         $vu = $this->UTF8ToUTF16BE($v, false);
4105                                         $alias_a = $this->_escape($k);
4106                                         $alias_au = $this->_escape("{".$k."}");
4107                                         if ($this->isunicode) {
4108                                                 $alias_b = $this->_escape($this->UTF8ToLatin1($k));
4109                                                 $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$k."}"));
4110                                                 $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
4111                                                 $alias_cu = $this->_escape($this->utf8StrRev("{".$k."}", false, $this->tmprtl));
4112                                         }
4113                                         for ($n = 1; $n <= $nb; $n++) {
4114                                                 $this->pages[$n] = str_replace($alias_au, $vu, $this->pages[$n]);
4115                                                 if ($this->isunicode) {
4116                                                         $this->pages[$n] = str_replace($alias_bu, $vu, $this->pages[$n]);
4117                                                         $this->pages[$n] = str_replace($alias_cu, $vu, $this->pages[$n]);
4118                                                         $this->pages[$n] = str_replace($alias_b, $v, $this->pages[$n]);
4119                                                         $this->pages[$n] = str_replace($alias_c, $v, $this->pages[$n]);
4120                                                 }
4121                                                 $this->pages[$n] = str_replace($alias_a, $v, $this->pages[$n]);
4122                                         }
4123                                 }
4124                         }
4125                         if (!empty($this->AliasNbPages)) {
4126                                 $nbu = $this->UTF8ToUTF16BE($nb, false); // replacement for unicode font
4127                                 $alias_a = $this->_escape($this->AliasNbPages);
4128                                 $alias_au = $this->_escape("{".$this->AliasNbPages."}");
4129                                 if ($this->isunicode) {
4130                                         $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
4131                                         $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$this->AliasNbPages."}"));
4132                                         $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
4133                                         $alias_cu = $this->_escape($this->utf8StrRev("{".$this->AliasNbPages."}", false, $this->tmprtl));
4134                                 }
4135                                 //Replace number of pages
4136                                 for($n = 1; $n <= $nb; $n++) {
4137                                         $this->pages[$n] = str_replace($alias_au, $nbu, $this->pages[$n]);
4138                                         if ($this->isunicode) {
4139                                                 $this->pages[$n] = str_replace($alias_bu, $nbu, $this->pages[$n]);
4140                                                 $this->pages[$n] = str_replace($alias_cu, $nbu, $this->pages[$n]);
4141                                                 $this->pages[$n] = str_replace($alias_b, $nb, $this->pages[$n]);
4142                                                 $this->pages[$n] = str_replace($alias_c, $nb, $this->pages[$n]);
4143                                         }
4144                                         $this->pages[$n] = str_replace($alias_a, $nb, $this->pages[$n]);
4145                                 }
4146                         }
4147                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4148                         for($n=1; $n <= $nb; $n++) {
4149                                 //Page
4150                                 $this->_newobj();
4151                                 $this->_out('<</Type /Page');
4152                                 $this->_out('/Parent 1 0 R');
4153                                 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
4154                                 $this->_out('/Resources 2 0 R');
4155                                 $this->_putannots($n);
4156                                 $this->_out('/Contents '.($this->n + 1).' 0 R>>');
4157                                 $this->_out('endobj');
4158                                 //Page content
4159                                 $p = ($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n];
4160                                 $this->_newobj();
4161                                 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
4162                                 $this->_putstream($p);
4163                                 $this->_out('endobj');
4164                         }
4165                         //Pages root
4166                         $this->offsets[1] = strlen($this->buffer);
4167                         $this->_out('1 0 obj');
4168                         $this->_out('<</Type /Pages');
4169                         $kids='/Kids [';
4170                         for($i=0; $i < $nb; $i++) {
4171                                 $kids .= (3+2*$i).' 0 R ';
4172                         }
4173                         $this->_out($kids.']');
4174                         $this->_out('/Count '.$nb);
4175                         //$this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
4176                         $this->_out('>>');
4177                         $this->_out('endobj');
4178                 }
4179
4180                 /**
4181                 * Output Page Annotations.
4182                 * See section 8.4 of PDF reference.
4183                 * @param int $n page number
4184                 * @access protected
4185                 * @author Nicola Asuni
4186                 * @since 4.0.018 (2008-08-06)
4187                 */
4188                 function _putannots($n) {
4189                         if (isset($this->PageAnnots[$n])) {
4190                                 $annots = '/Annots [';
4191                                 foreach ($this->PageAnnots[$n] as $key => $pl) {
4192                                         $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
4193                                         $a = $pl['x'] * $this->k;
4194                                         $b = $this->hPt - $pl['y'] * $this->k;
4195                                         $c = $pl['w'] * $this->k;
4196                                         $d = $pl['h'] * $this->k;
4197                                         $rect = sprintf('%.2f %.2f %.2f %.2f', $a, $b, $a+$c, $b-$d);
4198                                         $annots .= '<</Type /Annot';
4199                                         $annots .= ' /Subtype /'.$pl['opt']['subtype'];
4200                                         $annots .= ' /Rect ['.$rect.']';
4201                                         $annots .= ' /Contents '.$this->_textstring($pl['txt']);
4202                                         //$annots .= ' /P ';
4203                                         $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
4204                                         $annots .= ' /M '.$this->_datestring('D:'.date('YmdHis'));
4205                                         if (isset($pl['opt']['f'])) {
4206                                                 $val = 0;
4207                                                 if (is_array($pl['opt']['f'])) {
4208                                                         foreach ($pl['opt']['f'] as $f) {
4209                                                                 switch (strtolower($f)) {
4210                                                                         case 'invisible': {
4211                                                                                 $val += 1 << 0;
4212                                                                                 break;
4213                                                                         }
4214                                                                         case 'hidden': {
4215                                                                                 $val += 1 << 1;
4216                                                                                 break;
4217                                                                         }
4218                                                                         case 'print': {
4219                                                                                 $val += 1 << 2;
4220                                                                                 break;
4221                                                                         }
4222                                                                         case 'nozoom': {
4223                                                                                 $val += 1 << 3;
4224                                                                                 break;
4225                                                                         }
4226                                                                         case 'norotate': {
4227                                                                                 $val += 1 << 4;
4228                                                                                 break;
4229                                                                         }
4230                                                                         case 'noview': {
4231                                                                                 $val += 1 << 5;
4232                                                                                 break;
4233                                                                         }
4234                                                                         case 'readonly': {
4235                                                                                 $val += 1 << 6;
4236                                                                                 break;
4237                                                                         }
4238                                                                         case 'locked': {
4239                                                                                 $val += 1 << 8;
4240                                                                                 break;
4241                                                                         }
4242                                                                         case 'togglenoview': {
4243                                                                                 $val += 1 << 9;
4244                                                                                 break;
4245                                                                         }
4246                                                                         case 'lockedcontents': {
4247                                                                                 $val += 1 << 10;
4248                                                                                 break;
4249                                                                         }
4250                                                                         default: {
4251                                                                                 break;
4252                                                                         }
4253                                                                 }
4254                                                         }
4255                                                 }
4256                                                 $annots .= ' /F '.intval($val);
4257                                         }
4258                                         //$annots .= ' /AP ';
4259                                         //$annots .= ' /AS ';
4260                                         $annots .= ' /Border [';
4261                                         if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
4262                                                 $annots .= intval($pl['opt']['border'][0]).' ';
4263                                                 $annots .= intval($pl['opt']['border'][1]).' ';
4264                                                 $annots .= intval($pl['opt']['border'][2]);
4265                                                 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
4266                                                         $annots .= ' [';
4267                                                         foreach ($pl['opt']['border'][3] as $dash) {
4268                                                                 $annots .= intval($dash).' ';
4269                                                         }
4270                                                         $annots .= ']';
4271                                                 }
4272                                         } else {
4273                                                 $annots .= '0 0 0';
4274                                         }
4275                                         $annots .= ']';
4276                                         if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
4277                                                 $annots .= ' /BS <<Type /Border';
4278                                                 if (isset($pl['opt']['bs']['w'])) {
4279                                                         $annots .= ' /W '.sprintf("%.4f", floatval($pl['opt']['bs']['w']));
4280                                                 }
4281                                                 $bstyles = array('S', 'D', 'B', 'I', 'U');
4282                                                 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $markups)) {
4283                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
4284                                                 }
4285                                                 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
4286                                                         $annots .= ' /D [';
4287                                                         foreach ($pl['opt']['bs']['d'] as $cord) {
4288                                                                 $cord = floatval($cord);
4289                                                                 $annots .= sprintf(" %.4f", $cord);
4290                                                         }
4291                                                         $annots .= ']';
4292                                                 }
4293                                                 $annots .= '>>';
4294                                         }
4295                                         if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
4296                                                 $annots .= ' /BE <<';
4297                                                 $bstyles = array('S', 'C');
4298                                                 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
4299                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
4300                                                 } else {
4301                                                         $annots .= ' /S /S';
4302                                                 }
4303                                                 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
4304                                                         $annots .= ' /I '.sprintf(" %.4f", $pl['opt']['be']['i']);
4305                                                 }
4306                                                 $annots .= '>>';
4307                                         }
4308                                         $annots .= ' /C [';
4309                                         if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
4310                                                 foreach ($pl['opt']['c'] as $col) {
4311                                                         $col = intval($col);
4312                                                         $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
4313                                                         $annots .= sprintf(" %.4f", $color);
4314                                                 }
4315                                         }
4316                                         $annots .= ']';
4317                                         //$annots .= ' /StructParent ';
4318                                         //$annots .= ' /OC ';
4319                                         $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight',  'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
4320                                         if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
4321                                                 // this is a markup type
4322                                                 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
4323                                                         $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
4324                                                 }
4325                                                 //$annots .= ' /Popup ';
4326                                                 if (isset($pl['opt']['ca'])) {
4327                                                         $annots .= ' /CA '.sprintf("%.4f", floatval($pl['opt']['ca']));
4328                                                 }
4329                                                 if (isset($pl['opt']['rc'])) {
4330                                                         $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4331                                                 }
4332                                                 $annots .= ' /CreationDate '.$this->_datestring('D:'.date('YmdHis'));
4333                                                 //$annots .= ' /IRT ';
4334                                                 if (isset($pl['opt']['subj'])) {
4335                                                         $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
4336                                                 }
4337                                                 //$annots .= ' /RT ';
4338                                                 //$annots .= ' /IT ';
4339                                                 //$annots .= ' /ExData ';
4340                                         }
4341                                         switch (strtolower($pl['opt']['subtype'])) {
4342                                                 case 'text': {
4343                                                         if (isset($pl['opt']['open'])) {
4344                                                                 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
4345                                                         }
4346                                                         $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
4347                                                         if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
4348                                                                 $annots .= ' /Name /'.$pl['opt']['name'];
4349                                                         } else {
4350                                                                 $annots .= ' /Name /Note';
4351                                                         }
4352                                                         $statemodels = array('Marked', 'Review');
4353                                                         if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
4354                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4355                                                         } else {
4356                                                                 $pl['opt']['statemodel'] = 'Marked';
4357                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4358                                                         }
4359                                                         if ($pl['opt']['statemodel'] == 'Marked') {
4360                                                                 $states = array('Accepted', 'Unmarked');
4361                                                         } else {
4362                                                                 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
4363                                                         }
4364                                                         if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
4365                                                                 $annots .= ' /State /'.$pl['opt']['state'];
4366                                                         } else {
4367                                                                 if ($pl['opt']['statemodel'] == 'Marked') {
4368                                                                         $annots .= ' /State /Unmarked';
4369                                                                 } else {
4370                                                                         $annots .= ' /State /None';
4371                                                                 }
4372                                                         }
4373                                                         break;
4374                                                 }
4375                                                 case 'link': {
4376                                                         $annots .= ' /A <</S /URI /URI '.$this->_uristring($pl['txt']).'>>';
4377                                                         $hmodes = array('N', 'I', 'O', 'P');
4378                                                         if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
4379                                                                 $annots .= ' /H /'.$pl['opt']['h'];
4380                                                         } else {
4381                                                                 $annots .= ' /H /I';
4382                                                         }
4383                                                         //$annots .= ' /Dest ';
4384                                                         //$annots .= ' /PA ';
4385                                                         //$annots .= ' /Quadpoints ';
4386                                                         break;
4387                                                 }
4388                                                 case 'freetext': {
4389                                                         $annots .= ' /DA '.$this->_textstring($pl['txt']);
4390                                                         if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
4391                                                                 $annots .= ' /Q '.intval($pl['opt']['q']);
4392                                                         }
4393                                                         if (isset($pl['opt']['rc'])) {
4394                                                                 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4395                                                         }
4396                                                         if (isset($pl['opt']['ds'])) {
4397                                                                 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
4398                                                         }
4399                                                         if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
4400                                                                 $annots .= ' /CL [';
4401                                                                 foreach ($pl['opt']['cl'] as $cl) {
4402                                                                         $annots .= sprintf("%.4f ", $cl * $this->k);
4403                                                                 }
4404                                                                 $annots .= ']';
4405                                                         }
4406                                                         $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
4407                                                         if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
4408                                                                 $annots .= ' /IT '.$pl['opt']['it'];
4409                                                         }
4410                                                         if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
4411                                                                 $l = $pl['opt']['rd'][0] * $this->k;
4412                                                                 $r = $pl['opt']['rd'][1] * $this->k;
4413                                                                 $t = $pl['opt']['rd'][2] * $this->k;
4414                                                                 $b = $pl['opt']['rd'][3] * $this->k;
4415                                                                 $annots .= ' /RD ['.sprintf('%.2f %.2f %.2f %.2f', $l, $r, $t, $b).']';
4416                                                         }
4417                                                         //$annots .= ' /LE ';
4418                                                         break;
4419                                                 }
4420                                                 // ... to be completed ...
4421                                                 case 'line': {
4422                                                         break;
4423                                                 }
4424                                                 case 'square': {
4425                                                         break;
4426                                                 }
4427                                                 case 'circle': {
4428                                                         break;
4429                                                 }
4430                                                 case 'polygon': {
4431                                                         break;
4432                                                 }
4433                                                 case 'polyline': {
4434                                                         break;
4435                                                 }
4436                                                 case 'highlight': {
4437                                                         break;
4438                                                 }
4439                                                 case 'underline': {
4440                                                         break;
4441                                                 }
4442                                                 case 'squiggly': {
4443                                                         break;
4444                                                 }
4445                                                 case 'strikeout': {
4446                                                         break;
4447                                                 }
4448                                                 case 'stamp': {
4449                                                         break;
4450                                                 }
4451                                                 case 'caret': {
4452                                                         break;
4453                                                 }
4454                                                 case 'ink': {
4455                                                         break;
4456                                                 }
4457                                                 case 'popup': {
4458                                                         break;
4459                                                 }
4460                                                 case 'fileattachment': {
4461                                                         break;
4462                                                 }
4463                                                 case 'sound': {
4464                                                         break;
4465                                                 }
4466                                                 case 'movie': {
4467                                                         break;
4468                                                 }
4469                                                 case 'widget': {
4470                                                         break;
4471                                                 }
4472                                                 case 'screen': {
4473                                                         break;
4474                                                 }
4475                                                 case 'printermark': {
4476                                                         break;
4477                                                 }
4478                                                 case 'trapnet': {
4479                                                         break;
4480                                                 }
4481                                                 case 'watermark': {
4482                                                         break;
4483                                                 }
4484                                                 case '3d': {
4485                                                         break;
4486                                                 }
4487                                                 default: {
4488                                                         break;
4489                                                 }
4490                                         }
4491                                         
4492                                 $annots .= '>>';
4493                                 }
4494                                 $this->_out($annots.']');
4495                         }
4496                 }
4497
4498                 /**
4499                 * Output fonts.
4500                 * _putfonts
4501                 * @access protected
4502                 */
4503                 function _putfonts() {
4504                         $nf = $this->n;
4505                         foreach($this->diffs as $diff) {
4506                                 //Encodings
4507                                 $this->_newobj();
4508                                 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
4509                                 $this->_out('endobj');
4510                         }
4511                         $mqr = ini_get('magic_quotes_runtime');
4512                         ini_set('magic_quotes_runtime', 0);
4513                         foreach($this->FontFiles as $file => $info) {
4514                                 //Font file embedding
4515                                 $this->_newobj();
4516                                 $this->FontFiles[$file]['n'] = $this->n;
4517                                 $font = file_get_contents($this->_getfontpath().strtolower($file));
4518                                 $compressed = (substr($file,-2)=='.z');
4519                                 if ((!$compressed) AND (isset($info['length2']))) {
4520                                         $header = (ord($font[0]) == 128);
4521                                         if ($header) {
4522                                                 //Strip first binary header
4523                                                 $font = substr($font,6);
4524                                         }
4525                                         if ($header AND (ord($font[$info['length1']]) == 128)) {
4526                                                 //Strip second binary header
4527                                                 $font = substr($font, 0, $info['length1']).substr($font, $info['length1']+6);
4528                                         }
4529                                 }
4530                                 $this->_out('<</Length '.strlen($font));
4531                                 if ($compressed) {
4532                                         $this->_out('/Filter /FlateDecode');
4533                                 }
4534                                 $this->_out('/Length1 '.$info['length1']);
4535                                 if (isset($info['length2'])) {
4536                                         $this->_out('/Length2 '.$info['length2'].' /Length3 0');
4537                                 }
4538                                 $this->_out('>>');
4539                                 $this->_putstream($font);
4540                                 $this->_out('endobj');
4541                         }
4542                         ini_set('magic_quotes_runtime', $mqr);
4543                         foreach($this->fonts as $k => $font) {
4544                                 //Font objects
4545                                 $this->fonts[$k]['n'] = $this->n + 1;
4546                                 $type = $font['type'];
4547                                 $name = $font['name'];
4548                                 if ($type == 'core') {
4549                                         //Standard font
4550                                         $this->_newobj();
4551                                         $this->_out('<</Type /Font');
4552                                         $this->_out('/BaseFont /'.$name);
4553                                         $this->_out('/Subtype /Type1');
4554                                         if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
4555                                                 $this->_out('/Encoding /WinAnsiEncoding');
4556                                         }
4557                                         $this->_out('>>');
4558                                         $this->_out('endobj');
4559                                 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
4560                                         //Additional Type1 or TrueType font
4561                                         $this->_newobj();
4562                                         $this->_out('<</Type /Font');
4563                                         $this->_out('/BaseFont /'.$name);
4564                                         $this->_out('/Subtype /'.$type);
4565                                         $this->_out('/FirstChar 32 /LastChar 255');
4566                                         $this->_out('/Widths '.($this->n + 1).' 0 R');
4567                                         $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
4568                                         if ($font['enc']) {
4569                                                 if (isset($font['diff'])) {
4570                                                         $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
4571                                                 } else {
4572                                                         $this->_out('/Encoding /WinAnsiEncoding');
4573                                                 }
4574                                         }
4575                                         $this->_out('>>');
4576                                         $this->_out('endobj');
4577                                         //Widths
4578                                         $this->_newobj();
4579                                         $cw = &$font['cw'];
4580                                         $s = '[';
4581                                         for($i=32; $i <= 255; $i++) {
4582                                                 //$s .= $cw[chr($i)].' ';
4583                                                 $s .= $cw[$i].' ';
4584                                         }
4585                                         $this->_out($s.']');
4586                                         $this->_out('endobj');
4587                                         //Descriptor
4588                                         $this->_newobj();
4589                                         $s = '<</Type /FontDescriptor /FontName /'.$name;
4590                                         foreach($font['desc'] as $k => $v) {
4591                                                 $s .= ' /'.$k.' '.$v;
4592                                         }
4593                                         $file = $font['file'];
4594                                         if ($file) {
4595                                                 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
4596                                         }
4597                                         $this->_out($s.'>>');
4598                                         $this->_out('endobj');
4599                                 } else {
4600                                         //Allow for additional types
4601                                         $mtd = '_put'.strtolower($type);
4602                                         if (!method_exists($this, $mtd)) {
4603                                                 $this->Error('Unsupported font type: '.$type);
4604                                         }
4605                                         $this->$mtd($font);
4606                                 }
4607                         }
4608                 }
4609
4610                 /**
4611                  * Output CID-0 fonts.
4612                  * @param array $font font data
4613                  * @access protected
4614                  * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
4615                  * @since 3.2.000 (2008-06-23)
4616                  */
4617                 function _putcidfont0($font) {
4618                         if (isset($font['cidinfo']['uni2cid'])) {
4619                                 // convert unicode to cid.
4620                                 $uni2cid = $font['cidinfo']['uni2cid'];
4621                                 $cw = array();
4622                                 foreach ($font['cw'] as $uni => $width) {
4623                                         if (isset($uni2cid[$uni])) {
4624                                                 $cw[($uni2cid[$uni] + 31)] = $width;
4625                                         } elseif ($uni <= 255) {
4626                                                 $cw[$uni] = $width;
4627                                         } // else unknown character
4628                                 }
4629                                 ksort($cw);
4630                                 $font = array_merge($font, array('cw'=>$cw));
4631                         }
4632                         $longname = $name = $font['name'];
4633                         $enc = $font['enc'];
4634                         if ($enc) {
4635                                 $longname .= "-$enc";
4636                         }
4637                         $this->_newobj();
4638                         $this->_out('<</Type /Font');
4639                         $this->_out('/BaseFont /'.$longname);
4640                         $this->_out('/Subtype /Type0');
4641                         if ($enc) {
4642                                 $this->_out('/Encoding /'.$enc);
4643                         }
4644                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
4645                         $this->_out('>>');
4646                         $this->_out('endobj');
4647                         $this->_newobj();
4648                         $this->_out('<</Type /Font');
4649                         $this->_out('/BaseFont /'.$name);
4650                         $this->_out('/Subtype /CIDFontType0');
4651                         $cidinfo = '/Registry ('.$font['cidinfo']['Registry'].') ';
4652                         $cidinfo .= '/Ordering ('.$font['cidinfo']['Ordering'].') ';
4653                         $cidinfo .= '/Supplement '.$font['cidinfo']['Supplement'];
4654                         $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
4655                         $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
4656                         $codes = array_keys($font['cw']);
4657                         $first = current($codes);
4658                         $last = end($codes);
4659                         $this->_out('/DW '.$font['dw']);
4660                         $w = '/W [';
4661                         $ranges = array();
4662                         $currange = 0;
4663                         for($i = $first; $i <= $last; $i++) {
4664                                 if (isset($font['cw'][$i]) AND (!$currange)) {
4665                                         $currange = $i - 31;
4666                                 } elseif (!isset($font['cw'][$i])) {
4667                                         $currange = 0;
4668                                 }
4669                                 if ($currange) {
4670                                         $ranges[$currange][] = $font['cw'][$i];
4671                                 }
4672                         }
4673                         foreach($ranges as $k => $ws) {
4674                                 $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
4675                         }
4676                         $w .= ' ]';
4677                         $this->_out($w);
4678                         $this->_out('>>');
4679                         $this->_out('endobj');
4680                         $this->_newobj();
4681                         $s = '<</Type /FontDescriptor /FontName /'.$name;
4682                         foreach($font['desc'] as $k => $v) {
4683                                 $s .= ' /'.$k.' '.$v;
4684                         }
4685                         $this->_out($s.'>>');
4686                         $this->_out('endobj');
4687                 }
4688
4689                 /**
4690                  * Output images.
4691                  * @access protected
4692                  */
4693                 function _putimages() {
4694                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4695                         reset($this->images);
4696                         foreach ($this->images as $file => $info) {
4697                                 $this->_newobj();
4698                                 $this->images[$file]['n'] = $this->n;
4699                                 $this->_out('<</Type /XObject');
4700                                 $this->_out('/Subtype /Image');
4701                                 $this->_out('/Width '.$info['w']);
4702                                 $this->_out('/Height '.$info['h']);
4703                                 if (isset($info["masked"])) {
4704                                         $this->_out('/SMask '.($this->n-1).' 0 R');
4705                                 }
4706                                 if ($info['cs'] == 'Indexed') {
4707                                         $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal']) / 3 - 1).' '.($this->n + 1).' 0 R]');
4708                                 } else {
4709                                         $this->_out('/ColorSpace /'.$info['cs']);
4710                                         if ($info['cs'] == 'DeviceCMYK') {
4711                                                 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
4712                                         }
4713                                 }
4714                                 $this->_out('/BitsPerComponent '.$info['bpc']);
4715                                 if (isset($info['f'])) {
4716                                         $this->_out('/Filter /'.$info['f']);
4717                                 }
4718                                 if (isset($info['parms'])) {
4719                                         $this->_out($info['parms']);
4720                                 }
4721                                 if (isset($info['trns']) and is_array($info['trns'])) {
4722                                         $trns='';
4723                                         for($i=0; $i < count($info['trns']); $i++) {
4724                                                 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
4725                                         }
4726                                         $this->_out('/Mask ['.$trns.']');
4727                                 }
4728                                 $this->_out('/Length '.strlen($info['data']).'>>');
4729                                 $this->_putstream($info['data']);
4730                                 unset($this->images[$file]['data']);
4731                                 $this->_out('endobj');
4732                                 //Palette
4733                                 if ($info['cs'] == 'Indexed') {
4734                                         $this->_newobj();
4735                                         $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
4736                                         $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
4737                                         $this->_putstream($pal);
4738                                         $this->_out('endobj');
4739                                 }
4740                         }
4741                 }
4742
4743                 /**
4744                 * Output Spot Colors Resources.
4745                 * @access protected
4746                 * @since 4.0.024 (2008-09-12)
4747                 */
4748                 function _putspotcolors() {
4749                         foreach ($this->spot_colors as $name => $color) {
4750                                 $this->_newobj();
4751                                 $this->spot_colors[$name]['n'] = $this->n;
4752                                 $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
4753                                 $this->_out('/DeviceCMYK <<');
4754                                 $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
4755                                 $this->_out(sprintf('/C1 [%.4f %.4f %.4f %.4f] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
4756                                 $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
4757                                 $this->_out('endobj');
4758                         }
4759                 }
4760
4761                 /**
4762                 * Output object dictionary for images.
4763                 * @access protected
4764                 */
4765                 function _putxobjectdict() {
4766                         foreach($this->images as $image) {
4767                                 $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
4768                         }
4769                 }
4770
4771                 /**
4772                 * Output Resources Dictionary.
4773                 * @access protected
4774                 */
4775                 function _putresourcedict(){
4776                         $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
4777                         $this->_out('/Font <<');
4778                         foreach($this->fonts as $font) {
4779                                 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
4780                         }
4781                         $this->_out('>>');
4782                         $this->_out('/XObject <<');
4783                         $this->_putxobjectdict();
4784                         $this->_out('>>');
4785                         // visibility
4786                         $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
4787                         // transparency
4788                         $this->_out('/ExtGState <<');
4789                         foreach($this->extgstates as $k => $extgstate) {
4790                                 $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
4791                         }
4792                         $this->_out('>>');
4793                         // gradients
4794                         if (isset($this->gradients) AND (count($this->gradients) > 0)) {
4795                                 $this->_out('/Shading <<');
4796                                 foreach($this->gradients as $id => $grad) {
4797                                         $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
4798                                 }
4799                                 $this->_out('>>');
4800                         }
4801                         // spot colors
4802                         if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
4803                                 $this->_out('/ColorSpace <<');
4804                                 foreach ($this->spot_colors as $color) {
4805                                         $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
4806                                 }
4807                                 $this->_out('>>');
4808                         }
4809                 }
4810
4811                 /**
4812                 * Output Resources.
4813                 * @access protected
4814                 */
4815                 function _putresources() {
4816                         $this->_putextgstates();
4817                         $this->_putocg();
4818                         $this->_putfonts();
4819                         $this->_putimages();
4820                         $this->_putspotcolors();
4821                         $this->_putshaders();
4822                         //Resource dictionary
4823                         $this->offsets[2] = strlen($this->buffer);
4824                         $this->_out('2 0 obj');
4825                         $this->_out('<<');
4826                         $this->_putresourcedict();
4827                         $this->_out('>>');
4828                         $this->_out('endobj');
4829                         $this->_putjavascript();
4830                         $this->_putbookmarks();
4831                         // encryption
4832                         if ($this->encrypted) {
4833                                 $this->_newobj();
4834                                 $this->enc_obj_id = $this->n;
4835                                 $this->_out('<<');
4836                                 $this->_putencryption();
4837                                 $this->_out('>>');
4838                                 $this->_out('endobj');
4839                         }
4840                 }
4841
4842                 /**
4843                 * Adds some Metadata information
4844                 * (see Chapter 10.2 of PDF Reference)
4845                 * @access protected
4846                 */
4847                 function _putinfo() {
4848                         if (!empty($this->title)) {
4849                                 $this->_out('/Title '.$this->_textstring($this->title));
4850                         }
4851                         if (!empty($this->author)) {
4852                                 $this->_out('/Author '.$this->_textstring($this->author));
4853                         }
4854                         if (!empty($this->subject)) {
4855                                 $this->_out('/Subject '.$this->_textstring($this->subject));
4856                         }
4857                         if (!empty($this->keywords)) {
4858                                 $this->_out('/Keywords '.$this->_textstring($this->keywords));
4859                         }
4860                         if (!empty($this->creator)) {
4861                                 $this->_out('/Creator '.$this->_textstring($this->creator));
4862                         }
4863                         if (defined('PDF_PRODUCER')) {
4864                                 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
4865                         }
4866                         $this->_out('/CreationDate '.$this->_datestring('D:'.date('YmdHis')));
4867                         $this->_out('/ModDate '.$this->_datestring('D:'.date('YmdHis')));
4868                 }
4869
4870                 /**
4871                 * Format a date string for meta information
4872                 * @param string $s date string to escape.
4873                 * @return string escaped string.
4874                 * @access protected
4875                 */
4876                 function _datestring($s) {
4877                         if ($this->encrypted) {
4878                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
4879                         }
4880                         return '('. $this->_escape($s).')';
4881                 }
4882
4883                 /**
4884                 * Output Catalog.
4885                 * @access protected
4886                 */
4887                 function _putcatalog() {
4888                         $this->_out('/Type /Catalog');
4889                         $this->_out('/Pages 1 0 R');
4890
4891                         if ($this->ZoomMode == 'fullpage') {
4892                                 $this->_out('/OpenAction [3 0 R /Fit]');
4893                         } elseif ($this->ZoomMode == 'fullwidth') {
4894                                 $this->_out('/OpenAction [3 0 R /FitH null]');
4895                         } elseif ($this->ZoomMode == 'real') {
4896                                 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
4897                         } elseif (!is_string($this->ZoomMode)) {
4898                                 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
4899                         }
4900                         if (isset($this->LayoutMode) AND (!empty($this->LayoutMode))) {
4901                                 $this->_out('/PageLayout /'.$this->LayoutMode.'');
4902                         }
4903                         if (isset($this->PageMode) AND (!empty($this->PageMode))) {
4904                                 $this->_out('/PageMode /'.$this->PageMode);
4905                         }
4906                         if (isset($this->l['a_meta_language'])) {
4907                                 $this->_out('/Lang /'.$this->l['a_meta_language']);
4908                         }
4909                         if (!empty($this->javascript)) {
4910                                 $this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
4911                         }
4912                         if (count($this->outlines) > 0) {
4913                                 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
4914                                 $this->_out('/PageMode /UseOutlines');
4915                         }
4916                         $this->_putviewerpreferences();
4917                         $p = $this->n_ocg_print.' 0 R';
4918                         $v = $this->n_ocg_view.' 0 R';
4919                         $as = "<</Event /Print /OCGs [".$p." ".$v."] /Category [/Print]>> <</Event /View /OCGs [".$p." ".$v."] /Category [/View]>>";
4920                         $this->_out("/OCProperties <</OCGs [".$p." ".$v."] /D <</ON [".$p."] /OFF [".$v."] /AS [".$as."]>>>>");
4921                         $this->_putuserrights();
4922                 }
4923
4924                 /**
4925                 * Output viewer preferences.
4926                 * @author Nicola asuni
4927                 * @since 3.1.000 (2008-06-09)
4928                 * @access protected
4929                 */
4930                 function _putviewerpreferences() {
4931                         $this->_out('/ViewerPreferences<<');
4932                         if ($this->rtl) {
4933                                 $this->_out('/Direction /R2L');
4934                         } else {
4935                                 $this->_out('/Direction /L2R');
4936                         }
4937                         if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
4938                                 $this->_out('/HideToolbar true');
4939                         }
4940                         if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
4941                                 $this->_out('/HideMenubar true');
4942                         }
4943                         if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
4944                                 $this->_out('/HideWindowUI true');
4945                         }
4946                         if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
4947                                 $this->_out('/FitWindow true');
4948                         }
4949                         if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
4950                                 $this->_out('/CenterWindow true');
4951                         }
4952                         if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
4953                                 $this->_out('/DisplayDocTitle true');
4954                         }
4955                         if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
4956                                 $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
4957                         }
4958                         if (isset($this->viewer_preferences['ViewArea'])) {
4959                                 $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
4960                         }
4961                         if (isset($this->viewer_preferences['ViewClip'])) {
4962                                 $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
4963                         }
4964                         if (isset($this->viewer_preferences['PrintArea'])) {
4965                                 $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
4966                         }
4967                         if (isset($this->viewer_preferences['PrintClip'])) {
4968                                 $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
4969                         }
4970                         if (isset($this->viewer_preferences['PrintScaling'])) {
4971                                 $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
4972                         }
4973                         if (isset($this->viewer_preferences['Duplex']) AND (!empty($this->viewer_preferences['Duplex']))) {
4974                                 $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
4975                         }
4976                         if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
4977                                 if ($this->viewer_preferences['PickTrayByPDFSize']) {
4978                                         $this->_out('/PickTrayByPDFSize true');
4979                                 } else {
4980                                         $this->_out('/PickTrayByPDFSize false');
4981                                 }
4982                         }
4983                         if (isset($this->viewer_preferences['PrintPageRange'])) {
4984                                 $PrintPageRangeNum = "";
4985                                 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
4986                                         $PrintPageRangeNum .= " ".($v-1)."";
4987                                 }
4988                                 $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
4989                         }
4990                         if (isset($this->viewer_preferences['NumCopies'])) {
4991                                 $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
4992                         }
4993                         $this->_out('>>');
4994                 }
4995
4996                 /**
4997                 * Output trailer.
4998                 * @access protected
4999                 */
5000                 function _puttrailer() {
5001                         $this->_out('/Size '.($this->n + 1));
5002                         $this->_out('/Root '.$this->n.' 0 R');
5003                         $this->_out('/Info '.($this->n - 1).' 0 R');
5004                         if ($this->encrypted) {
5005                                 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
5006                                 $this->_out('/ID [()()]');
5007                         }
5008                 }
5009
5010                 /**
5011                 * Output PDF header.
5012                 * @access protected
5013                 */
5014                 function _putheader() {
5015                         $this->buffer = '%PDF-'.$this->PDFVersion."\n".$this->buffer;
5016 //                      $this->_out('%PDF-'.$this->PDFVersion);
5017                 }
5018
5019                 /**
5020                 * Output end of document (EOF).
5021                 * @access protected
5022                 */
5023                 function _enddoc() {
5024                         $this->_putheader();
5025                         $this->_putpages();
5026                         $this->_putresources();
5027                         //Info
5028                         $this->_newobj();
5029                         $this->_out('<<');
5030                         $this->_putinfo();
5031                         $this->_out('>>');
5032                         $this->_out('endobj');
5033                         //Catalog
5034                         $this->_newobj();
5035                         $this->_out('<<');
5036                         $this->_putcatalog();
5037                         $this->_out('>>');
5038                         $this->_out('endobj');
5039                         //Cross-ref
5040                         $o = strlen($this->buffer);
5041                         $this->_out('xref');
5042                         $this->_out('0 '.($this->n + 1));
5043                         $this->_out('0000000000 65535 f ');
5044                         for($i=1; $i <= $this->n; $i++) {
5045                                 $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i]));
5046                         }
5047                         //Trailer
5048                         $this->_out('trailer');
5049                         $this->_out('<<');
5050                         $this->_puttrailer();
5051                         $this->_out('>>');
5052                         $this->_out('startxref');
5053                         $this->_out($o);
5054                         $this->_out('%%EOF');
5055                         $this->state = 3;
5056                 }
5057
5058                 /**
5059                 * Initialize a new page.
5060                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
5061                 * @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>
5062                 * @access protected
5063                 */
5064                 function _beginpage($orientation='', $format='') {
5065                         $this->page++;
5066                         $this->pages[$this->page] = ""; // this mark should be removed before output
5067                         $this->state = 2;
5068                         if (empty($orientation)) {
5069                                 if (isset($this->CurOrientation)) {
5070                                         $orientation = $this->CurOrientation;
5071                                 } else {
5072                                         $orientation = 'P';
5073                                 }
5074                         }
5075                         if (!empty($format)) {
5076                                 $this->setPageFormat($format, $orientation);
5077                         } else {
5078                                 $this->setPageOrientation($orientation);
5079                         }
5080                         if ($this->rtl) {
5081                                 $this->x = $this->w - $this->rMargin;
5082                         } else {
5083                                 $this->x = $this->lMargin;
5084                         }
5085                         $this->y = $this->tMargin;
5086                         if ($this->newpagegroup){
5087                                 // start a new group
5088                                 $n = sizeof($this->pagegroups) + 1;
5089                                 $alias = "{nb".$n."}";
5090                                 $this->pagegroups[$alias] = 1;
5091                                 $this->currpagegroup = $alias;
5092                                 $this->newpagegroup = false;
5093                         } elseif ($this->currpagegroup) {
5094                                 $this->pagegroups[$this->currpagegroup]++;
5095                         }
5096                 }
5097
5098                 /**
5099                 * Mark end of page.
5100                 * @access protected
5101                 */
5102                 function _endpage() {
5103                         $this->setVisibility("all");
5104                         $this->state = 1;
5105                 }
5106
5107                 /**
5108                 * Begin a new object.
5109                 * @access protected
5110                 */
5111                 function _newobj() {
5112                         $this->n++;
5113                         $this->offsets[$this->n] = strlen($this->buffer);
5114                         $this->_out($this->n.' 0 obj');
5115                 }
5116
5117                 /**
5118                 * Underline text.
5119                 * @param int $x X coordinate
5120                 * @param int $y Y coordinate
5121                 * @param string $txt text to underline
5122                 * @access protected
5123                 */
5124                 function _dounderline($x, $y, $txt) {
5125                         $up = $this->CurrentFont['up'];
5126                         $ut = $this->CurrentFont['ut'];
5127                         $w = $this->GetStringWidth($txt);
5128                         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);
5129                 }
5130
5131                 /**
5132                 * Line through text.
5133                 * @param int $x X coordinate
5134                 * @param int $y Y coordinate
5135                 * @param string $txt text to underline
5136                 * @access protected
5137                 */
5138                 function _dolinethrough($x, $y, $txt) {
5139                         $up = $this->CurrentFont['up'];
5140                         $ut = $this->CurrentFont['ut'];
5141                         $w = $this->GetStringWidth($txt);
5142                         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);
5143                 }
5144
5145                 /**
5146                 * Read a 4-byte integer from file.
5147                 * @param string $f file name.
5148                 * @return 4-byte integer
5149                 * @access protected
5150                 */
5151                 function _freadint($f) {
5152                         $a = unpack('Ni', fread($f,4));
5153                         return $a['i'];
5154                 }
5155
5156                 /**
5157                 * Format a text string for meta information
5158                 * @param string $s string to escape.
5159                 * @return string escaped string.
5160                 * @access protected
5161                 */
5162                 function _textstring($s) {
5163                         if ($this->isunicode) {
5164                                 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5165                                         $s = $this->UTF8ToLatin1($s);
5166                                 } else {
5167                                         //Convert string to UTF-16BE
5168                                         $s = $this->UTF8ToUTF16BE($s, true);
5169                                 }
5170                         }
5171                         if ($this->encrypted) {
5172                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
5173                         }
5174                         return '('. $this->_escape($s).')';
5175                 }
5176
5177                 /**
5178                 * Format an URI string
5179                 * @param string $s string to escape.
5180                 * @return string escaped string.
5181                 * @access protected
5182                 */
5183                 function _uristring($s) {
5184                         if ($this->encrypted) {
5185                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
5186                         }
5187                         return '('.$this->_escape($s).')';
5188                 }
5189
5190                 /**
5191                 * Format a text string
5192                 * @param string $s string to escape.
5193                 * @return string escaped string.
5194                 * @access protected
5195                 */
5196                 function _escapetext($s) {
5197                         if ($this->isunicode) {
5198                                 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5199                                         $s = $this->UTF8ToLatin1($s);
5200                                 } else {
5201                                         //Convert string to UTF-16BE and reverse RTL language
5202                                         $s = $this->utf8StrRev($s, false, $this->tmprtl);
5203                                 }
5204                         }
5205                         return $this->_escape($s);
5206                 }
5207
5208                 /**
5209                 * Add "\" before "\", "(" and ")"
5210                 * @param string $s string to escape.
5211                 * @return string escaped string.
5212                 * @access protected
5213                 */
5214                 function _escape($s) {
5215                         // the chr(13) substitution fixes the Bugs item #1421290.
5216                         return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
5217                 }
5218
5219                 /**
5220                 * Output a stream.
5221                 * @param string $s string to output.
5222                 * @access protected
5223                 */
5224                 function _putstream($s) {
5225                         if ($this->encrypted) {
5226                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
5227                         }
5228                         $this->_out('stream');
5229                         $this->_out($s);
5230                         $this->_out('endstream');
5231                 }
5232
5233                 /**
5234                 * Output a string to the document.
5235                 * @param string $s string to output.
5236                 * @access protected
5237                 */
5238                 function _out($s) {
5239                         if ($this->state == 2) {
5240                                 if (isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
5241                                         // puts data before page footer
5242                                         $page = substr($this->pages[$this->page], 0, -$this->footerlen[$this->page]);
5243                                         $footer = substr($this->pages[$this->page], -$this->footerlen[$this->page]);
5244                                         $this->pages[$this->page] = $page." ".$s."\n".$footer;
5245                                 } else {
5246                                         $this->pages[$this->page] .= $s."\n";
5247                                 }
5248                         } else {
5249                                 $this->buffer .= $s."\n";
5250                         }
5251                 }
5252
5253                 /**
5254                 * Adds unicode fonts.<br>
5255                 * Based on PDF Reference 1.3 (section 5)
5256                 * @access protected
5257                 * @author Nicola Asuni
5258                 * @since 1.52.0.TC005 (2005-01-05)
5259                 */
5260                 function _puttruetypeunicode($font) {
5261                         // Type0 Font
5262                         // A composite font composed of other fonts, organized hierarchically
5263                         $this->_newobj();
5264                         $this->_out('<</Type /Font');
5265                         $this->_out('/Subtype /Type0');
5266                         $this->_out('/BaseFont /'.$font['name'].'');
5267                         $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.
5268                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
5269                         $this->_out('/ToUnicode '.($this->n + 2).' 0 R');
5270                         $this->_out('>>');
5271                         $this->_out('endobj');
5272                         // CIDFontType2
5273                         // A CIDFont whose glyph descriptions are based on TrueType font technology
5274                         $this->_newobj();
5275                         $this->_out('<</Type /Font');
5276                         $this->_out('/Subtype /CIDFontType2');
5277                         $this->_out('/BaseFont /'.$font['name'].'');
5278                         $this->_out('/CIDSystemInfo '.($this->n + 2).' 0 R');
5279                         $this->_out('/FontDescriptor '.($this->n + 3).' 0 R');
5280                         if (isset($font['desc']['MissingWidth'])){
5281                                 $this->_out('/DW '.$font['desc']['MissingWidth'].''); // The default width for glyphs in the CIDFont MissingWidth
5282                         }
5283                         $w = "";
5284                         foreach ($font['cw'] as $cid => $width) {
5285                                 $w .= ''.$cid.' ['.$width.'] '; // define a specific width for each individual CID
5286                         }
5287                         $this->_out('/W ['.$w.']'); // A description of the widths for the glyphs in the CIDFont
5288                         $this->_out('/CIDToGIDMap '.($this->n + 4).' 0 R');
5289                         $this->_out('>>');
5290                         $this->_out('endobj');
5291                         // ToUnicode
5292                         // is a stream object that contains the definition of the CMap
5293                         // (PDF Reference 1.3 chap. 5.9)
5294                         $this->_newobj();
5295                         $this->_out('<</Length 345>>');
5296                         $this->_out('stream');
5297                         $this->_out('/CIDInit /ProcSet findresource begin');
5298                         $this->_out('12 dict begin');
5299                         $this->_out('begincmap');
5300                         $this->_out('/CIDSystemInfo');
5301                         $this->_out('<</Registry (Adobe)');
5302                         $this->_out('/Ordering (UCS)');
5303                         $this->_out('/Supplement 0');
5304                         $this->_out('>> def');
5305                         $this->_out('/CMapName /Adobe-Identity-UCS def');
5306                         $this->_out('/CMapType 2 def');
5307                         $this->_out('1 begincodespacerange');
5308                         $this->_out('<0000> <FFFF>');
5309                         $this->_out('endcodespacerange');
5310                         $this->_out('1 beginbfrange');
5311                         $this->_out('<0000> <FFFF> <0000>');
5312                         $this->_out('endbfrange');
5313                         $this->_out('endcmap');
5314                         $this->_out('CMapName currentdict /CMap defineresource pop');
5315                         $this->_out('end');
5316                         $this->_out('end');
5317                         $this->_out('endstream');
5318                         $this->_out('endobj');
5319                         // CIDSystemInfo dictionary
5320                         // A dictionary containing entries that define the character collection of the CIDFont.
5321                         $this->_newobj();
5322                         $this->_out('<</Registry (Adobe)'); // A string identifying an issuer of character collections
5323                         $this->_out('/Ordering (UCS)'); // A string that uniquely names a character collection issued by a specific registry
5324                         $this->_out('/Supplement 0'); // The supplement number of the character collection.
5325                         $this->_out('>>');
5326                         $this->_out('endobj');
5327                         // Font descriptor
5328                         // A font descriptor describing the CIDFont default metrics other than its glyph widths
5329                         $this->_newobj();
5330                         $this->_out('<</Type /FontDescriptor');
5331                         $this->_out('/FontName /'.$font['name']);
5332                         foreach ($font['desc'] as $key => $value) {
5333                                 $this->_out('/'.$key.' '.$value);
5334                         }
5335                         if ($font['file']) {
5336                                 // A stream containing a TrueType font program
5337                                 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
5338                         }
5339                         $this->_out('>>');
5340                         $this->_out('endobj');
5341                         // Embed CIDToGIDMap
5342                         // A specification of the mapping from CIDs to glyph indices
5343                         $this->_newobj();
5344                         $ctgfile = $this->_getfontpath().strtolower($font['ctg']);
5345                         if (!file_exists($ctgfile)) {
5346                                 $this->Error('Font file not found: '.$ctgfile);
5347                         }
5348                         $size = filesize($ctgfile);
5349                         $this->_out('<</Length '.$size.'');
5350                         if (substr($ctgfile, -2) == '.z') { // check file extension
5351                                 /* Decompresses data encoded using the public-domain
5352                                 zlib/deflate compression method, reproducing the
5353                                 original text or binary data */
5354                                 $this->_out('/Filter /FlateDecode');
5355                         }
5356                         $this->_out('>>');
5357                         $this->_putstream(file_get_contents($ctgfile));
5358                         $this->_out('endobj');
5359                 }
5360
5361                  /**
5362                  * Converts UTF-8 strings to codepoints array.<br>
5363                  * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
5364                  * Based on: http://www.faqs.org/rfcs/rfc3629.html
5365                  * <pre>
5366                  *        Char. number range  |        UTF-8 octet sequence
5367                  *       (hexadecimal)    |              (binary)
5368                  *    --------------------+-----------------------------------------------
5369                  *    0000 0000-0000 007F | 0xxxxxxx
5370                  *    0000 0080-0000 07FF | 110xxxxx 10xxxxxx
5371                  *    0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
5372                  *    0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
5373                  *    ---------------------------------------------------------------------
5374                  *
5375                  *   ABFN notation:
5376                  *   ---------------------------------------------------------------------
5377                  *   UTF8-octets = *( UTF8-char )
5378                  *   UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
5379                  *   UTF8-1      = %x00-7F
5380                  *   UTF8-2      = %xC2-DF UTF8-tail
5381                  *
5382                  *   UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
5383                  *                 %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
5384                  *   UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
5385                  *                 %xF4 %x80-8F 2( UTF8-tail )
5386                  *   UTF8-tail   = %x80-BF
5387                  *   ---------------------------------------------------------------------
5388                  * </pre>
5389                  * @param string $str string to process.
5390                  * @return array containing codepoints (UTF-8 characters values)
5391                  * @access protected
5392                  * @author Nicola Asuni
5393                  * @since 1.53.0.TC005 (2005-01-05)
5394                  */
5395                 function UTF8StringToArray($str) {
5396                         if (!$this->isunicode) {
5397                                 // split string into array of equivalent codes
5398                                 $strarr = array();
5399                                 $strlen = strlen($str);
5400                                 for($i=0; $i < $strlen; $i++) {
5401                                         $strarr[] = ord($str[$i]);
5402                                 }
5403                                 return $strarr;
5404                         }
5405                         $unicode = array(); // array containing unicode values
5406                         $bytes  = array(); // array containing single character byte sequences
5407                         $numbytes  = 1; // number of octetc needed to represent the UTF-8 character
5408                         $str .= ""; // force $str to be a string
5409                         $length = strlen($str);
5410                         for($i = 0; $i < $length; $i++) {
5411                                 $char = ord($str[$i]); // get one string character at time
5412                                 if (count($bytes) == 0) { // get starting octect
5413                                         if ($char <= 0x7F) {
5414                                                 $unicode[] = $char; // use the character "as is" because is ASCII
5415                                                 $numbytes = 1;
5416                                         } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
5417                                                 $bytes[] = ($char - 0xC0) << 0x06;
5418                                                 $numbytes = 2;
5419                                         } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
5420                                                 $bytes[] = ($char - 0xE0) << 0x0C;
5421                                                 $numbytes = 3;
5422                                         } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
5423                                                 $bytes[] = ($char - 0xF0) << 0x12;
5424                                                 $numbytes = 4;
5425                                         } else {
5426                                                 // use replacement character for other invalid sequences
5427                                                 $unicode[] = 0xFFFD;
5428                                                 $bytes = array();
5429                                                 $numbytes = 1;
5430                                         }
5431                                 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
5432                                         $bytes[] = $char - 0x80;
5433                                         if (count($bytes) == $numbytes) {
5434                                                 // compose UTF-8 bytes to a single unicode value
5435                                                 $char = $bytes[0];
5436                                                 for($j = 1; $j < $numbytes; $j++) {
5437                                                         $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
5438                                                 }
5439                                                 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
5440                                                         /* The definition of UTF-8 prohibits encoding character numbers between
5441                                                         U+D800 and U+DFFF, which are reserved for use with the UTF-16
5442                                                         encoding form (as surrogate pairs) and do not directly represent
5443                                                         characters. */
5444                                                         $unicode[] = 0xFFFD; // use replacement character
5445                                                 } else {
5446                                                         $unicode[] = $char; // add char to array
5447                                                 }
5448                                                 // reset data for next char
5449                                                 $bytes = array();
5450                                                 $numbytes = 1;
5451                                         }
5452                                 } else {
5453                                         // use replacement character for other invalid sequences
5454                                         $unicode[] = 0xFFFD;
5455                                         $bytes = array();
5456                                         $numbytes = 1;
5457                                 }
5458                         }
5459                         return $unicode;
5460                 }
5461
5462                 /**
5463                  * Converts UTF-8 strings to UTF16-BE.<br>
5464                  * @param string $str string to process.
5465                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5466                  * @return string
5467                  * @access protected
5468                  * @author Nicola Asuni
5469                  * @since 1.53.0.TC005 (2005-01-05)
5470                  * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
5471                  */
5472                 function UTF8ToUTF16BE($str, $setbom=true) {
5473                         if (!$this->isunicode) {
5474                                 return $str; // string is not in unicode
5475                         }
5476                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5477                         return $this->arrUTF8ToUTF16BE($unicode, $setbom);
5478                 }
5479
5480                 /**
5481                  * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
5482                  * @param string $str string to process.
5483                  * @return string
5484                  * @author Andrew Whitehead, Nicola Asuni
5485                  * @access protected
5486                  * @since 3.2.000 (2008-06-23)
5487                  */
5488                 function UTF8ToLatin1($str) {
5489                         if (!$this->isunicode) {
5490                                 return $str; // string is not in unicode
5491                         }
5492                         $outstr = ""; // string to be returned
5493                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5494                         foreach ($unicode as $char) {
5495                                 if ($char == 0xFFFD) {
5496                                         // skip
5497                                 } elseif ($char == 0x2022) {
5498                                         // fix for middot
5499                                         $outstr .= chr(183);
5500                                 } elseif ($char < 256) {
5501                                         $outstr .= chr($char);
5502                                 } else {
5503                                         $outstr .= '?';
5504                                 }
5505                         }
5506                         return $outstr;
5507                 }
5508
5509                 /**
5510                  * Converts array of UTF-8 characters to UTF16-BE string.<br>
5511                  * Based on: http://www.faqs.org/rfcs/rfc2781.html
5512                  * <pre>
5513                  *   Encoding UTF-16:
5514                  *
5515                  *   Encoding of a single character from an ISO 10646 character value to
5516                  *    UTF-16 proceeds as follows. Let U be the character number, no greater
5517                  *    than 0x10FFFF.
5518                  *
5519                  *    1) If U < 0x10000, encode U as a 16-bit unsigned integer and
5520                  *       terminate.
5521                  *
5522                  *    2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
5523                  *       U' must be less than or equal to 0xFFFFF. That is, U' can be
5524                  *       represented in 20 bits.
5525                  *
5526                  *    3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
5527                  *       0xDC00, respectively. These integers each have 10 bits free to
5528                  *       encode the character value, for a total of 20 bits.
5529                  *
5530                  *    4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
5531                  *       bits of W1 and the 10 low-order bits of U' to the 10 low-order
5532                  *       bits of W2. Terminate.
5533                  *
5534                  *    Graphically, steps 2 through 4 look like:
5535                  *    U' = yyyyyyyyyyxxxxxxxxxx
5536                  *    W1 = 110110yyyyyyyyyy
5537                  *    W2 = 110111xxxxxxxxxx
5538                  * </pre>
5539                  * @param array $unicode array containing UTF-8 unicode values
5540                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5541                  * @return string
5542                  * @access protected
5543                  * @author Nicola Asuni
5544                  * @since 2.1.000 (2008-01-08)
5545                  * @see UTF8ToUTF16BE()
5546                  */
5547                 function arrUTF8ToUTF16BE($unicode, $setbom=true) {
5548                         $outstr = ""; // string to be returned
5549                         if ($setbom) {
5550                                 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
5551                         }
5552                         foreach($unicode as $char) {
5553                                 if ($char == 0xFFFD) {
5554                                         $outstr .= "\xFF\xFD"; // replacement character
5555                                 } elseif ($char < 0x10000) {
5556                                         $outstr .= chr($char >> 0x08);
5557                                         $outstr .= chr($char & 0xFF);
5558                                 } else {
5559                                         $char -= 0x10000;
5560                                         $w1 = 0xD800 | ($char >> 0x10);
5561                                         $w2 = 0xDC00 | ($char & 0x3FF);
5562                                         $outstr .= chr($w1 >> 0x08);
5563                                         $outstr .= chr($w1 & 0xFF);
5564                                         $outstr .= chr($w2 >> 0x08);
5565                                         $outstr .= chr($w2 & 0xFF);
5566                                 }
5567                         }
5568                         return $outstr;
5569                 }
5570                 // ====================================================
5571
5572                 /**
5573                  * Set header font.
5574                  * @param array $font font
5575                  * @since 1.1
5576                  */
5577                 function setHeaderFont($font) {
5578                         $this->header_font = $font;
5579                 }
5580
5581                 /**
5582                  * Get header font.
5583                  * @return array()
5584                  * @since 4.0.012 (2008-07-24)
5585                  */
5586                 function getHeaderFont() {
5587                         return $this->header_font;
5588                 }
5589
5590                 /**
5591                  * Set footer font.
5592                  * @param array $font font
5593                  * @since 1.1
5594                  */
5595                 function setFooterFont($font) {
5596                         $this->footer_font = $font;
5597                 }
5598
5599                 /**
5600                  * Get Footer font.
5601                  * @return array()
5602                  * @since 4.0.012 (2008-07-24)
5603                  */
5604                 function getFooterFont() {
5605                         return $this->footer_font;
5606                 }
5607
5608                 /**
5609                  * Set language array.
5610                  * @param array $language
5611                  * @since 1.1
5612                  */
5613                 function setLanguageArray($language) {
5614                         $this->l = $language;
5615                         $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
5616                 }
5617
5618                 /**
5619                  * Returns the PDF data.
5620                  */
5621                 function getPDFData() {
5622                         if ($this->state < 3) {
5623                                 $this->Close();
5624                         }
5625                         return $this->buffer;
5626                 }
5627
5628                 /**
5629                  * Sets font style.
5630                  * @param string $tag tag name in lowercase. Supported tags are:<ul>
5631                  * <li>b : bold text</li>
5632                  * <li>i : italic</li>
5633                  * <li>u : underlined</li>
5634                  * <li>d : line-through</li></ul>
5635                  * @param boolean $enable
5636                  * @access protected
5637                  */
5638                 function setStyle($tag, $enable) {
5639                         $this->$tag += ($enable ? 1 : -1);
5640                         $style = '';
5641                         foreach(array('b', 'i', 'u', 'd') as $s) {
5642                                 if ($this->$s > 0) {
5643                                         $style .= $s;
5644                                 }
5645                         }
5646                         $this->SetFont('', $style);
5647                 }
5648
5649                 /**
5650                  * Output anchor link.
5651                  * @param string $url link URL
5652                  * @param string $name link name
5653                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
5654                  * @param boolean $firstline if true prints only the first line and return the remaining string.
5655                  * @return the number of cells used or the remaining text if $firstline = true;
5656                  * @access public
5657                  */
5658                 function addHtmlLink($url, $name, $fill=0, $firstline=false) {
5659                         $prevcolor = $this->fgcolor;
5660                         $this->SetTextColor(0, 0, 255);
5661                         $this->setStyle('u', true);
5662                         $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
5663                         $this->setStyle('u', false);
5664                         $this->SetTextColorArray($prevcolor);
5665                         return $ret;
5666                 }
5667
5668                 /**
5669                  * 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).
5670                  * @param string $color html color
5671                  * @return array
5672                  * @access protected
5673                  */
5674                 function convertHTMLColorToDec($color="#000000") {
5675                         global $webcolor;
5676                         $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
5677                         // set default color to be returned in case of error
5678                         $returncolor = array ('R' => 0, 'G' => 0, 'B' => 0);
5679                         if (empty($color)) {
5680                                 return $returncolor;
5681                         }
5682                         if (substr(strtolower($color), 0, 3) == 'rgb') {
5683                                 $codes = substr($color, 4);
5684                                 $codes = str_replace(')', '', $codes);
5685                                 $returncolor = explode(',', $codes, 3);
5686                                 return $returncolor;    
5687                         }
5688                         if (substr($color, 0, 1) != "#") {
5689                                 // decode color name
5690                                 if (isset($webcolor[strtolower($color)])) {
5691                                         $color_code = $webcolor[strtolower($color)];
5692                                 } else {
5693                                         return $returncolor;
5694                                 }
5695                         } else {
5696                                 $color_code = substr($color, 1);
5697                         }
5698                         switch (strlen($color_code)) {
5699                                 case 3: {
5700                                         // three-digit hexadecimal representation
5701                                         $r = substr($color_code, 0, 1);
5702                                         $g = substr($color_code, 1, 1);
5703                                         $b = substr($color_code, 2, 1);
5704                                         $returncolor['R'] = hexdec($r.$r);
5705                                         $returncolor['G'] = hexdec($g.$g);
5706                                         $returncolor['B'] = hexdec($b.$b);
5707                                         break;
5708                                 }
5709                                 case 6: {
5710                                         // six-digit hexadecimal representation
5711                                         $returncolor['R'] = hexdec(substr($color_code, 0, 2));
5712                                         $returncolor['G'] = hexdec(substr($color_code, 2, 2));
5713                                         $returncolor['B'] = hexdec(substr($color_code, 4, 2));
5714                                         break;
5715                                 }
5716                         }
5717                         return $returncolor;
5718                 }
5719
5720                 /**
5721                  * Converts pixels to Units.
5722                  * @param int $px pixels
5723                  * @return float millimeters
5724                  * @access public
5725                  */
5726                 function pixelsToUnits($px){
5727                         return $px / $this->k;
5728                 }
5729
5730                 /**
5731                  * Reverse function for htmlentities.
5732                  * Convert entities in UTF-8.
5733                  * @param $text_to_convert Text to convert.
5734                  * @return string converted
5735                  */
5736                 function unhtmlentities($text_to_convert) {
5737                         return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
5738                 }
5739
5740                 // ENCRYPTION METHODS ----------------------------------
5741                 // SINCE 2.0.000 (2008-01-02)
5742                 /**
5743                 * Compute encryption key depending on object number where the encrypted data is stored
5744                 * @param int $n object number
5745                 * @since 2.0.000 (2008-01-02)
5746                 */
5747                 function _objectkey($n) {
5748                         return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);
5749                 }
5750
5751                 /**
5752                  * Put encryption on PDF document.
5753                  * @since 2.0.000 (2008-01-02)
5754                  */
5755                 function _putencryption() {
5756                         $this->_out('/Filter /Standard');
5757                         $this->_out('/V 1');
5758                         $this->_out('/R 2');
5759                         $this->_out('/O ('.$this->_escape($this->Ovalue).')');
5760                         $this->_out('/U ('.$this->_escape($this->Uvalue).')');
5761                         $this->_out('/P '.$this->Pvalue);
5762                 }
5763
5764                 /**
5765                 * Returns the input text exrypted using RC4 algorithm and the specified key.
5766                 * RC4 is the standard encryption algorithm used in PDF format
5767                 * @param string $key encryption key
5768                 * @param String $text input text to be encrypted
5769                 * @return String encrypted text
5770                 * @since 2.0.000 (2008-01-02)
5771                 * @author Klemen Vodopivec
5772                 */
5773                 function _RC4($key, $text) {
5774                         if ($this->last_rc4_key != $key) {
5775                                 $k = str_repeat($key, 256/strlen($key)+1);
5776                                 $rc4 = range(0,255);
5777                                 $j = 0;
5778                                 for ($i=0; $i < 256; $i++) {
5779                                         $t = $rc4[$i];
5780                                         $j = ($j + $t + ord($k[$i])) % 256;
5781                                         $rc4[$i] = $rc4[$j];
5782                                         $rc4[$j] = $t;
5783                                 }
5784                                 $this->last_rc4_key = $key;
5785                                 $this->last_rc4_key_c = $rc4;
5786                         } else {
5787                                 $rc4 = $this->last_rc4_key_c;
5788                         }
5789                         $len = strlen($text);
5790                         $a = 0;
5791                         $b = 0;
5792                         $out = '';
5793                         for ($i=0; $i < $len; $i++) {
5794                                 $a = ($a + 1) % 256;
5795                                 $t = $rc4[$a];
5796                                 $b = ($b + $t) % 256;
5797                                 $rc4[$a] = $rc4[$b];
5798                                 $rc4[$b] = $t;
5799                                 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
5800                                 $out .= chr(ord($text[$i]) ^ $k);
5801                         }
5802                         return $out;
5803                 }
5804
5805                 /**
5806                 * Encrypts a string using MD5 and returns it's value as a binary string.
5807                 * @param string $str input string
5808                 * @return String MD5 encrypted binary string
5809                 * @since 2.0.000 (2008-01-02)
5810                 * @author Klemen Vodopivec
5811                 */
5812                 function _md5_16($str) {
5813                         return pack('H*',md5($str));
5814                 }
5815
5816                 /**
5817                 * Compute O value (used for RC4 encryption)
5818                 * @param String $user_pass user password
5819                 * @param String $owner_pass user password
5820                 * @return String O value
5821                 * @since 2.0.000 (2008-01-02)
5822                 * @author Klemen Vodopivec
5823                 */
5824                 function _Ovalue($user_pass, $owner_pass) {
5825                         $tmp = $this->_md5_16($owner_pass);
5826                         $owner_RC4_key = substr($tmp,0,5);
5827                         return $this->_RC4($owner_RC4_key, $user_pass);
5828                 }
5829
5830                 /**
5831                 * Compute U value (used for RC4 encryption)
5832                 * @return String U value
5833                 * @since 2.0.000 (2008-01-02)
5834                 * @author Klemen Vodopivec
5835                 */
5836                 function _Uvalue() {
5837                         return $this->_RC4($this->encryption_key, $this->padding);
5838                 }
5839
5840                 /**
5841                 * Compute encryption key
5842                 * @param String $user_pass user password
5843                 * @param String $owner_pass user password
5844                 * @param String $protection protection type
5845                 * @since 2.0.000 (2008-01-02)
5846                 * @author Klemen Vodopivec
5847                 */
5848                 function _generateencryptionkey($user_pass, $owner_pass, $protection) {
5849                         // Pad passwords
5850                         $user_pass = substr($user_pass.$this->padding,0,32);
5851                         $owner_pass = substr($owner_pass.$this->padding,0,32);
5852                         // Compute O value
5853                         $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
5854                         // Compute encyption key
5855                         $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
5856                         $this->encryption_key = substr($tmp,0,5);
5857                         // Compute U value
5858                         $this->Uvalue = $this->_Uvalue();
5859                         // Compute P value
5860                         $this->Pvalue = -(($protection^255)+1);
5861                 }
5862
5863                 /**
5864                 * Set document protection
5865                 * The permission array is composed of values taken from the following ones:
5866                 * - copy: copy text and images to the clipboard
5867                 * - print: print the document
5868                 * - modify: modify it (except for annotations and forms)
5869                 * - annot-forms: add annotations and forms
5870                 * Remark: the protection against modification is for people who have the full Acrobat product.
5871                 * 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.
5872                 * 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.
5873                 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
5874                 * @param String $user_pass user password. Empty by default.
5875                 * @param String $owner_pass owner password. If not specified, a random value is used.
5876                 * @since 2.0.000 (2008-01-02)
5877                 * @author Klemen Vodopivec
5878                 */
5879                 function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
5880                         $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
5881                         $protection = 192;
5882                         foreach($permissions as $permission) {
5883                                 if (!isset($options[$permission])) {
5884                                         $this->Error('Incorrect permission: '.$permission);
5885                                 }
5886                                 $protection += $options[$permission];
5887                         }
5888                         if ($owner_pass === null) {
5889                                 $owner_pass = uniqid(rand());
5890                         }
5891                         $this->encrypted = true;
5892                         $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
5893                 }
5894
5895                 // END OF ENCRYPTION FUNCTIONS -------------------------
5896
5897                 // START TRANSFORMATIONS SECTION -----------------------
5898                 // authors: Moritz Wagner, Andreas Wurmser, Nicola Asuni
5899
5900                 /**
5901                 * Starts a 2D tranformation saving current graphic state.
5902                 * This function must be called before scaling, mirroring, translation, rotation and skewing.
5903                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5904                 * @since 2.1.000 (2008-01-07)
5905                 * @see StartTransform(), StopTransform()
5906                 */
5907                 function StartTransform() {
5908                         $this->_out('q');
5909                 }
5910
5911                 /**
5912                 * Stops a 2D tranformation restoring previous graphic state.
5913                 * This function must be called after scaling, mirroring, translation, rotation and skewing.
5914                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5915                 * @since 2.1.000 (2008-01-07)
5916                 * @see StartTransform(), StopTransform()
5917                 */
5918                 function StopTransform() {
5919                         $this->_out('Q');
5920                 }
5921                 /**
5922                 * Horizontal Scaling.
5923                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5924                 * @param int $x abscissa of the scaling center. Default is current x position
5925                 * @param int $y ordinate of the scaling center. Default is current y position
5926                 * @since 2.1.000 (2008-01-07)
5927                 * @see StartTransform(), StopTransform()
5928                 */
5929                 function ScaleX($s_x, $x='', $y=''){
5930                         $this->Scale($s_x, 100, $x, $y);
5931                 }
5932
5933                 /**
5934                 * Vertical Scaling.
5935                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5936                 * @param int $x abscissa of the scaling center. Default is current x position
5937                 * @param int $y ordinate of the scaling center. Default is current y position
5938                 * @since 2.1.000 (2008-01-07)
5939                 * @see StartTransform(), StopTransform()
5940                 */
5941                 function ScaleY($s_y, $x='', $y=''){
5942                         $this->Scale(100, $s_y, $x, $y);
5943                 }
5944
5945                 /**
5946                 * Vertical and horizontal proportional Scaling.
5947                 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
5948                 * @param int $x abscissa of the scaling center. Default is current x position
5949                 * @param int $y ordinate of the scaling center. Default is current y position
5950                 * @since 2.1.000 (2008-01-07)
5951                 * @see StartTransform(), StopTransform()
5952                 */
5953                 function ScaleXY($s, $x='', $y=''){
5954                         $this->Scale($s, $s, $x, $y);
5955                 }
5956
5957                 /**
5958                 * Vertical and horizontal non-proportional Scaling.
5959                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5960                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5961                 * @param int $x abscissa of the scaling center. Default is current x position
5962                 * @param int $y ordinate of the scaling center. Default is current y position
5963                 * @since 2.1.000 (2008-01-07)
5964                 * @see StartTransform(), StopTransform()
5965                 */
5966                 function Scale($s_x, $s_y, $x='', $y=''){
5967                         if ($x === '') {
5968                                 $x=$this->x;
5969                         }
5970                         if ($y === '') {
5971                                 $y=$this->y;
5972                         }
5973                         if ($this->rtl) {
5974                                 $x = $this->w - $x;
5975                         }
5976                         if (($s_x == 0) OR ($s_y == 0)) {
5977                                 $this->Error('Please do not use values equal to zero for scaling');
5978                         }
5979                         $y = ($this->h - $y) * $this->k;
5980                         $x *= $this->k;
5981                         //calculate elements of transformation matrix
5982                         $s_x /= 100;
5983                         $s_y /= 100;
5984                         $tm[0] = $s_x;
5985                         $tm[1] = 0;
5986                         $tm[2] = 0;
5987                         $tm[3] = $s_y;
5988                         $tm[4] = $x * (1 - $s_x);
5989                         $tm[5] = $y * (1 - $s_y);
5990                         //scale the coordinate system
5991                         $this->Transform($tm);
5992                 }
5993
5994                 /**
5995                 * Horizontal Mirroring.
5996                 * @param int $x abscissa of the point. Default is current x position
5997                 * @since 2.1.000 (2008-01-07)
5998                 * @see StartTransform(), StopTransform()
5999                 */
6000                 function MirrorH($x=''){
6001                         $this->Scale(-100, 100, $x);
6002                 }
6003
6004                 /**
6005                 * Verical Mirroring.
6006                 * @param int $y ordinate of the point. Default is current y position
6007                 * @since 2.1.000 (2008-01-07)
6008                 * @see StartTransform(), StopTransform()
6009                 */
6010                 function MirrorV($y=''){
6011                         $this->Scale(100, -100, '', $y);
6012                 }
6013
6014                 /**
6015                 * Point reflection mirroring.
6016                 * @param int $x abscissa of the point. Default is current x position
6017                 * @param int $y ordinate of the point. Default is current y position
6018                 * @since 2.1.000 (2008-01-07)
6019                 * @see StartTransform(), StopTransform()
6020                 */
6021                 function MirrorP($x='',$y=''){
6022                         $this->Scale(-100, -100, $x, $y);
6023                 }
6024
6025                 /**
6026                 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
6027                 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
6028                 * @param int $x abscissa of the point. Default is current x position
6029                 * @param int $y ordinate of the point. Default is current y position
6030                 * @since 2.1.000 (2008-01-07)
6031                 * @see StartTransform(), StopTransform()
6032                 */
6033                 function MirrorL($angle=0, $x='',$y=''){
6034                         $this->Scale(-100, 100, $x, $y);
6035                         $this->Rotate(-2*($angle-90), $x, $y);
6036                 }
6037
6038                 /**
6039                 * Translate graphic object horizontally.
6040                 * @param int $t_x movement to the right (or left for RTL)
6041                 * @since 2.1.000 (2008-01-07)
6042                 * @see StartTransform(), StopTransform()
6043                 */
6044                 function TranslateX($t_x){
6045                         $this->Translate($t_x, 0);
6046                 }
6047
6048                 /**
6049                 * Translate graphic object vertically.
6050                 * @param int $t_y movement to the bottom
6051                 * @since 2.1.000 (2008-01-07)
6052                 * @see StartTransform(), StopTransform()
6053                 */
6054                 function TranslateY($t_y){
6055                         $this->Translate(0, $t_y);
6056                 }
6057
6058                 /**
6059                 * Translate graphic object horizontally and vertically.
6060                 * @param int $t_x movement to the right
6061                 * @param int $t_y movement to the bottom
6062                 * @since 2.1.000 (2008-01-07)
6063                 * @see StartTransform(), StopTransform()
6064                 */
6065                 function Translate($t_x, $t_y){
6066                         if ($this->rtl) {
6067                                 $t_x = -$t_x;
6068                         }
6069                         //calculate elements of transformation matrix
6070                         $tm[0] = 1;
6071                         $tm[1] = 0;
6072                         $tm[2] = 0;
6073                         $tm[3] = 1;
6074                         $tm[4] = $t_x * $this->k;
6075                         $tm[5] = -$t_y * $this->k;
6076                         //translate the coordinate system
6077                         $this->Transform($tm);
6078                 }
6079
6080                 /**
6081                 * Rotate object.
6082                 * @param float $angle angle in degrees for counter-clockwise rotation
6083                 * @param int $x abscissa of the rotation center. Default is current x position
6084                 * @param int $y ordinate of the rotation center. Default is current y position
6085                 * @since 2.1.000 (2008-01-07)
6086                 * @see StartTransform(), StopTransform()
6087                 */
6088                 function Rotate($angle, $x='', $y=''){
6089                         if ($x === '') {
6090                                 $x=$this->x;
6091                         }
6092                         if ($y === '') {
6093                                 $y=$this->y;
6094                         }
6095                         if ($this->rtl) {
6096                                 $x = $this->w - $x;
6097                                 $angle = -$angle;
6098                         }
6099                         $y = ($this->h - $y) * $this->k;
6100                         $x *= $this->k;
6101                         //calculate elements of transformation matrix
6102                         $tm[0] = cos(deg2rad($angle));
6103                         $tm[1] = sin(deg2rad($angle));
6104                         $tm[2] = -$tm[1];
6105                         $tm[3] = $tm[0];
6106                         $tm[4] = $x + $tm[1] * $y - $tm[0] * $x;
6107                         $tm[5] = $y - $tm[0] * $y - $tm[1] * $x;
6108                         //rotate the coordinate system around ($x,$y)
6109                         $this->Transform($tm);
6110                 }
6111
6112                 /**
6113                 * Skew horizontally.
6114                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6115                 * @param int $x abscissa of the skewing center. default is current x position
6116                 * @param int $y ordinate of the skewing center. default is current y position
6117                 * @since 2.1.000 (2008-01-07)
6118                 * @see StartTransform(), StopTransform()
6119                 */
6120                 function SkewX($angle_x, $x='', $y=''){
6121                         $this->Skew($angle_x, 0, $x, $y);
6122                 }
6123
6124                 /**
6125                 * Skew vertically.
6126                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6127                 * @param int $x abscissa of the skewing center. default is current x position
6128                 * @param int $y ordinate of the skewing center. default is current y position
6129                 * @since 2.1.000 (2008-01-07)
6130                 * @see StartTransform(), StopTransform()
6131                 */
6132                 function SkewY($angle_y, $x='', $y=''){
6133                         $this->Skew(0, $angle_y, $x, $y);
6134                 }
6135
6136                 /**
6137                 * Skew.
6138                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6139                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6140                 * @param int $x abscissa of the skewing center. default is current x position
6141                 * @param int $y ordinate of the skewing center. default is current y position
6142                 * @since 2.1.000 (2008-01-07)
6143                 * @see StartTransform(), StopTransform()
6144                 */
6145                 function Skew($angle_x, $angle_y, $x='', $y=''){
6146                         if ($x === '') {
6147                                 $x = $this->x;
6148                         }
6149                         if ($y === '') {
6150                                 $y = $this->y;
6151                         }
6152                         if ($this->rtl) {
6153                                 $x = $this->w - $x;
6154                                 $angle_x = -$angle_x;
6155                         }
6156                         if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
6157                                 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
6158                         }
6159                         $x *= $this->k;
6160                         $y = ($this->h - $y) * $this->k;
6161                         //calculate elements of transformation matrix
6162                         $tm[0] = 1;
6163                         $tm[1] = tan(deg2rad($angle_y));
6164                         $tm[2] = tan(deg2rad($angle_x));
6165                         $tm[3] = 1;
6166                         $tm[4] = -$tm[2] * $y;
6167                         $tm[5] = -$tm[1] * $x;
6168                         //skew the coordinate system
6169                         $this->Transform($tm);
6170                 }
6171
6172                 /**
6173                 * Apply graphic transformations.
6174                 * @since 2.1.000 (2008-01-07)
6175                 * @see StartTransform(), StopTransform()
6176                 */
6177                 function Transform($tm){
6178                         $this->_out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
6179                 }
6180
6181                 // END TRANSFORMATIONS SECTION -------------------------
6182
6183
6184                 // START GRAPHIC FUNCTIONS SECTION ---------------------
6185                 // The following section is based on the code provided by David Hernandez Sanz
6186
6187                 /**
6188                 * 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.
6189                 * @param float $width The width.
6190                 * @since 1.0
6191                 * @see Line(), Rect(), Cell(), MultiCell()
6192                 */
6193                 function SetLineWidth($width) {
6194                         //Set line width
6195                         $this->LineWidth = $width;
6196                         //$this->linestyleWidth = sprintf('%.2f w', ($width * $this->k));
6197                         // FrontAccounting fix
6198                         // My PHP 5.2.6 environment gave an "Unsupported operand types"
6199                         // error for the multiplication on the next line some of the
6200                         // time when this method is called - I debugged and sometimes
6201                         // the $width parameter is some sort of weird array.  I don't
6202                         // understand what's going on, but casting it to a (float) seems
6203                         // to "fix" the problem.  -Jason Maas, 2009/09/25
6204                         $this->linestyleWidth = sprintf('%.2f w', ((float) $width * (float) $this->k));
6205                         $this->_out($this->linestyleWidth);
6206                 }
6207
6208                 /**
6209                 * Returns the current the line width.
6210                 * @return int Line width
6211                 * @since 2.1.000 (2008-01-07)
6212                 * @see Line(), SetLineWidth()
6213                 */
6214                 function GetLineWidth() {
6215                         return $this->LineWidth;
6216                 }
6217
6218                 /**
6219                 * Set line style.
6220                 * @param array $style Line style. Array with keys among the following:
6221                 * <ul>
6222                 *        <li>width (float): Width of the line in user units.</li>
6223                 *        <li>cap (string): Type of cap to put on the line. Possible values are:
6224                 * butt, round, square. The difference between "square" and "butt" is that
6225                 * "square" projects a flat end past the end of the line.</li>
6226                 *        <li>join (string): Type of join. Possible values are: miter, round,
6227                 * bevel.</li>
6228                 *        <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
6229                 * series of length values, which are the lengths of the on and off dashes.
6230                 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
6231                 * 1 off, 2 on, 1 off, ...</li>
6232                 *        <li>phase (integer): Modifier on the dash pattern which is used to shift
6233                 * the point at which the pattern starts.</li>
6234                 *        <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
6235                 * </ul>
6236                 * @access public
6237                 * @since 2.1.000 (2008-01-08)
6238                 */
6239                 function SetLineStyle($style) {
6240                         extract($style);
6241                         if (isset($width)) {
6242                                 $width_prev = $this->LineWidth;
6243                                 $this->SetLineWidth($width);
6244                                 $this->LineWidth = $width_prev;
6245                         }
6246                         if (isset($cap)) {
6247                                 $ca = array("butt" => 0, "round"=> 1, "square" => 2);
6248                                 if (isset($ca[$cap])) {
6249                                         $this->linestyleCap = $ca[$cap]." J";
6250                                         $this->_out($this->linestyleCap);
6251                                 }
6252                         }
6253                         if (isset($join)) {
6254                                 $ja = array("miter" => 0, "round" => 1, "bevel" => 2);
6255                                 if (isset($ja[$join])) {
6256                                         $this->linestyleJoin = $ja[$join]." j";
6257                                         $this->_out($this->linestyleJoin);
6258                                 }
6259                         }
6260                         if (isset($dash)) {
6261                                 $dash_string = "";
6262                                 if ($dash) {
6263                                         if (preg_match("/^.+,/", $dash)) {
6264                                                 $tab = explode(",", $dash);
6265                                         } else {
6266                                                 $tab = array($dash);
6267                                         }
6268                                         $dash_string = "";
6269                                         foreach ($tab as $i => $v) {
6270                                                 if ($i) {
6271                                                         $dash_string .= " ";
6272                                                 }
6273                                                 $dash_string .= sprintf("%.2f", $v);
6274                                         }
6275                                 }
6276                                 if (!isset($phase) OR !$dash) {
6277                                         $phase = 0;
6278                                 }
6279                                 $this->linestyleDash = sprintf("[%s] %.2f d", $dash_string, $phase);
6280                                 $this->_out($this->linestyleDash);
6281                         }
6282                         if (isset($color)) {
6283                                 $this->SetDrawColorArray($color);
6284                         }
6285                 }
6286
6287                 /*
6288                 * Set a draw point.
6289                 * @param float $x Abscissa of point.
6290                 * @param float $y Ordinate of point.
6291                 * @access protected
6292                 * @since 2.1.000 (2008-01-08)
6293                 */
6294                 function _outPoint($x, $y) {
6295                         if ($this->rtl) {
6296                                 $x = $this->w - $x;
6297                         }
6298                         $this->_out(sprintf("%.2f %.2f m", $x * $this->k, ($this->h - $y) * $this->k));
6299                 }
6300
6301                 /*
6302                 * Draws a line from last draw point.
6303                 * @param float $x Abscissa of end point.
6304                 * @param float $y Ordinate of end point.
6305                 * @access protected
6306                 * @since 2.1.000 (2008-01-08)
6307                 */
6308                 function _outLine($x, $y) {
6309                         if ($this->rtl) {
6310                                 $x = $this->w - $x;
6311                         }
6312                         $this->_out(sprintf("%.2f %.2f l", $x * $this->k, ($this->h - $y) * $this->k));
6313                 }
6314
6315                 /**
6316                 * Draws a rectangle.
6317                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6318                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6319                 * @param float $w Width.
6320                 * @param float $h Height.
6321                 * @param string $op options
6322                 * @access protected
6323                 * @since 2.1.000 (2008-01-08)
6324                 */
6325                 function _outRect($x, $y, $w, $h, $op) {
6326                         if ($this->rtl) {
6327                                 $x = $this->w - $x - $w;
6328                         }
6329                         $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
6330                 }
6331
6332                 /*
6333                 * Draws a Bezier curve from last draw point.
6334                 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
6335                 * @param float $x1 Abscissa of control point 1.
6336                 * @param float $y1 Ordinate of control point 1.
6337                 * @param float $x2 Abscissa of control point 2.
6338                 * @param float $y2 Ordinate of control point 2.
6339                 * @param float $x3 Abscissa of end point.
6340                 * @param float $y3 Ordinate of end point.
6341                 * @access protected
6342                 * @since 2.1.000 (2008-01-08)
6343                 */
6344                 function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
6345                         if ($this->rtl) {
6346                                 $x1 = $this->w - $x1;
6347                                 $x2 = $this->w - $x2;
6348                                 $x3 = $this->w - $x3;
6349                         }
6350                         $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));
6351                 }
6352
6353                 /**
6354                 * Draws a line between two points.
6355                 * @param float $x1 Abscissa of first point.
6356                 * @param float $y1 Ordinate of first point.
6357                 * @param float $x2 Abscissa of second point.
6358                 * @param float $y2 Ordinate of second point.
6359                 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6360                 * @access public
6361                 * @since 1.0
6362                 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
6363                 */
6364                 function Line($x1, $y1, $x2, $y2, $style=array()) {
6365                         if ($style) {
6366                                 $this->SetLineStyle($style);
6367                         }
6368                         $this->_outPoint($x1, $y1);
6369                         $this->_outLine($x2, $y2);
6370                         $this->_out(" S");
6371                 }
6372
6373                 /**
6374                 * Draws a rectangle.
6375                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6376                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6377                 * @param float $w Width.
6378                 * @param float $h Height.
6379                 * @param string $style Style of rendering. Possible values are:
6380                 * <ul>
6381                 *        <li>D or empty string: Draw (default).</li>
6382                 *        <li>F: Fill.</li>
6383                 *        <li>DF or FD: Draw and fill.</li>
6384                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6385                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6386                 * </ul>
6387                 * @param array $border_style Border style of rectangle. Array with keys among the following:
6388                 * <ul>
6389                 *        <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
6390                 *        <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
6391                 * </ul>
6392                 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
6393                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6394                 * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
6395                 * @access public
6396                 * @since 1.0
6397                 * @see SetLineStyle()
6398                 */
6399                 function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
6400                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6401                                 $this->SetFillColorArray($fill_color);
6402                         }
6403                         switch ($style) {
6404                                 case "F": {
6405                                         $op = 'f';
6406                                         $border_style = array();
6407                                         $this->_outRect($x, $y, $w, $h, $op);
6408                                         break;
6409                                 }
6410                                 case "DF":
6411                                 case "FD": {
6412                                         if ((!$border_style) OR (isset($border_style["all"]))) {
6413                                                 $op = 'B';
6414                                                 if (isset($border_style["all"])) {
6415                                                         $this->SetLineStyle($border_style["all"]);
6416                                                         $border_style = array();
6417                                                 }
6418                                         } else {
6419                                                 $op = 'f';
6420                                         }
6421                                         $this->_outRect($x, $y, $w, $h, $op);
6422                                         break;
6423                                 }
6424                                 case "CNZ": {
6425                                         $op = "W n";
6426                                         break;
6427                                 }
6428                                 case "CEO": {
6429                                         $op = "W* n";
6430                                         break;
6431                                 }
6432                                 default: {
6433                                         $op = 'S';
6434                                         if ((!$border_style) OR (isset($border_style["all"]))) {
6435                                                 if (isset($border_style["all"]) AND $border_style["all"]) {
6436                                                         $this->SetLineStyle($border_style["all"]);
6437                                                         $border_style = array();
6438                                                 }
6439                                                 $this->_outRect($x, $y, $w, $h, $op);
6440                                         }
6441                                         break;
6442                                 }
6443                         }
6444                         if ($border_style) {
6445                                 $border_style2 = array();
6446                                 foreach ($border_style as $line => $value) {
6447                                         $lenght = strlen($line);
6448                                         for ($i = 0; $i < $lenght; $i++) {
6449                                                 $border_style2[$line[$i]] = $value;
6450                                         }
6451                                 }
6452                                 $border_style = $border_style2;
6453                                 if (isset($border_style["L"]) AND $border_style["L"]) {
6454                                         $this->Line($x, $y, $x, $y + $h, $border_style["L"]);
6455                                 }
6456                                 if (isset($border_style["T"]) AND $border_style["T"]) {
6457                                         $this->Line($x, $y, $x + $w, $y, $border_style["T"]);
6458                                 }
6459                                 if (isset($border_style["R"]) AND $border_style["R"]) {
6460                                         $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style["R"]);
6461                                 }
6462                                 if (isset($border_style["B"]) AND $border_style["B"]) {
6463                                         $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style["B"]);
6464                                 }
6465                         }
6466                 }
6467
6468
6469                 /**
6470                 * Draws a Bezier curve.
6471                 * The Bezier curve is a tangent to the line between the control points at
6472                 * either end of the curve.
6473                 * @param float $x0 Abscissa of start point.
6474                 * @param float $y0 Ordinate of start point.
6475                 * @param float $x1 Abscissa of control point 1.
6476                 * @param float $y1 Ordinate of control point 1.
6477                 * @param float $x2 Abscissa of control point 2.
6478                 * @param float $y2 Ordinate of control point 2.
6479                 * @param float $x3 Abscissa of end point.
6480                 * @param float $y3 Ordinate of end point.
6481                 * @param string $style Style of rendering. Possible values are:
6482                 * <ul>
6483                 *        <li>D or empty string: Draw (default).</li>
6484                 *        <li>F: Fill.</li>
6485                 *        <li>DF or FD: Draw and fill.</li>
6486                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6487                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6488                 * </ul>
6489                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6490                 * @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).
6491                 * @access public
6492                 * @see SetLineStyle()
6493                 * @since 2.1.000 (2008-01-08)
6494                 */
6495                 function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style="", $line_style=array(), $fill_color=array()) {
6496                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6497                                 $this->SetFillColorArray($fill_color);
6498                         }
6499                         switch ($style) {
6500                                 case "F": {
6501                                         $op = "f";
6502                                         $line_style = array();
6503                                         break;
6504                                 }
6505                                 case "FD":
6506                                 case "DF": {
6507                                         $op = "B";
6508                                         break;
6509                                 }
6510                                 case "CNZ": {
6511                                         $op = "W n";
6512                                         break;
6513                                 }
6514                                 case "CEO": {
6515                                         $op = "W* n";
6516                                         break;
6517                                 }
6518                                 default: {
6519                                         $op = "S";
6520                                         break;
6521                                 }
6522                         }
6523                         if ($line_style) {
6524                                 $this->SetLineStyle($line_style);
6525                         }
6526                         $this->_outPoint($x0, $y0);
6527                         $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6528                         $this->_out($op);
6529                 }
6530
6531                 /**
6532                 * Draws a poly-Bezier curve.
6533                 * Each Bezier curve segment is a tangent to the line between the control points at
6534                 * either end of the curve.
6535                 * @param float $x0 Abscissa of start point.
6536                 * @param float $y0 Ordinate of start point.
6537                 * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
6538                 * @param string $style Style of rendering. Possible values are:
6539                 * <ul>
6540                 *        <li>D or empty string: Draw (default).</li>
6541                 *        <li>F: Fill.</li>
6542                 *        <li>DF or FD: Draw and fill.</li>
6543                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6544                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6545                 * </ul>
6546                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6547                 * @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).
6548                 * @access public
6549                 * @see SetLineStyle()
6550                 * @since 3.0008 (2008-05-12)
6551                 */
6552                 function Polycurve($x0, $y0, $segments, $style="", $line_style=array(), $fill_color=array()) {
6553                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6554                                 $this->SetFillColorArray($fill_color);
6555                         }
6556                         switch ($style) {
6557                                 case "F": {
6558                                         $op = "f";
6559                                         $line_style = array();
6560                                         break;
6561                                 }
6562                                 case "FD":
6563                                 case "DF": {
6564                                         $op = "B";
6565                                         break;
6566                                 }
6567                                 case "CNZ": {
6568                                         $op = "W n";
6569                                         break;
6570                                 }
6571                                 case "CEO": {
6572                                         $op = "W* n";
6573                                         break;
6574                                 }
6575                                 default: {
6576                                         $op = "S";
6577                                         break;
6578                                 }
6579                         }
6580                         if ($line_style) {
6581                                 $this->SetLineStyle($line_style);
6582                         }
6583                         $this->_outPoint($x0, $y0);
6584                         foreach ($segments as $segment) {
6585                                 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
6586                                 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6587                         }
6588                         $this->_out($op);
6589                 }
6590
6591                 /**
6592                 * Draws an ellipse.
6593                 * An ellipse is formed from n Bezier curves.
6594                 * @param float $x0 Abscissa of center point.
6595                 * @param float $y0 Ordinate of center point.
6596                 * @param float $rx Horizontal radius.
6597                 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
6598                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6599                 * @param float $astart: Angle start of draw line. Default value: 0.
6600                 * @param float $afinish: Angle finish of draw line. Default value: 360.
6601                 * @param string $style Style of rendering. Possible values are:
6602                 * <ul>
6603                 *        <li>D or empty string: Draw (default).</li>
6604                 *        <li>F: Fill.</li>
6605                 *        <li>DF or FD: Draw and fill.</li>
6606                 *        <li>C: Draw close.</li>
6607                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6608                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6609                 * </ul>
6610                 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6611                 * @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).
6612                 * @param integer $nc Number of curves used in ellipse. Default value: 8.
6613                 * @access public
6614                 * @since 2.1.000 (2008-01-08)
6615                 */
6616                 function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6617                         if ($angle) {
6618                                 $this->StartTransform();
6619                                 $this->Rotate($angle, $x0, $y0);
6620                                 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6621                                 $this->StopTransform();
6622                                 return;
6623                         }
6624                         if ($rx) {
6625                                 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6626                                         $this->SetFillColorArray($fill_color);
6627                                 }
6628                                 switch ($style) {
6629                                         case "F": {
6630                                                 $op = "f";
6631                                                 $line_style = array();
6632                                                 break;
6633                                         }
6634                                         case "FD":
6635                                         case "DF": {
6636                                                 $op = "B";
6637                                                 break;
6638                                         }
6639                                         case "C": {
6640                                                 $op = "s"; // Small "s" signifies closing the path as well
6641                                                 break;
6642                                         }
6643                                         case "CNZ": {
6644                                                 $op = "W n";
6645                                                 break;
6646                                         }
6647                                         case "CEO": {
6648                                                 $op = "W* n";
6649                                                 break;
6650                                         }
6651                                         default: {
6652                                                 $op = "S";
6653                                                 break;
6654                                         }
6655                                 }
6656                                 if ($line_style) {
6657                                         $this->SetLineStyle($line_style);
6658                                 }
6659                                 if (!$ry) {
6660                                         $ry = $rx;
6661                                 }
6662                                 $rx *= $this->k;
6663                                 $ry *= $this->k;
6664                                 if ($nc < 2){
6665                                         $nc = 2;
6666                                 }
6667                                 $astart = deg2rad((float) $astart);
6668                                 $afinish = deg2rad((float) $afinish);
6669                                 $total_angle = $afinish - $astart;
6670                                 $dt = $total_angle / $nc;
6671                                 $dtm = $dt / 3;
6672                                 $x0 *= $this->k;
6673                                 $y0 = ($this->h - $y0) * $this->k;
6674                                 $t1 = $astart;
6675                                 $a0 = $x0 + ($rx * cos($t1));
6676                                 $b0 = $y0 + ($ry * sin($t1));
6677                                 $c0 = -$rx * sin($t1);
6678                                 $d0 = $ry * cos($t1);
6679                                 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
6680                                 for ($i = 1; $i <= $nc; $i++) {
6681                                         // Draw this bit of the total curve
6682                                         $t1 = ($i * $dt) + $astart;
6683                                         $a1 = $x0 + ($rx * cos($t1));
6684                                         $b1 = $y0 + ($ry * sin($t1));
6685                                         $c1 = -$rx * sin($t1);
6686                                         $d1 = $ry * cos($t1);
6687                                         $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));
6688                                         $a0 = $a1;
6689                                         $b0 = $b1;
6690                                         $c0 = $c1;
6691                                         $d0 = $d1;
6692                                 }
6693                                 $this->_out($op);
6694                         }
6695                 }
6696
6697                 /**
6698                 * Draws a circle.
6699                 * A circle is formed from n Bezier curves.
6700                 * @param float $x0 Abscissa of center point.
6701                 * @param float $y0 Ordinate of center point.
6702                 * @param float $r Radius.
6703                 * @param float $astart: Angle start of draw line. Default value: 0.
6704                 * @param float $afinish: Angle finish of draw line. Default value: 360.
6705                 * @param string $style Style of rendering. Possible values are:
6706                 * <ul>
6707                 *        <li>D or empty string: Draw (default).</li>
6708                 *        <li>F: Fill.</li>
6709                 *        <li>DF or FD: Draw and fill.</li>
6710                 *        <li>C: Draw close.</li>
6711                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6712                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6713                 * </ul>
6714                 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6715                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6716                 * @param integer $nc Number of curves used in circle. Default value: 8.
6717                 * @access public
6718                 * @since 2.1.000 (2008-01-08)
6719                 */
6720                 function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6721                         $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6722                 }
6723
6724                 /**
6725                 * Draws a polygon.
6726                 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
6727                 * @param string $style Style of rendering. Possible values are:
6728                 * <ul>
6729                 *        <li>D or empty string: Draw (default).</li>
6730                 *        <li>F: Fill.</li>
6731                 *        <li>DF or FD: Draw and fill.</li>
6732                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6733                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6734                 * </ul>
6735                 * @param array $line_style Line style of polygon. Array with keys among the following:
6736                 * <ul>
6737                 *        <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
6738                 *        <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
6739                 * </ul>
6740                 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
6741                 * @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).
6742                 * @access public
6743                 * @since 2.1.000 (2008-01-08)
6744                 */
6745                 function Polygon($p, $style="", $line_style=array(), $fill_color=array()) {
6746                         $np = count($p) / 2;
6747                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6748                                 $this->SetFillColorArray($fill_color);
6749                         }
6750                         switch ($style) {
6751                                 case "F": {
6752                                         $line_style = array();
6753                                         $op = "f";
6754                                         break;
6755                                 }
6756                                 case "FD":
6757                                 case "DF": {
6758                                         $op = "B";
6759                                         break;
6760                                 }
6761                                 case "CNZ": {
6762                                         $op = "W n";
6763                                         break;
6764                                 }
6765                                 case "CEO": {
6766                                         $op = "W* n";
6767                                         break;
6768                                 }
6769                                 default: {
6770                                         $op = "S";
6771                                         break;
6772                                 }
6773                         }
6774                         $draw = true;
6775                         if ($line_style) {
6776                                 if (isset($line_style["all"])) {
6777                                         $this->SetLineStyle($line_style["all"]);
6778                                 } else { // 0 .. (np - 1), op = {B, S}
6779                                         $draw = false;
6780                                         if ("B" == $op) {
6781                                                 $op = "f";
6782                                                 $this->_outPoint($p[0], $p[1]);
6783                                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6784                                                         $this->_outLine($p[$i], $p[$i + 1]);
6785                                                 }
6786                                                 $this->_outLine($p[0], $p[1]);
6787                                                 $this->_out($op);
6788                                         }
6789                                         $p[($np * 2)] = $p[0];
6790                                         $p[(($np * 2) + 1)] = $p[1];
6791                                         for ($i = 0; $i < $np; $i++) {
6792                                                 if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
6793                                                         $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
6794                                                 }
6795                                         }
6796                                 }
6797                         }
6798                         if ($draw) {
6799                                 $this->_outPoint($p[0], $p[1]);
6800                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6801                                         $this->_outLine($p[$i], $p[$i + 1]);
6802                                 }
6803                                 $this->_outLine($p[0], $p[1]);
6804                                 $this->_out($op);
6805                         }
6806                 }
6807
6808                 /**
6809                 * Draws a regular polygon.
6810                 * @param float $x0 Abscissa of center point.
6811                 * @param float $y0 Ordinate of center point.
6812                 * @param float $r: Radius of inscribed circle.
6813                 * @param integer $ns Number of sides.
6814                 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
6815                 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
6816                 * @param string $style Style of rendering. Possible values are:
6817                 * <ul>
6818                 *        <li>D or empty string: Draw (default).</li>
6819                 *        <li>F: Fill.</li>
6820                 *        <li>DF or FD: Draw and fill.</li>
6821                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6822                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6823                 * </ul>
6824                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6825                 * <ul>
6826                 *        <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
6827                 *        <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6828                 * </ul>
6829                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6830                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6831                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6832                 * <ul>
6833                 *        <li>D or empty string: Draw (default).</li>
6834                 *        <li>F: Fill.</li>
6835                 *        <li>DF or FD: Draw and fill.</li>
6836                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6837                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6838                 * </ul>
6839                 * @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).
6840                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6841                 * @access public
6842                 * @since 2.1.000 (2008-01-08)
6843                 */
6844                 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()) {
6845                         if (3 > $ns) {
6846                                 $ns = 3;
6847                         }
6848                         if ($draw_circle) {
6849                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6850                         }
6851                         $p = array();
6852                         for ($i = 0; $i < $ns; $i++) {
6853                                 $a = $angle + ($i * 360 / $ns);
6854                                 $a_rad = deg2rad((float) $a);
6855                                 $p[] = $x0 + ($r * sin($a_rad));
6856                                 $p[] = $y0 + ($r * cos($a_rad));
6857                         }
6858                         $this->Polygon($p, $style, $line_style, $fill_color);
6859                 }
6860
6861                 /**
6862                 * Draws a star polygon
6863                 * @param float $x0 Abscissa of center point.
6864                 * @param float $y0 Ordinate of center point.
6865                 * @param float $r Radius of inscribed circle.
6866                 * @param integer $nv Number of vertices.
6867                 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
6868                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6869                 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
6870                 * @param string $style Style of rendering. Possible values are:
6871                 * <ul>
6872                 *        <li>D or empty string: Draw (default).</li>
6873                 *        <li>F: Fill.</li>
6874                 *        <li>DF or FD: Draw and fill.</li>
6875                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6876                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6877                 * </ul>
6878                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6879                 * <ul>
6880                 *        <li>all: Line style of all sides. Array like for
6881                 * {@link SetLineStyle SetLineStyle}.</li>
6882                 *        <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6883                 * </ul>
6884                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6885                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6886                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6887                 * <ul>
6888                 *        <li>D or empty string: Draw (default).</li>
6889                 *        <li>F: Fill.</li>
6890                 *        <li>DF or FD: Draw and fill.</li>
6891                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6892                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6893                 * </ul>
6894                 * @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).
6895                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6896                 * @access public
6897                 * @since 2.1.000 (2008-01-08)
6898                 */
6899                 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()) {
6900                         if (2 > $nv) {
6901                                 $nv = 2;
6902                         }
6903                         if ($draw_circle) {
6904                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6905                         }
6906                         $p2 = array();
6907                         $visited = array();
6908                         for ($i = 0; $i < $nv; $i++) {
6909                                 $a = $angle + ($i * 360 / $nv);
6910                                 $a_rad = deg2rad((float) $a);
6911                                 $p2[] = $x0 + ($r * sin($a_rad));
6912                                 $p2[] = $y0 + ($r * cos($a_rad));
6913                                 $visited[] = false;
6914                         }
6915                         $p = array();
6916                         $i = 0;
6917                         do {
6918                                 $p[] = $p2[$i * 2];
6919                                 $p[] = $p2[($i * 2) + 1];
6920                                 $visited[$i] = true;
6921                                 $i += $ng;
6922                                 $i %= $nv;
6923                         } while (!$visited[$i]);
6924                         $this->Polygon($p, $style, $line_style, $fill_color);
6925                 }
6926
6927                 /**
6928                 * Draws a rounded rectangle.
6929                 * @param float $x Abscissa of upper-left corner.
6930                 * @param float $y Ordinate of upper-left corner.
6931                 * @param float $w Width.
6932                 * @param float $h Height.
6933                 * @param float $r Radius of the rounded corners.
6934                 * @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").
6935                 * @param string $style Style of rendering. Possible values are:
6936                 * <ul>
6937                 *        <li>D or empty string: Draw (default).</li>
6938                 *        <li>F: Fill.</li>
6939                 *        <li>DF or FD: Draw and fill.</li>
6940                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6941                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6942                 * </ul>
6943                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6944                 * @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).
6945                 * @access public
6946                 * @since 2.1.000 (2008-01-08)
6947                 */
6948                 function RoundedRect($x, $y, $w, $h, $r, $round_corner="1111", $style="", $border_style=array(), $fill_color=array()) {
6949                         if ("0000" == $round_corner) { // Not rounded
6950                                 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
6951                         } else { // Rounded
6952                                 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6953                                         $this->SetFillColorArray($fill_color);
6954                                 }
6955                                 switch ($style) {
6956                                         case "F": {
6957                                                 $border_style = array();
6958                                                 $op = "f";
6959                                                 break;
6960                                         }
6961                                         case "FD":
6962                                         case "DF": {
6963                                                 $op = "B";
6964                                                 break;
6965                                         }
6966                                         case "CNZ": {
6967                                                 $op = "W n";
6968                                                 break;
6969                                         }
6970                                         case "CEO": {
6971                                                 $op = "W* n";
6972                                                 break;
6973                                         }
6974                                         default: {
6975                                                 $op = "S";
6976                                                 break;
6977                                         }
6978                                 }
6979                                 if ($border_style) {
6980                                         $this->SetLineStyle($border_style);
6981                                 }
6982                                 $MyArc = 4 / 3 * (sqrt(2) - 1);
6983                                 $this->_outPoint($x + $r, $y);
6984                                 $xc = $x + $w - $r;
6985                                 $yc = $y + $r;
6986                                 $this->_outLine($xc, $y);
6987                                 if ($round_corner[0]) {
6988                                         $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
6989                                 } else {
6990                                         $this->_outLine($x + $w, $y);
6991                                 }
6992                                 $xc = $x + $w - $r;
6993                                 $yc = $y + $h - $r;
6994                                 $this->_outLine($x + $w, $yc);
6995                                 if ($round_corner[1]) {
6996                                         $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
6997                                 } else {
6998                                         $this->_outLine($x + $w, $y + $h);
6999                                 }
7000                                 $xc = $x + $r;
7001                                 $yc = $y + $h - $r;
7002                                 $this->_outLine($xc, $y + $h);
7003                                 if ($round_corner[2]) {
7004                                         $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
7005                                 } else {
7006                                         $this->_outLine($x, $y + $h);
7007                                 }
7008                                 $xc = $x + $r;
7009                                 $yc = $y + $r;
7010                                 $this->_outLine($x, $yc);
7011                                 if ($round_corner[3]) {
7012                                         $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
7013                                 } else {
7014                                         $this->_outLine($x, $y);
7015                                         $this->_outLine($x + $r, $y);
7016                                 }
7017                                 $this->_out($op);
7018                         }
7019                 }
7020
7021                 // END GRAPHIC FUNCTIONS SECTION -----------------------
7022
7023                 // BIDIRECTIONAL TEXT SECTION --------------------------
7024                 /**
7025                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7026                  * @param string $str string to manipulate.
7027                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7028                  * @return string
7029                  * @author Nicola Asuni
7030                  * @since 2.1.000 (2008-01-08)
7031                 */
7032                 function utf8StrRev($str, $setbom=false, $forcertl=false) {
7033                         return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $forcertl), $setbom);
7034                 }
7035
7036                 /**
7037                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7038                  * @param array $ta array of characters composing the string.
7039                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7040                  * @return string
7041                  * @author Nicola Asuni
7042                  * @since 2.4.000 (2008-03-06)
7043                 */
7044                 function utf8Bidi($ta, $forcertl=false) {
7045                         global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
7046                         // paragraph embedding level
7047                         $pel = 0;
7048                         // max level
7049                         $maxlevel = 0;
7050                         // create string from array
7051                         $str = $this->UTF8ArrSubString($ta);
7052                         // check if string contains arabic text
7053                         if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
7054                                 $arabic = true;
7055                         } else {
7056                                 $arabic = false;
7057                         }
7058                         // check if string contains RTL text
7059                         if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
7060                                 return $ta;
7061                         }
7062                         
7063                         // get number of chars
7064                         $numchars = count($ta);
7065                         
7066                         if ($forcertl == 'R') {
7067                                         $pel = 1;
7068                         } elseif ($forcertl == 'L') {
7069                                         $pel = 0;
7070                         } else {
7071                                 // P2. In each paragraph, find the first character of type L, AL, or R.
7072                                 // 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.
7073                                 for ($i=0; $i < $numchars; $i++) {
7074                                         $type = $unicode[$ta[$i]];
7075                                         if ($type == 'L') {
7076                                                 $pel = 0;
7077                                                 break;
7078                                         } elseif (($type == 'AL') OR ($type == 'R')) {
7079                                                 $pel = 1;
7080                                                 break;
7081                                         }
7082                                 }
7083                         }
7084                         
7085                         // Current Embedding Level
7086                         $cel = $pel;
7087                         // directional override status
7088                         $dos = 'N';
7089                         $remember = array();
7090                         // start-of-level-run
7091                         $sor = $pel % 2 ? 'R' : 'L';
7092                         $eor = $sor;
7093
7094                         //$levels = array(array('level' => $cel, 'sor' => $sor, 'eor' => '', 'chars' => array()));
7095                         //$current_level = &$levels[count( $levels )-1];
7096
7097                         // Array of characters data
7098                         $chardata = Array();
7099
7100                         // 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.
7101                         //      In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
7102                         for ($i=0; $i < $numchars; $i++) {
7103                                 if ($ta[$i] == K_RLE) {
7104                                         // X2. With each RLE, compute the least greater odd embedding level.
7105                                         //      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.
7106                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7107                                         $next_level = $cel + ($cel % 2) + 1;
7108                                         if ($next_level < 62) {
7109                                                 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
7110                                                 $cel = $next_level;
7111                                                 $dos = 'N';
7112                                                 $sor = $eor;
7113                                                 $eor = $cel % 2 ? 'R' : 'L';
7114                                         }
7115                                 } elseif ($ta[$i] == K_LRE) {
7116                                         // X3. With each LRE, compute the least greater even embedding level.
7117                                         //      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.
7118                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7119                                         $next_level = $cel + 2 - ($cel % 2);
7120                                         if ( $next_level < 62 ) {
7121                                                 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
7122                                                 $cel = $next_level;
7123                                                 $dos = 'N';
7124                                                 $sor = $eor;
7125                                                 $eor = $cel % 2 ? 'R' : 'L';
7126                                         }
7127                                 } elseif ($ta[$i] == K_RLO) {
7128                                         // X4. With each RLO, compute the least greater odd embedding level.
7129                                         //      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.
7130                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7131                                         $next_level = $cel + ($cel % 2) + 1;
7132                                         if ($next_level < 62) {
7133                                                 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
7134                                                 $cel = $next_level;
7135                                                 $dos = 'R';
7136                                                 $sor = $eor;
7137                                                 $eor = $cel % 2 ? 'R' : 'L';
7138                                         }
7139                                 } elseif ($ta[$i] == K_LRO) {
7140                                         // X5. With each LRO, compute the least greater even embedding level.
7141                                         //      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.
7142                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7143                                         $next_level = $cel + 2 - ($cel % 2);
7144                                         if ( $next_level < 62 ) {
7145                                                 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
7146                                                 $cel = $next_level;
7147                                                 $dos = 'L';
7148                                                 $sor = $eor;
7149                                                 $eor = $cel % 2 ? 'R' : 'L';
7150                                         }
7151                                 } elseif ($ta[$i] == K_PDF) {
7152                                         // 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.
7153                                         if (count($remember)) {
7154                                                 $last = count($remember ) - 1;
7155                                                 if (($remember[$last]['num'] == K_RLE) OR
7156                                                           ($remember[$last]['num'] == K_LRE) OR
7157                                                           ($remember[$last]['num'] == K_RLO) OR
7158                                                           ($remember[$last]['num'] == K_LRO)) {
7159                                                         $match = array_pop($remember);
7160                                                         $cel = $match['cel'];
7161                                                         $dos = $match['dos'];
7162                                                         $sor = $eor;
7163                                                         $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
7164                                                 }
7165                                         }
7166                                 } elseif (($ta[$i] != K_RLE) AND
7167                                                                  ($ta[$i] != K_LRE) AND
7168                                                                  ($ta[$i] != K_RLO) AND
7169                                                                  ($ta[$i] != K_LRO) AND
7170                                                                  ($ta[$i] != K_PDF)) {
7171                                         // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
7172                                         //      a. Set the level of the current character to the current embedding level.
7173                                         //      b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
7174                                         if ($dos != 'N') {
7175                                                 $chardir = $dos;
7176                                         } else {
7177                                                 $chardir = $unicode[$ta[$i]];
7178                                         }
7179                                         // stores string characters and other information
7180                                         $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
7181                                 }
7182                         } // end for each char
7183
7184                         // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
7185                         // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
7186                         // 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.
7187
7188                         // 3.3.3 Resolving Weak Types
7189                         // 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.
7190                         // Nonspacing marks are now resolved based on the previous characters.
7191                         $numchars = count($chardata);
7192
7193                         // 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.
7194                         $prevlevel = -1; // track level changes
7195                         $levcount = 0; // counts consecutive chars at the same level
7196                         for ($i=0; $i < $numchars; $i++) {
7197                                 if ($chardata[$i]['type'] == 'NSM') {
7198                                         if ($levcount) {
7199                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7200                                         } elseif ($i > 0) {
7201                                                 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
7202                                         }
7203                                 }
7204                                 if ($chardata[$i]['level'] != $prevlevel) {
7205                                         $levcount = 0;
7206                                 } else {
7207                                         $levcount++;
7208                                 }
7209                                 $prevlevel = $chardata[$i]['level'];
7210                         }
7211
7212                         // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number.
7213                         $prevlevel = -1;
7214                         $levcount = 0;
7215                         for ($i=0; $i < $numchars; $i++) {
7216                                 if ($chardata[$i]['char'] == 'EN') {
7217                                         for ($j=$levcount; $j >= 0; $j--) {
7218                                                 if ($chardata[$j]['type'] == 'AL') {
7219                                                         $chardata[$i]['type'] = 'AN';
7220                                                 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
7221                                                         break;
7222                                                 }
7223                                         }
7224                                 }
7225                                 if ($chardata[$i]['level'] != $prevlevel) {
7226                                         $levcount = 0;
7227                                 } else {
7228                                         $levcount++;
7229                                 }
7230                                 $prevlevel = $chardata[$i]['level'];
7231                         }
7232
7233                         // W3. Change all ALs to R.
7234                         for ($i=0; $i < $numchars; $i++) {
7235                                 if ($chardata[$i]['type'] == 'AL') {
7236                                         $chardata[$i]['type'] = 'R';
7237                                 }
7238                         }
7239
7240                         // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type.
7241                         $prevlevel = -1;
7242                         $levcount = 0;
7243                         for ($i=0; $i < $numchars; $i++) {
7244                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7245                                         if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7246                                                 $chardata[$i]['type'] = 'EN';
7247                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7248                                                 $chardata[$i]['type'] = 'EN';
7249                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
7250                                                 $chardata[$i]['type'] = 'AN';
7251                                         }
7252                                 }
7253                                 if ($chardata[$i]['level'] != $prevlevel) {
7254                                         $levcount = 0;
7255                                 } else {
7256                                         $levcount++;
7257                                 }
7258                                 $prevlevel = $chardata[$i]['level'];
7259                         }
7260
7261                         // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
7262                         $prevlevel = -1;
7263                         $levcount = 0;
7264                         for ($i=0; $i < $numchars; $i++) {
7265                                 if ($chardata[$i]['type'] == 'ET') {
7266                                         if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
7267                                                 $chardata[$i]['type'] = 'EN';
7268                                         } else {
7269                                                 $j = $i+1;
7270                                                 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
7271                                                         if ($chardata[$j]['type'] == 'EN') {
7272                                                                 $chardata[$i]['type'] = 'EN';
7273                                                                 break;
7274                                                         } elseif ($chardata[$j]['type'] != 'ET') {
7275                                                                 break;
7276                                                         }
7277                                                         $j++;
7278                                                 }
7279                                         }
7280                                 }
7281                                 if ($chardata[$i]['level'] != $prevlevel) {
7282                                         $levcount = 0;
7283                                 } else {
7284                                         $levcount++;
7285                                 }
7286                                 $prevlevel = $chardata[$i]['level'];
7287                         }
7288
7289                         // W6. Otherwise, separators and terminators change to Other Neutral.
7290                         $prevlevel = -1;
7291                         $levcount = 0;
7292                         for ($i=0; $i < $numchars; $i++) {
7293                                 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
7294                                         $chardata[$i]['type'] = 'ON';
7295                                 }
7296                                 if ($chardata[$i]['level'] != $prevlevel) {
7297                                         $levcount = 0;
7298                                 } else {
7299                                         $levcount++;
7300                                 }
7301                                 $prevlevel = $chardata[$i]['level'];
7302                         }
7303
7304                         //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L.
7305                         $prevlevel = -1;
7306                         $levcount = 0;
7307                         for ($i=0; $i < $numchars; $i++) {
7308                                 if ($chardata[$i]['char'] == 'EN') {
7309                                         for ($j=$levcount; $j >= 0; $j--) {
7310                                                 if ($chardata[$j]['type'] == 'L') {
7311                                                         $chardata[$i]['type'] = 'L';
7312                                                 } elseif ($chardata[$j]['type'] == 'R') {
7313                                                         break;
7314                                                 }
7315                                         }
7316                                 }
7317                                 if ($chardata[$i]['level'] != $prevlevel) {
7318                                         $levcount = 0;
7319                                 } else {
7320                                         $levcount++;
7321                                 }
7322                                 $prevlevel = $chardata[$i]['level'];
7323                         }
7324
7325                         // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries.
7326                         $prevlevel = -1;
7327                         $levcount = 0;
7328                         for ($i=0; $i < $numchars; $i++) {
7329                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7330                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7331                                                 $chardata[$i]['type'] = 'L';
7332                                         } elseif (($chardata[$i]['type'] == 'N') AND
7333                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7334                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7335                                                 $chardata[$i]['type'] = 'R';
7336                                         } elseif ($chardata[$i]['type'] == 'N') {
7337                                                 // N2. Any remaining neutrals take the embedding direction
7338                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7339                                         }
7340                                 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7341                                         // first char
7342                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7343                                                 $chardata[$i]['type'] = 'L';
7344                                         } elseif (($chardata[$i]['type'] == 'N') AND
7345                                          (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
7346                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7347                                                 $chardata[$i]['type'] = 'R';
7348                                         } elseif ($chardata[$i]['type'] == 'N') {
7349                                                 // N2. Any remaining neutrals take the embedding direction
7350                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7351                                         }
7352                                 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
7353                                         //last char
7354                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
7355                                                 $chardata[$i]['type'] = 'L';
7356                                         } elseif (($chardata[$i]['type'] == 'N') AND
7357                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7358                                          (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
7359                                                 $chardata[$i]['type'] = 'R';
7360                                         } elseif ($chardata[$i]['type'] == 'N') {
7361                                                 // N2. Any remaining neutrals take the embedding direction
7362                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7363                                         }
7364                                 } elseif ($chardata[$i]['type'] == 'N') {
7365                                         // N2. Any remaining neutrals take the embedding direction
7366                                         $chardata[$i]['type'] = $chardata[$i]['sor'];
7367                                 }
7368                                 if ($chardata[$i]['level'] != $prevlevel) {
7369                                         $levcount = 0;
7370                                 } else {
7371                                         $levcount++;
7372                                 }
7373                                 $prevlevel = $chardata[$i]['level'];
7374                         }
7375
7376                         // 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.
7377                         // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
7378                         for ($i=0; $i < $numchars; $i++) {
7379                                 $odd = $chardata[$i]['level'] % 2;
7380                                 if ($odd) {
7381                                         if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7382                                                 $chardata[$i]['level'] += 1;
7383                                         }
7384                                 } else {
7385                                         if ($chardata[$i]['type'] == 'R') {
7386                                                 $chardata[$i]['level'] += 1;
7387                                         } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7388                                                 $chardata[$i]['level'] += 2;
7389                                         }
7390                                 }
7391                                 $maxlevel = max($chardata[$i]['level'],$maxlevel);
7392                         }
7393
7394                         // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
7395                         //      1. Segment separators,
7396                         //      2. Paragraph separators,
7397                         //      3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
7398                         //      4. Any sequence of white space characters at the end of the line.
7399                         for ($i=0; $i < $numchars; $i++) {
7400                                 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
7401                                         $chardata[$i]['level'] = $pel;
7402                                 } elseif ($chardata[$i]['type'] == 'WS') {
7403                                         $j = $i+1;
7404                                         while ($j < $numchars) {
7405                                                 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
7406                                                         (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
7407                                                         $chardata[$i]['level'] = $pel;
7408                                                         break;
7409                                                 } elseif ($chardata[$j]['type'] != 'WS') {
7410                                                         break;
7411                                                 }
7412                                                 $j++;
7413                                         }
7414                                 }
7415                         }
7416
7417                         // Arabic Shaping
7418                         // 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.
7419                         if ($arabic) {
7420                                 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
7421                                 $alfletter = array(1570,1571,1573,1575);
7422                                 $chardata2 = $chardata;
7423                                 $laaletter = false;
7424                                 $charAL = array();
7425                                 $x = 0;
7426                                 for ($i=0; $i < $numchars; $i++) {
7427                                         if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
7428                                                 $charAL[$x] = $chardata[$i];
7429                                                 $charAL[$x]['i'] = $i;
7430                                                 $chardata[$i]['x'] = $x;
7431                                                 $x++;
7432                                         }
7433                                 }
7434                                 $numAL = $x;
7435                                 for ($i=0; $i < $numchars; $i++) {
7436                                         $thischar = $chardata[$i];
7437                                         if ($i > 0) {
7438                                                 $prevchar = $chardata[($i-1)];
7439                                         } else {
7440                                                 $prevchar = false;
7441                                         }
7442                                         if (($i+1) < $numchars) {
7443                                                 $nextchar = $chardata[($i+1)];
7444                                         } else {
7445                                                 $nextchar = false;
7446                                         }
7447                                         if ($unicode[$thischar['char']] == 'AL') {
7448                                                 $x = $thischar['x'];
7449                                                 if ($x > 0) {
7450                                                         $prevchar = $charAL[($x-1)];
7451                                                 } else {
7452                                                         $prevchar = false;
7453                                                 }
7454                                                 if (($x+1) < $numAL) {
7455                                                         $nextchar = $charAL[($x+1)];
7456                                                 } else {
7457                                                         $nextchar = false;
7458                                                 }
7459                                                 // if laa letter
7460                                                 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
7461                                                         $arabicarr = $laa_array;
7462                                                         $laaletter = true;
7463                                                         if ($x > 1) {
7464                                                                 $prevchar = $charAL[($x-2)];
7465                                                         } else {
7466                                                                 $prevchar = false;
7467                                                         }
7468                                                 } else {
7469                                                         $arabicarr = $unicode_arlet;
7470                                                         $laaletter = false;
7471                                                 }
7472                                                 if (($prevchar !== false) AND ($nextchar !== false) AND
7473                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7474                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7475                                                         ($prevchar['type'] == $thischar['type']) AND
7476                                                         ($nextchar['type'] == $thischar['type']) AND
7477                                                         ($nextchar['char'] != 1567)) {
7478                                                         if (in_array($prevchar['char'], $endedletter)) {
7479                                                                 if (isset($arabicarr[$thischar['char']][2])) {
7480                                                                         // initial
7481                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7482                                                                 }
7483                                                         } else {
7484                                                                 if (isset($arabicarr[$thischar['char']][3])) {
7485                                                                         // medial
7486                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
7487                                                                 }
7488                                                         }
7489                                                 } elseif (($nextchar !== false) AND
7490                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7491                                                         ($nextchar['type'] == $thischar['type']) AND
7492                                                         ($nextchar['char'] != 1567)) {
7493                                                         if (isset($arabicarr[$chardata[$i]['char']][2])) {
7494                                                                 // initial
7495                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7496                                                         }
7497                                                 } elseif ((($prevchar !== false) AND
7498                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7499                                                         ($prevchar['type'] == $thischar['type'])) OR
7500                                                         (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
7501                                                         // final
7502                                                         if (($i > 1) AND ($thischar['char'] == 1607) AND
7503                                                                 ($chardata[$i-1]['char'] == 1604) AND
7504                                                                 ($chardata[$i-2]['char'] == 1604)) {
7505                                                                 //Allah Word
7506                                                                 // mark characters to delete with false
7507                                                                 $chardata2[$i-2]['char'] = false;
7508                                                                 $chardata2[$i-1]['char'] = false;
7509                                                                 $chardata2[$i]['char'] = 65010;
7510                                                         } else {
7511                                                                 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
7512                                                                         if (isset($arabicarr[$thischar['char']][0])) {
7513                                                                                 // isolated
7514                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7515                                                                         }
7516                                                                 } else {
7517                                                                         if (isset($arabicarr[$thischar['char']][1])) {
7518                                                                                 // final
7519                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
7520                                                                         }
7521                                                                 }
7522                                                         }
7523                                                 } elseif (isset($arabicarr[$thischar['char']][0])) {
7524                                                         // isolated
7525                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7526                                                 }
7527                                                 // if laa letter
7528                                                 if ($laaletter) {
7529                                                         // mark characters to delete with false
7530                                                         $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
7531                                                 }
7532                                         } // end if AL (Arabic Letter)
7533                                 } // end for each char
7534                                 /*
7535                                  * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
7536                                  * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
7537                                  */
7538                                 $cw = &$this->CurrentFont['cw'];
7539                                 for ($i=0; $i < ($numchars-1); $i++) {
7540                                         if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
7541                                                 // check if the subtitution font is defined on current font
7542                                                 if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
7543                                                         $chardata2[$i]['char'] = false;
7544                                                         $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
7545                                                 }
7546                                         }
7547                                 }
7548                                 // remove marked characters
7549                                 foreach($chardata2 as $key => $value) {
7550                                         if ($value['char'] === false) {
7551                                                 unset($chardata2[$key]);
7552                                         }
7553                                 }
7554                                 $chardata = array_values($chardata2);
7555                                 $numchars = count($chardata);
7556                                 unset($chardata2);
7557                                 unset($arabicarr);
7558                                 unset($laaletter);
7559                                 unset($charAL);
7560                         }
7561
7562                         // 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.
7563                         for ($j=$maxlevel; $j > 0; $j--) {
7564                                 $ordarray = Array();
7565                                 $revarr = Array();
7566                                 $onlevel = false;
7567                                 for ($i=0; $i < $numchars; $i++) {
7568                                         if ($chardata[$i]['level'] >= $j) {
7569                                                 $onlevel = true;
7570                                                 if (isset($unicode_mirror[$chardata[$i]['char']])) {
7571                                                         // 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.
7572                                                         $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
7573                                                 }
7574                                                 $revarr[] = $chardata[$i];
7575                                         } else {
7576                                                 if ($onlevel) {
7577                                                         $revarr = array_reverse($revarr);
7578                                                         $ordarray = array_merge($ordarray, $revarr);
7579                                                         $revarr = Array();
7580                                                         $onlevel = false;
7581                                                 }
7582                                                 $ordarray[] = $chardata[$i];
7583                                         }
7584                                 }
7585                                 if ($onlevel) {
7586                                         $revarr = array_reverse($revarr);
7587                                         $ordarray = array_merge($ordarray, $revarr);
7588                                 }
7589                                 $chardata = $ordarray;
7590                         }
7591
7592                         $ordarray = array();
7593                         for ($i=0; $i < $numchars; $i++) {
7594                                 $ordarray[] = $chardata[$i]['char'];
7595                         }
7596
7597                         return $ordarray;
7598                 }
7599
7600                 // END OF BIDIRECTIONAL TEXT SECTION -------------------
7601
7602                 /*
7603                 * Adds a bookmark.
7604                 * @param string $txt bookmark description.
7605                 * @param int $level bookmark level (minimum value is 0).
7606                 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
7607                 * @access public
7608                 * @author Olivier Plathey, Nicola Asuni
7609                 * @since 2.1.002 (2008-02-12)
7610                 */
7611                 function Bookmark($txt, $level=0, $y=-1) {
7612                         if ($level < 0) {
7613                                 $level = 0;
7614                         }
7615                         if (isset($this->outlines[0])) {
7616                                 $lastoutline = end($this->outlines);
7617                                 $maxlevel = $lastoutline['l'] + 1;
7618                         } else {
7619                                 $maxlevel = 0;
7620                         }
7621                         if ($level > $maxlevel) {
7622                                 $level = $maxlevel;
7623                         }
7624                         if ($y == -1) {
7625                                 $y = $this->GetY();
7626                         }
7627                         $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $this->PageNo());
7628                 }
7629
7630                 /*
7631                 * Create a bookmark PDF string.
7632                 * @access protected
7633                 * @author Olivier Plathey, Nicola Asuni
7634                 * @since 2.1.002 (2008-02-12)
7635                 */
7636                 function _putbookmarks() {
7637                         $nb = count($this->outlines);
7638                         if ($nb == 0) {
7639                                 return;
7640                         }
7641                         $lru = array();
7642                         $level = 0;
7643                         foreach($this->outlines as $i => $o) {
7644                                 if ($o['l'] > 0) {
7645                                         $parent = $lru[($o['l'] - 1)];
7646                                         //Set parent and last pointers
7647                                         $this->outlines[$i]['parent'] = $parent;
7648                                         $this->outlines[$parent]['last'] = $i;
7649                                         if ($o['l'] > $level) {
7650                                                 //Level increasing: set first pointer
7651                                                 $this->outlines[$parent]['first'] = $i;
7652                                         }
7653                                 } else {
7654                                         $this->outlines[$i]['parent'] = $nb;
7655                                 }
7656                                 if (($o['l'] <= $level) AND ($i > 0)) {
7657                                         //Set prev and next pointers
7658                                         $prev = $lru[$o['l']];
7659                                         $this->outlines[$prev]['next'] = $i;
7660                                         $this->outlines[$i]['prev'] = $prev;
7661                                 }
7662                                 $lru[$o['l']] = $i;
7663                                 $level = $o['l'];
7664                         }
7665                         //Outline items
7666                         $n = $this->n + 1;
7667                         foreach($this->outlines as $i => $o) {
7668                                 $this->_newobj();
7669                                 $this->_out('<</Title '.$this->_textstring($o['t']));
7670                                 $this->_out('/Parent '.($n+$o['parent']).' 0 R');
7671                                 if (isset($o['prev']))
7672                                 $this->_out('/Prev '.($n+$o['prev']).' 0 R');
7673                                 if (isset($o['next']))
7674                                 $this->_out('/Next '.($n+$o['next']).' 0 R');
7675                                 if (isset($o['first']))
7676                                 $this->_out('/First '.($n+$o['first']).' 0 R');
7677                                 if (isset($o['last']))
7678                                 $this->_out('/Last '.($n+$o['last']).' 0 R');
7679                                 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]', 1+2*$o['p'], ($this->h-$o['y'])*$this->k));
7680                                 $this->_out('/Count 0>>');
7681                                 $this->_out('endobj');
7682                         }
7683                         //Outline root
7684                         $this->_newobj();
7685                         $this->OutlineRoot=$this->n;
7686                         $this->_out('<</Type /Outlines /First '.$n.' 0 R');
7687                         $this->_out('/Last '.($n+$lru[0]).' 0 R>>');
7688                         $this->_out('endobj');
7689                 }
7690
7691
7692                 // --- JAVASCRIPT - FORMS ------------------------------
7693
7694                 /*
7695                 * Adds a javascript
7696                 * @access public
7697                 * @author Johannes Güntert, Nicola Asuni
7698                 * @since 2.1.002 (2008-02-12)
7699                 */
7700                 function IncludeJS($script) {
7701                         $this->javascript .= $script;
7702                 }
7703
7704                 /*
7705                 * Create a javascript PDF string.
7706                 * @access protected
7707                 * @author Johannes Güntert, Nicola Asuni
7708                 * @since 2.1.002 (2008-02-12)
7709                 */
7710                 function _putjavascript() {
7711                         if (empty($this->javascript)) {
7712                                 return;
7713                         }
7714                         // the following two lines are uded to avoid form fields duplication after saving
7715                         $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2f,%.2f,%.2f,%.2f]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
7716                         $js2 = "getField('tcpdfdocsaved').value = 'saved';";
7717                         $this->_newobj();
7718                         $this->n_js = $this->n;
7719                         $this->_out('<<');
7720                         $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
7721                         $this->_out('>>');
7722                         $this->_out('endobj');
7723                         $this->_newobj();
7724                         $this->_out('<<');
7725                         $this->_out('/S /JavaScript');
7726                         $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
7727                         $this->_out('>>');
7728                         $this->_out('endobj');
7729                 }
7730
7731                 /*
7732                 * Convert color to javascript color.
7733                 * @param string $color color name or #RRGGBB
7734                 * @access protected
7735                 * @author Denis Van Nuffelen, Nicola Asuni
7736                 * @since 2.1.002 (2008-02-12)
7737                 */
7738                 function _JScolor($color) {
7739                         static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
7740                         if (substr($color,0,1) == '#') {
7741                                 return sprintf("['RGB',%.3f,%.3f,%.3f]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
7742                         }
7743                         if (!in_array($color,$aColors)) {
7744                                 $this->Error('Invalid color: '.$color);
7745                         }
7746                         return 'color.'.$color;
7747                 }
7748
7749                 /*
7750                 * Adds a javascript form field.
7751                 * @param string $type field type
7752                 * @param string $name field name
7753                 * @param int $x horizontal position
7754                 * @param int $y vertical position
7755                 * @param int $w width
7756                 * @param int $h height
7757                 * @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>
7758                 * @access protected
7759                 * @author Denis Van Nuffelen, Nicola Asuni
7760                 * @since 2.1.002 (2008-02-12)
7761                 */
7762                 function _addfield($type, $name, $x, $y, $w, $h, $prop) {
7763                         // the followind avoid fields duplication after saving the document
7764                         $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
7765                         $k = $this->k;
7766                         $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";
7767                         $this->javascript .= "f".$name.".textSize=".$this->FontSizePt.";\n";
7768                         foreach ($prop as $key => $val) {
7769                                 if (strcmp(substr($key,-5),"Color") == 0) {
7770                                         $val = $this->_JScolor($val);
7771                                 } else {
7772                                         $val = "'".$val."'";
7773                                 }
7774                                 $this->javascript .= "f".$name.".".$key."=".$val.";\n";
7775                         }
7776                         $this->x += $w;
7777                         $this->javascript .= "}";
7778                 }
7779
7780                 /*
7781                 * Creates a text field
7782                 * @param string $name field name
7783                 * @param int $w width
7784                 * @param int $h height
7785                 * @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>
7786                 * @access public
7787                 * @author Denis Van Nuffelen, Nicola Asuni
7788                 * @since 2.1.002 (2008-02-12)
7789                 */
7790                 function TextField($name, $w, $h, $prop=array()) {
7791                         $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
7792                 }
7793
7794                 /*
7795                 * Creates a RadioButton field
7796                 * @param string $name field name
7797                 * @param int $w width
7798                 * @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>
7799                 * @access public
7800                 * @author Nicola Asuni
7801                 * @since 2.2.003 (2008-03-03)
7802                 */
7803                 function RadioButton($name, $w, $prop=array()) {
7804                         if (!isset($prop['strokeColor'])) {
7805                                 $prop['strokeColor']='black';
7806                         }
7807                         $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
7808                 }
7809
7810                 /*
7811                 * Creates a List-box field
7812                 * @param string $name field name
7813                 * @param int $w width
7814                 * @param int $h height
7815                 * @param array $values array containing the list of values.
7816                 * @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>
7817                 * @access public
7818                 * @author Nicola Asuni
7819                 * @since 2.2.003 (2008-03-03)
7820                 */
7821                 function ListBox($name, $w, $h, $values, $prop=array()) {
7822                         if (!isset($prop['strokeColor'])) {
7823                                 $prop['strokeColor'] = 'ltGray';
7824                         }
7825                         $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
7826                         $s = '';
7827                         foreach($values as $value) {
7828                                 $s .= "'".addslashes($value)."',";
7829                         }
7830                         $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7831                 }
7832
7833                 /*
7834                 * Creates a Combo-box field
7835                 * @param string $name field name
7836                 * @param int $w width
7837                 * @param int $h height
7838                 * @param array $values array containing the list of values.
7839                 * @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>
7840                 * @access public
7841                 * @author Denis Van Nuffelen, Nicola Asuni
7842                 * @since 2.1.002 (2008-02-12)
7843                 */
7844                 function ComboBox($name, $w, $h, $values, $prop=array()) {
7845                         $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
7846                         $s = '';
7847                         foreach($values as $value) {
7848                                 $s .= "'".addslashes($value)."',";
7849                         }
7850                         $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7851                 }
7852
7853                 /*
7854                 * Creates a CheckBox field
7855                 * @param string $name field name
7856                 * @param int $w width
7857                 * @param boolean $checked define the initial state (default = false).
7858                 * @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>
7859                 * @access public
7860                 * @author Denis Van Nuffelen, Nicola Asuni
7861                 * @since 2.1.002 (2008-02-12)
7862                 */
7863                 function CheckBox($name, $w, $checked=false, $prop=array()) {
7864                         $prop['value'] = ($checked ? 'Yes' : 'Off');
7865                         if (!isset($prop['strokeColor'])) {
7866                                 $prop['strokeColor'] = 'black';
7867                         }
7868                         $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
7869                 }
7870
7871                 /*
7872                 * Creates a button field
7873                 * @param string $name field name
7874                 * @param int $w width
7875                 * @param int $h height
7876                 * @param string $caption caption.
7877                 * @param string $action action triggered by the button (JavaScript code).
7878                 * @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>
7879                 * @access public
7880                 * @author Denis Van Nuffelen, Nicola Asuni
7881                 * @since 2.1.002 (2008-02-12)
7882                 */
7883                 function Button($name, $w, $h, $caption, $action, $prop=array()) {
7884                         if (!isset($prop['strokeColor'])) {
7885                                 $prop['strokeColor'] = 'black';
7886                         }
7887                         if (!isset($prop['borderStyle'])) {
7888                                 $prop['borderStyle'] = 'beveled';
7889                         }
7890                         $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
7891                         $this->javascript .= "f".$name.".buttonSetCaption('".addslashes($caption)."');\n";
7892                         $this->javascript .= "f".$name.".setAction('MouseUp','".addslashes($action)."');\n";
7893                         $this->javascript .= "f".$name.".highlight='push';\n";
7894                         $this->javascript .= "f".$name.".print=false;\n";
7895                 }
7896
7897                 // END JAVASCRIPT - FORMS ------------------------------
7898
7899                 /*
7900                 * Enable Write permissions for PDF Reader.
7901                 * @access protected
7902                 * @author Nicola Asuni
7903                 * @since 2.9.000 (2008-03-26)
7904                 */
7905                 function _putuserrights() {
7906                         if (!$this->ur) {
7907                                 return;
7908                         }
7909                         $this->_out('/Perms');
7910                         $this->_out('<<');
7911                         $this->_out('/UR3');
7912                         $this->_out('<<');
7913                         //$this->_out('/SubFilter/adbe.pkcs7.detached/Filter/Adobe.PPKLite/Contents');
7914                         //$this->_out('<0>');
7915                         //$this->_out('/ByteRange[0 3]');
7916                         $this->_out('/M '.$this->_datestring('D:'.date('YmdHis')));
7917                         $this->_out('/Name(TCPDF)');
7918                         $this->_out('/Reference[');
7919                         $this->_out('<<');
7920                         $this->_out('/TransformParams');
7921                         $this->_out('<<');
7922                         $this->_out('/Type/TransformParams');
7923                         $this->_out('/V/2.2');
7924                         if (!empty($this->ur_document)) {
7925                                 $this->_out('/Document['.$this->ur_document.']');
7926                         }
7927                         if (!empty($this->ur_annots)) {
7928                                 $this->_out('/Annots['.$this->ur_annots.']');
7929                         }
7930                         if (!empty($this->ur_form)) {
7931                                 $this->_out('/Form['.$this->ur_form.']');
7932                         }
7933                         if (!empty($this->ur_signature)) {
7934                                 $this->_out('/Signature['.$this->ur_signature.']');
7935                         }
7936                         $this->_out('>>');
7937                         $this->_out('/TransformMethod/UR3');
7938                         $this->_out('/Type/SigRef');
7939                         $this->_out('>>');
7940                         $this->_out(']');
7941                         $this->_out('/Type/Sig');
7942                         $this->_out('>>');
7943                         $this->_out('>>');
7944                 }
7945
7946                 /*
7947                 * Set User's Rights for PDF Reader
7948                 * Check the PDF Reference 8.7.1 Transform Methods,
7949                 * Table 8.105 Entries in the UR transform parameters dictionary
7950                 * @param boolean $enable if true enable user's rights on PDF reader
7951                 * @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.
7952                 * @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.
7953                 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
7954                 * @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.
7955                 * @access public
7956                 * @author Nicola Asuni
7957                 * @since 2.9.000 (2008-03-26)
7958                 */
7959                 function setUserRights(
7960                                 $enable=true,
7961                                 $document="/FullSave",
7962                                 $annots="/Create/Delete/Modify/Copy/Import/Export",
7963                                 $form="/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate",
7964                                 $signature="/Modify") {
7965                         $this->ur = $enable;
7966                         $this->ur_document = $document;
7967                         $this->ur_annots = $annots;
7968                         $this->ur_form = $form;
7969                         $this->ur_signature = $signature;
7970                 }
7971
7972                 /*
7973                 * Create a new page group.
7974                 * NOTE: call this function before calling AddPage()
7975                 * @access public
7976                 * @since 3.0.000 (2008-03-27)
7977                 */
7978                 function startPageGroup() {
7979                         $this->newpagegroup = true;
7980                 }
7981
7982                 /*
7983                 * Return the current page in the group.
7984                 * @return current page in the group
7985                 * @access public
7986                 * @since 3.0.000 (2008-03-27)
7987                 */
7988                 function getGroupPageNo() {
7989                         return $this->pagegroups[$this->currpagegroup];
7990                 }
7991
7992                 /*
7993                 * Return the alias of the current page group
7994         * If the current font is unicode type, the returned string is surrounded by additional curly braces.
7995                 * (will be replaced by the total number of pages in this group).
7996                 * @return alias of the current page group
7997                 * @access public
7998                 * @since 3.0.000 (2008-03-27)
7999                 */
8000                 function getPageGroupAlias() {
8001                         if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
8002                                 return "{".$this->currpagegroup."}";
8003             }
8004                         return $this->currpagegroup;
8005                 }
8006
8007                 /*
8008                 * Put visibility settings.
8009                 * @access protected
8010                 * @since 3.0.000 (2008-03-27)
8011                 */
8012                 function _putocg() {
8013                         $this->_newobj();
8014                         $this->n_ocg_print = $this->n;
8015                         $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
8016                         $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
8017                         $this->_out('endobj');
8018                         $this->_newobj();
8019                         $this->n_ocg_view=$this->n;
8020                         $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
8021                         $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
8022                         $this->_out('endobj');
8023                 }
8024
8025                 /*
8026                 * Set the visibility of the successive elements.
8027                 * This can be useful, for instance, to put a background
8028                 * image or color that will show on screen but won't print.
8029                 * @param string $v visibility mode. Legal values are: all, print, screen.
8030                 * @access public
8031                 * @since 3.0.000 (2008-03-27)
8032                 */
8033                 function setVisibility($v) {
8034                         if ($this->openMarkedContent) {
8035                                 // close existing open marked-content
8036                                 $this->_out('EMC');
8037                                 $this->openMarkedContent = false;
8038                         }
8039                         switch($v) {
8040                                 case "print": {
8041                                         $this->_out('/OC /OC1 BDC');
8042                                         $this->openMarkedContent = true;
8043                                         break;
8044                                 }
8045                                 case "screen": {
8046                                         $this->_out('/OC /OC2 BDC');
8047                                         $this->openMarkedContent = true;
8048                                         break;
8049                                 }
8050                                 case "all": {
8051                                         $this->_out('');
8052                                         break;
8053                                 }
8054                                 default: {
8055                                         $this->Error('Incorrect visibility: '.$v);
8056                                         break;
8057                                 }
8058                         }
8059                         $this->visibility = $v;
8060                 }
8061
8062                 /*
8063                 * Add transparency parameters to the current extgstate
8064                 * @param array $params parameters
8065                 * @return the number of extgstates
8066                 * @access protected
8067                 * @since 3.0.000 (2008-03-27)
8068                 */
8069                 function addExtGState($parms) {
8070                         $n = count($this->extgstates) + 1;
8071                         $this->extgstates[$n]['parms'] = $parms;
8072                         return $n;
8073                 }
8074
8075                 /*
8076                 * Add an extgstate
8077                 * @param array $gs extgstate
8078                 * @access protected
8079                 * @since 3.0.000 (2008-03-27)
8080                 */
8081                 function setExtGState($gs) {
8082                         $this->_out(sprintf('/GS%d gs', $gs));
8083                 }
8084
8085                 /*
8086                 * Put extgstates for object transparency
8087                 * @param array $gs extgstate
8088                 * @access protected
8089                 * @since 3.0.000 (2008-03-27)
8090                 */
8091                 function _putextgstates() {
8092                         $ne = count($this->extgstates);
8093                         for ($i = 1; $i <= $ne; $i++) {
8094                                 $this->_newobj();
8095                                 $this->extgstates[$i]['n'] = $this->n;
8096                                 $this->_out('<</Type /ExtGState');
8097                                 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
8098                                         $this->_out('/'.$k.' '.$v);
8099                                 }
8100                                 $this->_out('>>');
8101                                 $this->_out('endobj');
8102                         }
8103                 }
8104
8105                 /*
8106                 * Set alpha for stroking (CA) and non-stroking (ca) operations.
8107                 * @param float $alpha real value from 0 (transparent) to 1 (opaque)
8108                 * @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
8109                 * @access public
8110                 * @since 3.0.000 (2008-03-27)
8111                 */
8112                 function setAlpha($alpha, $bm='Normal') {
8113                         $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
8114                         $this->setExtGState($gs);
8115                 }
8116
8117                 /*
8118                 * Set the default JPEG compression quality (1-100)
8119                 * @param int $quality JPEG quality, integer between 1 and 100
8120                 * @access public
8121                 * @since 3.0.000 (2008-03-27)
8122                 */
8123                 function setJPEGQuality($quality) {
8124                         if (($quality < 1) OR ($quality > 100)) {
8125                                 $quality = 75;
8126                         }
8127                         $this->jpeg_quality = intval($quality);
8128                 }
8129
8130                 /*
8131                 * Set the default number of columns in a row for HTML tables.
8132                 * @param int $cols number of columns
8133                 * @access public
8134                 * @since 3.0.014 (2008-06-04)
8135                 */
8136                 function setDefaultTableColumns($cols=4) {
8137                         $this->default_table_columns = intval($cols);
8138                 }
8139
8140                 /*
8141                 * Set the height of cell repect font height.
8142                 * @param int $h cell proportion respect font height (typical value = 1.25).
8143                 * @access public
8144                 * @since 3.0.014 (2008-06-04)
8145                 */
8146                 function setCellHeightRatio($h) {
8147                         $this->cell_height_ratio = $h;
8148                 }
8149
8150                 /*
8151                 * return the height of cell repect font height.
8152                 * @access public
8153                 * @since 4.0.012 (2008-07-24)
8154                 */
8155                 function getCellHeightRatio() {
8156                         return $this->cell_height_ratio;
8157                 }
8158
8159                 /*
8160                 * Set the PDF version (check PDF reference for valid values).
8161                 * Default value is 1.t
8162                 * @access public
8163                 * @since 3.1.000 (2008-06-09)
8164                 */
8165                 function setPDFVersion($version="1.7") {
8166                         $this->PDFVersion = $version;
8167                 }
8168
8169                 /*
8170                 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
8171                 * (see Section 8.1 of PDF reference, "Viewer Preferences").
8172                 * <ul>
8173                 * <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>
8174                 * <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>
8175                 * <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>
8176                 * <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>
8177                 * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
8178                 * <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>
8179                 * <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>
8180                 * <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>
8181                 * <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>
8182                 * <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>
8183                 * <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>
8184                 * <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>
8185                 * <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>
8186                 * <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>
8187                 * <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>
8188                 * <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>
8189                 * </ul>
8190                 * @param array $preferences array of options.
8191                 * @author Nicola Asuni
8192                 * @access public
8193                 * @since 3.1.000 (2008-06-09)
8194                 */
8195                 function setViewerPreferences($preferences) {
8196                         $this->viewer_preferences = $preferences;
8197                 }
8198
8199                 /**
8200                 * Paints a linear colour gradient.
8201                 * @param float $x abscissa of the top left corner of the rectangle.
8202                 * @param float $y ordinate of the top left corner of the rectangle.
8203                 * @param float $w width of the rectangle.
8204                 * @param float $h height of the rectangle.
8205                 * @param array $col1 first color (RGB components).
8206                 * @param array $col2 second color (RGB components).
8207                 * @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).
8208                 * @author Andreas Würmser, Nicola Asuni
8209                 * @since 3.1.000 (2008-06-09)
8210                 * @access public
8211                 */
8212                 function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
8213                         $this->Clip($x, $y, $w, $h);
8214                         $this->Gradient(2, $col1, $col2, $coords);
8215                 }
8216
8217                 /**
8218                 * Paints a radial colour gradient.
8219                 * @param float $x abscissa of the top left corner of the rectangle.
8220                 * @param float $y ordinate of the top left corner of the rectangle.
8221                 * @param float $w width of the rectangle.
8222                 * @param float $h height of the rectangle.
8223                 * @param array $col1 first color (RGB components).
8224                 * @param array $col2 second color (RGB components).
8225                 * @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.
8226                 * @author Andreas Würmser, Nicola Asuni
8227                 * @since 3.1.000 (2008-06-09)
8228                 * @access public
8229                 */
8230                 function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
8231                         $this->Clip($x, $y, $w, $h);
8232                         $this->Gradient(3, $col1, $col2, $coords);
8233                 }
8234
8235                 /**
8236                 * Paints a coons patch mesh.
8237                 * @param float $x abscissa of the top left corner of the rectangle.
8238                 * @param float $y ordinate of the top left corner of the rectangle.
8239                 * @param float $w width of the rectangle.
8240                 * @param float $h height of the rectangle.
8241                 * @param array $col1 first color (lower left corner) (RGB components).
8242                 * @param array $col2 second color (lower right corner) (RGB components).
8243                 * @param array $col3 third color (upper right corner) (RGB components).
8244                 * @param array $col4 fourth color (upper left corner) (RGB components).
8245                 * @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>
8246                 * @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
8247                 * @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
8248                 * @author Andreas Würmser, Nicola Asuni
8249                 * @since 3.1.000 (2008-06-09)
8250                 * @access public
8251                 */
8252                 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) {
8253                         $this->Clip($x, $y, $w, $h);
8254                         $n = count($this->gradients) + 1;
8255                         $this->gradients[$n]['type'] = 6; //coons patch mesh
8256                         //check the coords array if it is the simple array or the multi patch array
8257                         if (!isset($coords[0]['f'])){
8258                                 //simple array -> convert to multi patch array
8259                                 if (!isset($col1[1])) {
8260                                         $col1[1] = $col1[2] = $col1[0];
8261                                 }
8262                                 if (!isset($col2[1])) {
8263                                         $col2[1] = $col2[2] = $col2[0];
8264                                 }
8265                                 if (!isset($col3[1])) {
8266                                         $col3[1] = $col3[2] = $col3[0];
8267                                 }
8268                                 if (!isset($col4[1])) {
8269                                         $col4[1] = $col4[2] = $col4[0];
8270                                 }
8271                                 $patch_array[0]['f'] = 0;
8272                                 $patch_array[0]['points'] = $coords;
8273                                 $patch_array[0]['colors'][0]['r'] = $col1[0];
8274                                 $patch_array[0]['colors'][0]['g'] = $col1[1];
8275                                 $patch_array[0]['colors'][0]['b'] = $col1[2];
8276                                 $patch_array[0]['colors'][1]['r'] = $col2[0];
8277                                 $patch_array[0]['colors'][1]['g'] = $col2[1];
8278                                 $patch_array[0]['colors'][1]['b'] = $col2[2];
8279                                 $patch_array[0]['colors'][2]['r'] = $col3[0];
8280                                 $patch_array[0]['colors'][2]['g'] = $col3[1];
8281                                 $patch_array[0]['colors'][2]['b'] = $col3[2];
8282                                 $patch_array[0]['colors'][3]['r'] = $col4[0];
8283                                 $patch_array[0]['colors'][3]['g'] = $col4[1];
8284                                 $patch_array[0]['colors'][3]['b'] = $col4[2];
8285                         } else {
8286                                 //multi patch array
8287                                 $patch_array = $coords;
8288                         }
8289                         $bpcd = 65535; //16 BitsPerCoordinate
8290                         //build the data stream
8291                         $this->gradients[$n]['stream'] = "";
8292                         for($i=0; $i < count($patch_array); $i++) {
8293                                 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
8294                                 for($j=0; $j < count($patch_array[$i]['points']); $j++) {
8295                                         //each point as 16 bit
8296                                         $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j]-$coords_min)/($coords_max-$coords_min))*$bpcd;
8297                                         if ($patch_array[$i]['points'][$j] < 0) {
8298                                                 $patch_array[$i]['points'][$j] = 0;
8299                                         }
8300                                         if ($patch_array[$i]['points'][$j] > $bpcd) {
8301                                                 $patch_array[$i]['points'][$j] = $bpcd;
8302                                         }
8303                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]/256));
8304                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]%256));
8305                                 }
8306                                 for($j=0; $j < count($patch_array[$i]['colors']); $j++) {
8307                                         //each color component as 8 bit
8308                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
8309                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
8310                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
8311                                 }
8312                         }
8313                         //paint the gradient
8314                         $this->_out('/Sh'.$n.' sh');
8315                         //restore previous Graphic State
8316                         $this->_out('Q');
8317                 }
8318
8319                 /**
8320                 * Set a rectangular clipping area.
8321                 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
8322                 * @param float $y ordinate of the top left corner of the rectangle.
8323                 * @param float $w width of the rectangle.
8324                 * @param float $h height of the rectangle.
8325                 * @author Andreas Würmser, Nicola Asuni
8326                 * @since 3.1.000 (2008-06-09)
8327                 * @access protected
8328                 */
8329                 function Clip($x, $y, $w, $h){
8330                         if ($this->rtl) {
8331                                 $x = $this->w - $x - $w;
8332                         }
8333                         //save current Graphic State
8334                         $s = 'q';
8335                         //set clipping area
8336                         $s .= sprintf(' %.2f %.2f %.2f %.2f re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
8337                         //set up transformation matrix for gradient
8338                         $s .= sprintf(' %.3f 0 0 %.3f %.3f %.3f cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
8339                         $this->_out($s);
8340                 }
8341
8342                 /**
8343                 * Output gradient.
8344                 * @param int $type type of gradient.
8345                 * @param array $col1 first color (RGB components).
8346                 * @param array $col2 second color (RGB components).
8347                 * @param array $coords array of coordinates.
8348                 * @author Andreas Würmser, Nicola Asuni
8349                 * @since 3.1.000 (2008-06-09)
8350                 * @access protected
8351                 */
8352                 function Gradient($type, $col1, $col2, $coords){
8353                         $n = count($this->gradients) + 1;
8354                         $this->gradients[$n]['type'] = $type;
8355                         if (!isset($col1[1])) {
8356                                 $col1[1]=$col1[2]=$col1[0];
8357                         }
8358                         $this->gradients[$n]['col1'] = sprintf('%.3f %.3f %.3f', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
8359                         if (!isset($col2[1])) {
8360                                 $col2[1] = $col2[2] = $col2[0];
8361                         }
8362                         $this->gradients[$n]['col2'] = sprintf('%.3f %.3f %.3f', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
8363                         $this->gradients[$n]['coords'] = $coords;
8364                         //paint the gradient
8365                         $this->_out('/Sh'.$n.' sh');
8366                         //restore previous Graphic State
8367                         $this->_out('Q');
8368                 }
8369
8370                 /**
8371                 * Output shaders.
8372                 * @author Andreas Würmser, Nicola Asuni
8373                 * @since 3.1.000 (2008-06-09)
8374                 * @access protected
8375                 */
8376                 function _putshaders() {
8377                         foreach($this->gradients as $id => $grad) {
8378                                 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
8379                                         $this->_newobj();
8380                                         $this->_out('<<');
8381                                         $this->_out('/FunctionType 2');
8382                                         $this->_out('/Domain [0.0 1.0]');
8383                                         $this->_out('/C0 ['.$grad['col1'].']');
8384                                         $this->_out('/C1 ['.$grad['col2'].']');
8385                                         $this->_out('/N 1');
8386                                         $this->_out('>>');
8387                                         $this->_out('endobj');
8388                                         $f1 = $this->n;
8389                                 }
8390                                 $this->_newobj();
8391                                 $this->_out('<<');
8392                                 $this->_out('/ShadingType '.$grad['type']);
8393                                 $this->_out('/ColorSpace /DeviceRGB');
8394                                 if ($grad['type'] == 2) {
8395                                         $this->_out(sprintf('/Coords [%.3f %.3f %.3f %.3f]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
8396                                         $this->_out('/Function '.$f1.' 0 R');
8397                                         $this->_out('/Extend [true true] ');
8398                                         $this->_out('>>');
8399                                 } elseif ($grad['type'] == 3) {
8400                                         //x0, y0, r0, x1, y1, r1
8401                                         //at this this time radius of inner circle is 0
8402                                         $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]));
8403                                         $this->_out('/Function '.$f1.' 0 R');
8404                                         $this->_out('/Extend [true true] ');
8405                                         $this->_out('>>');
8406                                 } elseif ($grad['type'] == 6) {
8407                                         $this->_out('/BitsPerCoordinate 16');
8408                                         $this->_out('/BitsPerComponent 8');
8409                                         $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
8410                                         $this->_out('/BitsPerFlag 8');
8411                                         $this->_out('/Length '.strlen($grad['stream']));
8412                                         $this->_out('>>');
8413                                         $this->_putstream($grad['stream']);
8414                                 }
8415                                 $this->_out('endobj');
8416                                 $this->gradients[$id]['id'] = $this->n;
8417                         }
8418                 }
8419
8420                 /**
8421                 * Output an arc
8422                 * @author Maxime Delorme, Nicola Asuni
8423                 * @since 3.1.000 (2008-06-09)
8424                 * @access protected
8425                 */
8426                 function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
8427                         $h = $this->h;
8428                         $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));
8429                 }
8430
8431                 /**
8432                 * Draw the sector of a circle.
8433                 * It can be used for instance to render pie charts.
8434                 * @param float $xc abscissa of the center.
8435                 * @param float $yc ordinate of the center.
8436                 * @param float $r radius.
8437                 * @param float $a start angle (in degrees).
8438                 * @param float $b end angle (in degrees).
8439                 * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
8440                 * @param float $cw: indicates whether to go clockwise (default: true).
8441                 * @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.
8442                 * @author Maxime Delorme, Nicola Asuni
8443                 * @since 3.1.000 (2008-06-09)
8444                 * @access public
8445                 */
8446                 function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
8447                         if ($this->rtl) {
8448                                 $xc = $this->w - $xc - $w;
8449                         }
8450                         if ($cw) {
8451                                 $d = $b;
8452                                 $b = $o - $a;
8453                                 $a = $o - $d;
8454                         } else {
8455                                 $b += $o;
8456                                 $a += $o;
8457                         }
8458                         $a = ($a % 360) + 360;
8459                         $b = ($b % 360) + 360;
8460                         if ($a > $b) {
8461                                 $b +=360;
8462                         }
8463                         $b = $b / 360 * 2 * M_PI;
8464                         $a = $a / 360 * 2 * M_PI;
8465                         $d = $b - $a;
8466                         if ($d == 0 ) {
8467                                 $d = 2 * M_PI;
8468                         }
8469                         $k = $this->k;
8470                         $hp = $this->h;
8471                         if ($style=='F') {
8472                                 $op = 'f';
8473                         } elseif ($style=='FD' or $style=='DF') {
8474                                 $op = 'b';
8475                         } else {
8476                                 $op = 's';
8477                         }
8478                         if (sin($d/2)) {
8479                                 $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
8480                         }
8481                         //first put the center
8482                         $this->_out(sprintf('%.2f %.2f m', ($xc)*$k, ($hp-$yc)*$k));
8483                         //put the first point
8484                         $this->_out(sprintf('%.2f %.2f l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
8485                         //draw the arc
8486                         if ($d < (M_PI/2)) {
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                         } else {
8489                                 $b = $a + $d/4;
8490                                 $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
8491                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
8492                                 $a = $b;
8493                                 $b = $a + $d/4;
8494                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
8495                                 $a = $b;
8496                                 $b = $a + $d/4;
8497                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b) );
8498                                 $a = $b;
8499                                 $b = $a + $d/4;
8500                                 $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));
8501                         }
8502                         //terminate drawing
8503                         $this->_out($op);
8504                 }
8505
8506                 /**
8507                 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
8508                 * Only vector drawing is supported, not text or bitmap.
8509                 * 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).
8510                 * @param string $file Name of the file containing the image.
8511                 * @param float $x Abscissa of the upper-left corner.
8512                 * @param float $y Ordinate of the upper-left corner.
8513                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
8514                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
8515                 * @param mixed $link URL or identifier returned by AddLink().
8516                 * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
8517                 * @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>
8518                 * @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>
8519                 * @author Valentin Schmidt, Nicola Asuni
8520                 * @since 3.1.000 (2008-06-09)
8521                 * @access public
8522                 */
8523                 function ImageEps($file, $x, $y, $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='') {
8524                         $data = file_get_contents($file);
8525                         if ($data === false) {
8526                                 $this->Error('EPS file not found: '.$file);
8527                         }
8528                         $regs = array();
8529                         // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
8530                         preg_match ('/%%Creator:([^\r\n]+)/', $data, $regs); # find Creator
8531                         if (count($regs) > 1) {
8532                                 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
8533                                 if (strpos($version_str, 'Adobe Illustrator') !== false) {
8534                                         $versexp = explode(' ', $version_str);
8535                                         $version = (float)array_pop($versexp);
8536                                         if ($version >= 9) {
8537                                                 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
8538                                         }
8539                                 }
8540                         }
8541                         // strip binary bytes in front of PS-header
8542                         $start = strpos($data, '%!PS-Adobe');
8543                         if ($start > 0) {
8544                                 $data = substr($data, $start);
8545                         }
8546                         // find BoundingBox params
8547                         preg_match ("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
8548                         if (count($regs) > 1) {
8549                                 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
8550                         } else {
8551                                 $this->Error('No BoundingBox found in EPS file: '.$file);
8552                         }
8553                         $start = strpos($data, '%%EndSetup');
8554                         if ($start === false) {
8555                                 $start = strpos($data, '%%EndProlog');
8556                         }
8557                         if ($start === false) {
8558                                 $start = strpos($data, '%%BoundingBox');
8559                         }
8560                         $data = substr($data, $start);
8561                         $end = strpos($data, '%%PageTrailer');
8562                         if ($end===false) {
8563                                 $end = strpos($data, 'showpage');
8564                         }
8565                         if ($end) {
8566                                 $data = substr($data, 0, $end);
8567                         }
8568                         $k = $this->k;
8569                         if ($w > 0) {
8570                                 $scale_x = $w/(($x2-$x1)/$k);
8571                                 if ($h > 0) {
8572                                         $scale_y = $h/(($y2-$y1)/$k);
8573                                 } else {
8574                                         $scale_y = $scale_x;
8575                                         $h = ($y2-$y1)/$k * $scale_y;
8576                                 }
8577                         } else {
8578                                 if ($h > 0) {
8579                                         $scale_y = $h/(($y2-$y1)/$k);
8580                                         $scale_x = $scale_y;
8581                                         $w = ($x2-$x1)/$k * $scale_x;
8582                                 } else {
8583                                         $w = ($x2 - $x1) / $k;
8584                                         $h = ($y2 - $y1) / $k;
8585                                 }
8586                         }
8587                         // Check whether we need a new page first as this does not fit
8588                         if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
8589                                 // Automatic page break
8590                                 $this->AddPage($this->CurOrientation);
8591                                 // Reset coordinates to top fo next page
8592                                 //$x = $this->GetX();
8593                                 $y = $this->GetY() + $this->cMargin;
8594                         }
8595                         // set bottomcoordinates
8596                         $this->img_rb_y = $y + $h;
8597                         // set alignment
8598                         if ($this->rtl) {
8599                                 if ($palign == 'L') {
8600                                         $ximg = $this->lMargin;
8601                                         // set right side coordinate
8602                                         $this->img_rb_x = $ximg + $w;
8603                                 } elseif ($palign == 'C') {
8604                                         $ximg = ($this->w - $x - $w) / 2;
8605                                         // set right side coordinate
8606                                         $this->img_rb_x = $ximg + $w;
8607                                 } else {
8608                                         $ximg = $this->w - $x - $w;
8609                                         // set left side coordinate
8610                                         $this->img_rb_x = $ximg;
8611                                 }
8612                         } else {
8613                                 if ($palign == 'R') {
8614                                         $ximg = $this->w - $this->rMargin - $w;
8615                                         // set left side coordinate
8616                                         $this->img_rb_x = $ximg;
8617                                 } elseif ($palign == 'C') {
8618                                         $ximg = ($this->w - $x - $w) / 2;
8619                                         // set right side coordinate
8620                                         $this->img_rb_x = $ximg + $w;
8621                                 } else {
8622                                         $ximg = $x;
8623                                         // set right side coordinate
8624                                         $this->img_rb_x = $ximg + $w;
8625                                 }
8626                         }
8627                         if ($useBoundingBox){
8628                                 $dx = $ximg * $k - $x1;
8629                                 $dy = $y * $k - $y1;
8630                         } else {
8631                                 $dx = $ximg * $k;
8632                                 $dy = $y * $k;
8633                         }
8634                         // save the current graphic state
8635                         $this->_out('q');
8636                         // translate
8637                         $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy+($this->hPt - 2*$y*$k - ($y2-$y1))));
8638                         // scale
8639                         if (isset($scale_x)) {
8640                                 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1*(1-$scale_x), $y2*(1-$scale_y)));
8641                         }
8642                         // handle pc/unix/mac line endings
8643                         $lines = preg_split("/\r\n|[\r\n]/", $data);
8644                         $u=0;
8645                         $cnt = count($lines);
8646                         for ($i=0; $i < $cnt; $i++) {
8647                                 $line = $lines[$i];
8648                                 if (($line == '') OR ($line[0] == '%')) {
8649                                         continue;
8650                                 }
8651                                 $len = strlen($line);
8652                                 $chunks = explode(' ', $line);
8653                                 $cmd = array_pop($chunks);
8654                                 // RGB
8655                                 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
8656                                         $b = array_pop($chunks);
8657                                         $g = array_pop($chunks);
8658                                         $r = array_pop($chunks);
8659                                         $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!
8660                                         continue;
8661                                 }
8662                                 switch ($cmd) {
8663                                         case 'm':
8664                                         case 'l':
8665                                         case 'v':
8666                                         case 'y':
8667                                         case 'c':
8668                                         case 'k':
8669                                         case 'K':
8670                                         case 'g':
8671                                         case 'G':
8672                                         case 's':
8673                                         case 'S':
8674                                         case 'J':
8675                                         case 'j':
8676                                         case 'w':
8677                                         case 'M':
8678                                         case 'd':
8679                                         case 'n':
8680                                         case 'v': {
8681                                                 $this->_out($line);
8682                                                 break;
8683                                         }
8684                                         case 'x': {// custom fill color
8685                                                 list($c,$m,$y,$k) = $chunks;
8686                                                 $this->_out("$c $m $y $k k");
8687                                                 break;
8688                                         }
8689                                         case 'X': { // custom stroke color
8690                                                 list($c,$m,$y,$k) = $chunks;
8691                                                 $this->_out("$c $m $y $k K");
8692                                                 break;
8693                                         }
8694                                         case 'Y':
8695                                         case 'N':
8696                                         case 'V':
8697                                         case 'L':
8698                                         case 'C': {
8699                                                 $line[$len-1] = strtolower($cmd);
8700                                                 $this->_out($line);
8701                                                 break;
8702                                         }
8703                                         case 'b':
8704                                         case 'B': {
8705                                                 $this->_out($cmd . '*');
8706                                                 break;
8707                                         }
8708                                         case 'f':
8709                                         case 'F': {
8710                                                 if ($u > 0) {
8711                                                         $isU = false;
8712                                                         $max = min($i+5, $cnt);
8713                                                         for ($j=$i+1; $j < $max; $j++)
8714                                                           $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
8715                                                         if ($isU) {
8716                                                                 $this->_out("f*");
8717                                                         }
8718                                                 } else {
8719                                                         $this->_out("f*");
8720                                                 }
8721                                                 break;
8722                                         }
8723                                         case '*u': {
8724                                                 $u++;
8725                                                 break;
8726                                         }
8727                                         case '*U': {
8728                                                 $u--;
8729                                                 break;
8730                                         }
8731                                 }
8732                         }
8733                         // restore previous graphic state
8734                         $this->_out('Q');
8735                         if ($link) {
8736                                 $this->Link($ximg, $y, $w, $h, $link);
8737                         }
8738                         // set pointer to align the successive text/objects
8739                         switch($align) {
8740                                 case 'T':{
8741                                         $this->y = $y;
8742                                         $this->x = $this->img_rb_x;
8743                                         break;
8744                                 }
8745                                 case 'M':{
8746                                         $this->y = $y + round($h/2);
8747                                         $this->x = $this->img_rb_x;
8748                                         break;
8749                                 }
8750                                 case 'B':{
8751                                         $this->y = $this->img_rb_y;
8752                                         $this->x = $this->img_rb_x;
8753                                         break;
8754                                 }
8755                                 case 'N':{
8756                                         $this->SetY($this->img_rb_y);
8757                                         break;
8758                                 }
8759                                 default:{
8760                                         break;
8761                                 }
8762                         }
8763                         $this->endlinex = $this->img_rb_x;
8764                 }
8765
8766                 /**
8767                  * Set document barcode.
8768                  * @param string $bc barcode
8769                  */
8770                 function setBarcode($bc="") {
8771                         $this->barcode = $bc;
8772                 }
8773
8774                 /**
8775                  * Get current barcode.
8776                  * @return string
8777                  * @since 4.0.012 (2008-07-24)
8778                  */
8779                 function getBarcode() {
8780                         return $this->barcode;
8781                 }
8782
8783                 /**
8784                  * Print Barcode.
8785                  * @param string $code code to print
8786                  * @param string $type type of barcode.
8787                  * @param int $x x position in user units
8788                  * @param int $y y position in user units
8789                  * @param int $w width in user units
8790                  * @param int $h height position in user units
8791                  * @param float $xres width of the smallest bar in user units
8792                  * @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>
8793                  * @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>
8794                  * @author Nicola Asuni
8795                  * @since 3.1.000 (2008-06-09)
8796                  * @access public
8797                  */
8798                 function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
8799                         if (empty($code)) {
8800                                 return;
8801                         }
8802                         $barcodeobj = new TCPDFbarcode($code, $type);
8803                         $arrcode = $barcodeobj->getBarcodeArray();
8804                         if ($arrcode === false) {
8805                                 $this->Error('Error in barcode string');
8806                         }
8807                         // set default values
8808                         if (!isset($style["position"])) {
8809                                 if ($this->rtl) {
8810                                         $style["position"] = "R";
8811                                 } else {
8812                                         $style["position"] = "L";
8813                                 }
8814                         }
8815                         if (!isset($style["padding"])) {
8816                                 $style["padding"] = 0;
8817                         }
8818                         if (!isset($style["fgcolor"])) {
8819                                 $style["fgcolor"] = array(0,0,0); // default black
8820                         }
8821                         if (!isset($style["bgcolor"])) {
8822                                 $style["bgcolor"] = false; // default transparent
8823                         }
8824                         if (!isset($style["border"])) {
8825                                 $style["border"] = false;
8826                         }
8827                         if (!isset($style["text"])) {
8828                                 $style["text"] = false;
8829                                 $fontsize = 0;
8830                         }
8831                         if ($style["text"] AND isset($style["font"])) {
8832                                 $prevFontFamily = $this->FontFamily;
8833                                 $prevFontStyle = $this->FontStyle;
8834                                 $prevFontSizePt = $this->FontSizePt;
8835                                 if (isset($style["fontsize"])) {
8836                                         $fontsize = $style["fontsize"];
8837                                 } else {
8838                                         $fontsize = 0;
8839                                 }
8840                                 $this->SetFont($style["font"], '', $fontsize);
8841                         }
8842                         if (!isset($style["stretchtext"])) {
8843                                 $style["stretchtext"] = 4;
8844                         }
8845                         // set foreground color
8846                         $prevDrawColor = $this->DrawColor;
8847                         $prevTextColor = $this->TextColor;
8848                         $this->SetDrawColorArray($style["fgcolor"]);
8849                         $this->SetTextColorArray($style["fgcolor"]);
8850                         if (empty($w) OR ($w <= 0)) {
8851                                 if ($this->rtl) {
8852                                         $w = $this->x - $this->lMargin;
8853                                 } else {
8854                                         $w = $this->w - $this->rMargin - $this->x;
8855                                 }
8856                         }
8857                         if (empty($x)) {
8858                                 $x = $this->GetX();
8859                         }
8860                         if ($this->rtl) {
8861                                 $x = $this->w - $x;
8862                         }
8863                         if (empty($y)) {
8864                                 $y = $this->GetY();
8865                         }
8866                         if (empty($xres)) {
8867                                 $xres = 0.4;
8868                         }
8869                         $fbw = ($arrcode["maxw"] * $xres) + (2 * $style["padding"]);
8870                         $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style["padding"]);
8871                         if (empty($h)) {
8872                                 $h = 10 + $extraspace;
8873                         }
8874                         if ((($y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
8875                                 //Automatic page break
8876                                 $x = $this->x;
8877                                 $ws = $this->ws;
8878                                 if ($ws > 0) {
8879                                         $this->ws = 0;
8880                                         $this->_out('0 Tw');
8881                                 }
8882                                 $this->AddPage($this->CurOrientation);
8883                                 if ($ws > 0) {
8884                                         $this->ws = $ws;
8885                                         $this->_out(sprintf('%.3f Tw',$ws * $k));
8886                                 }
8887                                 $this->x = $x;
8888                                 $y = $this->y;
8889                         }
8890                         // maximum bar heigth
8891                         $barh = $h - $extraspace;
8892                         switch ($style["position"]) {
8893                                 case "L": { // left
8894                                         if ($this->rtl) {
8895                                                 $xpos = $x - $w;
8896                                         } else {
8897                                                 $xpos = $x;
8898                                         }
8899                                         break;
8900                                 }
8901                                 case "C": { // center
8902                                         $xdiff = (($w - $fbw) / 2);
8903                                         if ($this->rtl) {
8904                                                 $xpos = $x - $w + $xdiff;
8905                                         } else {
8906                                                 $xpos = $x + $xdiff;
8907                                         }
8908                                         break;
8909                                 }
8910                                 case "R": { // right
8911                                         if ($this->rtl) {
8912                                                 $xpos = $x - $fbw;
8913                                         } else {
8914                                                 $xpos = $x + $w - $fbw;
8915                                         }
8916                                         break;
8917                                 }
8918                                 case "S": { // stretch
8919                                         $fbw = $w;
8920                                         $xres = ($w - (2 * $style["padding"])) / $arrcode["maxw"];
8921                                         if ($this->rtl) {
8922                                                 $xpos = $x - $w;
8923                                         } else {
8924                                                 $xpos = $x;
8925                                         }
8926                                         break;
8927                                 }
8928                         }
8929                         $xpos_rect = $xpos;
8930                         $xpos = $xpos_rect + $style["padding"];
8931                         $xpos_text = $xpos;
8932                         // barcode is always printed in LTR direction
8933                         $tempRTL = $this->rtl;
8934                         $this->rtl = false;
8935                         // print background color
8936                         if ($style["bgcolor"]) {
8937                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style["bgcolor"]);
8938                         } elseif ($style["border"]) {
8939                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
8940                         }
8941                         // print bars
8942                         if ($arrcode !== false) {
8943                                 foreach ($arrcode["bcode"] as $k => $v) {
8944                                         $bw = ($v["w"] * $xres);
8945                                         if ($v["t"]) {
8946                                                 // braw a vertical bar
8947                                                 $ypos = $y + $style["padding"] + ($v["p"] * $barh / $arrcode["maxh"]);
8948                                                 $this->Rect($xpos, $ypos, $bw, ($v["h"] * $barh  / $arrcode["maxh"]), 'DF', array("L"=>0,"T"=>0,"R"=>0,"B"=>0), $style["fgcolor"]);
8949                                         }
8950                                         $xpos += $bw;
8951                                 }
8952                         }
8953                         // print text
8954                         if ($style["text"]) {
8955                                 // print text
8956                                 $this->x = $xpos_text;
8957                                 $this->y = $y + $style["padding"] + $barh;
8958                                 $this->Cell(($arrcode["maxw"] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style["stretchtext"]);
8959                         }
8960                         // restore original direction
8961                         $this->rtl = $tempRTL;
8962                         // restore previous font
8963                         if ($style["text"] AND isset($style["font"])) {
8964                                 $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
8965                         }
8966                         // restore colors
8967                         $this->DrawColor = $prevDrawColor;
8968                         $this->TextColor = $prevTextColor;
8969                         // set bottomcoordinates
8970                         $this->img_rb_y = $y + $h;
8971                         if ($this->rtl) {
8972                                 // set left side coordinate
8973                                 $this->img_rb_x = ($this->w - $x - $w);
8974                         } else {
8975                                 // set right side coordinate
8976                                 $this->img_rb_x = $x + $w;
8977                         }
8978                         // set pointer to align the successive text/objects
8979                         switch($align) {
8980                                 case 'T':{
8981                                         $this->y = $y;
8982                                         $this->x = $this->img_rb_x;
8983                                         break;
8984                                 }
8985                                 case 'M':{
8986                                         $this->y = $y + round($h/2);
8987                                         $this->x = $this->img_rb_x;
8988                                         break;
8989                                 }
8990                                 case 'B':{
8991                                         $this->y = $this->img_rb_y;
8992                                         $this->x = $this->img_rb_x;
8993                                         break;
8994                                 }
8995                                 case 'N':{
8996                                         $this->SetY($this->img_rb_y);
8997                                         break;
8998                                 }
8999                                 default:{
9000                                         break;
9001                                 }
9002                         }
9003                 }
9004
9005                 /**
9006                  * This function is DEPRECATED, please use the new write1DBarcode() function.
9007                  * @param int $x x position in user units
9008                  * @param int $y y position in user units
9009                  * @param int $w width in user units
9010                  * @param int $h height position in user units
9011                  * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
9012                  * @param string $style barcode style
9013                  * @param string $font font for text
9014                  * @param int $xres x resolution
9015                  * @param string $code code to print
9016                  * @deprecated deprecated since version 3.1.000 (2008-06-10)
9017                  * @see write1DBarcode()
9018                  */
9019                 function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
9020                         // convert old settings for the new write1DBarcode() function.
9021                         $xres = 1 / $xres;
9022                         $newstyle = array(
9023                                 "position" => "L",
9024                                 "border" => false,
9025                                 "padding" => 0,
9026                                 "fgcolor" => array(0,0,0),
9027                                 "bgcolor" => false,
9028                                 "text" => true,
9029                                 "font" => $font,
9030                                 "fontsize" => 8,
9031                                 "stretchtext" => 4
9032                         );
9033                         if ($style & 1) {
9034                                 $newstyle["border"] = true;
9035                         }
9036                         if ($style & 2) {
9037                                 $newstyle["bgcolor"] = false;
9038                         }
9039                         if ($style & 4) {
9040                                 $newstyle["position"] = "C";
9041                         } elseif ($style & 8) {
9042                                 $newstyle["position"] = "L";
9043                         } elseif ($style & 16) {
9044                                 $newstyle["position"] = "R";
9045                         }
9046                         if ($style & 128) {
9047                                 $newstyle["text"] = true;
9048                         }
9049                         if ($style & 256) {
9050                                 $newstyle["stretchtext"] = 4;
9051                         }
9052                         $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
9053                 }
9054
9055                 /**
9056                  * Returns an array containing current margins:
9057                  * <ul>
9058                                 <li>$ret['left'] = left  margin</li>
9059                                 <li>$ret['right'] = right margin</li>
9060                                 <li>$ret['top'] = top margin</li>
9061                                 <li>$ret['bottom'] = bottom margin</li>
9062                                 <li>$ret['header'] = header margin</li>
9063                                 <li>$ret['footer'] = footer margin</li>
9064                                 <li>$ret['cell'] = cell margin</li>
9065                  * </ul>
9066                  * @return array containing all margins measures
9067                  * @since 3.2.000 (2008-06-23)
9068                  */
9069                 function getMargins() {
9070                         $ret = array(
9071                                 'left' => $this->lMargin,
9072                                 'right' => $this->rMargin,
9073                                 'top' => $this->tMargin,
9074                                 'bottom' => $this->bMargin,
9075                                 'header' => $this->header_margin,
9076                                 'footer' => $this->footer_margin,
9077                                 'cell' => $this->cMargin,
9078                         );
9079                         return $ret;
9080                 }
9081
9082                 /**
9083                  * Returns an array containing original margins:
9084                  * <ul>
9085                                 <li>$ret['left'] = left  margin</li>
9086                                 <li>$ret['right'] = right margin</li>
9087                  * </ul>
9088                  * @return array containing all margins measures
9089                  * @since 4.0.012 (2008-07-24)
9090                  */
9091                 function getOriginalMargins() {
9092                         $ret = array(
9093                                 'left' => $this->original_lMargin,
9094                                 'right' => $this->original_rMargin
9095                         );
9096                         return $ret;
9097                 }
9098
9099                 /**
9100                  * Returns the current font size.
9101                  * @return current font size
9102                  * @since 3.2.000 (2008-06-23)
9103                  */
9104                 function getFontSize() {
9105                         return $this->FontSize;
9106                 }
9107
9108                 /**
9109                  * Returns the current font size in points unit.
9110                  * @return current font size in points unit
9111                  * @since 3.2.000 (2008-06-23)
9112                  */
9113                 function getFontSizePt() {
9114                         return $this->FontSizePt;
9115                 }
9116
9117                 /**
9118                  * Prints a cell (rectangular area) with optional borders, background color and html text string.
9119                  * 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 />
9120                  * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
9121                  * @param float $w Cell width. If 0, the cell extends up to the right margin.
9122                  * @param float $h Cell minimum height. The cell extends automatically if needed.
9123                  * @param float $x upper-left corner X coordinate
9124                  * @param float $y upper-left corner Y coordinate
9125                  * @param string $html html text to print. Default value: empty string.
9126                  * @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>
9127                  * @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>
9128         Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
9129                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
9130                  * @param boolean $reseth if true reset the last cell height (default true).
9131                  * @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>
9132                  * @uses MultiCell()
9133                  * @see Multicell(), writeHTML()
9134                  */
9135                 function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='') {
9136                         return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true);
9137                 }
9138
9139                 /**
9140                  * Returns the HTML DOM array.
9141                  * <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>
9142                  * @param string $html html code
9143                  * @return array
9144                  * @since 3.2.000 (2008-06-20)
9145                  */
9146                 function getHtmlDomArray($html) {
9147                         // remove all unsupported tags (the line below lists all supported tags)
9148                         $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>");
9149                         //replace carriage returns, newlines and tabs
9150                         $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ", "\\" => "\\\\");
9151                         $html = strtr($html, $repTable);
9152                         // remove extra spaces from tables
9153                         $html = preg_replace('/[\s]*<\/table>[\s]*/', '</table>', $html);
9154                         $html = preg_replace('/[\s]*<\/tr>[\s]*/', '</tr>', $html);
9155                         $html = preg_replace('/[\s]*<tr/', '<tr', $html);
9156                         $html = preg_replace('/[\s]*<\/th>[\s]*/', '</th>', $html);
9157                         $html = preg_replace('/[\s]*<th/', '<th', $html);
9158                         $html = preg_replace('/[\s]*<\/td>[\s]*/', '</td>', $html);
9159                         $html = preg_replace('/[\s]*<td/', '<td', $html);
9160                         $html = preg_replace('/<\/th>/', '<span></span></th>', $html);
9161                         $html = preg_replace('/<\/td>/', '<span></span></td>', $html);
9162                         // pattern for generic tag
9163                         $tagpattern = '/(<[^>]+>)/Uu';
9164                         // explodes the string
9165                         $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
9166                         // count elements
9167                         $maxel = count($a);
9168                         $key = 0;
9169                         // create an array of elements
9170                         $dom = array();
9171                         $dom[$key] = array();
9172                         // set first void element
9173                         $dom[$key]['tag'] = false;
9174                         $dom[$key]['value'] = "";
9175                         $dom[$key]['parent'] = 0;
9176                         $dom[$key]['fontname'] = $this->FontFamily;
9177                         $dom[$key]['fontstyle'] = $this->FontStyle;
9178                         $dom[$key]['fontsize'] = $this->FontSizePt;
9179                         $dom[$key]['bgcolor'] = false;
9180                         $dom[$key]['fgcolor'] = $this->fgcolor;
9181                         $dom[$key]['align'] = '';
9182                         $key++;
9183                         $level = array();
9184                         array_push($level, 0); // root
9185                         while ($key <= $maxel) {
9186                                 if ($key > 0) {
9187                                         $dom[$key] = array();
9188                                 }
9189                                 $element = $a[($key-1)];
9190                                 if (preg_match($tagpattern, $element)) {
9191                                         // html tag
9192                                         $dom[$key]['tag'] = true;
9193                                         $element = substr($element, 1, -1);
9194                                         // get tag name
9195                                         preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
9196                                         $dom[$key]['value'] = strtolower($tag[1]);
9197                                         if ($element[0] == '/') {
9198                                                 // closing html tag
9199                                                 $dom[$key]['opening'] = false;
9200                                                 $dom[$key]['parent'] = end($level);
9201                                                 array_pop($level);
9202                                                 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
9203                                                 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
9204                                                 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
9205                                                 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
9206                                                 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
9207                                                 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
9208                                                 // set the number of columns in table tag
9209                                                 if (($dom[$key]['value'] == "tr") AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
9210                                                         $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
9211                                                 }
9212                                                 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9213                                                         $dom[($dom[$key]['parent'])]['content'] = "";
9214                                                         for ($i = ($dom[$key]['parent'] + 1); $i < $key; $i++) {
9215                                                                 $dom[($dom[$key]['parent'])]['content'] .= $a[($i-1)];
9216                                                         }
9217                                                         $key = $i;
9218                                                 }
9219                                         } else {
9220                                                 // opening html tag
9221                                                 $dom[$key]['opening'] = true;
9222                                                 $dom[$key]['parent'] = end($level);
9223                                                 if (substr($element, -1, 1) != '/') {
9224                                                         // not self-closing tag
9225                                                         array_push($level, $key);
9226                                                         $dom[$key]['self'] = false;
9227                                                 } else {
9228                                                         $dom[$key]['self'] = true;
9229                                                 }
9230                                                 // copy some values from parent
9231                                                 if ($key > 0) {
9232                                                         $dom[$key]['fontname'] = $dom[($dom[$key]['parent'])]['fontname'];
9233                                                         $dom[$key]['fontstyle'] = $dom[($dom[$key]['parent'])]['fontstyle'];
9234                                                         $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'];
9235                                                         $dom[$key]['bgcolor'] = $dom[($dom[$key]['parent'])]['bgcolor'];
9236                                                         $dom[$key]['fgcolor'] = $dom[($dom[$key]['parent'])]['fgcolor'];
9237                                                         $dom[$key]['align'] = $dom[($dom[$key]['parent'])]['align'];
9238                                                 }
9239                                                 // get attributes
9240                                                 preg_match_all('/([^=\s]*)=["\']?([^"\']*)["\']?/', $element, $attr_array, PREG_PATTERN_ORDER);
9241                                                 $dom[$key]['attribute'] = array(); // reset attribute array
9242                                                 foreach ($attr_array[1] as $id => $name) {
9243                                                         $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
9244                                                 }
9245                                                 // split style attributes
9246                                                 if (isset($dom[$key]['attribute']['style'])) {
9247                                                         // get style attributes
9248                                                         preg_match_all('/([^:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
9249                                                         $dom[$key]['style'] = array(); // reset style attribute array
9250                                                         foreach ($style_array[1] as $id => $name) {
9251                                                                 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
9252                                                         }
9253                                                         // --- get some style attributes ---
9254                                                         if (isset($dom[$key]['style']['font-family'])) {
9255                                                                 // font family
9256                                                                 if (isset($dom[$key]['style']['font-family'])) {
9257                                                                         $fontslist = preg_split("/,/", strtolower($dom[$key]['style']['font-family']));
9258                                                                         foreach($fontslist as $font) {
9259                                                                                 $font = trim(strtolower($font));
9260                                                                                 if (in_array($font, $this->fontlist)){
9261                                                                                         $dom[$key]['fontname'] = $font;
9262                                                                                         break;
9263                                                                                 }
9264                                                                         }
9265                                                                 }
9266                                                         }
9267                                                         // font size
9268                                                         if (isset($dom[$key]['style']['font-size'])) {
9269                                                                 $fsize = trim($dom[$key]['style']['font-size']);
9270                                                                 switch ($fsize) {
9271                                                                         case 'xx-small': {
9272                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
9273                                                                                 break;
9274                                                                         }
9275                                                                         case 'x-small': {
9276                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
9277                                                                                 break;
9278                                                                         }
9279                                                                         case 'small': {
9280                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
9281                                                                                 break;
9282                                                                         }
9283                                                                         case 'medium': {
9284                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
9285                                                                                 break;
9286                                                                         }
9287                                                                         case 'large': {
9288                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
9289                                                                                 break;
9290                                                                         }
9291                                                                         case 'x-large': {
9292                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
9293                                                                                 break;
9294                                                                         }
9295                                                                         case 'xx-large': {
9296                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
9297                                                                                 break;
9298                                                                         }
9299                                                                         default: {
9300                                                                                 $dom[$key]['fontsize'] = intval($fsize);
9301                                                                         }
9302                                                                 }
9303                                                         }
9304                                                         // font style
9305                                                         $dom[$key]['fontstyle'] = "";
9306                                                         if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight'][0]) == "b")) {
9307                                                                 $dom[$key]['fontstyle'] .= "B";
9308                                                         }
9309                                                         if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style'][0]) == "i")) {
9310                                                                 $dom[$key]['fontstyle'] .= "I";
9311                                                         }
9312                                                         // font color
9313                                                         if (isset($dom[$key]['style']['color']) AND (!empty($dom[$key]['style']['color']))) {
9314                                                                 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
9315                                                         }
9316                                                         // background color
9317                                                         if (isset($dom[$key]['style']['background-color']) AND (!empty($dom[$key]['style']['background-color']))) {
9318                                                                 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
9319                                                         }
9320                                                         // text-decoration
9321                                                         if (isset($dom[$key]['style']['text-decoration'])) {
9322                                                                 $decors = explode(" ", strtolower($dom[$key]['style']['text-decoration']));
9323                                                                 foreach ($decors as $dec) {
9324                                                                         $dec = trim($dec);
9325                                                                         if ($dec[0] == "u") {
9326                                                                                 $dom[$key]['fontstyle'] .= "U";
9327                                                                         } elseif ($dec[0] == "l") {
9328                                                                                 $dom[$key]['fontstyle'] .= "D";
9329                                                                         }
9330                                                                 }
9331                                                         }
9332                                                         // check for width attribute
9333                                                         if (isset($dom[$key]['style']['width'])) {
9334                                                                 $dom[$key]['width'] = intval($dom[$key]['style']['width']);
9335                                                         }
9336                                                         // check for height attribute
9337                                                         if (isset($dom[$key]['style']['height'])) {
9338                                                                 $dom[$key]['height'] = intval($dom[$key]['style']['height']);
9339                                                         }
9340                                                         // check for text alignment
9341                                                         if (isset($dom[$key]['style']['text-align'])) {
9342                                                                 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align'][0]);
9343                                                         }
9344                                                 }
9345                                                 // check for font tag
9346                                                 if ($dom[$key]['value'] == "font") {
9347                                                         // font family
9348                                                         if (isset($dom[$key]['attribute']['face'])) {
9349                                                                 $fontslist = preg_split("/,/", strtolower($dom[$key]['attribute']['face']));
9350                                                                 foreach($fontslist as $font) {
9351                                                                         $font = trim(strtolower($font));
9352                                                                         if (in_array($font, $this->fontlist)){
9353                                                                                 $dom[$key]['fontname'] = $font;
9354                                                                                 break;
9355                                                                         }
9356                                                                 }
9357                                                         }
9358                                                         // font size
9359                                                         if (isset($dom[$key]['attribute']['size'])) {
9360                                                                 if ($key > 0) {
9361                                                                         if ($dom[$key]['attribute']['size'][0] == "+") {
9362                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
9363                                                                         } elseif ($dom[$key]['attribute']['size'][0] == "-") {
9364                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
9365                                                                         } else {
9366                                                                                 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9367                                                                         }
9368                                                                 } else {
9369                                                                         $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9370                                                                 }
9371                                                         }
9372                                                 }
9373                                                 if (($dom[$key]['value'] == "ul") OR ($dom[$key]['value'] == "ol") OR ($dom[$key]['value'] == "dl")) {
9374                                                         // force natural alignment for lists
9375                                                         if ($this->rtl) {
9376                                                                 $dom[$key]['align'] = "R";
9377                                                         } else {
9378                                                                 $dom[$key]['align'] = "L";
9379                                                         }
9380                                                 }
9381                                                 if (($dom[$key]['value'] == "small") OR ($dom[$key]['value'] == "sup") OR ($dom[$key]['value'] == "sub")) {
9382                                                         $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
9383                                                 }
9384                                                 if (($dom[$key]['value'] == "strong") OR ($dom[$key]['value'] == "b")) {
9385                                                         $dom[$key]['fontstyle'] .= "B";
9386                                                 }
9387                                                 if (($dom[$key]['value'] == "em") OR ($dom[$key]['value'] == "i")) {
9388                                                         $dom[$key]['fontstyle'] .= "I";
9389                                                 }
9390                                                 if (($dom[$key]['value'][0] == "h") AND (intval($dom[$key]['value'][1]) > 0) AND (intval($dom[$key]['value'][1]) < 7)) {
9391                                                         $headsize = (4 - intval($dom[$key]['value'][1])) * 2;
9392                                                         $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
9393                                                         $dom[$key]['fontstyle'] .= "B";
9394                                                 }
9395                                                 if (($dom[$key]['value'] == "table")) {
9396                                                         $dom[$key]['rows'] = 0; // number of rows
9397                                                         $dom[$key]['trids'] = array(); // IDs of TR elements
9398                                                 }
9399                                                 if (($dom[$key]['value'] == "tr")) {
9400                                                         $dom[$key]['cols'] = 0;
9401                                                         // store the number of rows on table element
9402                                                         $dom[($dom[$key]['parent'])]['rows']++;
9403                                                         // store the TR elements IDs on table element
9404                                                         array_push($dom[($dom[$key]['parent'])]['trids'], $key);
9405                                                 }
9406                                                 if (($dom[$key]['value'] == "th") OR ($dom[$key]['value'] == "td")) {
9407                                                         if (isset($dom[$key]['attribute']['colspan'])) {
9408                                                                 $colspan = intval($dom[$key]['attribute']['colspan']);
9409                                                         } else {
9410                                                                 $colspan = 1;
9411                                                         }
9412                                                         $dom[$key]['attribute']['colspan'] = $colspan;
9413                                                         $dom[($dom[$key]['parent'])]['cols'] += $colspan;
9414                                                 }
9415                                                 // set foreground color attribute
9416                                                 if (isset($dom[$key]['attribute']['color']) AND (!empty($dom[$key]['attribute']['color']))) {
9417                                                         $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
9418                                                 }
9419                                                 // set background color attribute
9420                                                 if (isset($dom[$key]['attribute']['bgcolor']) AND (!empty($dom[$key]['attribute']['bgcolor']))) {
9421                                                         $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
9422                                                 }
9423                                                 // check for width attribute
9424                                                 if (isset($dom[$key]['attribute']['width'])) {
9425                                                         $dom[$key]['width'] = intval($dom[$key]['attribute']['width']);
9426                                                 }
9427                                                 // check for height attribute
9428                                                 if (isset($dom[$key]['attribute']['height'])) {
9429                                                         $dom[$key]['height'] = intval($dom[$key]['attribute']['height']);
9430                                                 }
9431                                                 // check for text alignment
9432                                                 if (isset($dom[$key]['attribute']['align']) AND (!empty($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
9433                                                         $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align'][0]);
9434                                                 }
9435                                         } // end opening tag
9436                                 } else {
9437                                         // text
9438                                         $dom[$key]['tag'] = false;
9439                                         $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
9440                                         $dom[$key]['parent'] = end($level);
9441                                         // calculate text width
9442                                         //$dom[$key]['width'] = $this->GetStringWidth($dom[$key]['value'], $dom[($dom[$key]['parent'])]['fontname'], $dom[($dom[$key]['parent'])]['fontstyle'], $dom[($dom[$key]['parent'])]['fontsize']);
9443                                 }
9444                                 $key++;
9445                         }
9446                         return $dom;
9447                 }
9448
9449                 /**
9450                  * Allows to preserve some HTML formatting (limited support).<br />
9451                  * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
9452                  * 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,
9453                  * @param string $html text to display
9454                  * @param boolean $ln if true add a new line after text (default = true)
9455                  * @param int $fill Indicates if the background must be painted (true) or transparent (false).
9456                  * @param boolean $reseth if true reset the last cell height (default false).
9457                  * @param boolean $cell if true add the default cMargin space to each Write (default false).
9458                  * @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>
9459                  */
9460                 function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
9461                         // store current values
9462                         $prevlMargin = $this->lMargin;
9463                         $prevrMargin = $this->rMargin;
9464                         $prevcMargin = $this->cMargin;
9465                         $prevFontFamily = $this->FontFamily;
9466                         $prevFontStyle = $this->FontStyle;
9467                         $prevFontSizePt = $this->FontSizePt;
9468                         $curfontname = $prevFontFamily;
9469                         $curfontstyle = $prevFontStyle;
9470                         $curfontsize = $prevFontSizePt;
9471                         $prevbgcolor = $this->bgcolor;
9472                         $prevfgcolor = $this->fgcolor;
9473                         $this->newline = true;
9474                         $minstartliney = $this->y;
9475                         $yshift = 0;
9476                         $startlinepage = $this->page;
9477                         $newline = true;
9478                         if (isset($this->footerlen[$this->page])) {
9479                                 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9480                         } else {
9481                                 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9482                         }
9483                         $startlinepos = $this->footerpos[$this->page];
9484                         $lalign = $align;
9485                         $plalign = $align;
9486                         if ($this->rtl) {
9487                                 $w = $this->x - $this->lMargin;
9488                         } else {
9489                                 $w = $this->w - $this->rMargin - $this->x;
9490                         }
9491                         $w -= (2 * $this->cMargin);
9492                         if ($cell) {
9493                                 if ($this->rtl) {
9494                                         $this->x -= $this->cMargin;
9495                                 } else {
9496                                         $this->x += $this->cMargin;
9497                                 }
9498                         }
9499                         $this->listindent = $this->GetStringWidth("0000");
9500                         $this->listnum = 0;
9501                         if ((empty($this->lasth))OR ($reseth)) {
9502                                 //set row height
9503                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9504                         }
9505                         $dom = $this->getHtmlDomArray($html);
9506                         $maxel = count($dom);
9507                         $key = 0;
9508                         while ($key < $maxel) {
9509                                 if ($dom[$key]['tag'] OR ($key == 0)) {
9510                                         if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
9511                                                 $dom[$key]['align'] = ($this->rtl)?'R':'L';
9512                                         }
9513                                         // vertically align image in line
9514                                         if ((!$this->newline) AND ($dom[$key]['value'] == 'img') 
9515                                                 AND (isset($dom[$key]['attribute']['height']))
9516                                                 AND ($dom[$key]['attribute']['height'] > 0)
9517                                                 ) {
9518                                                 $this->y += (($curfontsize / $this->k) - $this->pixelsToUnits($dom[$key]['attribute']['height']));
9519                                                 $minstartliney = min($this->y, $minstartliney);
9520                                         } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
9521                                                 // account for different font size
9522                                                 $pfontname = $curfontname;
9523                                                 $pfontstyle = $curfontstyle;
9524                                                 $pfontsize = $curfontsize;
9525                                                 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
9526                                                 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
9527                                                 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
9528                                                 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
9529                                                         $this->SetFont($fontname, $fontstyle, $fontsize);
9530                                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
9531                                                         if (is_numeric($fontsize) AND ($fontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($fontsize != $curfontsize) AND (!$this->newline)) {
9532                                                                 $this->y += (($curfontsize - $fontsize) / $this->k);
9533                                                                 $minstartliney = min($this->y, $minstartliney);
9534                                                         }
9535                                                         $curfontname = $fontname;
9536                                                         $curfontstyle = $fontstyle;
9537                                                         $curfontsize = $fontsize;
9538                                                 }
9539                                         }
9540                                         if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
9541                                                 $this->SetFillColorArray($dom[$key]['bgcolor']);
9542                                                 $wfill = true;
9543                                         } else {
9544                                                 $wfill = $fill | false;
9545                                         }
9546                                         if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
9547                                                 $this->SetTextColorArray($dom[$key]['fgcolor']);
9548                                         }
9549                                         if (isset($dom[$key]['align'])) {
9550                                                 $lalign = $dom[$key]['align'];
9551                                         }
9552                                         if (empty($lalign)) {
9553                                                 $lalign = $align;
9554                                         }
9555                                 }
9556                                 // align lines
9557                                 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
9558                                         $newline = true;
9559                                         // we are at the beginning of a new line
9560                                         if (isset($startlinex)) {
9561                                                 $yshift = $minstartliney - $startliney;
9562                                                 if ($yshift > 0) {
9563                                                         $yshift = 0;
9564                                                 }
9565                                                 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9566                                                         // the last line must be shifted to be aligned as requested
9567                                                         $linew = abs($this->endlinex - $startlinex);
9568                                                         $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9569                                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9570                                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9571                                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9572                                                         } elseif (isset($opentagpos)) {
9573                                                                 $midpos = $opentagpos;
9574                                                         } elseif (isset($this->footerlen[$startlinepage])) {
9575                                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9576                                                                 $midpos = $this->footerpos[$startlinepage];
9577                                                         } else {
9578                                                                 $midpos = 0;
9579                                                         }
9580                                                         if ($midpos > 0) {
9581                                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9582                                                                 $pend = substr($this->pages[$startlinepage], $midpos);
9583                                                         } else {
9584                                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9585                                                                 $pend = "";
9586                                                         }
9587                                                         // calculate shifting amount
9588                                                         $mdiff = abs($w - $linew);
9589                                                         if ($plalign == "C") {
9590                                                                 if ($this->rtl) {
9591                                                                         $t_x = -($mdiff / 2);
9592                                                                 } else {
9593                                                                         $t_x = ($mdiff / 2);
9594                                                                 }
9595                                                         }       elseif (($plalign == "R") AND (!$this->rtl)) {
9596                                                                 // right alignment on LTR document
9597                                                                 $t_x = $mdiff;
9598                                                         }       elseif (($plalign == "L") AND ($this->rtl)) {
9599                                                                 // left alignment on RTL document
9600                                                                 $t_x = -$mdiff;
9601                                                         } else {
9602                                                                 $t_x = 0;
9603                                                         }
9604                                                         if (($t_x != 0) OR ($yshift < 0)) {
9605                                                                 // shift the line
9606                                                                 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9607                                                                 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9608                                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9609                                                                 // shift the annotations and links
9610                                                                 if (isset($this->PageAnnots[$this->page])) {
9611                                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9612                                                                                 if ($pac['y'] >= $minstartliney) {
9613                                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9614                                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9615                                                                                 }
9616                                                                         }
9617                                                                 }
9618                                                                 $this->y -= $yshift;
9619                                                         }
9620                                                 }
9621                                         }
9622                                         $this->checkPageBreak($this->lasth);
9623                                         $this->SetFont($fontname, $fontstyle, $fontsize);
9624                                         if ($wfill) {
9625                                                 $this->SetFillColorArray($this->bgcolor);
9626                                         }
9627                                         $startlinex = $this->x;
9628                                         $startliney = $this->y;
9629                                         $minstartliney = $this->y;
9630                                         $startlinepage = $this->page;
9631                                         if (isset($endlinepos)) {
9632                                                 $startlinepos = $endlinepos;
9633                                                 unset($endlinepos);
9634                                         } else {
9635                                                 if (isset($this->footerlen[$this->page])) {
9636                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9637                                                 } else {
9638                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9639                                                 }
9640                                                 $startlinepos = $this->footerpos[$this->page];
9641                                         }
9642                                         $plalign = $lalign;
9643                                         $this->newline = false;
9644                                 }
9645                                 if (isset($opentagpos)) {
9646                                         unset($opentagpos);
9647                                 }
9648                                 if ($dom[$key]['tag']) {
9649                                         if ($dom[$key]['opening']) {
9650                                                 // table content is handled in a special way
9651                                                 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9652                                                         $trid = $dom[$key]['parent'];
9653                                                         $table_el = $dom[$trid]['parent'];
9654                                                         if (!isset($dom[$table_el]['cols'])) {
9655                                                                 $dom[$table_el]['cols'] = $trid['cols'];
9656                                                         }
9657                                                         // calculate cell width
9658                                                         if (isset($dom[($dom[$key]['parent'])]['width'])) {
9659                                                                 $table_width = $this->pixelsToUnits($dom[($dom[$key]['parent'])]['width']);
9660                                                         } else {
9661                                                                 $table_width = $w;
9662                                                         }
9663                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
9664                                                                 $currentcmargin = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding']);
9665                                                         } else {
9666                                                                 $currentcmargin = 0;
9667                                                         }
9668                                                         $this->cMargin = $currentcmargin;
9669                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
9670                                                                 $cellspacing = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing']);
9671                                                         } else {
9672                                                                 $cellspacing = 0;
9673                                                         }
9674                                                         if ($this->rtl) {
9675                                                                 $cellspacingx = -$cellspacing;
9676                                                         } else {
9677                                                                 $cellspacingx = $cellspacing;
9678                                                         }
9679                                                         $colspan = $dom[$key]['attribute']['colspan'];
9680                                                         if (isset($dom[$key]['width'])) {
9681                                                                 $cellw = $this->pixelsToUnits($dom[$key]['width']);
9682                                                         } else {
9683                                                                 $cellw = ($colspan * ($table_width / $dom[$table_el]['cols']));
9684                                                         }
9685                                                         $cellw -= $cellspacing;
9686                                                         if (isset($dom[$key]['content'])) {
9687                                                                 $cell_content = $dom[$key]['content'];
9688                                                         } else {
9689                                                                 $cell_content = "&nbsp;";
9690                                                         }
9691                                                         $tagtype = $dom[$key]['value'];
9692                                                         $parentid = $key;
9693                                                         while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
9694                                                                 // move $key index forward
9695                                                                 $key++;
9696                                                         }
9697                                                         if (!isset($dom[$trid]['startpage'])) {
9698                                                                 $dom[$trid]['startpage'] = $this->page;
9699                                                         } else {
9700                                                                 $this->setPage($dom[$trid]['startpage']);
9701                                                         }
9702                                                         if (!isset($dom[$trid]['starty'])) {
9703                                                                 $dom[$trid]['starty'] = $this->y;
9704                                                         } else {
9705                                                                 $this->y = $dom[$trid]['starty'];
9706                                                         }
9707                                                         if (!isset($dom[$trid]['startx'])) {
9708                                                                 $dom[$trid]['startx'] = $this->x;
9709                                                         }
9710                                                         $this->x += ($cellspacingx / 2);
9711                                                         if (isset($dom[$parentid]['attribute']['rowspan'])) {
9712                                                                 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
9713                                                         }       else {
9714                                                                 $rowspan = 1;
9715                                                         }
9716                                                         // skip row-spanned cells started on the previous rows
9717                                                         if (isset($dom[$table_el]['rowspans'])) {
9718                                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9719                                                                         if  (($trwsp['startx'] == $this->x) AND (($trwsp['starty'] < $this->y) OR ($trwsp['startpage'] < $this->page)) AND ($trwsp['rowspan'] > 0)) {
9720                                                                                 $this->x = $trwsp['endx'] + $cellspacingx;
9721                                                                         }
9722                                                                 }
9723                                                         }
9724                                                         // add rowspan information to table element
9725                                                         if ($rowspan > 1) {
9726                                                                 if (isset($this->footerlen[$this->page])) {
9727                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9728                                                                 } else {
9729                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9730                                                                 }
9731                                                                 $trintmrkpos = $this->footerpos[$this->page];
9732                                                                 $trsid = array_push($dom[$table_el]['rowspans'], array('rowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startx' => $this->x, 'starty' => $this->y, 'intmrkpos' => $trintmrkpos));
9733                                                         }
9734                                                         $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
9735                                                         if ($rowspan > 1) {
9736                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
9737                                                         }
9738                                                         // push background colors
9739                                                         if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
9740                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
9741                                                         }
9742
9743                                                         // write the cell content
9744                                                         $this->MultiCell($cellw, 0, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
9745
9746                                                         $this->cMargin = $currentcmargin;
9747                                                         $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
9748                                                         
9749                                                         // update the end of row position
9750                                                         if ($rowspan <= 1) {
9751                                                                 if (isset($dom[$trid]['endy'])) {
9752                                                                         if ($this->page == $dom[$trid]['endpage']) {
9753                                                                                 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
9754                                                                         } elseif ($this->page > $dom[$trid]['endpage']) {
9755                                                                                 $dom[$trid]['endy'] = $this->y;
9756                                                                         }
9757                                                                 } else {
9758                                                                         $dom[$trid]['endy'] = $this->y;
9759                                                                 }
9760                                                                 if (isset($dom[$trid]['endpage'])) {
9761                                                                         $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
9762                                                                 } else {
9763                                                                         $dom[$trid]['endpage'] = $this->page;
9764                                                                 }
9765                                                         } else {
9766                                                         // account for row-spanned cells
9767                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
9768                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
9769                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
9770                                                         }
9771                                                         if (isset($dom[$table_el]['rowspans'])) {
9772                                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9773                                                                         if ($trwsp['rowspan'] > 0) {
9774                                                                                 if (isset($dom[$trid]['endpage'])) {
9775                                                                                         if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
9776                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
9777                                                                                         } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[$trid]['endpage']) {
9778                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $trwsp['endy'];
9779                                                                                         } else {
9780                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
9781                                                                                                 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
9782                                                                                         }
9783                                                                                 }
9784                                                                         }
9785                                                                 }
9786                                                         }
9787                                                         $this->x += ($cellspacingx / 2);
9788                                                 } else {
9789                                                         // opening tag (or self-closing tag)
9790                                                         if (!isset($opentagpos)) {
9791                                                                 if (isset($this->footerlen[$this->page])) {
9792                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9793                                                                 } else {
9794                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9795                                                                 }
9796                                                                 $opentagpos = $this->footerpos[$this->page];
9797                                                         }
9798                                                         $this->openHTMLTagHandler($dom, $key, $cell);
9799                                                 }
9800                                         } else {
9801                                                 // closing tag
9802                                                 $this->closeHTMLTagHandler($dom, $key, $cell);
9803                                         }
9804                                 } elseif (strlen($dom[$key]['value']) > 0) {
9805                                         // print list-item
9806                                         if (!empty($this->lispacer)) {
9807                                                 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
9808                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9809                                                 $minstartliney = $this->y;
9810                                                 $tmpx = $this->x;
9811                                                 $lspace = $this->GetStringWidth($this->lispacer."  ");
9812                                                 if ($this->rtl) {
9813                                                         $this->x += $lspace;
9814                                                 } else {
9815                                                         $this->x -= $lspace;
9816                                                 }
9817                                                 $this->Write($this->lasth, $this->lispacer, '', false, '', false, 0, false);
9818                                                 $this->x = $tmpx;
9819                                                 $this->lispacer = "";
9820                                                 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
9821                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9822                                                 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
9823                                                         $this->y += (($pfontsize - $curfontsize) / $this->k);
9824                                                         $minstartliney = min($this->y, $minstartliney);
9825                                                 }
9826                                         }
9827                                         // text
9828                                         $this->htmlvspace = 0;
9829                                         if ($newline) {
9830                                                 if ($this->rtl OR $this->tmprtl) {
9831                                                         $dom[$key]['value'] = rtrim($dom[$key]['value']);
9832                                                 } else {
9833                                                         $dom[$key]['value'] = ltrim($dom[$key]['value']);
9834                                                 }
9835                                                 $newline = false;
9836                                         }
9837                                         if ($this->HREF) {
9838                                                 // HTML <a> Link
9839                                                 $strrest = $this->addHtmlLink($this->HREF, $dom[$key]['value'], $wfill, true);
9840                                         } else {
9841                                                 $ctmpmargin = $this->cMargin;
9842                                                 $this->cMargin = 0;
9843                                                 // write only until the end of the line and get the rest
9844                                                 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, "", false, 0, true);
9845                                                 $this->cMargin = $ctmpmargin;
9846                                         }
9847                                         if (strlen($strrest) > 0) {
9848                                                 // store the remaining string on the previous $key position
9849                                                 $this->newline = true;
9850                                                 if ($cell) {
9851                                                         if ($this->rtl) {
9852                                                                 $this->x -= $this->cMargin;
9853                                                         } else {
9854                                                                 $this->x += $this->cMargin;
9855                                                         }
9856                                                 }
9857                                                 $dom[$key]['value'] = ltrim($strrest);
9858                                                 $key--;
9859                                         }
9860                                 }
9861                                 $key++;
9862                         } // end for each $key
9863                         // align the last line
9864                         if (isset($startlinex)) {
9865                                 $yshift = $minstartliney - $startliney;
9866                                 if ($yshift > 0) {
9867                                         $yshift = 0;
9868                                 }
9869                                 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9870                                         // the last line must be shifted to be aligned as requested
9871                                         $linew = abs($this->endlinex - $startlinex);
9872                                         $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9873                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9874                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9875                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9876                                         } elseif (isset($opentagpos)) {
9877                                                 $midpos = $opentagpos;
9878                                         } elseif (isset($this->footerlen[$startlinepage])) {
9879                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9880                                                 $midpos = $this->footerpos[$startlinepage];
9881                                         } else {
9882                                                 $midpos = 0;
9883                                         }
9884                                         if ($midpos > 0) {
9885                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9886                                                 $pend = substr($this->pages[$startlinepage], $midpos);
9887                                         } else {
9888                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9889                                                 $pend = "";
9890                                         }
9891                                         // calculate shifting amount
9892                                         $mdiff = abs($w - $linew);
9893                                         if ($plalign == "C") {
9894                                                 if ($this->rtl) {
9895                                                         $t_x = -($mdiff / 2);
9896                                                 } else {
9897                                                         $t_x = ($mdiff / 2);
9898                                                 }
9899                                         }       elseif (($plalign == "R") AND (!$this->rtl)) {
9900                                                 // right alignment on LTR document
9901                                                 $t_x = $mdiff;
9902                                         }       elseif (($plalign == "L") AND ($this->rtl)) {
9903                                                 // left alignment on RTL document
9904                                                 $t_x = -$mdiff;
9905                                         } else {
9906                                                 $t_x = 0;
9907                                         }
9908                                         if (($t_x != 0) OR ($yshift < 0)) {
9909                                                 // shift the line
9910                                                 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9911                                                 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9912                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9913                                                 // shift the annotations and links
9914                                                 if (isset($this->PageAnnots[$this->page])) {
9915                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9916                                                                 if ($pac['y'] >= $minstartliney) {
9917                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9918                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9919                                                                 }
9920                                                         }
9921                                                 }
9922                                                 $this->y -= $yshift;
9923                                         }
9924                                 }
9925                         }
9926                         if ($ln AND (!($cell AND ($dom[$key-1]['value'] == "table")))) {
9927                                 $this->Ln($this->lasth);
9928                         }
9929                         // restore previous values
9930                         $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
9931                         $this->SetFillColorArray($prevbgcolor);
9932                         $this->SetTextColorArray($prevfgcolor);
9933                         $this->lMargin = $prevlMargin;
9934                         $this->rMargin = $prevrMargin;
9935                         $this->cMargin = $prevcMargin;
9936                         unset($dom);
9937                 }
9938
9939                 /**
9940                  * Process opening tags.
9941                  * @param array $dom html dom array
9942                  * @param int $key current element id
9943                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
9944                  * @access protected
9945                  */
9946                 function openHTMLTagHandler(&$dom, $key, $cell=false) {
9947                         $tag = $dom[$key];
9948                         $parent = $dom[($dom[$key]['parent'])];
9949                         // check for text direction attribute
9950                         if (isset($tag['attribute']['dir'])) {
9951                                 $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
9952                         } else {
9953                                 $this->tmprtl = false;
9954                         }
9955                         //Opening tag
9956                         switch($tag['value']) {
9957                                 case 'table': {
9958                                         $dom[$key]['rowspans'] = array();
9959                                         if (isset($tag['attribute']['cellpadding'])) {
9960                                                 $this->oldcMargin = $this->cMargin;
9961                                                 $this->cMargin = $this->pixelsToUnits($tag['attribute']['cellpadding']);
9962                                         }
9963                                         break;
9964                                 }
9965                                 case 'tr': {
9966                                         // array of columns positions
9967                                         $dom[$key]['cellpos'] = array();
9968                                         break;
9969                                 }
9970                                 case 'td':
9971                                 case 'th': {
9972                                         break;
9973                                 }
9974                                 case 'hr': {
9975                                         $this->addHTMLVertSpace(1, $cell);
9976                                         $this->htmlvspace = 0;
9977                                         if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
9978                                                 $hrWidth = $this->pixelsToUnits($tag['attribute']['width']);
9979                                         } else {
9980                                                 $hrWidth = $this->w - $this->lMargin - $this->rMargin;
9981                                         }
9982                                         $x = $this->GetX();
9983                                         $y = $this->GetY();
9984                                         $prevlinewidth = $this->GetLineWidth();
9985                                         $this->Line($x, $y, $x + $hrWidth, $y);
9986                                         $this->SetLineWidth($prevlinewidth);
9987                                         $this->addHTMLVertSpace(1, $cell);
9988                                         break;
9989                                 }
9990                                 case 'b': {
9991                                         $this->setStyle('b', true);
9992                                         break;
9993                                 }
9994                                 case 'i': {
9995                                         $this->setStyle('i', true);
9996                                         break;
9997                                 }
9998                                 case 'u': {
9999                                         $this->setStyle('u', true);
10000                                         break;
10001                                 }
10002                                 case 'del': {
10003                                         $this->setStyle('d', true);
10004                                         break;
10005                                 }
10006                                 case 'a': {
10007                                         if (array_key_exists('href', $tag['attribute'])) {
10008                                                 $this->HREF = $tag['attribute']['href'];
10009                                         }
10010                                         break;
10011                                 }
10012                                 case 'img': {
10013                                         if (isset($tag['attribute']['src'])) {
10014                                                 // replace relative path with real server path
10015                                                 if ($tag['attribute']['src'][0] == '/') {
10016                                                         $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
10017                                                 }
10018                                                 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
10019                                                 if (!isset($tag['attribute']['width'])) {
10020                                                         $tag['attribute']['width'] = 0;
10021                                                 }
10022                                                 if (!isset($tag['attribute']['height'])) {
10023                                                         $tag['attribute']['height'] = 0;
10024                                                 }
10025                                                 //if (!isset($tag['attribute']['align'])) {
10026                                                         // the only alignment supported is "bottom"
10027                                                         // further development is required for other modes.
10028                                                         $tag['attribute']['align'] = 'bottom';
10029                                                 //} 
10030                                                 switch($tag['attribute']['align']) {
10031                                                         case 'top': {
10032                                                                 $align = 'T';
10033                                                                 break;
10034                                                         }
10035                                                         case 'middle': {
10036                                                                 $align = 'M';
10037                                                                 break;
10038                                                         }
10039                                                         case 'bottom': {
10040                                                                 $align = 'B';
10041                                                                 break;
10042                                                         }
10043                                                         default: {
10044                                                                 $align = 'B';
10045                                                                 break;
10046                                                         }
10047                                                 }
10048                                                 $fileinfo = pathinfo($tag['attribute']['src']);
10049                                                 if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
10050                                                         $type = strtolower($fileinfo['extension']);
10051                                                 }
10052                                                 $prevy = $this->y;
10053                                                 if (($type == "eps") OR ($type == "ai")) {
10054                                                         $this->ImageEps($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', true, $align);
10055                                                 } else {
10056                                                         $this->Image($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', '', $align);
10057                                                 }
10058                                                 switch($align) {
10059                                                         case 'T': {
10060                                                                 $this->y = $prevy;
10061                                                                 break;
10062                                                         }
10063                                                         case 'M': {
10064                                                                 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
10065                                                                 break;
10066                                                         }
10067                                                         case 'B': {
10068                                                                 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
10069                                                                 break;
10070                                                         }
10071                                                 }
10072                                         }
10073                                         break;
10074                                 }
10075                                 case 'dl': {
10076                                         $this->listnum++;
10077                                         break;
10078                                 }
10079                                 case 'dt': {
10080                                         $this->addHTMLVertSpace(1, $cell);
10081                                         break;
10082                                 }
10083                                 case 'dd': {
10084                                         if ($this->rtl) {
10085                                                 $this->rMargin += $this->listindent;
10086                                         } else {
10087                                                 $this->lMargin += $this->listindent;
10088                                         }
10089                                         $this->addHTMLVertSpace(1, $cell);
10090                                         break;
10091                                 }
10092                                 case 'ul':
10093                                 case 'ol': {
10094                                         $this->listnum++;
10095                                         if ($tag['value'] == "ol") {
10096                                                 $this->listordered[$this->listnum] = true;
10097                                         } else {
10098                                                 $this->listordered[$this->listnum] = false;
10099                                         }
10100                                         $this->listcount[$this->listnum] = 0;
10101                                         if ($this->rtl) {
10102                                                 $this->rMargin += $this->listindent;
10103                                         } else {
10104                                                 $this->lMargin += $this->listindent;
10105                                         }
10106                                         break;
10107                                 }
10108                                 case 'li': {
10109                                         $this->Ln('', $cell);
10110                                         if ($tag['value'] == 'li') {
10111                                                 if ($this->listordered[$this->listnum]) {
10112                                                         if (isset($tag['attribute']['value'])) {
10113                                                                 $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
10114                                                         }
10115                                                         $this->listcount[$this->listnum]++;
10116                                                         if ($this->rtl) {
10117                                                                 $this->lispacer = ".".($this->listcount[$this->listnum]);
10118                                                         } else {
10119                                                                 $this->lispacer = ($this->listcount[$this->listnum]).".";
10120                                                         }
10121                                                 } else {
10122                                                         //unordered list symbol
10123                                                         $this->lispacer = "-";
10124                                                 }
10125                                         } else {
10126                                                 $this->lispacer = "";
10127                                         }
10128                                         break;
10129                                 }
10130                                 case 'blockquote': {
10131                                         if ($this->rtl) {
10132                                                 $this->rMargin += $this->listindent;
10133                                         } else {
10134                                                 $this->lMargin += $this->listindent;
10135                                         }
10136                                         $this->addHTMLVertSpace(2, $cell);
10137                                         break;
10138                                 }
10139                                 case 'br': {
10140                                         $this->Ln('', $cell);
10141                                         break;
10142                                 }
10143                                 case 'div': {
10144                                         $this->addHTMLVertSpace(2, $cell);
10145                                         break;
10146                                 }
10147                                 case 'p': {
10148                                         $this->addHTMLVertSpace(2, $cell);
10149                                         break;
10150                                 }
10151                                 case 'sup': {
10152                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
10153                                         break;
10154                                 }
10155                                 case 'sub': {
10156                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
10157                                         break;
10158                                 }
10159                                 case 'h1':
10160                                 case 'h2':
10161                                 case 'h3':
10162                                 case 'h4':
10163                                 case 'h5':
10164                                 case 'h6': {
10165                                         $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k);
10166                                         break;
10167                                 }
10168                                 default: {
10169                                         break;
10170                                 }
10171                         }
10172                 }
10173
10174                 /**
10175                  * Process closing tags.
10176                  * @param array $dom html dom array
10177                  * @param int $key current element id
10178                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
10179                  * @access protected
10180                  */
10181                 function closeHTMLTagHandler(&$dom, $key, $cell=false) {
10182                         $tag = $dom[$key];
10183                         $parent = $dom[($dom[$key]['parent'])];
10184                         //Closing tag
10185                         switch($tag['value']) {
10186                                 case 'td':
10187                                 case 'th': {
10188                                         break;
10189                                 }
10190                                 case 'tr': {
10191                                         $table_el = $dom[($dom[$key]['parent'])]['parent'];
10192                                         // update row-spanned cells
10193                                         if (isset($dom[$table_el]['rowspans'])) {
10194                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
10195                                                         $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
10196                                                         if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
10197                                                                 if ($dom[$table_el]['rowspans'][$k]['endpage'] == $dom[($dom[$key]['parent'])]['endpage']) {
10198                                                                         $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
10199                                                                 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[($dom[$key]['parent'])]['endpage']) {
10200                                                                         $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
10201                                                                         $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
10202                                                                 }
10203                                                         }
10204                                                 }
10205                                         }
10206                                         $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
10207                                         $this->y = $dom[($dom[$key]['parent'])]['endy'];
10208                                         if (isset($dom[$table_el]['attribute']['cellspacing'])) {
10209                                                 $cellspacing = $this->pixelsToUnits($dom[$table_el]['attribute']['cellspacing']);
10210                                                 $this->y += $cellspacing;
10211                                         }                               
10212                                         $this->Ln(0, $cell);
10213                                         $this->x = $dom[($dom[$key]['parent'])]['startx'];
10214                                         break;
10215                                 }
10216                                 case 'table': {
10217                                         // draw borders
10218                                         $table_el = $parent;
10219                                         if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
10220                                                 OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
10221                                                         $border = 1;
10222                                         } else {
10223                                                 $border = 0;
10224                                         }
10225                                         // for each row
10226                                         foreach ($table_el['trids'] as $j => $trkey) {
10227                                                 $parent = $dom[$trkey];
10228                                                 $restspace = $this->getPageHeight() - $this->y - $this->getBreakMargin();
10229                                                 // for each cell on the row
10230                                                 foreach ($parent['cellpos'] as $k => $cellpos) {
10231                                                         if (isset($cellpos['rowspanid'])) {
10232                                                                 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
10233                                                                 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
10234                                                                 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
10235                                                                 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
10236                                                                 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
10237                                                         } else {
10238                                                                 $endy = $parent['endy'];
10239                                                                 $startpage = $parent['startpage'];
10240                                                                 $endpage = $parent['endpage'];
10241                                                         }
10242                                                         $this->setPage($startpage);
10243                                                         $this->y = $parent['starty'];
10244                                                         if ($endpage > $startpage) {
10245                                                                 // design borders around HTML cells.
10246                                                                 for ($page=$startpage; $page <= $endpage; $page++) {
10247                                                                         $this->setPage($page);
10248                                                                         if ($page == $startpage) {
10249                                                                                 $this->y = $this->getPageHeight() - $restspace - $this->getBreakMargin();
10250                                                                                 $ch = $restspace;
10251                                                                         } elseif ($page == $endpage) {
10252                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of text
10253                                                                                 $ch = $endy - $this->tMargin;
10254                                                                         } else {
10255                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of text
10256                                                                                 $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
10257                                                                         }
10258
10259                                                                         if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10260                                                                                 $this->SetFillColorArray($cellpos['bgcolor']);
10261                                                                                 $fill = true;
10262                                                                         } else {
10263                                                                                 $fill = false;
10264                                                                         }
10265                                                                         $cw = abs($cellpos['endx'] - $cellpos['startx']);
10266                                                                         $this->x = $cellpos['startx'];
10267                                                                         // design a cell around the text
10268                                                                         $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10269                                                                         $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10270                                                                         $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10271                                                                         $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10272                                                                         $this->intmrk[$this->page] += strlen($ccode."\n");
10273                                                                 }
10274                                                         } else {
10275                                                                 $ch = $endy - $parent['starty'];
10276                                                                 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10277                                                                         $this->SetFillColorArray($cellpos['bgcolor']);
10278                                                                         $fill = true;
10279                                                                 } else {
10280                                                                         $fill = false;
10281                                                                 }
10282                                                                 $cw = abs($cellpos['endx'] - $cellpos['startx']);
10283                                                                 $this->x = $cellpos['startx'];
10284                                                                 $this->y = $parent['starty'];
10285                                                                 // design a cell around the text
10286                                                                 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10287                                                                 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10288                                                                 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10289                                                                 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10290                                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
10291                                                         }
10292                                                 }
10293                                                 if (isset($table_el['attribute']['cellspacing'])) {
10294                                                         $cellspacing = $this->pixelsToUnits($table_el['attribute']['cellspacing']);
10295                                                         $this->y += $cellspacing;
10296                                                 }
10297                                                 $this->Ln(0, $cell);
10298                                                 $this->x = $parent['startx'];
10299                                         }
10300                                         if (isset($parent['cellpadding'])) {
10301                                                 $this->cMargin = $this->oldcMargin;
10302                                         }
10303                                         //set row height
10304                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
10305                                         break;
10306                                 }
10307                                 case 'b': {
10308                                         $this->setStyle('b', false);
10309                                         break;
10310                                 }
10311                                 case 'i': {
10312                                         $this->setStyle('i', false);
10313                                         break;
10314                                 }
10315                                 case 'u': {
10316                                         $this->setStyle('u', false);
10317                                         break;
10318                                 }
10319                                 case 'del': {
10320                                         $this->setStyle('d', false);
10321                                         break;
10322                                 }
10323                                 case 'a': {
10324                                         $this->HREF = '';
10325                                         break;
10326                                 }
10327                                 case 'sup': {
10328                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
10329                                         break;
10330                                 }
10331                                 case 'sub': {
10332                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
10333                                         break;
10334                                 }
10335                                 case 'div': {
10336                                         $this->addHTMLVertSpace(1, $cell);
10337                                         break;
10338                                 }
10339                                 case 'blockquote': {
10340                                         if ($this->rtl) {
10341                                                 $this->rMargin -= $this->listindent;
10342                                         } else {
10343                                                 $this->lMargin -= $this->listindent;
10344                                         }
10345                                         $this->addHTMLVertSpace(2, $cell);
10346                                         break;
10347                                 }
10348                                 case 'p': {
10349                                         $this->addHTMLVertSpace(2, $cell);
10350                                         break;
10351                                 }
10352                                 case 'dl': {
10353                                         $this->listnum--;
10354                                         if ($this->listnum <= 0) {
10355                                                 $this->listnum = 0;
10356                                                 $this->addHTMLVertSpace(2, $cell);
10357                                         }
10358                                         break;
10359                                 }
10360                                 case 'dt': {
10361                                         $this->lispacer = "";
10362                                         break;
10363                                 }
10364                                 case 'dd': {
10365                                         $this->lispacer = "";
10366                                         if ($this->rtl) {
10367                                                 $this->rMargin -= $this->listindent;
10368                                         } else {
10369                                                 $this->lMargin -= $this->listindent;
10370                                         }
10371                                         break;
10372                                 }
10373                                 case 'ul':
10374                                 case 'ol': {
10375                                         $this->listnum--;
10376                                         $this->lispacer = "";
10377                                         if ($this->rtl) {
10378                                                 $this->rMargin -= $this->listindent;
10379                                         } else {
10380                                                 $this->lMargin -= $this->listindent;
10381                                         }
10382                                         if ($this->listnum <= 0) {
10383                                                 $this->listnum = 0;
10384                                                 $this->addHTMLVertSpace(2, $cell);
10385                                         }
10386                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
10387                                         break;
10388                                 }
10389                                 case 'li': {
10390                                         $this->lispacer = "";
10391                                         break;
10392                                 }
10393                                 case 'h1':
10394                                 case 'h2':
10395                                 case 'h3':
10396                                 case 'h4':
10397                                 case 'h5':
10398                                 case 'h6': {
10399                                         $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k);
10400                                         break;
10401                                 }
10402                                 default : {
10403                                         break;
10404                                 }
10405                         }
10406                         $this->tmprtl = false;
10407                 }
10408                 
10409                 /**
10410                  * Add vertical spaces if needed.
10411                  * @param int $n number of spaces to add
10412                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
10413                  * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
10414                  * @access protected
10415                  */
10416                 function addHTMLVertSpace($n, $cell=false, $h='') {
10417                         if (is_string($h)) {
10418                                 $vsize = $n * $this->lasth;
10419                         } else {
10420                                 $vsize = $n * $h;
10421                         }
10422                         if ($vsize > $this->htmlvspace) {
10423                                 $this->Ln(($vsize - $this->htmlvspace), $cell);
10424                                 $this->htmlvspace = $vsize;
10425             }
10426         }
10427                 
10428         } // END OF TCPDF CLASS
10429 }
10430 //============================================================+
10431 // END OF FILE
10432 //============================================================+