Merge branch 'master' of https://git.code.sf.net/p/frontaccounting/git
[fa-stable.git] / reporting / includes / tcpdf.php
1 <?php
2 //============================================================+
3 // File name   : tcpdf.php
4 // Begin       : 2002-08-03
5 // Last Update : 2008-09-19
6 // Author      : Nicola Asuni - info@tecnick.com - http://www.tcpdf.org
7 // Version     : 4.0.027_PHP4
8 // License     : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
9 //      ----------------------------------------------------------------------------
10 //  Copyright (C) 2002-2008  Nicola Asuni - Tecnick.com S.r.l.
11 //
12 //      This program is free software: you can redistribute it and/or modify
13 //      it under the terms of the GNU Lesser General Public License as published by
14 //      the Free Software Foundation, either version 2.1 of the License, or
15 //      (at your option) any later version.
16 //
17 //      This program is distributed in the hope that it will be useful,
18 //      but WITHOUT ANY WARRANTY; without even the implied warranty of
19 //      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 //      GNU Lesser General Public License for more details.
21 //
22 //      You should have received a copy of the GNU Lesser General Public License
23 //      along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 //
25 //      See LICENSE.TXT file for more information.
26 //  ----------------------------------------------------------------------------
27 //
28 // Description : This is a PHP class for generating PDF documents without
29 //               requiring external extensions.
30 //
31 // NOTE:
32 // This class was originally derived in 2002 from the Public
33 // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
34 // but now is almost entirely rewritten.
35 //
36 // Main features:
37 //  * no external libraries are required for the basic functions;
38 //      * supports all ISO page formats;
39 //      * supports UTF-8 Unicode and Right-To-Left languages;
40 //      * supports document encryption;
41 //      * includes methods to publish some XHTML code;
42 //      * includes graphic (geometric) and transformation methods;
43 //      * includes bookmarks;
44 //      * includes Javascript and forms support;
45 //      * includes a method to print various barcode formats;
46 //      * supports TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;
47 //      * supports custom page formats, margins and units of measure;
48 //      * includes methods for page header and footer management;
49 //      * supports automatic page break;
50 //      * supports automatic page numbering and page groups;
51 //      * supports automatic line break and text justification;
52 //      * supports JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
53 //      * supports stroke and clipping mode for text;
54 //      * supports clipping masks;
55 //      * supports Grayscale, RGB, CMYK, Spot colors and transparency;
56 //      * supports links and annotations;
57 //      * supports page compression (requires zlib extension);
58 //      * supports PDF user's rights.
59 //
60 // -----------------------------------------------------------
61 // THANKS TO:
62 //
63 // Olivier Plathey (http://www.fpdf.org) for original FPDF.
64 // Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support.
65 // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm.
66 // Warren Sherliker (wsherliker@gmail.com) for better image handling.
67 // dullus for text Justification.
68 // Bob Vincent (pillarsdotnet@users.sourceforge.net) for <li> value attribute.
69 // Patrick Benny for text stretch suggestion on Cell().
70 // Johannes Güntert for JavaScript support.
71 // Denis Van Nuffelen for Dynamic Form.
72 // Jacek Czekaj for multibyte justification
73 // Anthony Ferrara for the reintroduction of legacy image methods.
74 // Sourceforge user 1707880 (hucste) for line-trough mode.
75 // Larry Stanbery for page groups.
76 // Martin Hall-May for transparency.
77 // Aaron C. Spike for Polycurve method.
78 // Mohamad Ali Golkar, Saleh AlMatrafe, Charles Abbott for Arabic and Persian support.
79 // Moritz Wagner and Andreas Wurmser for graphic functions.
80 // Andrew Whitehead for core fonts support.
81 // Esteban Joël Marín for OpenType font conversion.
82 // Teus Hagen for several suggestions and fixes.
83 // Yukihiro Nakadaira for CID-0 CJK fonts fixes.
84 // Kosmas Papachristos for some CSS improvements.
85 // Anyone that has reported a bug or sent a suggestion.
86 //============================================================+
87
88 /**
89  * This is a PHP class for generating PDF documents without requiring external extensions.<br>
90  * TCPDF project (http://www.tcpdf.org) was originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
91  * <h3>TCPDF main features are:</h3>
92  * <ul>
93  * <li>no external libraries are required for the basic functions;</li>
94  * <li>supports all ISO page formats;</li>
95  * <li>supports UTF-8 Unicode and Right-To-Left languages;</li>
96  * <li>supports document encryption;</li>
97  * <li>includes methods to publish some XHTML code;</li>
98  * <li>includes graphic (geometric) and transformation methods;</li>
99  * <li>includes bookmarks;</li>
100  * <li>includes Javascript and forms support;</li>
101  * <li>includes a method to print various barcode formats;</li>
102  * <li>supports TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;</li>
103  * <li>supports custom page formats, margins and units of measure;</li>
104  * <li>includes methods for page header and footer management;</li>
105  * <li>supports automatic page break;</li>
106  * <li>supports automatic page numbering and page groups;</li>
107  * <li>supports automatic line break and text justification;
108  * <li>supports JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;</li>
109  * <li>supports stroke and clipping mode for text;</li>
110  * <li>supports clipping masks;</li>
111  * <li>supports Grayscale, RGB and CMYK colors and transparency;</li>
112  * <li>supports links and annotations;</li>
113  * <li>supports page compression (requires zlib extension);</li>
114  * <li>supports PDF user's rights.</li>
115  * </ul>
116  * Tools to encode your unicode fonts are on fonts/utils directory.</p>
117  * @package com.tecnick.tcpdf
118  * @abstract Class for generating PDF files on-the-fly without requiring external extensions.
119  * @author Nicola Asuni
120  * @copyright 2004-2008 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
121  * @link http://www.tcpdf.org
122  * @license http://www.gnu.org/copyleft/lesser.html LGPL
123  * @version 4.0.027_PHP4
124  */
125
126 /**
127  * main configuration file
128  */
129 /** -------------------------------FrontAccounting 2.0  ---------------------------
130   * following changes are done for FrontAccounting 2.0 - Joe Hunt 06.08.2008
131   * 1. /config/tcpdf_config.php is not included, commented out
132   * 2. Following 3 defines instead:
133   *    if (!defined("K_PATH_FONTS"))
134   *        define ("K_PATH_FONTS", '../reporting/fonts/');
135   *    define ("K_PATH_CACHE", '../reporting/fonts/');
136   *    define("K_CELL_HEIGHT_RATIO", 1.25);
137   * 3. ./unicode_data2.php only included if unicode is set. (in class constructor)
138   *    We only use a reduced variant of unicode_data.php (unicode_data.php).af wrap the
139   *    following defines
140   *    if (!defined("K_RE_PATTERN_RTL"))
141   *    and
142   *    if (!defined("K_RE_PATTERN_ARABIC"))
143   * 4. Parameter $unicode in constructor renamed to $uni.
144   * 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                         $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
1128                         $this->tmprtl = false;
1129                         //Some checks
1130                         $this->_dochecks();
1131                         //Initialization of properties
1132                         $this->isunicode = $uni;
1133                         $this->page = 0;
1134                         $this->pagedim = array();
1135                         $this->n = 2;
1136                         $this->buffer = '';
1137                         $this->pages = array();
1138                         $this->state = 0;
1139                         $this->fonts = array();
1140                         $this->FontFiles = array();
1141                         $this->diffs = array();
1142                         $this->images = array();
1143                         $this->links = array();
1144                         $this->gradients = array();
1145                         $this->InFooter = false;
1146                         $this->lasth = 0;
1147                         $this->FontFamily = 'helvetica';
1148                         $this->FontStyle = '';
1149                         $this->FontSizePt = 12;
1150                         $this->underline = false;
1151                         $this->linethrough = false;
1152                         $this->DrawColor = '0 G';
1153                         $this->FillColor = '0 g';
1154                         $this->TextColor = '0 g';
1155                         $this->ColorFlag = false;
1156                         $this->ws = 0;
1157                         // encryption values
1158                         $this->encrypted = false;
1159                         $this->last_rc4_key = '';
1160                         $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";
1161                         //Standard Unicode fonts
1162                         $this->CoreFonts = array(
1163                                 'courier'=>'Courier',
1164                                 'courierB'=>'Courier-Bold',
1165                                 'courierI'=>'Courier-Oblique',
1166                                 'courierBI'=>'Courier-BoldOblique',
1167                                 'helvetica'=>'Helvetica',
1168                                 'helveticaB'=>'Helvetica-Bold',
1169                                 'helveticaI'=>'Helvetica-Oblique',
1170                                 'helveticaBI'=>'Helvetica-BoldOblique',
1171                                 'times'=>'Times-Roman',
1172                                 'timesB'=>'Times-Bold',
1173                                 'timesI'=>'Times-Italic',
1174                                 'timesBI'=>'Times-BoldItalic',
1175                                 'symbol'=>'Symbol',
1176                                 'zapfdingbats'=>'ZapfDingbats'
1177                         );
1178                         //Set scale factor
1179                         $this->setPageUnit($unit);
1180                         // set page format and orientation
1181                         $this->setPageFormat($format, $orientation);
1182                         //Page margins (1 cm)
1183                         $margin = 28.35 / $this->k;
1184                         $this->SetMargins($margin,$margin);
1185                         //Interior cell margin (1 mm)
1186                         $this->cMargin = $margin / 10;
1187                         //Line width (0.2 mm)
1188                         $this->LineWidth = 0.57 / $this->k;
1189                         $this->linestyleWidth = sprintf('%.2f w', ($this->LineWidth * $this->k));
1190                         $this->linestyleCap = "0 J";
1191                         $this->linestyleJoin = "0 j";
1192                         $this->linestyleDash = "[] 0 d";
1193                         //Automatic page break
1194                         $this->SetAutoPageBreak(true, 2*$margin);
1195                         //Full width display mode
1196                         $this->SetDisplayMode('fullwidth');
1197                         //Compression
1198                         $this->SetCompression(true);
1199                         //Set default PDF version number
1200                         $this->PDFVersion = "1.7";
1201                         $this->encoding = $encoding;
1202                         $this->HREF = '';
1203                         $this->getFontsList();
1204                         $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
1205                         $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
1206                         $this->extgstates = array();
1207                         // user's rights
1208                         $this->ur = false;
1209                         $this->ur_document = "/FullSave";
1210                         $this->ur_annots = "/Create/Delete/Modify/Copy/Import/Export";
1211                         $this->ur_form = "/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate";
1212                         $this->ur_signature = "/Modify";
1213                         // set default JPEG quality
1214                         $this->jpeg_quality = 75;
1215                         // initialize some settings
1216                         $this->utf8Bidi(array(""));
1217                 }
1218
1219                 /**
1220                  * Default destructor.
1221                  * @since 1.53.0.TC016
1222                  */
1223                 function TCPDFDestruct() {
1224                         // restore internal encoding
1225                         if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
1226                                 mb_internal_encoding($this->internal_encoding);
1227                         }
1228                 }
1229
1230                 /**
1231                 * Set the units of measure for the document.
1232                 * @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.
1233                 * @since 3.0.015 (2008-06-06)
1234                 */
1235                 function setPageUnit($unit) {
1236                 //Set scale factor
1237                         switch (strtolower($unit)) {
1238                                 // points
1239                                 case 'pt': {
1240                                         $this->k = 1;
1241                                         break;
1242                                 }
1243                                 // millimeters
1244                                 case 'mm': {
1245                                         $this->k = $this->dpi / 25.4;
1246                                         break;
1247                                 }
1248                                 // centimeters
1249                                 case 'cm': {
1250                                         $this->k = $this->dpi / 2.54;
1251                                         break;
1252                                 }
1253                                 // inches
1254                                 case 'in': {
1255                                         $this->k = $this->dpi;
1256                                         break;
1257                                 }
1258                                 // unsupported unit
1259                                 default : {
1260                                         $this->Error('Incorrect unit: '.$unit);
1261                                         break;
1262                                 }
1263                         }
1264                         if (isset($this->CurOrientation)) {
1265                                         $this->setPageOrientation($this->CurOrientation);
1266                         }
1267                 }
1268
1269                 /**
1270                 * Set the page format
1271                 * @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>
1272                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1273                 * @since 3.0.015 (2008-06-06)
1274                 */
1275                 function setPageFormat($format, $orientation="P") {
1276                         //Page format
1277                         if (is_string($format)) {
1278                                 // Page formats (45 standard ISO paper formats and 4 american common formats).
1279                                 // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm)
1280                                 switch (strtoupper($format)){
1281                                         case '4A0': {$format = array(4767.87,6740.79); break;}
1282                                         case '2A0': {$format = array(3370.39,4767.87); break;}
1283                                         case 'A0': {$format = array(2383.94,3370.39); break;}
1284                                         case 'A1': {$format = array(1683.78,2383.94); break;}
1285                                         case 'A2': {$format = array(1190.55,1683.78); break;}
1286                                         case 'A3': {$format = array(841.89,1190.55); break;}
1287                                         case 'A4': default: {$format = array(595.28,841.89); break;}
1288                                         case 'A5': {$format = array(419.53,595.28); break;}
1289                                         case 'A6': {$format = array(297.64,419.53); break;}
1290                                         case 'A7': {$format = array(209.76,297.64); break;}
1291                                         case 'A8': {$format = array(147.40,209.76); break;}
1292                                         case 'A9': {$format = array(104.88,147.40); break;}
1293                                         case 'A10': {$format = array(73.70,104.88); break;}
1294                                         case 'B0': {$format = array(2834.65,4008.19); break;}
1295                                         case 'B1': {$format = array(2004.09,2834.65); break;}
1296                                         case 'B2': {$format = array(1417.32,2004.09); break;}
1297                                         case 'B3': {$format = array(1000.63,1417.32); break;}
1298                                         case 'B4': {$format = array(708.66,1000.63); break;}
1299                                         case 'B5': {$format = array(498.90,708.66); break;}
1300                                         case 'B6': {$format = array(354.33,498.90); break;}
1301                                         case 'B7': {$format = array(249.45,354.33); break;}
1302                                         case 'B8': {$format = array(175.75,249.45); break;}
1303                                         case 'B9': {$format = array(124.72,175.75); break;}
1304                                         case 'B10': {$format = array(87.87,124.72); break;}
1305                                         case 'C0': {$format = array(2599.37,3676.54); break;}
1306                                         case 'C1': {$format = array(1836.85,2599.37); break;}
1307                                         case 'C2': {$format = array(1298.27,1836.85); break;}
1308                                         case 'C3': {$format = array(918.43,1298.27); break;}
1309                                         case 'C4': {$format = array(649.13,918.43); break;}
1310                                         case 'C5': {$format = array(459.21,649.13); break;}
1311                                         case 'C6': {$format = array(323.15,459.21); break;}
1312                                         case 'C7': {$format = array(229.61,323.15); break;}
1313                                         case 'C8': {$format = array(161.57,229.61); break;}
1314                                         case 'C9': {$format = array(113.39,161.57); break;}
1315                                         case 'C10': {$format = array(79.37,113.39); break;}
1316                                         case 'RA0': {$format = array(2437.80,3458.27); break;}
1317                                         case 'RA1': {$format = array(1729.13,2437.80); break;}
1318                                         case 'RA2': {$format = array(1218.90,1729.13); break;}
1319                                         case 'RA3': {$format = array(864.57,1218.90); break;}
1320                                         case 'RA4': {$format = array(609.45,864.57); break;}
1321                                         case 'SRA0': {$format = array(2551.18,3628.35); break;}
1322                                         case 'SRA1': {$format = array(1814.17,2551.18); break;}
1323                                         case 'SRA2': {$format = array(1275.59,1814.17); break;}
1324                                         case 'SRA3': {$format = array(907.09,1275.59); break;}
1325                                         case 'SRA4': {$format = array(637.80,907.09); break;}
1326                                         case 'LETTER': {$format = array(612.00,792.00); break;}
1327                                         case 'LEGAL': {$format = array(612.00,1008.00); break;}
1328                                         case 'EXECUTIVE': {$format = array(521.86,756.00); break;}
1329                                         case 'FOLIO': {$format = array(612.00,936.00); break;}
1330                                 }
1331                                 $this->fwPt = $format[0];
1332                                 $this->fhPt = $format[1];
1333                         }
1334                         else {
1335                                 $this->fwPt = $format[0] * $this->k;
1336                                 $this->fhPt = $format[1] * $this->k;
1337                         }
1338                         $this->setPageOrientation($orientation);
1339                 }
1340
1341
1342                 /**
1343                 * Set page orientation.
1344                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1345                 * @param boolean $autopagebreak Boolean indicating if auto-page-break mode should be on or off.
1346                 * @param float $bottommargin bottom margin of the page.
1347                 * @since 3.0.015 (2008-06-06)
1348                 */
1349                 function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
1350                         $orientation = strtoupper($orientation);
1351                         if (($orientation == 'P') OR ($orientation == 'PORTRAIT')) {
1352                                 $this->CurOrientation = 'P';
1353                                 $this->wPt = $this->fwPt;
1354                                 $this->hPt = $this->fhPt;
1355                         } elseif (($orientation == 'L') OR ($orientation == 'LANDSCAPE')) {
1356                                 $this->CurOrientation = 'L';
1357                                 $this->wPt = $this->fhPt;
1358                                 $this->hPt = $this->fwPt;
1359                         }
1360                         else {
1361                                 $this->Error('Incorrect orientation: '.$orientation);
1362                         }
1363                         $this->w = $this->wPt / $this->k;
1364                         $this->h = $this->hPt / $this->k;
1365                         if (empty($autopagebreak)) {
1366                                 if (isset($this->AutoPageBreak)) {
1367                                         $autopagebreak = $this->AutoPageBreak;
1368                                 } else {
1369                                         $autopagebreak = true;
1370                                 }
1371                         }
1372                         if (empty($bottommargin)) {
1373                                 if (isset($this->bMargin)) {
1374                                         $bottommargin = $this->bMargin;
1375                                 } else {
1376                                         // default value = 2 cm
1377                                         $bottommargin = 2 * 28.35 / $this->k;
1378                                 }
1379                         }
1380                         $this->SetAutoPageBreak($autopagebreak, $bottommargin);
1381                         // store page dimensions
1382                         $this->pagedim[$this->page] = array('w' => $this->wPt, 'h' => $this->hPt, 'tm' => $this->tMargin, 'bm' => $bottommargin, 'lm' => $this->lMargin, 'rm' => $this->rMargin, 'pb' => $autopagebreak, 'or' => $this->CurOrientation);
1383                 }
1384
1385                 /**
1386                  * Enable or disable Right-To-Left language mode
1387                  * @param Boolean $enable if true enable Right-To-Left language mode.
1388                  * @since 2.0.000 (2008-01-03)
1389                  */
1390                 function setRTL($enable) {
1391                         $this->rtl = $enable ? true : false;
1392                         $this->tmprtl = false;
1393                 }
1394
1395                 /**
1396                  * Return the RTL status
1397                  * @return boolean
1398                  * @since 4.0.012 (2008-07-24)
1399                  */
1400                 function getRTL() {
1401                         return $this->rtl;
1402                 }
1403
1404                 /**
1405                 * Force temporary RTL language direction
1406                 * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL
1407                 * @since 2.1.000 (2008-01-09)
1408                 */
1409                 function setTempRTL($mode) {
1410                         switch ($mode) {
1411                                 case false:
1412                                 case 'L':
1413                                 case 'R': {
1414                                         $this->tmprtl = $mode;
1415                                 }
1416                         }
1417                 }
1418
1419                 /**
1420                 * Set the last cell height.
1421                 * @param float $h cell height.
1422                 * @author Nicola Asuni
1423                 * @since 1.53.0.TC034
1424                 */
1425                 function setLastH($h) {
1426                         $this->lasth = $h;
1427                 }
1428
1429                 /**
1430                 * Get the last cell height.
1431                 * @return last cell height
1432                 * @since 4.0.017 (2008-08-05)
1433                 */
1434                 function getLastH() {
1435                         return $this->lasth;
1436                 }
1437
1438                 /**
1439                 * Set the image scale.
1440                 * @param float $scale image scale.
1441                 * @author Nicola Asuni
1442                 * @since 1.5.2
1443                 */
1444                 function setImageScale($scale) {
1445                         $this->imgscale = $scale;
1446                 }
1447
1448                 /**
1449                 * Returns the image scale.
1450                 * @return float image scale.
1451                 * @author Nicola Asuni
1452                 * @since 1.5.2
1453                 */
1454                 function getImageScale() {
1455                         return $this->imgscale;
1456                 }
1457
1458                 /**
1459                 * Returns the page width in units.
1460                 * @return int page width.
1461                 * @author Nicola Asuni
1462                 * @since 1.5.2
1463                 */
1464                 function getPageWidth() {
1465                         return $this->w;
1466                 }
1467
1468                 /**
1469                 * Returns the page height in units.
1470                 * @return int page height.
1471                 * @author Nicola Asuni
1472                 * @since 1.5.2
1473                 */
1474                 function getPageHeight() {
1475                         return $this->h;
1476                 }
1477
1478                 /**
1479                 * Returns the page break margin.
1480                 * @return int page break margin.
1481                 * @author Nicola Asuni
1482                 * @since 1.5.2
1483                 */
1484                 function getBreakMargin() {
1485                         return $this->bMargin;
1486                 }
1487
1488                 /**
1489                 * Returns the scale factor (number of points in user unit).
1490                 * @return int scale factor.
1491                 * @author Nicola Asuni
1492                 * @since 1.5.2
1493                 */
1494                 function getScaleFactor() {
1495                         return $this->k;
1496                 }
1497
1498                 /**
1499                 * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
1500                 * @param float $left Left margin.
1501                 * @param float $top Top margin.
1502                 * @param float $right Right margin. Default value is the left one.
1503                 * @since 1.0
1504                 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
1505                 */
1506                 function SetMargins($left, $top, $right=-1) {
1507                         //Set left, top and right margins
1508                         $this->lMargin = $left;
1509                         $this->tMargin = $top;
1510                         if ($right == -1) {
1511                                 $right = $left;
1512                         }
1513                         $this->rMargin = $right;
1514                 }
1515
1516                 /**
1517                 * 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.
1518                 * @param float $margin The margin.
1519                 * @since 1.4
1520                 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1521                 */
1522                 function SetLeftMargin($margin) {
1523                         //Set left margin
1524                         $this->lMargin=$margin;
1525                         if (($this->page > 0) AND ($this->x < $margin)) {
1526                                 $this->x = $margin;
1527                         }
1528                 }
1529
1530                 /**
1531                 * Defines the top margin. The method can be called before creating the first page.
1532                 * @param float $margin The margin.
1533                 * @since 1.5
1534                 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
1535                 */
1536                 function SetTopMargin($margin) {
1537                         //Set top margin
1538                         $this->tMargin=$margin;
1539                         if (($this->page > 0) AND ($this->y < $margin)) {
1540                                 $this->y = $margin;
1541                         }
1542                 }
1543
1544                 /**
1545                 * Defines the right margin. The method can be called before creating the first page.
1546                 * @param float $margin The margin.
1547                 * @since 1.5
1548                 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1549                 */
1550                 function SetRightMargin($margin) {
1551                         $this->rMargin=$margin;
1552                         if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
1553                                 $this->x = $this->w - $margin;
1554                         }
1555                 }
1556
1557                 /**
1558                 * Set the internal Cell padding.
1559                 * @param float $pad internal padding.
1560                 * @since 2.1.000 (2008-01-09)
1561                 * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
1562                 */
1563                 function SetCellPadding($pad) {
1564                         $this->cMargin = $pad;
1565                 }
1566
1567                 /**
1568                 * 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.
1569                 * @param boolean $auto Boolean indicating if mode should be on or off.
1570                 * @param float $margin Distance from the bottom of the page.
1571                 * @since 1.0
1572                 * @see Cell(), MultiCell(), AcceptPageBreak()
1573                 */
1574                 function SetAutoPageBreak($auto, $margin=0) {
1575                         //Set auto page break mode and triggering margin
1576                         $this->AutoPageBreak = $auto;
1577                         $this->bMargin = $margin;
1578                         $this->PageBreakTrigger = $this->h - $margin;
1579                 }
1580
1581                 /**
1582                 * Defines the way the document is to be displayed by the viewer.
1583                 * @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>
1584                 * @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>
1585                 * @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>
1586                 * @since 1.2
1587                 */
1588                 function SetDisplayMode($zoom, $layout='SinglePage', $mode="UseNone") {
1589                         //Set display mode in viewer
1590                         if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
1591                                 $this->ZoomMode = $zoom;
1592                         } else {
1593                                 $this->Error('Incorrect zoom display mode: '.$zoom);
1594                         }
1595                         switch ($layout) {
1596                                 case "default":
1597                                 case "single":
1598                                 case "SinglePage": {
1599                                         $this->LayoutMode = "SinglePage";
1600                                         break;
1601                                 }
1602                                 case "continuous":
1603                                 case "OneColumn": {
1604                                         $this->LayoutMode = "OneColumn";
1605                                         break;
1606                                 }
1607                                 case "two":
1608                                 case "TwoColumnLeft": {
1609                                         $this->LayoutMode = "TwoColumnLeft";
1610                                         break;
1611                                 }
1612                                 case "TwoColumnRight": {
1613                                         $this->LayoutMode = "TwoColumnRight";
1614                                         break;
1615                                 }
1616                                 case "TwoPageLeft": {
1617                                         $this->LayoutMode = "TwoPageLeft";
1618                                         break;
1619                                 }
1620                                 case "TwoPageRight": {
1621                                         $this->LayoutMode = "TwoPageRight";
1622                                         break;
1623                                 }
1624                                 default: {
1625                                         $this->LayoutMode = "SinglePage";
1626                                 }
1627                         }
1628                         switch ($mode) {
1629                                 case "UseNone": {
1630                                         $this->PageMode = "UseNone";
1631                                         break;
1632                                 }
1633                                 case "UseOutlines": {
1634                                         $this->PageMode = "UseOutlines";
1635                                         break;
1636                                 }
1637                                 case "UseThumbs": {
1638                                         $this->PageMode = "UseThumbs";
1639                                         break;
1640                                 }
1641                                 case "FullScreen": {
1642                                         $this->PageMode = "FullScreen";
1643                                         break;
1644                                 }
1645                                 case "UseOC": {
1646                                         $this->PageMode = "UseOC";
1647                                         break;
1648                                 }
1649                                 case "": {
1650                                         $this->PageMode = "UseAttachments";
1651                                         break;
1652                                 }
1653                                 default: {
1654                                         $this->PageMode = "UseNone";
1655                                 }
1656                         }
1657                 }
1658
1659                 /**
1660                 * 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.
1661                 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
1662                 * @param boolean $compress Boolean indicating if compression must be enabled.
1663                 * @since 1.4
1664                 */
1665                 function SetCompression($compress) {
1666                         //Set page compression
1667                         if (function_exists('gzcompress')) {
1668                                 $this->compress = $compress;
1669                         } else {
1670                                 $this->compress = false;
1671                         }
1672                 }
1673
1674                 /**
1675                 * Defines the title of the document.
1676                 * @param string $title The title.
1677                 * @since 1.2
1678                 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
1679                 */
1680                 function SetTitle($title) {
1681                         //Title of document
1682                         $this->title = $title;
1683                 }
1684
1685                 /**
1686                 * Defines the subject of the document.
1687                 * @param string $subject The subject.
1688                 * @since 1.2
1689                 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
1690                 */
1691                 function SetSubject($subject) {
1692                         //Subject of document
1693                         $this->subject = $subject;
1694                 }
1695
1696                 /**
1697                 * Defines the author of the document.
1698                 * @param string $author The name of the author.
1699                 * @since 1.2
1700                 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
1701                 */
1702                 function SetAuthor($author) {
1703                         //Author of document
1704                         $this->author = $author;
1705                 }
1706
1707                 /**
1708                 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
1709                 * @param string $keywords The list of keywords.
1710                 * @since 1.2
1711                 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
1712                 */
1713                 function SetKeywords($keywords) {
1714                         //Keywords of document
1715                         $this->keywords = $keywords;
1716                 }
1717
1718                 /**
1719                 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
1720                 * @param string $creator The name of the creator.
1721                 * @since 1.2
1722                 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
1723                 */
1724                 function SetCreator($creator) {
1725                         //Creator of document
1726                         $this->creator = $creator;
1727                 }
1728
1729                 /**
1730                 * Defines an alias for the total number of pages. It will be substituted as the document is closed.<br />
1731                 * @param string $alias The alias. Default value: {nb}.
1732                 * @since 1.4
1733                 * @see getAliasNbPages(), PageNo(), Footer()
1734                 */
1735                 function AliasNbPages($alias='{nb}') {
1736                         //Define an alias for total number of pages
1737                         $this->AliasNbPages = $alias;
1738                 }
1739                 
1740                 /**
1741                  * Returns the string alias used for the total number of pages.
1742          * If the current font is unicode type, the returned string is surrounded by additional curly braces.
1743                  * @return string
1744                  * @since 4.0.018 (2008-08-08)
1745                  * @see AliasNbPages(), PageNo(), Footer()
1746                 */
1747                 function getAliasNbPages() {
1748                         if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
1749                                 return "{".$this->AliasNbPages."}";
1750             }
1751                         return $this->AliasNbPages;
1752                 }
1753
1754                 /**
1755                 * 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.
1756                 * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
1757                 * @param string $msg The error message
1758                 * @since 1.0
1759                 */
1760                 function Error($msg) {
1761                         //Fatal error
1762                         display_error('<strong>TCPDF error: </strong>'.$msg);
1763                         exit;
1764                 }
1765
1766                 /**
1767                 * This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.
1768                 * Note: no page is created by this method
1769                 * @since 1.0
1770                 * @see AddPage(), Close()
1771                 */
1772                 function Open() {
1773                         //Begin document
1774                         $this->state = 1;
1775                 }
1776
1777                 /**
1778                 * 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.
1779                 * @since 1.0
1780                 * @see Open(), Output()
1781                 */
1782                 function Close() {
1783                         //Terminate document
1784                         if ($this->state == 3) {
1785                                 return;
1786                         }
1787                         if ($this->page == 0) {
1788                                 $this->AddPage();
1789                         }
1790                         //Page footer
1791                         $this->setFooter();
1792                         //Close page
1793                         $this->_endpage();
1794                         //Close document
1795                         $this->_enddoc();
1796                 }
1797
1798                 /**
1799                 * Move pointer at the specified document page and update page dimensions.
1800                 * @param int $pnum page number
1801                 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
1802                 * @since 2.1.000 (2008-01-07)
1803                 * @see getPage(), lastpage(), getNumPages()
1804                 */
1805                 function setPage($pnum, $resetmargins=false) {
1806                         if (($pnum > 0) AND ($pnum <= count($this->pages))) {
1807                                 $this->page = $pnum;
1808                                 $this->wPt = $this->pagedim[$this->page]['w'];
1809                                 $this->hPt = $this->pagedim[$this->page]['h'];
1810                                 $this->w = $this->wPt / $this->k;
1811                                 $this->h = $this->hPt / $this->k;
1812                                 $this->tMargin = $this->pagedim[$this->page]['tm'];
1813                                 $this->bMargin = $this->pagedim[$this->page]['bm'];
1814                                 $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
1815                                 $this->CurOrientation = $this->pagedim[$this->page]['or'];
1816                                 $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
1817                                 if ($resetmargins) {
1818                                         $this->lMargin = $this->pagedim[$this->page]['lm'];
1819                                         $this->rMargin = $this->pagedim[$this->page]['rm'];
1820                                         $this->SetY($this->tMargin);
1821                                 }
1822                         } else {
1823                                 $this->Error('Wrong page number on setPage() function.');
1824                         }
1825                 }
1826
1827                 /**
1828                 * Reset pointer to the last document page.
1829                 * @since 2.0.000 (2008-01-04)
1830                 * @see setPage(), getPage(), getNumPages()
1831                 */
1832                 function lastPage() {
1833                         $this->setPage($this->getNumPages());
1834                 }
1835
1836                 /**
1837                 * Get current document page number.
1838                 * @return int page number
1839                 * @since 2.1.000 (2008-01-07)
1840                 * @see setPage(), lastpage(), getNumPages()
1841                 */
1842                 function getPage() {
1843                         return $this->page;
1844                 }
1845
1846
1847                 /**
1848                 * Get the total number of insered pages.
1849                 * @return int number of pages
1850                 * @since 2.1.000 (2008-01-07)
1851                 * @see setPage(), getPage(), lastpage()
1852                 */
1853                 function getNumPages() {
1854                         return count($this->pages);
1855                 }
1856
1857                 /**
1858                 * 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.
1859                 * 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.
1860                 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
1861                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
1862                 * @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>
1863                 * @since 1.0
1864                 * @see TCPDF(), Header(), Footer(), SetMargins()
1865                 */
1866                 function AddPage($orientation='', $format='') {
1867                         if (!isset($this->original_lMargin)) {
1868                                 $this->original_lMargin = $this->lMargin;
1869                         }
1870                         if (!isset($this->original_rMargin)) {
1871                                 $this->original_rMargin = $this->rMargin;
1872                         }
1873                         if (count($this->pages) > $this->page) {
1874                                 // this page has been already added
1875                                 $this->setPage(($this->page + 1));
1876                                 $this->SetY($this->tMargin);
1877                                 return;
1878                         }
1879                         //Start a new page
1880                         if ($this->state == 0) {
1881                                 $this->Open();
1882                         }
1883                         // save current settings
1884                         $font_family = $this->FontFamily;
1885                         $font_style = $this->FontStyle.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '');
1886                         $font_size = $this->FontSizePt;
1887                         $prev_rMargin = $this->rMargin;
1888                         $prev_lMargin = $this->lMargin;
1889                         $prev_cMargin = $this->cMargin;
1890                         $prev_linestyleWidth = $this->linestyleWidth;
1891                         $prev_linestyleCap = $this->linestyleCap;
1892                         $prev_linestyleJoin = $this->linestyleJoin;
1893                         $prev_linestyleDash = $this->linestyleDash;
1894                         $prev_DrawColor = $this->DrawColor;
1895                         $prev_FillColor = $this->FillColor;
1896                         $prev_TextColor = $this->TextColor;
1897                         $prev_ColorFlag = $this->ColorFlag;
1898                         if ($this->page > 0) {
1899                                 //Page footer
1900                                 $this->setFooter();
1901                                 //Close page
1902                                 $this->_endpage();
1903                         }
1904                         //Start new page
1905                         $this->_beginpage($orientation, $format);
1906                         // restore graphic styles
1907                         $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1908                         if (!empty($font_family)) {
1909                                 $this->SetFont($font_family, $font_style, $font_size);
1910                         }
1911                         //Page header
1912                         $this->setHeader();
1913                         // restore graphic styles
1914                         $this->_out("".$prev_linestyleWidth." ".$prev_linestyleCap." ".$prev_linestyleJoin." ".$prev_linestyleDash." ".$prev_DrawColor." ".$prev_FillColor."");
1915                         if (!empty($font_family)) {
1916                                 $this->SetFont($font_family, $font_style, $font_size);
1917                         }
1918                         // restore settings
1919                         $this->FontFamily = $font_family;
1920                         $this->FontStyle = $font_style;
1921                         $this->FontSizePt = $font_size;
1922                         $this->rMargin = $prev_rMargin;
1923                         $this->lMargin = $prev_lMargin;
1924                         $this->cMargin = $prev_cMargin;
1925                         $this->linestyleWidth = $prev_linestyleWidth;
1926                         $this->linestyleCap = $prev_linestyleCap;
1927                         $this->linestyleJoin = $prev_linestyleJoin;
1928                         $this->linestyleDash = $prev_linestyleDash;
1929                         $this->DrawColor = $prev_DrawColor;
1930                         $this->FillColor = $prev_FillColor;
1931                         $this->TextColor = $prev_TextColor;
1932                         $this->ColorFlag = $prev_ColorFlag;
1933                         // mark this point
1934                         $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1935                 }
1936
1937                 /**
1938                  * Set start-writing mark on current page for multicell borders and fills.
1939                  * This function must be called after calling Image() function for a background image.
1940                  * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
1941                  * @access public
1942                  * @since 4.0.016 (2008-07-30)
1943                  */
1944                 function setPageMark() {
1945                         $this->intmrk[$this->page] = strlen($this->pages[$this->page]);
1946                 }
1947
1948                 /**
1949                  * Set header data.
1950                  * @param string $ln header image logo
1951                  * @param string $lw header image logo width in mm
1952                  * @param string $ht string to print as title on document header
1953                  * @param string $hs string to print on document header
1954                 */
1955                 function setHeaderData($ln="", $lw=0, $ht="", $hs="") {
1956                         $this->header_logo = $ln;
1957                         $this->header_logo_width = $lw;
1958                         $this->header_title = $ht;
1959                         $this->header_string = $hs;
1960                 }
1961
1962                 /**
1963                  * Returns header data:
1964                  * <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>
1965                  * @return array()
1966                  * @since 4.0.012 (2008-07-24)
1967                  */
1968                 function getHeaderData() {
1969                         $ret = array();
1970                         $ret['logo'] = $this->header_logo;
1971                         $ret['logo_width'] = $this->header_logo_width;
1972                         $ret['title'] = $this->header_title;
1973                         $ret['string'] = $this->header_string;
1974                         return $ret;
1975                 }
1976
1977                 /**
1978                  * Set header margin.
1979                  * (minimum distance between header and top page margin)
1980                  * @param int $hm distance in user units
1981                 */
1982                 function setHeaderMargin($hm=10) {
1983                         $this->header_margin = $hm;
1984                 }
1985
1986                 /**
1987                  * Returns header margin in user units.
1988                  * @return float
1989                  * @since 4.0.012 (2008-07-24)
1990                 */
1991                 function getHeaderMargin() {
1992                         return $this->header_margin;
1993                 }
1994
1995                 /**
1996                  * Set footer margin.
1997                  * (minimum distance between footer and bottom page margin)
1998                  * @param int $fm distance in user units
1999                 */
2000                 function setFooterMargin($fm=10) {
2001                         $this->footer_margin = $fm;
2002                 }
2003
2004                 /**
2005                  * Returns footer margin in user units.
2006                  * @return float
2007                  * @since 4.0.012 (2008-07-24)
2008                 */
2009                 function getFooterMargin() {
2010                         return $this->footer_margin;
2011                 }
2012                 /**
2013                  * Set a flag to print page header.
2014                  * @param boolean $val set to true to print the page header (default), false otherwise.
2015                  */
2016                 function setPrintHeader($val=true) {
2017                         $this->print_header = $val;
2018                 }
2019
2020                 /**
2021                  * Set a flag to print page footer.
2022                  * @param boolean $value set to true to print the page footer (default), false otherwise.
2023                  */
2024                 function setPrintFooter($val=true) {
2025                         $this->print_footer = $val;
2026                 }
2027
2028                 /**
2029                  * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
2030                  * @return float
2031                  */
2032                 function getImageRBX() {
2033                         return $this->img_rb_x;
2034                 }
2035
2036                 /**
2037                  * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
2038                  * @return float
2039                  */
2040                 function getImageRBY() {
2041                         return $this->img_rb_y;
2042                 }
2043
2044                 /**
2045                  * This method is used to render the page header.
2046                  * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2047                  */
2048                 function Header1() {
2049                         $ormargins = $this->getOriginalMargins();
2050                         $headerfont = $this->getHeaderFont();
2051                         $headerdata = $this->getHeaderData();
2052                         if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
2053                                 $this->Image(K_PATH_IMAGES.$headerdata['logo'], $this->GetX(), $this->getHeaderMargin(), $headerdata['logo_width']);
2054                                 $imgy = $this->getImageRBY();
2055                         } else {
2056                                 $imgy = $this->GetY();
2057                         }
2058                         $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2);
2059                         // set starting margin for text data cell
2060                         if ($this->getRTL()) {
2061                                 $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1);
2062                         } else {
2063                                 $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1);
2064                         }
2065                         $this->SetTextColor(0, 0, 0);
2066                         // header title
2067                         $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
2068                         $this->SetX($header_x);
2069                         $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '');
2070                         // header string
2071                         $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
2072                         $this->SetX($header_x);
2073                         $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, 0, 0, true, 0);
2074                         // print an ending header line
2075                         $this->SetLineStyle(array("width" => 0.85 / $this->getScaleFactor(), "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2076                         $this->SetY(1 + max($imgy, $this->GetY()));
2077                         if ($this->getRTL()) {
2078                                 $this->SetX($ormargins['right']);
2079                         } else {
2080                                 $this->SetX($ormargins['left']);
2081                         }
2082                         $this->Cell(0, 0, '', 'T', 0, 'C');
2083                 }
2084
2085                 /**
2086                  * This method is used to render the page footer.
2087                  * It is automatically called by AddPage() and could be overwritten in your own inherited class.
2088                  */
2089                 function Footer() {
2090                         $cur_y = $this->GetY();
2091                         $ormargins = $this->getOriginalMargins();
2092                         $this->SetTextColor(0, 0, 0);
2093                         //set style for cell border
2094                         $line_width = 0.85 / $this->getScaleFactor();
2095                         $this->SetLineStyle(array("width" => $line_width, "cap" => "butt", "join" => "miter", "dash" => 0, "color" => array(0, 0, 0)));
2096                         //print document barcode
2097                         $barcode = $this->getBarcode();
2098                         if (!empty($barcode)) {
2099                                 $this->Ln();
2100                                 $barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right'])/3);
2101                                 $this->write1DBarcode($barcode, "C128B", $this->GetX(), $cur_y + $line_width, $barcode_width, (($this->getFooterMargin() / 3) - $line_width), 0.3, '', '');
2102                         }
2103                         $pagenumtxt = $this->l['w_page']." ".$this->PageNo().' / '.$this->getAliasNbPages();
2104                         $this->SetY($cur_y);
2105                         //Print page number
2106                         if ($this->getRTL()) {
2107                                 $this->SetX($ormargins['right']);
2108                                 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
2109                         } else {
2110                                 $this->SetX($ormargins['left']);
2111                                 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R');
2112                         }
2113                 }
2114
2115                 /**
2116                  * This method is used to render the page header.
2117                  * @access protected
2118                  * @since 4.0.012 (2008-07-24)
2119                  */
2120                 function setHeader() {
2121                         if ($this->print_header) {
2122                                 $lasth = $this->lasth;
2123                                 $this->_out("q");
2124                                 $this->rMargin = $this->original_rMargin;
2125                                 $this->lMargin = $this->original_lMargin;
2126                                 //set current position
2127                                 if ($this->rtl) {
2128                                         $this->SetXY($this->original_rMargin, $this->header_margin);
2129                                 } else {
2130                                         $this->SetXY($this->original_lMargin, $this->header_margin);
2131                                 }
2132                                 $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
2133                                 $this->Header1();
2134                                 //restore position
2135                                 if ($this->rtl) {
2136                                         $this->SetXY($this->original_rMargin, $this->tMargin);
2137                                 } else {
2138                                         $this->SetXY($this->original_lMargin, $this->tMargin);
2139                                 }
2140                                 $this->_out("Q");
2141                                 $this->lasth = $lasth;
2142                         }
2143                 }
2144
2145                 /**
2146                  * This method is used to render the page footer.
2147                  * @access protected
2148                  * @since 4.0.012 (2008-07-24)
2149                  */
2150                 function setFooter() {
2151                         //Page footer
2152                         $this->InFooter = true;
2153                         // mark this point
2154                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
2155                         if ($this->print_footer) {
2156                                 $lasth = $this->lasth;
2157                                 $this->_out("q");
2158                                 $this->rMargin = $this->original_rMargin;
2159                                 $this->lMargin = $this->original_lMargin;
2160                                 //set current position
2161                                 $footer_y = $this->h - $this->footer_margin;
2162                                 if ($this->rtl) {
2163                                         $this->SetXY($this->original_rMargin, $footer_y);
2164                                 } else {
2165                                         $this->SetXY($this->original_lMargin, $footer_y);
2166                                 }
2167                                 $this->SetFont($this->footer_font[0], $this->footer_font[1] , $this->footer_font[2]);
2168                                 $this->Footer();
2169                                 //restore position
2170                                 if ($this->rtl) {
2171                                         $this->SetXY($this->original_rMargin, $this->tMargin);
2172                                 } else {
2173                                         $this->SetXY($this->original_lMargin, $this->tMargin);
2174                                 }
2175                                 $this->_out("Q");
2176                                 $this->lasth = $lasth;
2177                         }
2178                         $this->footerlen[$this->page] = strlen($this->pages[$this->page]) - $this->footerpos[$this->page];
2179                         $this->InFooter = false;
2180                 }
2181
2182                 /**
2183                 * Returns the current page number.
2184                 * @return int page number
2185                 * @since 1.0
2186                 * @see AliasNbPages(), getAliasNbPages()
2187                 */
2188                 function PageNo() {
2189                         return $this->page;
2190                 }
2191
2192                 /**
2193                 * Defines a new spot color. 
2194                 * It can be expressed in RGB components or gray scale. 
2195                 * The method can be called before the first page is created and the value is retained from page to page.
2196                 * @param int $c Cyan color for CMYK. Value between 0 and 255
2197                 * @param int $m Magenta color for CMYK. Value between 0 and 255
2198                 * @param int $y Yellow color for CMYK. Value between 0 and 255
2199                 * @param int $k Key (Black) color for CMYK. Value between 0 and 255
2200                 * @since 4.0.024 (2008-09-12)
2201                 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2202                 */
2203                 function AddSpotColor($name, $c, $m, $y, $k) {
2204                         if (!isset($this->spot_colors[$name])) {
2205                                 $i = 1 + count($this->spot_colors);
2206                                 $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k);
2207                         }
2208                 }
2209
2210                 /**
2211                 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
2212                 * It can be expressed in RGB components or gray scale.
2213                 * The method can be called before the first page is created and the value is retained from page to page.
2214                 * @param array $color array of colors
2215                 * @since 3.1.000 (2008-06-11)
2216                 * @see SetDrawColor()
2217                 */
2218                 function SetDrawColorArray($color) {
2219                         if (isset($color)) {
2220                                 $color = array_values($color);
2221                                 $r = isset($color[0]) ? $color[0] : -1;
2222                                 $g = isset($color[1]) ? $color[1] : -1;
2223                                 $b = isset($color[2]) ? $color[2] : -1;
2224                                 $k = isset($color[3]) ? $color[3] : -1;
2225                                 if ($r >= 0) {
2226                                         $this->SetDrawColor($r, $g, $b, $k);
2227                                 }
2228                         }
2229                 }
2230
2231                 /**
2232                 * 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.
2233                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2234                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2235                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2236                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2237                 * @since 1.3
2238                 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
2239                 */
2240                 function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2241                         // set default values
2242                         if (!is_numeric($col1)) {
2243                                 $col1 = 0;
2244                         }
2245                         if (!is_numeric($col2)) {
2246                                 $col2 = -1;
2247                         }
2248                         if (!is_numeric($col3)) {
2249                                 $col3 = -1;
2250                         }
2251                         if (!is_numeric($col4)) {
2252                                 $col4 = -1;
2253                         }
2254                         //Set color for all stroking operations
2255                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2256                                 // Grey scale
2257                                 $this->DrawColor = sprintf('%.3f G', $col1/255);
2258                         } elseif ($col4 == -1) {
2259                                 // RGB
2260                                 $this->DrawColor = sprintf('%.3f %.3f %.3f RG', $col1/255, $col2/255, $col3/255);
2261                         } else {
2262                                 // CMYK
2263                                 $this->DrawColor = sprintf('%.3f %.3f %.3f %.3f K', $col1/100, $col2/100, $col3/100, $col4/100);
2264                         }
2265                         if ($this->page > 0) {
2266                                 $this->_out($this->DrawColor);
2267                         }
2268                 }
2269                 
2270                 /**
2271                 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
2272                 * @param string $name name of the spot color
2273                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2274                 * @since 4.0.024 (2008-09-12)
2275                 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
2276                 */
2277                 function SetDrawSpotColor($name, $tint=100) {
2278                         if (!isset($this->spot_colors[$name])) {
2279                                 $this->Error('Undefined spot color: '.$name);
2280                         }
2281                         $this->DrawColor = sprintf('/CS%d CS %.3f SCN', $this->spot_colors[$name]['i'], $tint/100);
2282                         if ($this->page > 0) {
2283                                 $this->_out($this->DrawColor);
2284                         }
2285                 }
2286
2287                 /**
2288                 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
2289                 * It can be expressed in RGB components or gray scale.
2290                 * The method can be called before the first page is created and the value is retained from page to page.
2291                 * @param array $color array of colors
2292                 * @since 3.1.000 (2008-6-11)
2293                 * @see SetFillColor()
2294                 */
2295                 function SetFillColorArray($color) {
2296                         if (isset($color)) {
2297                                 $color = array_values($color);
2298                                 $r = isset($color[0]) ? $color[0] : -1;
2299                                 $g = isset($color[1]) ? $color[1] : -1;
2300                                 $b = isset($color[2]) ? $color[2] : -1;
2301                                 $k = isset($color[3]) ? $color[3] : -1;
2302                                 if ($r >= 0) {
2303                                         $this->SetFillColor($r, $g, $b, $k);
2304                                 }
2305                         }
2306                 }
2307
2308                 /**
2309                 * 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.
2310                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2311                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2312                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2313                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2314                 * @since 1.3
2315                 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
2316                 */
2317                 function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2318                         // set default values
2319                         if (!is_numeric($col1)) {
2320                                 $col1 = 0;
2321                         }
2322                         if (!is_numeric($col2)) {
2323                                 $col2 = -1;
2324                         }
2325                         if (!is_numeric($col3)) {
2326                                 $col3 = -1;
2327                         }
2328                         if (!is_numeric($col4)) {
2329                                 $col4 = -1;
2330                         }
2331                         //Set color for all filling operations
2332                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2333                                 // Grey scale
2334                                 $this->FillColor = sprintf('%.3f g', $col1/255);
2335                                 $this->bgcolor = array('G' => $col1);
2336                         } elseif ($col4 == -1) {
2337                                 // RGB
2338                                 $this->FillColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2339                                 $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2340                         } else {
2341                                 // CMYK
2342                                 $this->FillColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2343                                 $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2344                         }
2345                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2346                         if ($this->page > 0) {
2347                                 $this->_out($this->FillColor);
2348                         }
2349                 }
2350                 
2351                 /**
2352                 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
2353                 * @param string $name name of the spot color
2354                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2355                 * @since 4.0.024 (2008-09-12)
2356                 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
2357                 */
2358                 function SetFillSpotColor($name, $tint=100) {
2359                         if (!isset($this->spot_colors[$name])) {
2360                                 $this->Error('Undefined spot color: '.$name);
2361                         }
2362                         $this->FillColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2363                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2364                         if ($this->page > 0) {
2365                                 $this->_out($this->FillColor);
2366                         }
2367                 }
2368
2369                 /**
2370                 * Defines the color used for text. It can be expressed in RGB components or gray scale.
2371                 * The method can be called before the first page is created and the value is retained from page to page.
2372                 * @param array $color array of colors
2373                 * @since 3.1.000 (2008-6-11)
2374                 * @see SetFillColor()
2375                 */
2376                 function SetTextColorArray($color) {
2377                         if (isset($color)) {
2378                                 $color = array_values($color);
2379                                 $r = isset($color[0]) ? $color[0] : -1;
2380                                 $g = isset($color[1]) ? $color[1] : -1;
2381                                 $b = isset($color[2]) ? $color[2] : -1;
2382                                 $k = isset($color[3]) ? $color[3] : -1;
2383                                 if ($r >= 0) {
2384                                         $this->SetTextColor($r, $g, $b, $k);
2385                                 }
2386                         }
2387                 }
2388
2389                 /**
2390                 * 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.
2391                 * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255
2392                 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255
2393                 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255
2394                 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255
2395                 * @since 1.3
2396                 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
2397                 */
2398                 function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1) {
2399                         // set default values
2400                         if (!is_numeric($col1)) {
2401                                 $col1 = 0;
2402                         }
2403                         if (!is_numeric($col2)) {
2404                                 $col2 = -1;
2405                         }
2406                         if (!is_numeric($col3)) {
2407                                 $col3 = -1;
2408                         }
2409                         if (!is_numeric($col4)) {
2410                                 $col4 = -1;
2411                         }
2412                         //Set color for text
2413                         if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
2414                                 // Grey scale
2415                                 $this->TextColor = sprintf('%.3f g', $col1/255);
2416                                 $this->fgcolor = array('G' => $col1);
2417                         } elseif ($col4 == -1) {
2418                                 // RGB
2419                                 $this->TextColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255);
2420                                 $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
2421                         } else {
2422                                 // CMYK
2423                                 $this->TextColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100);
2424                                 $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
2425                         }
2426                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2427                 }
2428
2429                 /**
2430                 * Defines the spot color used for text.
2431                 * @param string $name name of the spot color
2432                 * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
2433                 * @since 4.0.024 (2008-09-12)
2434                 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
2435                 */
2436                 function SetTextSpotColor($name, $tint=100) {
2437                         if (!isset($this->spot_colors[$name])) {
2438                                 $this->Error('Undefined spot color: '.$name);
2439                         }
2440                         $this->TextColor = sprintf('/CS%d cs %.3f scn', $this->spot_colors[$name]['i'], $tint/100);
2441                         $this->ColorFlag = ($this->FillColor != $this->TextColor);
2442                         if ($this->page > 0) {
2443                                 $this->_out($this->TextColor);
2444                         }
2445                 }
2446
2447                 /**
2448                 * Returns the length of a string in user unit. A font must be selected.<br>
2449                 * @param string $s The string whose length is to be computed
2450                 * @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.
2451                 * @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.
2452                 * @param float $fontsize Font size in points. The default value is the current size.
2453                 * @return int string length
2454                 * @author Nicola Asuni
2455                 * @since 1.2
2456                 */
2457                 function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0) {
2458                         return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $this->tmprtl), $fontname, $fontstyle, $fontsize);
2459                 }
2460
2461                 /**
2462                 * Returns the string length of an array of chars in user unit. A font must be selected.<br>
2463                 * @param string $arr The array of chars whose total length is to be computed
2464                 * @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.
2465                 * @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.
2466                 * @param float $fontsize Font size in points. The default value is the current size.
2467                 * @return int string length
2468                 * @author Nicola Asuni
2469                 * @since 2.4.000 (2008-03-06)
2470                 */
2471                 function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0) {
2472                         // store current values
2473                         if (!empty($fontname)) {
2474                                 $prev_FontFamily = $this->FontFamily;
2475                                 $prev_FontStyle = $this->FontStyle;
2476                                 $prev_FontSizePt = $this->FontSizePt;
2477                                 $this->SetFont($fontname, $fontstyle, $fontsize);
2478                         }
2479                         $w = 0;
2480                         foreach($sa as $char) {
2481                                 $w += $this->GetCharWidth($char);
2482                         }
2483                         // restore previous values
2484                         if (!empty($fontname)) {
2485                                 $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt);
2486                         }
2487                         return $w;
2488                 }
2489
2490                 /**
2491                 * Returns the length of the char in user unit for the current font.<br>
2492                 * @param int $char The char code whose length is to be returned
2493                 * @return int char width
2494                 * @author Nicola Asuni
2495                 * @since 2.4.000 (2008-03-06)
2496                 */
2497                 function GetCharWidth($char) {
2498                         $cw = &$this->CurrentFont['cw'];
2499                         if (isset($cw[$char])) {
2500                                 $w = $cw[$char];
2501                                 /*
2502                         } elseif (isset($cw[ord($char)])) {
2503                                 $w = $cw[ord($char)];
2504                         } elseif (isset($cw[chr($char)])) {
2505                                 $w = $cw[chr($char)];
2506                                 */
2507                         } elseif (isset($this->CurrentFont['dw'])) {
2508                                 $w = $this->CurrentFont['dw'];
2509                         } elseif (isset($this->CurrentFont['desc']['MissingWidth'])) {
2510                                 $w = $this->CurrentFont['desc']['MissingWidth']; // set default size
2511                         } else {
2512                                 $w = 500; // default width
2513                         }
2514                         return ($w * $this->FontSize / 1000);
2515                 }
2516
2517                 /**
2518                 * Returns the numbero of characters in a string.
2519                 * @param string $s The input string.
2520                 * @return int number of characters
2521                 * @since 2.0.0001 (2008-01-07)
2522                 */
2523                 function GetNumChars($s) {
2524                         if ($this->isunicode) {
2525                                 return count($this->UTF8StringToArray($s));
2526                         }
2527                         return strlen($s);
2528                 }
2529
2530                 /**
2531                 * Fill the list of available fonts ($this->fontlist).
2532                 * @access protected
2533                 * @since 4.0.013 (2008-07-28)
2534                 */
2535                 function getFontsList() {
2536                         $fontsdir = opendir($this->_getfontpath());
2537                         while (($file = readdir($fontsdir)) !== false) {
2538                                 if (substr($file, -4) == ".php") {
2539                                                 array_push($this->fontlist, strtolower(basename($file, ".php")));
2540                                 }
2541                         }
2542                         closedir($fontsdir);
2543                 }
2544
2545                 /**
2546                 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
2547                 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
2548                 * 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.
2549                 * Changed to support UTF-8 Unicode [Nicola Asuni, 2005-01-02].
2550                 * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
2551                 * @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>
2552                 * @param string $file The font definition file. By default, the name is built from the family and style, in lower case with no space.
2553                 * @return array containing the font data, or false in case of error.
2554                 * @since 1.5
2555                 * @see SetFont()
2556                 */
2557                 function AddFont($family, $style='', $file='') {
2558                         if (empty($family)) {
2559                                 if (!empty($this->FontFamily)) {
2560                                         $family = $this->FontFamily;
2561                                 } else {
2562                                         $this->Error('Empty font family');
2563                                 }
2564                         }
2565                         $family = strtolower($family);
2566                         if ((!$this->isunicode) AND ($family == 'arial')) {
2567                                 $family = 'helvetica';
2568                         }
2569                         if (($family == "symbol") OR ($family == "zapfdingbats")) {
2570                                 $style = '';
2571                         }
2572                         $style = strtoupper($style);
2573                         // underline
2574                         if (strpos($style,'U') !== false) {
2575                                 $this->underline = true;
2576                                 $style = str_replace('U', '', $style);
2577                         } else {
2578                                 $this->underline = false;
2579                         }
2580                         //line through (deleted)
2581                         if (strpos($style,'D') !== false) {
2582                                 $this->linethrough = true;
2583                                 $style = str_replace('D', '', $style);
2584                         } else {
2585                                 $this->linethrough = false;
2586                         }
2587                         if ($style == 'IB') {
2588                                 $style = 'BI';
2589                         }
2590                         $fontkey = $family.$style;
2591                         $fontdata = array("fontkey" => $fontkey, "family" => $family, "style" => $style);
2592                         // check if the font has been already added
2593                         if (isset($this->fonts[$fontkey])) {
2594                                 return $fontdata;
2595                         }
2596                         if ($file == '') {
2597                                 $file = str_replace(' ', '', $family).strtolower($style).'.php';
2598                         }
2599                         if (!file_exists($this->_getfontpath().$file)) {
2600                                 // try to load the basic file without styles
2601                                 $file = str_replace(' ', '', $family).'.php';
2602                         }
2603                         if (isset($type)) {
2604                                 unset($type);
2605                         }
2606                         if (isset($cw)) {
2607                                 unset($cw);
2608                         }
2609                         @include($this->_getfontpath().$file);
2610                         if ((!isset($type)) OR (!isset($cw))) {
2611                                 $this->Error("Could not include font definition file: ".$file);
2612                         }
2613                         $i = count($this->fonts) + 1;
2614                         // register CID font (all styles at once)
2615                         if ($type == 'cidfont0') {
2616                                 $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
2617                                 foreach ($styles as $skey => $qual) {
2618                                         $sname = $name.$qual;
2619                                         $sfontkey = $family.$skey;
2620                                         $this->fonts[$sfontkey] = array('i' => $i, 'type' => $type, 'name' => $sname, 'desc' => $desc, 'cidinfo' => $cidinfo, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc);
2621                                         $i = count($this->fonts) + 1;
2622                                 }
2623                                 $file = '';
2624                         } elseif ($type == 'core') {
2625                                 $def_width = $cw[ord('?')];
2626                                 $this->fonts[$fontkey] = array('i' => $i, 'type' => 'core', 'name' => $this->CoreFonts[$fontkey], 'up' => -100, 'ut' => 50, 'cw' => $cw, 'dw' => $def_width);
2627                         } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
2628                                 if (!isset($file)) {
2629                                         $file = '';
2630                                 }
2631                                 if (!isset($enc)) {
2632                                         $enc = '';
2633                                 }
2634                                 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'file' => $file, 'enc' => $enc, 'desc' => $desc);
2635                         } elseif ($type == 'TrueTypeUnicode') {
2636                                 $this->fonts[$fontkey] = array('i' => $i, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'enc' => $enc, 'file' => $file, 'ctg' => $ctg);
2637                         } else {
2638                                 $this->Error('Unknow font type');
2639                         }
2640                         if (isset($diff) AND (!empty($diff))) {
2641                                 //Search existing encodings
2642                                 $d = 0;
2643                                 $nb = count($this->diffs);
2644                                 for($i=1; $i <= $nb; $i++) {
2645                                         if ($this->diffs[$i] == $diff) {
2646                                                 $d = $i;
2647                                                 break;
2648                                         }
2649                                 }
2650                                 if ($d == 0) {
2651                                         $d = $nb + 1;
2652                                         $this->diffs[$d] = $diff;
2653                                 }
2654                                 $this->fonts[$fontkey]['diff'] = $d;
2655                         }
2656                         if (!empty($file)) {
2657                                 if ((strcasecmp($type,"TrueType") == 0) OR (strcasecmp($type,"TrueTypeUnicode") == 0)) {
2658                                         $this->FontFiles[$file] = array('length1' => $originalsize);
2659                                 } elseif ($type != 'core') {
2660                                         $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2);
2661                                 }
2662                         }
2663                         return $fontdata;
2664                 }
2665
2666                 /**
2667                 * Sets the font used to print character strings.
2668                 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
2669                 * The method can be called before the first page is created and the font is retained from page to page.
2670                 * If you just wish to change the current font size, it is simpler to call SetFontSize().
2671                 * 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 />
2672                 * @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.
2673                 * @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.
2674                 * @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
2675                 * @since 1.0
2676                 * @see AddFont(), SetFontSize()
2677                 */
2678                 function SetFont($family, $style='', $size=0) {
2679                         //Select a font; size given in points
2680                         if ($size == 0) {
2681                                 $size = $this->FontSizePt;
2682                         }
2683                         // try to add font (if not already added)
2684                         $fontdata =  $this->AddFont($family, $style);
2685                         $this->FontFamily = $fontdata['family'];
2686                         $this->FontStyle = $fontdata['style'];
2687                         $this->CurrentFont = &$this->fonts[$fontdata['fontkey']];
2688                         $this->SetFontSize($size);
2689                 }
2690
2691                 /**
2692                 * Defines the size of the current font.
2693                 * @param float $size The size (in points)
2694                 * @since 1.0
2695                 * @see SetFont()
2696                 */
2697                 function SetFontSize($size) {
2698                         //Set font size in points
2699                         $this->FontSizePt = $size;
2700                         $this->FontSize = $size / $this->k;
2701                         if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
2702                                 $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000;
2703                         } else {
2704                                 $this->FontAscent = 0.8 * $this->FontSize;
2705                         }
2706                         if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] > 0)) {
2707                                 $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000;
2708                         } else {
2709                                 $this->FontDescent = 0.2 * $this->FontSize;
2710                         }
2711                         if (($this->page > 0) AND (isset($this->CurrentFont['i']))) {
2712                                 $this->_out(sprintf('BT /F%d %.2f Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
2713                         }
2714                 }
2715
2716                 /**
2717                 * 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 />
2718                 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
2719                 * @since 1.5
2720                 * @see Cell(), Write(), Image(), Link(), SetLink()
2721                 */
2722                 function AddLink() {
2723                         //Create a new internal link
2724                         $n = count($this->links) + 1;
2725                         $this->links[$n] = array(0, 0);
2726                         return $n;
2727                 }
2728
2729                 /**
2730                 * Defines the page and position a link points to.
2731                 * @param int $link The link identifier returned by AddLink()
2732                 * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
2733                 * @param int $page Number of target page; -1 indicates the current page. This is the default value
2734                 * @since 1.5
2735                 * @see AddLink()
2736                 */
2737                 function SetLink($link, $y=0, $page=-1) {
2738                         if ($y == -1) {
2739                                 $y = $this->y;
2740                         }
2741                         if ($page == -1) {
2742                                 $page = $this->page;
2743                         }
2744                         $this->links[$link] = array($page, $y);
2745                 }
2746
2747                 /**
2748                 * Puts a link on a rectangular area of the page.
2749                 * 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.
2750                 * @param float $x Abscissa of the upper-left corner of the rectangle
2751                 * @param float $y Ordinate of the upper-left corner of the rectangle
2752                 * @param float $w Width of the rectangle
2753                 * @param float $h Height of the rectangle
2754                 * @param mixed $link URL or identifier returned by AddLink()
2755                 * @since 1.5
2756                 * @see AddLink(), Annotation(), Cell(), Write(), Image()
2757                 */
2758                 function Link($x, $y, $w, $h, $link) {
2759                         $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'));
2760                 }
2761                 
2762                 /**
2763                 * Puts a text annotation on a rectangular area of the page.
2764                 * !!!! THIS FUNCTION IS NOT YET FULLY IMPLEMENTED !!!!
2765                 * @param float $x Abscissa of the upper-left corner of the rectangle
2766                 * @param float $y Ordinate of the upper-left corner of the rectangle
2767                 * @param float $w Width of the rectangle
2768                 * @param float $h Height of the rectangle
2769                 * @param string $text annotation text
2770                 * @param array $opt array of options (see section 8.4 of PDF reference 1.7).
2771                 * @since 4.0.018 (2008-08-06)
2772                 */
2773                 function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text')) {
2774                         $this->PageAnnots[$this->page][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt);
2775                 }
2776
2777                 /**
2778                 * 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.
2779                 * @param float $x Abscissa of the origin
2780                 * @param float $y Ordinate of the origin
2781                 * @param string $txt String to print
2782                 * @param int $stroke outline size in points (0 = disable)
2783                 * @param boolean $clip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
2784                 * @since 1.0
2785                 * @see SetFont(), SetTextColor(), Cell(), MultiCell(), Write()
2786                 */
2787                 function Text($x, $y, $txt, $stroke=0, $clip=false) {
2788                         //Output a string
2789                         if ($this->rtl) {
2790                                 // bidirectional algorithm (some chars may be changed affecting the line length)
2791                                 $s = $this->utf8Bidi($this->UTF8StringToArray($txt), $this->tmprtl);
2792                                 $l = $this->GetArrStringWidth($s);
2793                                 $xr = $this->w - $x - $this->GetArrStringWidth($s);
2794                         } else {
2795                                 $xr = $x;
2796                         }
2797                         $opt = "";
2798                         if (($stroke > 0) AND (!$clip)) {
2799                                 $opt .= "1 Tr ".intval($stroke)." w ";
2800                         } elseif (($stroke > 0) AND $clip) {
2801                                 $opt .= "5 Tr ".intval($stroke)." w ";
2802                         } elseif ($clip) {
2803                                 $opt .= "7 Tr ";
2804                         }
2805                         $s = sprintf('BT %.2f %.2f Td %s(%s) Tj ET 0 Tr', $xr * $this->k, ($this->h-$y) * $this->k, $opt, $this->_escapetext($txt));
2806                         if ($this->underline AND ($txt!='')) {
2807                                 $s .= ' '.$this->_dounderline($xr, $y, $txt);
2808                         }
2809                         if ($this->linethrough AND ($txt!='')) {
2810                                 $s .= ' '.$this->_dolinethrough($xr, $y, $txt);
2811                         }
2812                         if ($this->ColorFlag AND (!$clip)) {
2813                                 $s='q '.$this->TextColor.' '.$s.' Q';
2814                         }
2815                         $this->_out($s);
2816                 }
2817
2818                 /**
2819                 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
2820                 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
2821                 * This method is called automatically and should not be called directly by the application.
2822                 * @return boolean
2823                 * @since 1.4
2824                 * @see SetAutoPageBreak()
2825                 */
2826                 function AcceptPageBreak() {
2827                         return $this->AutoPageBreak;
2828                 }
2829
2830                 /**
2831                 * Add page if needed.
2832                 * @param float $h Cell height. Default value: 0.
2833                 * @since 3.2.000 (2008-07-01)
2834                 * @access protected
2835                 */
2836                 function checkPageBreak($h) {
2837                         if ((($this->y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
2838                                 $rs = "";
2839                                 //Automatic page break
2840                                 $x = $this->x;
2841                                 $ws = $this->ws;
2842                                 if ($ws > 0) {
2843                                         $this->ws = 0;
2844                                         $rs .= '0 Tw';
2845                                 }
2846                                 $this->AddPage($this->CurOrientation);
2847                                 if ($ws > 0) {
2848                                         $this->ws = $ws;
2849                                         $rs .= sprintf('%.3f Tw', $ws * $k);
2850                                 }
2851                                 $this->_out($rs);
2852                                 $this->y = $this->tMargin;
2853                                 $this->x = $x;
2854                         }
2855                 }
2856
2857                 /**
2858                 * 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 />
2859                 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2860                 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2861                 * @param float $h Cell height. Default value: 0.
2862                 * @param string $txt String to print. Default value: empty string.
2863                 * @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>
2864                 * @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>
2865                 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
2866                 * @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>
2867                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2868                 * @param mixed $link URL or identifier returned by AddLink().
2869                 * @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>
2870                 * @since 1.0
2871                 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
2872                 */
2873                 function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2874                         //$min_cell_height = $this->FontAscent + $this->FontDescent;
2875                         $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2876                         if ($h < $min_cell_height) {
2877                                 $h = $min_cell_height;
2878                         }
2879                         $this->checkPageBreak($h);
2880                         $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch));
2881                 }
2882
2883                 /**
2884                 * 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 />
2885                 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
2886                 * @param float $w Cell width. If 0, the cell extends up to the right margin.
2887                 * @param float $h Cell height. Default value: 0.
2888                 * @param string $txt String to print. Default value: empty string.
2889                 * @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>
2890                 * @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.
2891                 * @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>
2892                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
2893                 * @param mixed $link URL or identifier returned by AddLink().
2894                 * @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>
2895                 * @since 1.0
2896                 * @see Cell()
2897                 */
2898                 function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
2899                         $rs = ""; //string to be returned
2900                         $min_cell_height = $this->FontSize * $this->cell_height_ratio;
2901                         if ($h < $min_cell_height) {
2902                                 $h = $min_cell_height;
2903                         }
2904                         $k = $this->k;
2905                         if (empty($w) OR ($w <= 0)) {
2906                                 if ($this->rtl) {
2907                                         $w = $this->x - $this->lMargin;
2908                                 } else {
2909                                         $w = $this->w - $this->rMargin - $this->x;
2910                                 }
2911                         }
2912                         $s = '';
2913                         if (($fill == 1) OR ($border == 1)) {
2914                                 if ($fill == 1) {
2915                                         $op = ($border == 1) ? 'B' : 'f';
2916                                 } else {
2917                                         $op = 'S';
2918                                 }
2919                                 if ($this->rtl) {
2920                                         $xk = (($this->x  - $w) * $k);
2921                                 } else {
2922                                         $xk = ($this->x * $k);
2923                                 }
2924                                 $s .= sprintf('%.2f %.2f %.2f %.2f re %s ', $xk, (($this->h - $this->y) * $k), ($w * $k), (-$h * $k), $op);
2925                         }
2926
2927                         if (is_string($border)) {
2928                                 $x = $this->x;
2929                                 $y = $this->y;
2930                                 if (strpos($border,'L') !== false) {
2931                                         if ($this->rtl) {
2932                                                 $xk = ($x - $w) * $k;
2933                                         } else {
2934                                                 $xk = $x * $k;
2935                                         }
2936                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h)) * $k));
2937                                 }
2938                                 if (strpos($border,'T') !== false) {
2939                                         if ($this->rtl) {
2940                                                 $xk = ($x - $w) * $k;
2941                                                 $xwk = $x * $k;
2942                                         } else {
2943                                                 $xk = $x * $k;
2944                                                 $xwk = ($x + $w) * $k;
2945                                         }
2946                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xwk, (($this->h - $y) * $k));
2947                                 }
2948                                 if (strpos($border,'R') !== false) {
2949                                         if ($this->rtl) {
2950                                                 $xk = $x * $k;
2951                                         } else {
2952                                                 $xk = ($x + $w) * $k;
2953                                         }
2954                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - $y) * $k), $xk, (($this->h - ($y + $h))* $k));
2955                                 }
2956                                 if (strpos($border,'B') !== false) {
2957                                         if ($this->rtl) {
2958                                                 $xk = ($x - $w) * $k;
2959                                                 $xwk = $x * $k;
2960                                         } else {
2961                                                 $xk = $x * $k;
2962                                                 $xwk = ($x + $w) * $k;
2963                                         }
2964                                         $s .= sprintf('%.2f %.2f m %.2f %.2f l S ', $xk, (($this->h - ($y + $h)) * $k), $xwk, (($this->h - ($y + $h)) * $k));
2965                                 }
2966                         }
2967                         if ($txt != '') {
2968                                 // text lenght
2969                                 $width = $this->GetStringWidth($txt);
2970                                 // ratio between cell lenght and text lenght
2971                                 $ratio = ($w - (2 * $this->cMargin)) / $width;
2972
2973                                 // stretch text if required
2974                                 if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) {
2975                                         if ($stretch > 2) {
2976                                                 // spacing
2977                                                 //Calculate character spacing in points
2978                                                 $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1);
2979                                                 //Set character spacing
2980                                                 $rs .= sprintf('BT %.2f Tc ET ', $char_space);
2981                                         } else {
2982                                                 // scaling
2983                                                 //Calculate horizontal scaling
2984                                                 $horiz_scale = $ratio * 100.0;
2985                                                 //Set horizontal scaling
2986                                                 $rs .= sprintf('BT %.2f Tz ET ', $horiz_scale);
2987                                         }
2988                                         $align = '';
2989                                         $width = $w - (2 * $this->cMargin);
2990                                 } else {
2991                                         $stretch == 0;
2992                                 }
2993                                 if ($align == 'L') {
2994                                         if ($this->rtl) {
2995                                                 $dx = $w - $width - $this->cMargin;
2996                                         } else {
2997                                                 $dx = $this->cMargin;
2998                                         }
2999                                 } elseif ($align == 'R') {
3000                                         if ($this->rtl) {
3001                                                 $dx = $this->cMargin;
3002                                         } else {
3003                                                 $dx = $w - $width - $this->cMargin;
3004                                         }
3005                                 } elseif ($align == 'C') {
3006                                         $dx = ($w - $width) / 2;
3007                                 } elseif ($align == 'J') {
3008                                         if ($this->rtl) {
3009                                                 $dx = $w - $width - $this->cMargin;
3010                                         } else {
3011                                                 $dx = $this->cMargin;
3012                                         }
3013                                 } else {
3014                                         $dx = $this->cMargin;
3015                                 }
3016                                 if ($this->ColorFlag) {
3017                                         $s .= 'q '.$this->TextColor.' ';
3018                                 }
3019                                 $txt2 = $this->_escapetext($txt);
3020                                 if ($this->rtl) {
3021                                         $xdk = ($this->x - $dx - $width) * $k;
3022                                 } else {
3023                                         $xdk = ($this->x + $dx) * $k;
3024                                 }
3025                                 // Justification
3026                                 if ($align == 'J') {
3027                                         // count number of spaces
3028                                         $ns = substr_count($txt, ' ');
3029                                         //if ($this->isunicode) {
3030                                         if (($this->CurrentFont['type'] == "TrueTypeUnicode") OR ($this->CurrentFont['type'] == "cidfont0")) {
3031                                                 // get string width without spaces
3032                                                 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
3033                                                 // calculate average space width
3034                                                 $spacewidth = ($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1) / $this->FontSize / $this->k;
3035                                                 // set word position to be used with TJ operator
3036                                                 $txt2 = str_replace(chr(0).' ', ') '.(-2830 * $spacewidth).' (', $txt2);
3037                                         } else {
3038                                                 // get string width
3039                                                 $width = $this->GetStringWidth($txt);
3040                                                 $spacewidth = (($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1)) * $this->k;
3041                                                 $rs .= sprintf('BT %.3f Tw ET ', $spacewidth);
3042                                         }
3043                                 }
3044                                 // calculate approximate position of the font base line
3045                                 //$basefonty = $this->y + (($h + $this->FontAscent - $this->FontDescent)/2);
3046                                 $basefonty = $this->y + ($h/2) + ($this->FontSize/3);
3047                                 // print text
3048                                 $s .= sprintf('BT %.2f %.2f Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
3049                                 if ($this->rtl) {
3050                                         $xdx = $this->x - $dx - $width;
3051                                 } else {
3052                                         $xdx = $this->x + $dx;
3053                                 }
3054                                 if ($this->underline)  {
3055                                         $s .= ' '.$this->_dounderline($xdx, $basefonty, $txt);
3056                                 }
3057                                 if ($this->linethrough) {
3058                                         $s .= ' '.$this->_dolinethrough($xdx, $basefonty, $txt);
3059                                 }
3060                                 if ($this->ColorFlag) {
3061                                         $s .= ' Q';
3062                                 }
3063                                 if ($link) {
3064                                         $this->Link($xdx, $this->y + (($h - $this->FontSize)/2), $width, $this->FontSize, $link);
3065                                 }
3066                         }
3067                         // output cell
3068                         if ($s) {
3069                                 // output cell
3070                                 $rs .= $s;
3071                                 // reset text stretching
3072                                 if ($stretch > 2) {
3073                                         //Reset character horizontal spacing
3074                                         $rs .= ' BT 0 Tc ET';
3075                                 } elseif ($stretch > 0) {
3076                                         //Reset character horizontal scaling
3077                                         $rs .= ' BT 100 Tz ET';
3078                                 }
3079                         }
3080                         // reset word spacing
3081                         if ((!$this->isunicode) AND ($align == 'J')) {
3082                                 $rs .= ' BT 0 Tw ET';
3083                         }
3084                         $this->lasth = $h;
3085                         if ($ln > 0) {
3086                                 //Go to the beginning of the next line
3087                                 $this->y += $h;
3088                                 if ($ln == 1) {
3089                                         if ($this->rtl) {
3090                                                 $this->x = $this->w - $this->rMargin;
3091                                         } else {
3092                                                 $this->x = $this->lMargin;
3093                                         }
3094                                 }
3095                         } else {
3096                                 // go left or right by case
3097                                 if ($this->rtl) {
3098                                         $this->x -= $w;
3099                                 } else {
3100                                         $this->x += $w;
3101                                 }
3102                         }
3103                         $gstyles = $this->linestyleWidth." ".$this->linestyleCap." ".$this->linestyleJoin." ".$this->linestyleDash." ".$this->DrawColor." ".$this->FillColor."\n";
3104                         $rs = $gstyles.$rs;
3105                         return $rs;
3106                 }
3107
3108                 /**
3109                 * This method allows printing text with line breaks.
3110                 * 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 />
3111                 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
3112                 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
3113                 * @param float $h Cell minimum height. The cell extends automatically if needed.
3114                 * @param string $txt String to print
3115                 * @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>
3116                 * @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>
3117                 * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
3118                 * @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>
3119                 * @param int $x x position in user units
3120                 * @param int $y y position in user units
3121                 * @param boolean $reseth if true reset the last cell height (default true).
3122                 * @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>
3123                 * @param boolean $ishtml se to true if $txt is HTML content (default = false).
3124                 * @return int Return the number of cells or 1 for html mode.
3125                 * @since 1.3
3126                 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
3127                 */
3128                 function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false) {
3129                         if ((empty($this->lasth))OR ($reseth)) {
3130                                 //set row height
3131                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
3132                         }
3133                         if (!empty($y)) {
3134                                 $this->SetY($y);
3135                         } else {
3136                                 $y = $this->GetY();
3137                         }
3138                         // check for page break
3139                         $this->checkPageBreak($h);
3140                         $y = $this->GetY();
3141                         // get current page number
3142                         $startpage = $this->page;
3143                         if (!empty($x)) {
3144                                 $this->SetX($x);
3145                         } else {
3146                                 $x = $this->GetX();
3147                         }
3148                         if (empty($w) OR ($w <= 0)) {
3149                                 if ($this->rtl) {
3150                                         $w = $this->x - $this->lMargin;
3151                                 } else {
3152                                         $w = $this->w - $this->rMargin - $this->x;
3153                                 }
3154                         }
3155                         // store original margin values
3156                         $lMargin = $this->lMargin;
3157                         $rMargin = $this->rMargin;
3158                         if ($this->rtl) {
3159                                 $this->SetRightMargin($this->w - $this->x);
3160                                 $this->SetLeftMargin($this->x - $w);
3161                         } else {
3162                                 $this->SetLeftMargin($this->x);
3163                                 $this->SetRightMargin($this->w - $this->x - $w);
3164                         }
3165                         // calculate remaining vertical space on first page ($startpage)
3166                         $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin();
3167                         // Adjust internal padding
3168                         if ($this->cMargin < ($this->LineWidth / 2)) {
3169                                 $this->cMargin = ($this->LineWidth / 2);
3170                         }
3171                         // Add top space if needed
3172                         if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3173                                 $this->y += $this->LineWidth / 2;
3174                         }
3175                         // add top padding
3176                         $this->y += $this->cMargin;
3177                         if ($ishtml) {
3178                                 // Write HTML text
3179                                 $this->writeHTML($txt, true, 0, $reseth, true, $align);
3180                                 $nl = 1;
3181                         } else {
3182                                 // Write text
3183                                 $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false);
3184                         }
3185                         // add bottom padding
3186                         $this->y += $this->cMargin;
3187                         // Add bottom space if needed
3188                         if (($this->lasth - $this->FontSize) < $this->LineWidth) {
3189                                 $this->y += $this->LineWidth / 2;
3190                         }
3191                         // Get end-of-text Y position
3192                         $currentY = $this->GetY();
3193                         // get latest page number
3194                         $endpage = $this->page;
3195                         // check if a new page has been created
3196                         if ($endpage > $startpage) {
3197                                 // design borders around HTML cells.
3198                                 for ($page=$startpage; $page <= $endpage; $page++) {
3199                                         $this->setPage($page);
3200                                         if ($page == $startpage) {
3201                                                 $this->SetY($this->getPageHeight() - $restspace - $this->getBreakMargin());
3202                                                 $h = $restspace;
3203                                         } elseif ($page == $endpage) {
3204                                                 $this->SetY($this->tMargin); // put cursor at the beginning of text
3205                                                 $h = $currentY - $this->tMargin;
3206                                         } else {
3207                                                 $this->SetY($this->tMargin); // put cursor at the beginning of text
3208                                                 $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
3209                                         }
3210                                         $this->SetX($x);
3211                                         $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3212                                         if ($border OR $fill) {
3213                                                 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3214                                                 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3215                                                 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3216                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
3217                                         }
3218                                 }
3219                         } else {
3220                                 $h = max($h, ($currentY - $y));
3221                                 // put cursor at the beginning of text
3222                                 $this->SetY($y);
3223                                 $this->SetX($x);
3224                                 $ccode = $this->getCellCode($w, $h, "", $border, 1, '', $fill);
3225                                 if ($border OR $fill) {
3226                                         // design a cell around the text
3227                                         $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
3228                                         $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
3229                                         $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
3230                                         $this->intmrk[$this->page] += strlen($ccode."\n");
3231                                 }
3232                         }
3233                         // Get end-of-cell Y position
3234                         $currentY = $this->GetY();
3235                         // restore original margin values
3236                         $this->SetLeftMargin($lMargin);
3237                         $this->SetRightMargin($rMargin);
3238                         if ($ln > 0) {
3239                                 //Go to the beginning of the next line
3240                                 $this->SetY($currentY);
3241                                 if ($ln == 2) {
3242                                         $this->SetX($x + $w);
3243                                 }
3244                         } else {
3245                                 // go left or right by case
3246                                 $this->setPage($startpage);
3247                                 $this->y = $y;
3248                                 $this->SetX($x + $w);
3249                         }
3250                         return $nl;
3251                 }
3252
3253                 /**
3254                 * This method prints text from the current position.<br />
3255                 * @param float $h Line height
3256                 * @param string $txt String to print
3257                 * @param mixed $link URL or identifier returned by AddLink()
3258                 * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
3259                 * @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>
3260                 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
3261                 * @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>
3262                 * @param boolean $firstline if true prints only the first line and return the remaining string.
3263                 * @return mixed Return the number of cells or the remaining string if $firstline = true.
3264                 * @since 1.5
3265                 */
3266                 function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false) {
3267                         // remove carriage returns
3268                         $s = str_replace("\r", '', $txt);
3269                         // check if string contains arabic text
3270                         if (preg_match(K_RE_PATTERN_ARABIC, $s)) {
3271                                 $arabic = true;
3272                         } else {
3273                                 $arabic = false;
3274                         }
3275                         // get array of chars
3276                         $chars = $this->UTF8StringToArray($s);
3277                         // get the number of characters
3278                         $nb = count($chars);
3279                         // handle single space character
3280                         if (($nb == 1) AND preg_match("/[\s]/u", $s)) {
3281                                 if ($this->rtl) {
3282                                         $this->x -= $this->GetStringWidth($s);
3283                                 } else {
3284                                         $this->x += $this->GetStringWidth($s);
3285                                 }
3286                                 return;
3287                         }
3288                         // store current position
3289                         $prevx = $this->x;
3290                         $prevy = $this->y;
3291                         // calculate remaining line width ($w)
3292                         if ($this->rtl) {
3293                                 $w = $this->x - $this->lMargin;
3294                         } else {
3295                                 $w = $this->w - $this->rMargin - $this->x;
3296                         }
3297                         // max column width
3298                         $wmax = $w - (2 * $this->cMargin);
3299                         $i = 0; // character position
3300                         $j = 0; // current starting position
3301                         $sep = -1; // position of the last blank space
3302                         $l = 0; // current string lenght
3303                         $nl = 0; //number of lines
3304                         $linebreak = false;
3305                         // for each character
3306                         while ($i < $nb) {
3307                                 //Get the current character
3308                                 $c = $chars[$i];
3309                                 if ($c == 10) { // 10 = "\n" = new line
3310                                         //Explicit line break
3311                                         if ($align == "J") {
3312                                                 if ($this->rtl) {
3313                                                         $talign = "R";
3314                                                 } else {
3315                                                         $talign = "L";
3316                                                 }
3317                                         } else {
3318                                                 $talign = $align;
3319                                         }
3320                                         if ($firstline) {
3321                                                 $startx = $this->x;
3322                                                 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3323                                                 if ($this->rtl) {
3324                                                         $this->endlinex = $startx - $linew;
3325                                                 } else {
3326                                                         $this->endlinex = $startx + $linew;
3327                                                 }
3328                                                 $w = $linew;
3329                                                 $tmpcmargin = $this->cMargin;
3330                                                 $this->cMargin = 0;
3331                                         }
3332                                         $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $talign, $fill, $link, $stretch);
3333                                         if ($firstline) {
3334                                                 $this->cMargin = $tmpcmargin;
3335                                                 return ($this->UTF8ArrSubString($chars, $i));
3336                                         }
3337                                         $nl++;
3338                                         $j = $i + 1;
3339                                         $l = 0;
3340                                         $sep = -1;
3341                                         $w = $this->getRemainingWidth();
3342                                         $wmax = $w - (2 * $this->cMargin);
3343                                 } else {
3344                                         if (preg_match("/[\s]/u", $this->unichr($c))) {
3345                                                 // update last blank space position
3346                                                 $sep = $i;
3347                                         }
3348                                         // update string length
3349                                         if (($this->isunicode) AND ($arabic)) {
3350                                                 // with bidirectional algorithm some chars may be changed affecting the line length
3351                                                 // *** very slow ***
3352                                                 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), $this->tmprtl));
3353                                         } else {
3354                                                 $l += $this->GetCharWidth($c);
3355                                         }
3356                                         if ($l > $wmax) {
3357                                                 // we have reached the end of column
3358                                                 if ($sep == -1) {
3359                                                         // check if the line was already started
3360                                                         if (($this->rtl AND ($this->x < ($this->w - $this->rMargin)))
3361                                                                 OR ((!$this->rtl) AND ($this->x > $this->lMargin))) {
3362                                                                 // print a void cell and go to next line
3363                                                                 $this->Cell($w, $h, "", 0, 1);
3364                                                                 $linebreak = true;
3365                                                                 if ($firstline) {
3366                                                                         return ($this->UTF8ArrSubString($chars, $j));
3367                                                                 }
3368                                                         } else {
3369                                                                 // truncate the word because do not fit on column
3370                                                                 if ($firstline) {
3371                                                                         $startx = $this->x;
3372                                                                         $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i), $this->tmprtl));
3373                                                                         if ($this->rtl) {
3374                                                                                 $this->endlinex = $startx - $linew;
3375                                                                         } else {
3376                                                                                 $this->endlinex = $startx + $linew;
3377                                                                         }
3378                                                                         $w = $linew;
3379                                                                         $tmpcmargin = $this->cMargin;
3380                                                                         $this->cMargin = 0;
3381                                                                 }
3382                                                                 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $align, $fill, $link, $stretch);
3383                                                                 if ($firstline) {
3384                                                                         $this->cMargin = $tmpcmargin;
3385                                                                         return ($this->UTF8ArrSubString($chars, $i));
3386                                                                 }
3387                                                                 $j = $i;
3388                                                                 $i--;
3389                                                         }
3390                                                 } else {
3391                                                         // word wrapping
3392                                                         if ($firstline) {
3393                                                                 $startx = $this->x;
3394                                                                 $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $sep), $this->tmprtl));
3395                                                                 if ($this->rtl) {
3396                                                                         $this->endlinex = $startx - $linew;
3397                                                                 } else {
3398                                                                         $this->endlinex = $startx + $linew;
3399                                                                 }
3400                                                                 $w = $linew;
3401                                                                 $tmpcmargin = $this->cMargin;
3402                                                                 $this->cMargin = 0;
3403                                                         }
3404                                                         $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $sep), 0, 1, $align, $fill, $link, $stretch);
3405                                                         if ($firstline) {
3406                                                                 $this->cMargin = $tmpcmargin;
3407                                                                 return ($this->UTF8ArrSubString($chars, $sep));
3408                                                         }
3409                                                         $i = $sep;
3410                                                         $sep = -1;
3411                                                         $j = ($i+1);
3412                                                 }
3413                                                 $w = $this->getRemainingWidth();
3414                                                 $wmax = $w - (2 * $this->cMargin);
3415                                                 if ($linebreak) {
3416                                                         $linebreak = false;
3417                                                 } else {
3418                                                         $nl++;
3419                                                         $l = 0;
3420                                                 }
3421                                         }
3422                                 }
3423                                 $i++;
3424                         } // end while i < nb
3425                         // print last substring (if any)
3426                         if ($l > 0) {
3427                                 switch ($align) {
3428                                         case "J":
3429                                         case "C": {
3430                                                 $w = $w;
3431                                                 break;
3432                                         }
3433                                         case "L": {
3434                                                 if ($this->rtl) {
3435                                                         $w = $w;
3436                                                 } else {
3437                                                         $w = $l;
3438                                                 }
3439                                                 break;
3440                                         }
3441                                         case "R": {
3442                                                 if ($this->rtl) {
3443                                                         $w = $l;
3444                                                 } else {
3445                                                         $w = $w;
3446                                                 }
3447                                                 break;
3448                                         }
3449                                         default: {
3450                                                 $w = $l;
3451                                                 break;
3452                                         }
3453                                 }
3454                                 if ($firstline) {
3455                                         $startx = $this->x;
3456                                         $linew = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $nb), $this->tmprtl));
3457                                         if ($this->rtl) {
3458                                                 $this->endlinex = $startx - $linew;
3459                                         } else {
3460                                                 $this->endlinex = $startx + $linew;
3461                                         }
3462                                         $w = $linew;
3463                                         $tmpcmargin = $this->cMargin;
3464                                         $this->cMargin = 0;
3465                                 }
3466                                 $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $nb), 0, $ln, $align, $fill, $link, $stretch);
3467                                 if ($firstline) {
3468                                         $this->cMargin = $tmpcmargin;
3469                                         return ($this->UTF8ArrSubString($chars, $nb));
3470                                 }
3471                                 $nl++;
3472                         }
3473                         if ($firstline) {
3474                                 return "";
3475                         }
3476                         return $nl;
3477                 }
3478
3479                 /**
3480                 * Returns the remaining width between the current position and margins.
3481                 * @return int Return the remaining width
3482                 * @access protected
3483                 */
3484                 function getRemainingWidth() {
3485                         if ($this->rtl) {
3486                                 return ($this->x - $this->lMargin);
3487                         } else {
3488                                 return ($this->w - $this->rMargin - $this->x);
3489                         }
3490                 }
3491
3492          /**
3493                 * Extract a slice of the $strarr array and return it as string.
3494                 * @param string $strarr The input array of characters.
3495                 * @param int $start the starting element of $strarr.
3496                 * @param int $end first element that will not be returned.
3497                 * @return Return part of a string
3498                 */
3499                 function UTF8ArrSubString($strarr, $start='', $end='') {
3500                         if (strlen($start) == 0) {
3501                                 $start = 0;
3502                         }
3503                         if (strlen($end) == 0) {
3504                                 $end = count($strarr);
3505                         }
3506                         $string = "";
3507                         for ($i=$start; $i < $end; $i++) {
3508                                 $string .= $this->unichr($strarr[$i]);
3509                         }
3510                         return $string;
3511                 }
3512
3513                 /**
3514                 * Returns the unicode caracter specified by UTF-8 code
3515                 * @param int $c UTF-8 code
3516                 * @return Returns the specified character.
3517                 * @author Miguel Perez, Nicola Asuni
3518                 * @since 2.3.000 (2008-03-05)
3519                 */
3520                 function unichr($c) {
3521                         if (!$this->isunicode) {
3522                                 return chr($c);
3523                         } elseif ($c <= 0x7F) {
3524                                 // one byte
3525                                 return chr($c);
3526                         } elseif ($c <= 0x7FF) {
3527                                 // two bytes
3528                                 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
3529                         } elseif ($c <= 0xFFFF) {
3530                                 // three bytes
3531                                 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3532                         } elseif ($c <= 0x10FFFF) {
3533                                 // four bytes
3534                                 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
3535                         } else {
3536                                 return "";
3537                         }
3538                 }
3539
3540                 /**
3541                 * Puts an image in the page.
3542                 * The upper-left corner must be given.
3543                 * The dimensions can be specified in different ways:<ul>
3544                 * <li>explicit width and height (expressed in user unit)</li>
3545                 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
3546                 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
3547                 * 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;
3548                 * The format can be specified explicitly or inferred from the file extension.<br />
3549                 * It is possible to put a link on the image.<br />
3550                 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
3551                 * @param string $file Name of the file containing the image.
3552                 * @param float $x Abscissa of the upper-left corner.
3553                 * @param float $y Ordinate of the upper-left corner.
3554                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
3555                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
3556                 * @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.
3557                 * @param mixed $link URL or identifier returned by AddLink().
3558                 * @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>
3559                 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
3560                 * @param int $dpi dot-per-inch resolution used on resize
3561                 * @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>
3562                 * @since 1.1
3563                 * @see AddLink()
3564                 */
3565                 function Image($file, $x, $y, $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='') {
3566                         // get image size
3567                         list($pixw, $pixh) = getimagesize($file);
3568                         // calculate image width and height on document
3569                         if (($w <= 0) AND ($h <= 0)) {
3570                                 // convert image size to document unit
3571                                 $w = $pixw / ($this->imgscale * $this->k);
3572                                 $h = $pixh / ($this->imgscale * $this->k);
3573                         } elseif ($w <= 0) {
3574                                 $w = $h * $pixw / $pixh;
3575                         } elseif ($h <= 0) {
3576                                 $h = $w * $pixh / $pixw;
3577                         }
3578                         // calculate new minimum dimensions in pixels
3579                         $neww = round($w * $this->k * $dpi / $this->dpi);
3580                         $newh = round($h * $this->k * $dpi / $this->dpi);
3581                         // check if resize is necessary (resize is used only to reduce the image)
3582                         if (($neww * $newh) >= ($pixw * $pixh)) {
3583                                 $resize = false;
3584                         }
3585                         // check if image has been already added on document
3586                         if (!isset($this->images[$file])) {
3587                                 //First use of image, get info
3588                                 if ($type == '') {
3589                                         $fileinfo = pathinfo($file);
3590                                         if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
3591                                                 $type = $fileinfo['extension'];
3592                                         } else {
3593                                                 $this->Error('Image file has no extension and no type was specified: '.$file);
3594                                         }
3595                                 }
3596                                 $type = strtolower($type);
3597                                 if ($type == "jpg") {
3598                                         $type = "jpeg";
3599                                 }
3600                                 $mqr = ini_get('magic_quotes_runtime');
3601                                 ini_set('magic_quotes_runtime', 0);
3602                                 // Specific image handlers
3603                                 $mtd = '_parse'.$type;
3604                                 // GD image handler function
3605                                 $gdfunction = "imagecreatefrom".$type;
3606                                 $info = false;
3607                                 if ((method_exists($this,$mtd)) AND (!($resize AND function_exists($gdfunction)))) {
3608                                         $info = $this->$mtd($file);
3609                                 }
3610                                 if (!$info) {
3611                                         if (function_exists($gdfunction)) {
3612                                                 $img = $gdfunction($file);
3613                                                 if ($resize) {
3614                                                         $imgr = imagecreatetruecolor($neww, $newh);
3615                                                         imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
3616                                                         $info = $this->_toJPEG($imgr);
3617                                                 } else {
3618                                                         $info = $this->_toJPEG($img);
3619                                                 }
3620                                         } else {
3621                                                 return;
3622                                         }
3623                                 }
3624                                 if ($info === false) {
3625                                         //If false, we cannot process image
3626                                         return;
3627                                 }
3628                                 ini_set('magic_quotes_runtime', $mqr);
3629                                 $info['i'] = count($this->images) + 1;
3630                                 // add image to document
3631                                 $this->images[$file] = $info;
3632                         } else {
3633                                 $info = $this->images[$file];
3634                         }
3635                         // Check whether we need a new page first as this does not fit
3636                         if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
3637                                 // Automatic page break
3638                                 $this->AddPage($this->CurOrientation);
3639                                 // Reset coordinates to top fo next page
3640                                 //$x = $this->GetX();
3641                                 $y = $this->GetY() + $this->cMargin;
3642                         }
3643                         // 2007-10-19 Warren Sherliker: End Edit
3644                         // set bottomcoordinates
3645                         $this->img_rb_y = $y + $h;
3646                         // set alignment
3647                         if ($this->rtl) {
3648                                 if ($palign == 'L') {
3649                                         $ximg = $this->lMargin;
3650                                         // set right side coordinate
3651                                         $this->img_rb_x = $ximg + $w;
3652                                 } elseif ($palign == 'C') {
3653                                         $ximg = ($this->w - $x - $w) / 2;
3654                                         // set right side coordinate
3655                                         $this->img_rb_x = $ximg + $w;
3656                                 } else {
3657                                         $ximg = $this->w - $x - $w;
3658                                         // set left side coordinate
3659                                         $this->img_rb_x = $ximg;
3660                                 }
3661                         } else {
3662                                 if ($palign == 'R') {
3663                                         $ximg = $this->w - $this->rMargin - $w;
3664                                         // set left side coordinate
3665                                         $this->img_rb_x = $ximg;
3666                                 } elseif ($palign == 'C') {
3667                                         $ximg = ($this->w - $x - $w) / 2;
3668                                         // set right side coordinate
3669                                         $this->img_rb_x = $ximg + $w;
3670                                 } else {
3671                                         $ximg = $x;
3672                                         // set right side coordinate
3673                                         $this->img_rb_x = $ximg + $w;
3674                                 }
3675                         }
3676                         $xkimg = $ximg * $this->k;
3677                         $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']));
3678                         if ($link) {
3679                                 $this->Link($ximg, $y, $w, $h, $link);
3680                         }
3681                         // set pointer to align the successive text/objects
3682                         switch($align) {
3683                                 case 'T': {
3684                                         $this->y = $y;
3685                                         $this->x = $this->img_rb_x;
3686                                         break;
3687                                 }
3688                                 case 'M': {
3689                                         $this->y = $y + round($h/2);
3690                                         $this->x = $this->img_rb_x;
3691                                         break;
3692                                 }
3693                                 case 'B': {
3694                                         $this->y = $this->img_rb_y;
3695                                         $this->x = $this->img_rb_x;
3696                                         break;
3697                                 }
3698                                 case 'N': {
3699                                         $this->SetY($this->img_rb_y);
3700                                         break;
3701                                 }
3702                                 default:{
3703                                         break;
3704                                 }
3705                         }
3706                         $this->endlinex = $this->img_rb_x;
3707                 }
3708
3709                 /**
3710                 * Convert the loaded php image to a JPEG and then return a structure for the PDF creator.
3711                 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
3712                 * @param string $file Image file name.
3713                 * @param image $image Image object.
3714                 * return image JPEG image object.
3715                 * @access protected
3716                 */
3717                 function _toJPEG($image) {
3718                         $tempname = tempnam(K_PATH_CACHE,'jpg');
3719                         imagejpeg($image, $tempname, $this->jpeg_quality);
3720                         imagedestroy($image);
3721                         $retvars = $this->_parsejpeg($tempname);
3722                         // tidy up by removing temporary image
3723                         unlink($tempname);
3724                         return $retvars;
3725                 }
3726
3727                 /**
3728                 * Extract info from a JPEG file without using the GD library.
3729                 * @param string $file image file to parse
3730                 * @return array structure containing the image data
3731                 * @access protected
3732                 */
3733                 function _parsejpeg($file) {
3734                         $a = getimagesize($file);
3735                         if (empty($a)) {
3736                                 $this->Error('Missing or incorrect image file: '.$file);
3737                         }
3738                         if ($a[2] != 2) {
3739                                 $this->Error('Not a JPEG file: '.$file);
3740                         }
3741                         if ((!isset($a['channels'])) OR ($a['channels'] == 3)) {
3742                                 $colspace = 'DeviceRGB';
3743                         } elseif ($a['channels'] == 4) {
3744                                 $colspace = 'DeviceCMYK';
3745                         }       else {
3746                                 $colspace = 'DeviceGray';
3747                         }
3748                         $bpc = isset($a['bits']) ? $a['bits'] : 8;
3749                         $data = file_get_contents($file);
3750                         return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
3751                 }
3752
3753                 /**
3754                 * Extract info from a PNG file without using the GD library.
3755                 * @param string $file image file to parse
3756                 * @return array structure containing the image data
3757                 * @access protected
3758                 */
3759                 function _parsepng($file) {
3760                         $f = fopen($file,'rb');
3761                         if (empty($f)) {
3762                                 $this->Error('Can\'t open image file: '.$file);
3763                         }
3764                         //Check signature
3765                         if (fread($f,8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
3766                                 $this->Error('Not a PNG file: '.$file);
3767                         }
3768                         //Read header chunk
3769                         fread($f,4);
3770                         if (fread($f,4) != 'IHDR') {
3771                                 $this->Error('Incorrect PNG file: '.$file);
3772                         }
3773                         $w = $this->_freadint($f);
3774                         $h = $this->_freadint($f);
3775                         $bpc = ord(fread($f,1));
3776                         if ($bpc > 8) {
3777                                 //$this->Error('16-bit depth not supported: '.$file);
3778                                 return false;
3779                         }
3780                         $ct = ord(fread($f,1));
3781                         if ($ct == 0) {
3782                                 $colspace = 'DeviceGray';
3783                         } elseif ($ct == 2) {
3784                                 $colspace = 'DeviceRGB';
3785                         } elseif ($ct == 3) {
3786                                 $colspace = 'Indexed';
3787                         } else {
3788                                 //$this->Error('Alpha channel not supported: '.$file);
3789                                 return false;
3790                         }
3791                         if (ord(fread($f,1)) != 0) {
3792                                 //$this->Error('Unknown compression method: '.$file);
3793                                 return false;
3794                         }
3795                         if (ord(fread($f,1)) != 0) {
3796                                 //$this->Error('Unknown filter method: '.$file);
3797                                 return false;
3798                         }
3799                         if (ord(fread($f,1)) != 0) {
3800                                 //$this->Error('Interlacing not supported: '.$file);
3801                                 return false;
3802                         }
3803                         fread($f,4);
3804                         $parms = '/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
3805                         //Scan chunks looking for palette, transparency and image data
3806                         $pal = '';
3807                         $trns = '';
3808                         $data = '';
3809                         do {
3810                                 $n = $this->_freadint($f);
3811                                 $type = fread($f,4);
3812                                 if ($type == 'PLTE') {
3813                                         //Read palette
3814                                         $pal = fread($f,$n);
3815                                         fread($f,4);
3816                                 } elseif ($type == 'tRNS') {
3817                                         //Read transparency info
3818                                         $t = fread($f,$n);
3819                                         if ($ct == 0) {
3820                                                 $trns = array(ord(substr($t,1,1)));
3821                                         }
3822                                         elseif ($ct == 2) {
3823                                                 $trns = array(ord(substr($t,1,1)), ord(substr($t,3,1)), ord(substr($t,5,1)));
3824                                         } else {
3825                                                 $pos = strpos($t,chr(0));
3826                                                 if ($pos !== false) {
3827                                                         $trns = array($pos);
3828                                                 }
3829                                         }
3830                                         fread($f, 4);
3831                                 } elseif ($type == 'IDAT') {
3832                                         //Read image data block
3833                                         $data .= fread($f,$n);
3834                                         fread($f, 4);
3835                                 } elseif ($type == 'IEND') {
3836                                         break;
3837                                 } else {
3838                                         fread($f, $n+4);
3839                                 }
3840                         }
3841                         while ($n);
3842                         if (($colspace == 'Indexed') AND (empty($pal))) {
3843                                 //$this->Error('Missing palette in '.$file);
3844                                 return false;
3845                         }
3846                         fclose($f);
3847                         return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
3848                 }
3849
3850                 /**
3851                 * Performs a line break.
3852                 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
3853                 * @param float $h The height of the break. By default, the value equals the height of the last printed cell.
3854                 * @param boolean $cell if true add a cMargin to the x coordinate
3855                 * @since 1.0
3856                 * @see Cell()
3857                 */
3858                 function Ln($h='', $cell=false) {
3859                         //Line feed; default value is last cell height
3860                         if ($cell) {
3861                                 $cellmargin = $this->cMargin;
3862                         } else {
3863                                 $cellmargin = 0;
3864                         }
3865                         if ($this->rtl) {
3866                                 $this->x = $this->w - $this->rMargin - $cellmargin;
3867                         } else {
3868                                 $this->x = $this->lMargin + $cellmargin;
3869                         }
3870                         if (is_string($h)) {
3871                                 $this->y += $this->lasth;
3872                         } else {
3873                                 $this->y += $h;
3874                         }
3875                         $this->newline = true;
3876                 }
3877
3878                 /**
3879                 * Returns the relative X value of current position.
3880                 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
3881                 * @return float
3882                 * @since 1.2
3883                 * @see SetX(), GetY(), SetY()
3884                 */
3885                 function GetX() {
3886                         //Get x position
3887                         if ($this->rtl) {
3888                                 return ($this->w - $this->x);
3889                         } else {
3890                                 return $this->x;
3891                         }
3892                 }
3893
3894                 /**
3895                 * Returns the absolute X value of current position.
3896                 * @return float
3897                 * @since 1.2
3898                 * @see SetX(), GetY(), SetY()
3899                 */
3900                 function GetAbsX() {
3901                         return $this->x;
3902                 }
3903
3904                 /**
3905                 * Returns the ordinate of the current position.
3906                 * @return float
3907                 * @since 1.0
3908                 * @see SetY(), GetX(), SetX()
3909                 */
3910                 function GetY() {
3911                         //Get y position
3912                         return $this->y;
3913                 }
3914
3915                 /**
3916                 * Defines the abscissa of the current position.
3917                 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
3918                 * @param float $x The value of the abscissa.
3919                 * @since 1.2
3920                 * @see GetX(), GetY(), SetY(), SetXY()
3921                 */
3922                 function SetX($x) {
3923                         //Set x position
3924                         if ($this->rtl) {
3925                                 if ($x >= 0) {
3926                                         $this->x = $this->w - $x;
3927                                 } else {
3928                                         $this->x = abs($x);
3929                                 }
3930                         } else {
3931                                 if ($x >= 0) {
3932                                         $this->x = $x;
3933                                 } else {
3934                                         $this->x = $this->w + $x;
3935                                 }
3936                         }
3937                 }
3938
3939                 /**
3940                 * Moves the current abscissa back to the left margin and sets the ordinate.
3941                 * If the passed value is negative, it is relative to the bottom of the page.
3942                 * @param float $y The value of the ordinate.
3943                 * @since 1.0
3944                 * @see GetX(), GetY(), SetY(), SetXY()
3945                 */
3946                 function SetY($y) {
3947                         //Set y position and reset x
3948                         if ($this->rtl) {
3949                                 $this->x = $this->w - $this->rMargin;
3950                         } else {
3951                                 $this->x = $this->lMargin;
3952                         }
3953                         if ($y >= 0) {
3954                                 $this->y = $y;
3955                         } else {
3956                                 $this->y = $this->h + $y;
3957                         }
3958                 }
3959
3960                 /**
3961                 * Defines the abscissa and ordinate of the current position.
3962                 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
3963                 * @param float $x The value of the abscissa
3964                 * @param float $y The value of the ordinate
3965                 * @since 1.2
3966                 * @see SetX(), SetY()
3967                 */
3968                 function SetXY($x, $y) {
3969                         //Set x and y positions
3970                         $this->SetY($y);
3971                         $this->SetX($x);
3972                 }
3973
3974                 /**
3975                 * Send the document to a given destination: string, local file or browser.
3976                 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
3977                 * The method first calls Close() if necessary to terminate the document.
3978                 * @param string $name The name of the file when saved.
3979                 * @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>
3980                 * @since 1.0
3981                 * @see Close()
3982                 */
3983                 function Output($name='doc.pdf', $dest='I') {
3984                         //Output PDF to some destination
3985                         //Finish document if necessary
3986                         if ($this->state < 3) {
3987                                 $this->Close();
3988                         }
3989                         //Normalize parameters
3990                         if (is_bool($dest)) {
3991                                 $dest = $dest ? 'D' : 'F';
3992                         }
3993                         $dest = strtoupper($dest);
3994                         if ($dest != 'F') {
3995                                 $name = str_replace("+", "%20", urlencode($name));
3996                                 $name = preg_replace('/[\r\n]+\s*/', '' , $name);
3997                         }
3998                         switch($dest) {
3999                                 case 'I': {
4000                                         //Send to standard output
4001                                         if (ob_get_contents()) {
4002                                                 $this->Error('Some data has already been output, can\'t send PDF file');
4003                                         }
4004                                         if (php_sapi_name() != 'cli') {
4005                                                 //We send to a browser
4006                                                 header('Content-Type: application/pdf');
4007                                                 if (headers_sent()) {
4008                                                         $this->Error('Some data has already been output to browser, can\'t send PDF file');
4009                                                 }
4010                                                 header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4011                                                 header("Pragma: public");
4012                                                 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4013                                                 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");      
4014                                                 header('Content-Length: '.strlen($this->buffer));
4015                                                 header('Content-Disposition: inline; filename="'.basename($name).'";');
4016                                         }
4017                                         echo $this->buffer;
4018                                         break;
4019                                 }
4020                                 case 'D': {
4021                                         //Download file
4022                                         if (ob_get_contents()) {
4023                                                 $this->Error('Some data has already been output, can\'t send PDF file');
4024                                         }
4025                                         header('Content-Description: File Transfer');
4026                                         if (headers_sent()) {
4027                                                 $this->Error('Some data has already been output to browser, can\'t send PDF file');
4028                                         }
4029                                         header("Cache-Control: public, must-revalidate, max-age=0"); // HTTP/1.1
4030                                         header("Pragma: public");
4031                                         header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
4032                                         header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
4033                                         // force download dialog
4034                                         header("Content-Type: application/force-download");
4035                                         header("Content-Type: application/octet-stream", false);
4036                                         header("Content-Type: application/download", false);
4037                                         // use the Content-Disposition header to supply a recommended filename
4038                                         header('Content-Disposition: attachment; filename="'.basename($name).'";');
4039                                         header("Content-Transfer-Encoding: binary");
4040                                         header("Content-Length: ".strlen($this->buffer));
4041                                         echo $this->buffer;
4042                                         break;
4043                                 }
4044                                 case 'F': {
4045                                         //Save to local file
4046                                         $f = fopen($name, 'wb');
4047                                         if (!$f) {
4048                                                 $this->Error('Unable to create output file: '.$name);
4049                                         }
4050                                         fwrite($f, $this->buffer,strlen($this->buffer));
4051                                         fclose($f);
4052                                         break;
4053                                 }
4054                                 case 'S': {
4055                                         //Return as a string
4056                                         return $this->buffer;
4057                                 }
4058                                 default: {
4059                                         $this->Error('Incorrect output destination: '.$dest);
4060                                 }
4061                         }
4062                         return '';
4063                 }
4064
4065                 /**
4066                 * Check for locale-related bug
4067                 * @access protected
4068                 */
4069                 function _dochecks() {
4070                         //Check for locale-related bug
4071                         if (1.1 == 1) {
4072                                 $this->Error('Don\'t alter the locale before including class file');
4073                         }
4074                         //Check for decimal separator
4075                         if (sprintf('%.1f', 1.0) != '1.0') {
4076                                 setlocale(LC_NUMERIC, 'C');
4077                         }
4078                 }
4079
4080                 /**
4081                 * Return fonts path
4082                 * @return string
4083                 * @access protected
4084                 */
4085                 function _getfontpath() {
4086                         if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
4087                                 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
4088                         }
4089                         return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
4090                 }
4091
4092                 /**
4093                 * Output pages.
4094                 * @access protected
4095                 */
4096                 function _putpages() {
4097                         $nb = count($this->pages);
4098                         if (!empty($this->pagegroups)) {
4099                                 // do page number replacement
4100                                 foreach ($this->pagegroups as $k => $v) {
4101                                         $vu = $this->UTF8ToUTF16BE($v, false);
4102                                         $alias_a = $this->_escape($k);
4103                                         $alias_au = $this->_escape("{".$k."}");
4104                                         if ($this->isunicode) {
4105                                                 $alias_b = $this->_escape($this->UTF8ToLatin1($k));
4106                                                 $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$k."}"));
4107                                                 $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl));
4108                                                 $alias_cu = $this->_escape($this->utf8StrRev("{".$k."}", false, $this->tmprtl));
4109                                         }
4110                                         for ($n = 1; $n <= $nb; $n++) {
4111                                                 $this->pages[$n] = str_replace($alias_au, $vu, $this->pages[$n]);
4112                                                 if ($this->isunicode) {
4113                                                         $this->pages[$n] = str_replace($alias_bu, $vu, $this->pages[$n]);
4114                                                         $this->pages[$n] = str_replace($alias_cu, $vu, $this->pages[$n]);
4115                                                         $this->pages[$n] = str_replace($alias_b, $v, $this->pages[$n]);
4116                                                         $this->pages[$n] = str_replace($alias_c, $v, $this->pages[$n]);
4117                                                 }
4118                                                 $this->pages[$n] = str_replace($alias_a, $v, $this->pages[$n]);
4119                                         }
4120                                 }
4121                         }
4122                         if (!empty($this->AliasNbPages)) {
4123                                 $nbu = $this->UTF8ToUTF16BE($nb, false); // replacement for unicode font
4124                                 $alias_a = $this->_escape($this->AliasNbPages);
4125                                 $alias_au = $this->_escape("{".$this->AliasNbPages."}");
4126                                 if ($this->isunicode) {
4127                                         $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages));
4128                                         $alias_bu = $this->_escape($this->UTF8ToLatin1("{".$this->AliasNbPages."}"));
4129                                         $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl));
4130                                         $alias_cu = $this->_escape($this->utf8StrRev("{".$this->AliasNbPages."}", false, $this->tmprtl));
4131                                 }
4132                                 //Replace number of pages
4133                                 for($n = 1; $n <= $nb; $n++) {
4134                                         $this->pages[$n] = str_replace($alias_au, $nbu, $this->pages[$n]);
4135                                         if ($this->isunicode) {
4136                                                 $this->pages[$n] = str_replace($alias_bu, $nbu, $this->pages[$n]);
4137                                                 $this->pages[$n] = str_replace($alias_cu, $nbu, $this->pages[$n]);
4138                                                 $this->pages[$n] = str_replace($alias_b, $nb, $this->pages[$n]);
4139                                                 $this->pages[$n] = str_replace($alias_c, $nb, $this->pages[$n]);
4140                                         }
4141                                         $this->pages[$n] = str_replace($alias_a, $nb, $this->pages[$n]);
4142                                 }
4143                         }
4144                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4145                         for($n=1; $n <= $nb; $n++) {
4146                                 //Page
4147                                 $this->_newobj();
4148                                 $this->_out('<</Type /Page');
4149                                 $this->_out('/Parent 1 0 R');
4150                                 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]', $this->pagedim[$n]['w'], $this->pagedim[$n]['h']));
4151                                 $this->_out('/Resources 2 0 R');
4152                                 $this->_putannots($n);
4153                                 $this->_out('/Contents '.($this->n + 1).' 0 R>>');
4154                                 $this->_out('endobj');
4155                                 //Page content
4156                                 $p = ($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n];
4157                                 $this->_newobj();
4158                                 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
4159                                 $this->_putstream($p);
4160                                 $this->_out('endobj');
4161                         }
4162                         //Pages root
4163                         $this->offsets[1] = strlen($this->buffer);
4164                         $this->_out('1 0 obj');
4165                         $this->_out('<</Type /Pages');
4166                         $kids='/Kids [';
4167                         for($i=0; $i < $nb; $i++) {
4168                                 $kids .= (3+2*$i).' 0 R ';
4169                         }
4170                         $this->_out($kids.']');
4171                         $this->_out('/Count '.$nb);
4172                         //$this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$this->pagedim[0]['w'],$this->pagedim[0]['h']));
4173                         $this->_out('>>');
4174                         $this->_out('endobj');
4175                 }
4176
4177                 /**
4178                 * Output Page Annotations.
4179                 * See section 8.4 of PDF reference.
4180                 * @param int $n page number
4181                 * @access protected
4182                 * @author Nicola Asuni
4183                 * @since 4.0.018 (2008-08-06)
4184                 */
4185                 function _putannots($n) {
4186                         if (isset($this->PageAnnots[$n])) {
4187                                 $annots = '/Annots [';
4188                                 foreach ($this->PageAnnots[$n] as $key => $pl) {
4189                                         $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
4190                                         $a = $pl['x'] * $this->k;
4191                                         $b = $this->hPt - $pl['y'] * $this->k;
4192                                         $c = $pl['w'] * $this->k;
4193                                         $d = $pl['h'] * $this->k;
4194                                         $rect = sprintf('%.2f %.2f %.2f %.2f', $a, $b, $a+$c, $b-$d);
4195                                         $annots .= '<</Type /Annot';
4196                                         $annots .= ' /Subtype /'.$pl['opt']['subtype'];
4197                                         $annots .= ' /Rect ['.$rect.']';
4198                                         $annots .= ' /Contents '.$this->_textstring($pl['txt']);
4199                                         //$annots .= ' /P ';
4200                                         $annots .= ' /NM '.$this->_textstring(sprintf('%04u-%04u', $n, $key));
4201                                         $annots .= ' /M '.$this->_datestring('D:'.date('YmdHis'));
4202                                         if (isset($pl['opt']['f'])) {
4203                                                 $val = 0;
4204                                                 if (is_array($pl['opt']['f'])) {
4205                                                         foreach ($pl['opt']['f'] as $f) {
4206                                                                 switch (strtolower($f)) {
4207                                                                         case 'invisible': {
4208                                                                                 $val += 1 << 0;
4209                                                                                 break;
4210                                                                         }
4211                                                                         case 'hidden': {
4212                                                                                 $val += 1 << 1;
4213                                                                                 break;
4214                                                                         }
4215                                                                         case 'print': {
4216                                                                                 $val += 1 << 2;
4217                                                                                 break;
4218                                                                         }
4219                                                                         case 'nozoom': {
4220                                                                                 $val += 1 << 3;
4221                                                                                 break;
4222                                                                         }
4223                                                                         case 'norotate': {
4224                                                                                 $val += 1 << 4;
4225                                                                                 break;
4226                                                                         }
4227                                                                         case 'noview': {
4228                                                                                 $val += 1 << 5;
4229                                                                                 break;
4230                                                                         }
4231                                                                         case 'readonly': {
4232                                                                                 $val += 1 << 6;
4233                                                                                 break;
4234                                                                         }
4235                                                                         case 'locked': {
4236                                                                                 $val += 1 << 8;
4237                                                                                 break;
4238                                                                         }
4239                                                                         case 'togglenoview': {
4240                                                                                 $val += 1 << 9;
4241                                                                                 break;
4242                                                                         }
4243                                                                         case 'lockedcontents': {
4244                                                                                 $val += 1 << 10;
4245                                                                                 break;
4246                                                                         }
4247                                                                         default: {
4248                                                                                 break;
4249                                                                         }
4250                                                                 }
4251                                                         }
4252                                                 }
4253                                                 $annots .= ' /F '.intval($val);
4254                                         }
4255                                         //$annots .= ' /AP ';
4256                                         //$annots .= ' /AS ';
4257                                         $annots .= ' /Border [';
4258                                         if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
4259                                                 $annots .= intval($pl['opt']['border'][0]).' ';
4260                                                 $annots .= intval($pl['opt']['border'][1]).' ';
4261                                                 $annots .= intval($pl['opt']['border'][2]);
4262                                                 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
4263                                                         $annots .= ' [';
4264                                                         foreach ($pl['opt']['border'][3] as $dash) {
4265                                                                 $annots .= intval($dash).' ';
4266                                                         }
4267                                                         $annots .= ']';
4268                                                 }
4269                                         } else {
4270                                                 $annots .= '0 0 0';
4271                                         }
4272                                         $annots .= ']';
4273                                         if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
4274                                                 $annots .= ' /BS <<Type /Border';
4275                                                 if (isset($pl['opt']['bs']['w'])) {
4276                                                         $annots .= ' /W '.sprintf("%.4f", floatval($pl['opt']['bs']['w']));
4277                                                 }
4278                                                 $bstyles = array('S', 'D', 'B', 'I', 'U');
4279                                                 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $markups)) {
4280                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
4281                                                 }
4282                                                 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
4283                                                         $annots .= ' /D [';
4284                                                         foreach ($pl['opt']['bs']['d'] as $cord) {
4285                                                                 $cord = floatval($cord);
4286                                                                 $annots .= sprintf(" %.4f", $cord);
4287                                                         }
4288                                                         $annots .= ']';
4289                                                 }
4290                                                 $annots .= '>>';
4291                                         }
4292                                         if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
4293                                                 $annots .= ' /BE <<';
4294                                                 $bstyles = array('S', 'C');
4295                                                 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
4296                                                         $annots .= ' /S /'.$pl['opt']['bs']['s'];
4297                                                 } else {
4298                                                         $annots .= ' /S /S';
4299                                                 }
4300                                                 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
4301                                                         $annots .= ' /I '.sprintf(" %.4f", $pl['opt']['be']['i']);
4302                                                 }
4303                                                 $annots .= '>>';
4304                                         }
4305                                         $annots .= ' /C [';
4306                                         if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c']))) {
4307                                                 foreach ($pl['opt']['c'] as $col) {
4308                                                         $col = intval($col);
4309                                                         $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
4310                                                         $annots .= sprintf(" %.4f", $color);
4311                                                 }
4312                                         }
4313                                         $annots .= ']';
4314                                         //$annots .= ' /StructParent ';
4315                                         //$annots .= ' /OC ';
4316                                         $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight',  'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
4317                                         if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
4318                                                 // this is a markup type
4319                                                 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
4320                                                         $annots .= ' /T '.$this->_textstring($pl['opt']['t']);
4321                                                 }
4322                                                 //$annots .= ' /Popup ';
4323                                                 if (isset($pl['opt']['ca'])) {
4324                                                         $annots .= ' /CA '.sprintf("%.4f", floatval($pl['opt']['ca']));
4325                                                 }
4326                                                 if (isset($pl['opt']['rc'])) {
4327                                                         $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4328                                                 }
4329                                                 $annots .= ' /CreationDate '.$this->_datestring('D:'.date('YmdHis'));
4330                                                 //$annots .= ' /IRT ';
4331                                                 if (isset($pl['opt']['subj'])) {
4332                                                         $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj']);
4333                                                 }
4334                                                 //$annots .= ' /RT ';
4335                                                 //$annots .= ' /IT ';
4336                                                 //$annots .= ' /ExData ';
4337                                         }
4338                                         switch (strtolower($pl['opt']['subtype'])) {
4339                                                 case 'text': {
4340                                                         if (isset($pl['opt']['open'])) {
4341                                                                 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
4342                                                         }
4343                                                         $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
4344                                                         if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
4345                                                                 $annots .= ' /Name /'.$pl['opt']['name'];
4346                                                         } else {
4347                                                                 $annots .= ' /Name /Note';
4348                                                         }
4349                                                         $statemodels = array('Marked', 'Review');
4350                                                         if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
4351                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4352                                                         } else {
4353                                                                 $pl['opt']['statemodel'] = 'Marked';
4354                                                                 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
4355                                                         }
4356                                                         if ($pl['opt']['statemodel'] == 'Marked') {
4357                                                                 $states = array('Accepted', 'Unmarked');
4358                                                         } else {
4359                                                                 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
4360                                                         }
4361                                                         if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
4362                                                                 $annots .= ' /State /'.$pl['opt']['state'];
4363                                                         } else {
4364                                                                 if ($pl['opt']['statemodel'] == 'Marked') {
4365                                                                         $annots .= ' /State /Unmarked';
4366                                                                 } else {
4367                                                                         $annots .= ' /State /None';
4368                                                                 }
4369                                                         }
4370                                                         break;
4371                                                 }
4372                                                 case 'link': {
4373                                                         $annots .= ' /A <</S /URI /URI '.$this->_uristring($pl['txt']).'>>';
4374                                                         $hmodes = array('N', 'I', 'O', 'P');
4375                                                         if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
4376                                                                 $annots .= ' /H /'.$pl['opt']['h'];
4377                                                         } else {
4378                                                                 $annots .= ' /H /I';
4379                                                         }
4380                                                         //$annots .= ' /Dest ';
4381                                                         //$annots .= ' /PA ';
4382                                                         //$annots .= ' /Quadpoints ';
4383                                                         break;
4384                                                 }
4385                                                 case 'freetext': {
4386                                                         $annots .= ' /DA '.$this->_textstring($pl['txt']);
4387                                                         if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
4388                                                                 $annots .= ' /Q '.intval($pl['opt']['q']);
4389                                                         }
4390                                                         if (isset($pl['opt']['rc'])) {
4391                                                                 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc']);
4392                                                         }
4393                                                         if (isset($pl['opt']['ds'])) {
4394                                                                 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds']);
4395                                                         }
4396                                                         if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
4397                                                                 $annots .= ' /CL [';
4398                                                                 foreach ($pl['opt']['cl'] as $cl) {
4399                                                                         $annots .= sprintf("%.4f ", $cl * $this->k);
4400                                                                 }
4401                                                                 $annots .= ']';
4402                                                         }
4403                                                         $tfit = array('FreeTextCallout', 'FreeTextTypeWriter');
4404                                                         if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
4405                                                                 $annots .= ' /IT '.$pl['opt']['it'];
4406                                                         }
4407                                                         if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
4408                                                                 $l = $pl['opt']['rd'][0] * $this->k;
4409                                                                 $r = $pl['opt']['rd'][1] * $this->k;
4410                                                                 $t = $pl['opt']['rd'][2] * $this->k;
4411                                                                 $b = $pl['opt']['rd'][3] * $this->k;
4412                                                                 $annots .= ' /RD ['.sprintf('%.2f %.2f %.2f %.2f', $l, $r, $t, $b).']';
4413                                                         }
4414                                                         //$annots .= ' /LE ';
4415                                                         break;
4416                                                 }
4417                                                 // ... to be completed ...
4418                                                 case 'line': {
4419                                                         break;
4420                                                 }
4421                                                 case 'square': {
4422                                                         break;
4423                                                 }
4424                                                 case 'circle': {
4425                                                         break;
4426                                                 }
4427                                                 case 'polygon': {
4428                                                         break;
4429                                                 }
4430                                                 case 'polyline': {
4431                                                         break;
4432                                                 }
4433                                                 case 'highlight': {
4434                                                         break;
4435                                                 }
4436                                                 case 'underline': {
4437                                                         break;
4438                                                 }
4439                                                 case 'squiggly': {
4440                                                         break;
4441                                                 }
4442                                                 case 'strikeout': {
4443                                                         break;
4444                                                 }
4445                                                 case 'stamp': {
4446                                                         break;
4447                                                 }
4448                                                 case 'caret': {
4449                                                         break;
4450                                                 }
4451                                                 case 'ink': {
4452                                                         break;
4453                                                 }
4454                                                 case 'popup': {
4455                                                         break;
4456                                                 }
4457                                                 case 'fileattachment': {
4458                                                         break;
4459                                                 }
4460                                                 case 'sound': {
4461                                                         break;
4462                                                 }
4463                                                 case 'movie': {
4464                                                         break;
4465                                                 }
4466                                                 case 'widget': {
4467                                                         break;
4468                                                 }
4469                                                 case 'screen': {
4470                                                         break;
4471                                                 }
4472                                                 case 'printermark': {
4473                                                         break;
4474                                                 }
4475                                                 case 'trapnet': {
4476                                                         break;
4477                                                 }
4478                                                 case 'watermark': {
4479                                                         break;
4480                                                 }
4481                                                 case '3d': {
4482                                                         break;
4483                                                 }
4484                                                 default: {
4485                                                         break;
4486                                                 }
4487                                         }
4488                                         
4489                                 $annots .= '>>';
4490                                 }
4491                                 $this->_out($annots.']');
4492                         }
4493                 }
4494
4495                 /**
4496                 * Output fonts.
4497                 * _putfonts
4498                 * @access protected
4499                 */
4500                 function _putfonts() {
4501                         $nf = $this->n;
4502                         foreach($this->diffs as $diff) {
4503                                 //Encodings
4504                                 $this->_newobj();
4505                                 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
4506                                 $this->_out('endobj');
4507                         }
4508                         $mqr = ini_get('magic_quotes_runtime');
4509                         ini_set('magic_quotes_runtime', 0);
4510                         foreach($this->FontFiles as $file => $info) {
4511                                 //Font file embedding
4512                                 $this->_newobj();
4513                                 $this->FontFiles[$file]['n'] = $this->n;
4514                                 $font = file_get_contents($this->_getfontpath().strtolower($file));
4515                                 $compressed = (substr($file,-2)=='.z');
4516                                 if ((!$compressed) AND (isset($info['length2']))) {
4517                                         $header = (ord($font{0}) == 128);
4518                                         if ($header) {
4519                                                 //Strip first binary header
4520                                                 $font = substr($font,6);
4521                                         }
4522                                         if ($header AND (ord($font{$info['length1']}) == 128)) {
4523                                                 //Strip second binary header
4524                                                 $font = substr($font, 0, $info['length1']).substr($font, $info['length1']+6);
4525                                         }
4526                                 }
4527                                 $this->_out('<</Length '.strlen($font));
4528                                 if ($compressed) {
4529                                         $this->_out('/Filter /FlateDecode');
4530                                 }
4531                                 $this->_out('/Length1 '.$info['length1']);
4532                                 if (isset($info['length2'])) {
4533                                         $this->_out('/Length2 '.$info['length2'].' /Length3 0');
4534                                 }
4535                                 $this->_out('>>');
4536                                 $this->_putstream($font);
4537                                 $this->_out('endobj');
4538                         }
4539                         ini_set('magic_quotes_runtime', $mqr);
4540                         foreach($this->fonts as $k => $font) {
4541                                 //Font objects
4542                                 $this->fonts[$k]['n'] = $this->n + 1;
4543                                 $type = $font['type'];
4544                                 $name = $font['name'];
4545                                 if ($type == 'core') {
4546                                         //Standard font
4547                                         $this->_newobj();
4548                                         $this->_out('<</Type /Font');
4549                                         $this->_out('/BaseFont /'.$name);
4550                                         $this->_out('/Subtype /Type1');
4551                                         if (($name != 'symbol') AND ($name != 'zapfdingbats')) {
4552                                                 $this->_out('/Encoding /WinAnsiEncoding');
4553                                         }
4554                                         $this->_out('>>');
4555                                         $this->_out('endobj');
4556                                 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
4557                                         //Additional Type1 or TrueType font
4558                                         $this->_newobj();
4559                                         $this->_out('<</Type /Font');
4560                                         $this->_out('/BaseFont /'.$name);
4561                                         $this->_out('/Subtype /'.$type);
4562                                         $this->_out('/FirstChar 32 /LastChar 255');
4563                                         $this->_out('/Widths '.($this->n + 1).' 0 R');
4564                                         $this->_out('/FontDescriptor '.($this->n + 2).' 0 R');
4565                                         if ($font['enc']) {
4566                                                 if (isset($font['diff'])) {
4567                                                         $this->_out('/Encoding '.($nf + $font['diff']).' 0 R');
4568                                                 } else {
4569                                                         $this->_out('/Encoding /WinAnsiEncoding');
4570                                                 }
4571                                         }
4572                                         $this->_out('>>');
4573                                         $this->_out('endobj');
4574                                         //Widths
4575                                         $this->_newobj();
4576                                         $cw = &$font['cw'];
4577                                         $s = '[';
4578                                         for($i=32; $i <= 255; $i++) {
4579                                                 //$s .= $cw[chr($i)].' ';
4580                                                 $s .= $cw[$i].' ';
4581                                         }
4582                                         $this->_out($s.']');
4583                                         $this->_out('endobj');
4584                                         //Descriptor
4585                                         $this->_newobj();
4586                                         $s = '<</Type /FontDescriptor /FontName /'.$name;
4587                                         foreach($font['desc'] as $k => $v) {
4588                                                 $s .= ' /'.$k.' '.$v;
4589                                         }
4590                                         $file = $font['file'];
4591                                         if ($file) {
4592                                                 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
4593                                         }
4594                                         $this->_out($s.'>>');
4595                                         $this->_out('endobj');
4596                                 } else {
4597                                         //Allow for additional types
4598                                         $mtd = '_put'.strtolower($type);
4599                                         if (!method_exists($this, $mtd)) {
4600                                                 $this->Error('Unsupported font type: '.$type);
4601                                         }
4602                                         $this->$mtd($font);
4603                                 }
4604                         }
4605                 }
4606
4607                 /**
4608                  * Output CID-0 fonts.
4609                  * @param array $font font data
4610                  * @access protected
4611                  * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
4612                  * @since 3.2.000 (2008-06-23)
4613                  */
4614                 function _putcidfont0($font) {
4615                         if (isset($font['cidinfo']['uni2cid'])) {
4616                                 // convert unicode to cid.
4617                                 $uni2cid = $font['cidinfo']['uni2cid'];
4618                                 $cw = array();
4619                                 foreach ($font['cw'] as $uni => $width) {
4620                                         if (isset($uni2cid[$uni])) {
4621                                                 $cw[($uni2cid[$uni] + 31)] = $width;
4622                                         } elseif ($uni <= 255) {
4623                                                 $cw[$uni] = $width;
4624                                         } // else unknown character
4625                                 }
4626                                 ksort($cw);
4627                                 $font = array_merge($font, array('cw'=>$cw));
4628                         }
4629                         $longname = $name = $font['name'];
4630                         $enc = $font['enc'];
4631                         if ($enc) {
4632                                 $longname .= "-$enc";
4633                         }
4634                         $this->_newobj();
4635                         $this->_out('<</Type /Font');
4636                         $this->_out('/BaseFont /'.$longname);
4637                         $this->_out('/Subtype /Type0');
4638                         if ($enc) {
4639                                 $this->_out('/Encoding /'.$enc);
4640                         }
4641                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
4642                         $this->_out('>>');
4643                         $this->_out('endobj');
4644                         $this->_newobj();
4645                         $this->_out('<</Type /Font');
4646                         $this->_out('/BaseFont /'.$name);
4647                         $this->_out('/Subtype /CIDFontType0');
4648                         $cidinfo = '/Registry ('.$font['cidinfo']['Registry'].') ';
4649                         $cidinfo .= '/Ordering ('.$font['cidinfo']['Ordering'].') ';
4650                         $cidinfo .= '/Supplement '.$font['cidinfo']['Supplement'];
4651                         $this->_out('/CIDSystemInfo <<'.$cidinfo.'>>');
4652                         $this->_out('/FontDescriptor '.($this->n + 1).' 0 R');
4653                         $codes = array_keys($font['cw']);
4654                         $first = current($codes);
4655                         $last = end($codes);
4656                         $this->_out('/DW '.$font['dw']);
4657                         $w = '/W [';
4658                         $ranges = array();
4659                         $currange = 0;
4660                         for($i = $first; $i <= $last; $i++) {
4661                                 if (isset($font['cw'][$i]) AND (!$currange)) {
4662                                         $currange = $i - 31;
4663                                 } elseif (!isset($font['cw'][$i])) {
4664                                         $currange = 0;
4665                                 }
4666                                 if ($currange) {
4667                                         $ranges[$currange][] = $font['cw'][$i];
4668                                 }
4669                         }
4670                         foreach($ranges as $k => $ws) {
4671                                 $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
4672                         }
4673                         $w .= ' ]';
4674                         $this->_out($w);
4675                         $this->_out('>>');
4676                         $this->_out('endobj');
4677                         $this->_newobj();
4678                         $s = '<</Type /FontDescriptor /FontName /'.$name;
4679                         foreach($font['desc'] as $k => $v) {
4680                                 $s .= ' /'.$k.' '.$v;
4681                         }
4682                         $this->_out($s.'>>');
4683                         $this->_out('endobj');
4684                 }
4685
4686                 /**
4687                  * Output images.
4688                  * @access protected
4689                  */
4690                 function _putimages() {
4691                         $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
4692                         reset($this->images);
4693                         foreach ($this->images as $file => $info) {
4694                                 $this->_newobj();
4695                                 $this->images[$file]['n'] = $this->n;
4696                                 $this->_out('<</Type /XObject');
4697                                 $this->_out('/Subtype /Image');
4698                                 $this->_out('/Width '.$info['w']);
4699                                 $this->_out('/Height '.$info['h']);
4700                                 if (isset($info["masked"])) {
4701                                         $this->_out('/SMask '.($this->n-1).' 0 R');
4702                                 }
4703                                 if ($info['cs'] == 'Indexed') {
4704                                         $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal']) / 3 - 1).' '.($this->n + 1).' 0 R]');
4705                                 } else {
4706                                         $this->_out('/ColorSpace /'.$info['cs']);
4707                                         if ($info['cs'] == 'DeviceCMYK') {
4708                                                 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
4709                                         }
4710                                 }
4711                                 $this->_out('/BitsPerComponent '.$info['bpc']);
4712                                 if (isset($info['f'])) {
4713                                         $this->_out('/Filter /'.$info['f']);
4714                                 }
4715                                 if (isset($info['parms'])) {
4716                                         $this->_out($info['parms']);
4717                                 }
4718                                 if (isset($info['trns']) and is_array($info['trns'])) {
4719                                         $trns='';
4720                                         for($i=0; $i < count($info['trns']); $i++) {
4721                                                 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
4722                                         }
4723                                         $this->_out('/Mask ['.$trns.']');
4724                                 }
4725                                 $this->_out('/Length '.strlen($info['data']).'>>');
4726                                 $this->_putstream($info['data']);
4727                                 unset($this->images[$file]['data']);
4728                                 $this->_out('endobj');
4729                                 //Palette
4730                                 if ($info['cs'] == 'Indexed') {
4731                                         $this->_newobj();
4732                                         $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
4733                                         $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
4734                                         $this->_putstream($pal);
4735                                         $this->_out('endobj');
4736                                 }
4737                         }
4738                 }
4739
4740                 /**
4741                 * Output Spot Colors Resources.
4742                 * @access protected
4743                 * @since 4.0.024 (2008-09-12)
4744                 */
4745                 function _putspotcolors() {
4746                         foreach ($this->spot_colors as $name => $color) {
4747                                 $this->_newobj();
4748                                 $this->spot_colors[$name]['n'] = $this->n;
4749                                 $this->_out('[/Separation /'.str_replace(' ', '#20', $name));
4750                                 $this->_out('/DeviceCMYK <<');
4751                                 $this->_out('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] ');
4752                                 $this->_out(sprintf('/C1 [%.4f %.4f %.4f %.4f] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100));
4753                                 $this->_out('/FunctionType 2 /Domain [0 1] /N 1>>]');
4754                                 $this->_out('endobj');
4755                         }
4756                 }
4757
4758                 /**
4759                 * Output object dictionary for images.
4760                 * @access protected
4761                 */
4762                 function _putxobjectdict() {
4763                         foreach($this->images as $image) {
4764                                 $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
4765                         }
4766                 }
4767
4768                 /**
4769                 * Output Resources Dictionary.
4770                 * @access protected
4771                 */
4772                 function _putresourcedict(){
4773                         $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
4774                         $this->_out('/Font <<');
4775                         foreach($this->fonts as $font) {
4776                                 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
4777                         }
4778                         $this->_out('>>');
4779                         $this->_out('/XObject <<');
4780                         $this->_putxobjectdict();
4781                         $this->_out('>>');
4782                         // visibility
4783                         $this->_out('/Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>');
4784                         // transparency
4785                         $this->_out('/ExtGState <<');
4786                         foreach($this->extgstates as $k => $extgstate) {
4787                                 $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
4788                         }
4789                         $this->_out('>>');
4790                         // gradients
4791                         if (isset($this->gradients) AND (count($this->gradients) > 0)) {
4792                                 $this->_out('/Shading <<');
4793                                 foreach($this->gradients as $id => $grad) {
4794                                         $this->_out('/Sh'.$id.' '.$grad['id'].' 0 R');
4795                                 }
4796                                 $this->_out('>>');
4797                         }
4798                         // spot colors
4799                         if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
4800                                 $this->_out('/ColorSpace <<');
4801                                 foreach ($this->spot_colors as $color) {
4802                                         $this->_out('/CS'.$color['i'].' '.$color['n'].' 0 R');
4803                                 }
4804                                 $this->_out('>>');
4805                         }
4806                 }
4807
4808                 /**
4809                 * Output Resources.
4810                 * @access protected
4811                 */
4812                 function _putresources() {
4813                         $this->_putextgstates();
4814                         $this->_putocg();
4815                         $this->_putfonts();
4816                         $this->_putimages();
4817                         $this->_putspotcolors();
4818                         $this->_putshaders();
4819                         //Resource dictionary
4820                         $this->offsets[2] = strlen($this->buffer);
4821                         $this->_out('2 0 obj');
4822                         $this->_out('<<');
4823                         $this->_putresourcedict();
4824                         $this->_out('>>');
4825                         $this->_out('endobj');
4826                         $this->_putjavascript();
4827                         $this->_putbookmarks();
4828                         // encryption
4829                         if ($this->encrypted) {
4830                                 $this->_newobj();
4831                                 $this->enc_obj_id = $this->n;
4832                                 $this->_out('<<');
4833                                 $this->_putencryption();
4834                                 $this->_out('>>');
4835                                 $this->_out('endobj');
4836                         }
4837                 }
4838
4839                 /**
4840                 * Adds some Metadata information
4841                 * (see Chapter 10.2 of PDF Reference)
4842                 * @access protected
4843                 */
4844                 function _putinfo() {
4845                         if (!empty($this->title)) {
4846                                 $this->_out('/Title '.$this->_textstring($this->title));
4847                         }
4848                         if (!empty($this->author)) {
4849                                 $this->_out('/Author '.$this->_textstring($this->author));
4850                         }
4851                         if (!empty($this->subject)) {
4852                                 $this->_out('/Subject '.$this->_textstring($this->subject));
4853                         }
4854                         if (!empty($this->keywords)) {
4855                                 $this->_out('/Keywords '.$this->_textstring($this->keywords));
4856                         }
4857                         if (!empty($this->creator)) {
4858                                 $this->_out('/Creator '.$this->_textstring($this->creator));
4859                         }
4860                         if (defined('PDF_PRODUCER')) {
4861                                 $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER));
4862                         }
4863                         $this->_out('/CreationDate '.$this->_datestring('D:'.date('YmdHis')));
4864                         $this->_out('/ModDate '.$this->_datestring('D:'.date('YmdHis')));
4865                 }
4866
4867                 /**
4868                 * Format a date string for meta information
4869                 * @param string $s date string to escape.
4870                 * @return string escaped string.
4871                 * @access protected
4872                 */
4873                 function _datestring($s) {
4874                         if ($this->encrypted) {
4875                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
4876                         }
4877                         return '('. $this->_escape($s).')';
4878                 }
4879
4880                 /**
4881                 * Output Catalog.
4882                 * @access protected
4883                 */
4884                 function _putcatalog() {
4885                         $this->_out('/Type /Catalog');
4886                         $this->_out('/Pages 1 0 R');
4887
4888                         if ($this->ZoomMode == 'fullpage') {
4889                                 $this->_out('/OpenAction [3 0 R /Fit]');
4890                         } elseif ($this->ZoomMode == 'fullwidth') {
4891                                 $this->_out('/OpenAction [3 0 R /FitH null]');
4892                         } elseif ($this->ZoomMode == 'real') {
4893                                 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
4894                         } elseif (!is_string($this->ZoomMode)) {
4895                                 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode / 100).']');
4896                         }
4897                         if (isset($this->LayoutMode) AND (!empty($this->LayoutMode))) {
4898                                 $this->_out('/PageLayout /'.$this->LayoutMode.'');
4899                         }
4900                         if (isset($this->PageMode) AND (!empty($this->PageMode))) {
4901                                 $this->_out('/PageMode /'.$this->PageMode);
4902                         }
4903                         if (isset($this->l['a_meta_language'])) {
4904                                 $this->_out('/Lang /'.$this->l['a_meta_language']);
4905                         }
4906                         if (!empty($this->javascript)) {
4907                                 $this->_out('/Names <</JavaScript '.($this->n_js).' 0 R>>');
4908                         }
4909                         if (count($this->outlines) > 0) {
4910                                 $this->_out('/Outlines '.$this->OutlineRoot.' 0 R');
4911                                 $this->_out('/PageMode /UseOutlines');
4912                         }
4913                         $this->_putviewerpreferences();
4914                         $p = $this->n_ocg_print.' 0 R';
4915                         $v = $this->n_ocg_view.' 0 R';
4916                         $as = "<</Event /Print /OCGs [".$p." ".$v."] /Category [/Print]>> <</Event /View /OCGs [".$p." ".$v."] /Category [/View]>>";
4917                         $this->_out("/OCProperties <</OCGs [".$p." ".$v."] /D <</ON [".$p."] /OFF [".$v."] /AS [".$as."]>>>>");
4918                         $this->_putuserrights();
4919                 }
4920
4921                 /**
4922                 * Output viewer preferences.
4923                 * @author Nicola asuni
4924                 * @since 3.1.000 (2008-06-09)
4925                 * @access protected
4926                 */
4927                 function _putviewerpreferences() {
4928                         $this->_out('/ViewerPreferences<<');
4929                         if ($this->rtl) {
4930                                 $this->_out('/Direction /R2L');
4931                         } else {
4932                                 $this->_out('/Direction /L2R');
4933                         }
4934                         if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
4935                                 $this->_out('/HideToolbar true');
4936                         }
4937                         if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
4938                                 $this->_out('/HideMenubar true');
4939                         }
4940                         if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
4941                                 $this->_out('/HideWindowUI true');
4942                         }
4943                         if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
4944                                 $this->_out('/FitWindow true');
4945                         }
4946                         if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
4947                                 $this->_out('/CenterWindow true');
4948                         }
4949                         if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
4950                                 $this->_out('/DisplayDocTitle true');
4951                         }
4952                         if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
4953                                 $this->_out('/NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'].'');
4954                         }
4955                         if (isset($this->viewer_preferences['ViewArea'])) {
4956                                 $this->_out('/ViewArea /'.$this->viewer_preferences['ViewArea']);
4957                         }
4958                         if (isset($this->viewer_preferences['ViewClip'])) {
4959                                 $this->_out('/ViewClip /'.$this->viewer_preferences['ViewClip']);
4960                         }
4961                         if (isset($this->viewer_preferences['PrintArea'])) {
4962                                 $this->_out('/PrintArea /'.$this->viewer_preferences['PrintArea']);
4963                         }
4964                         if (isset($this->viewer_preferences['PrintClip'])) {
4965                                 $this->_out('/PrintClip /'.$this->viewer_preferences['PrintClip']);
4966                         }
4967                         if (isset($this->viewer_preferences['PrintScaling'])) {
4968                                 $this->_out('/PrintScaling /'.$this->viewer_preferences['PrintScaling']);
4969                         }
4970                         if (isset($this->viewer_preferences['Duplex']) AND (!empty($this->viewer_preferences['Duplex']))) {
4971                                 $this->_out('/Duplex /'.$this->viewer_preferences['Duplex']);
4972                         }
4973                         if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
4974                                 if ($this->viewer_preferences['PickTrayByPDFSize']) {
4975                                         $this->_out('/PickTrayByPDFSize true');
4976                                 } else {
4977                                         $this->_out('/PickTrayByPDFSize false');
4978                                 }
4979                         }
4980                         if (isset($this->viewer_preferences['PrintPageRange'])) {
4981                                 $PrintPageRangeNum = "";
4982                                 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
4983                                         $PrintPageRangeNum .= " ".($v-1)."";
4984                                 }
4985                                 $this->_out('/PrintPageRange ['.substr($PrintPageRangeNum,1).']');
4986                         }
4987                         if (isset($this->viewer_preferences['NumCopies'])) {
4988                                 $this->_out('/NumCopies '.intval($this->viewer_preferences['NumCopies']));
4989                         }
4990                         $this->_out('>>');
4991                 }
4992
4993                 /**
4994                 * Output trailer.
4995                 * @access protected
4996                 */
4997                 function _puttrailer() {
4998                         $this->_out('/Size '.($this->n + 1));
4999                         $this->_out('/Root '.$this->n.' 0 R');
5000                         $this->_out('/Info '.($this->n - 1).' 0 R');
5001                         if ($this->encrypted) {
5002                                 $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');
5003                                 $this->_out('/ID [()()]');
5004                         }
5005                 }
5006
5007                 /**
5008                 * Output PDF header.
5009                 * @access protected
5010                 */
5011                 function _putheader() {
5012                         $this->buffer = '%PDF-'.$this->PDFVersion."\n".$this->buffer;
5013 //                      $this->_out('%PDF-'.$this->PDFVersion);
5014                 }
5015
5016                 /**
5017                 * Output end of document (EOF).
5018                 * @access protected
5019                 */
5020                 function _enddoc() {
5021                         $this->_putheader();
5022                         $this->_putpages();
5023                         $this->_putresources();
5024                         //Info
5025                         $this->_newobj();
5026                         $this->_out('<<');
5027                         $this->_putinfo();
5028                         $this->_out('>>');
5029                         $this->_out('endobj');
5030                         //Catalog
5031                         $this->_newobj();
5032                         $this->_out('<<');
5033                         $this->_putcatalog();
5034                         $this->_out('>>');
5035                         $this->_out('endobj');
5036                         //Cross-ref
5037                         $o = strlen($this->buffer);
5038                         $this->_out('xref');
5039                         $this->_out('0 '.($this->n + 1));
5040                         $this->_out('0000000000 65535 f ');
5041                         for($i=1; $i <= $this->n; $i++) {
5042                                 $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i]));
5043                         }
5044                         //Trailer
5045                         $this->_out('trailer');
5046                         $this->_out('<<');
5047                         $this->_puttrailer();
5048                         $this->_out('>>');
5049                         $this->_out('startxref');
5050                         $this->_out($o);
5051                         $this->_out('%%EOF');
5052                         $this->state = 3;
5053                 }
5054
5055                 /**
5056                 * Initialize a new page.
5057                 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
5058                 * @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>
5059                 * @access protected
5060                 */
5061                 function _beginpage($orientation='', $format='') {
5062                         $this->page++;
5063                         $this->pages[$this->page] = ""; // this mark should be removed before output
5064                         $this->state = 2;
5065                         if (empty($orientation)) {
5066                                 if (isset($this->CurOrientation)) {
5067                                         $orientation = $this->CurOrientation;
5068                                 } else {
5069                                         $orientation = 'P';
5070                                 }
5071                         }
5072                         if (!empty($format)) {
5073                                 $this->setPageFormat($format, $orientation);
5074                         } else {
5075                                 $this->setPageOrientation($orientation);
5076                         }
5077                         if ($this->rtl) {
5078                                 $this->x = $this->w - $this->rMargin;
5079                         } else {
5080                                 $this->x = $this->lMargin;
5081                         }
5082                         $this->y = $this->tMargin;
5083                         if ($this->newpagegroup){
5084                                 // start a new group
5085                                 $n = sizeof($this->pagegroups) + 1;
5086                                 $alias = "{nb".$n."}";
5087                                 $this->pagegroups[$alias] = 1;
5088                                 $this->currpagegroup = $alias;
5089                                 $this->newpagegroup = false;
5090                         } elseif ($this->currpagegroup) {
5091                                 $this->pagegroups[$this->currpagegroup]++;
5092                         }
5093                 }
5094
5095                 /**
5096                 * Mark end of page.
5097                 * @access protected
5098                 */
5099                 function _endpage() {
5100                         $this->setVisibility("all");
5101                         $this->state = 1;
5102                 }
5103
5104                 /**
5105                 * Begin a new object.
5106                 * @access protected
5107                 */
5108                 function _newobj() {
5109                         $this->n++;
5110                         $this->offsets[$this->n] = strlen($this->buffer);
5111                         $this->_out($this->n.' 0 obj');
5112                 }
5113
5114                 /**
5115                 * Underline text.
5116                 * @param int $x X coordinate
5117                 * @param int $y Y coordinate
5118                 * @param string $txt text to underline
5119                 * @access protected
5120                 */
5121                 function _dounderline($x, $y, $txt) {
5122                         $up = $this->CurrentFont['up'];
5123                         $ut = $this->CurrentFont['ut'];
5124                         $w = $this->GetStringWidth($txt);
5125                         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);
5126                 }
5127
5128                 /**
5129                 * Line through text.
5130                 * @param int $x X coordinate
5131                 * @param int $y Y coordinate
5132                 * @param string $txt text to underline
5133                 * @access protected
5134                 */
5135                 function _dolinethrough($x, $y, $txt) {
5136                         $up = $this->CurrentFont['up'];
5137                         $ut = $this->CurrentFont['ut'];
5138                         $w = $this->GetStringWidth($txt);
5139                         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);
5140                 }
5141
5142                 /**
5143                 * Read a 4-byte integer from file.
5144                 * @param string $f file name.
5145                 * @return 4-byte integer
5146                 * @access protected
5147                 */
5148                 function _freadint($f) {
5149                         $a = unpack('Ni', fread($f,4));
5150                         return $a['i'];
5151                 }
5152
5153                 /**
5154                 * Format a text string for meta information
5155                 * @param string $s string to escape.
5156                 * @return string escaped string.
5157                 * @access protected
5158                 */
5159                 function _textstring($s) {
5160                         if ($this->isunicode) {
5161                                 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5162                                         $s = $this->UTF8ToLatin1($s);
5163                                 } else {
5164                                         //Convert string to UTF-16BE
5165                                         $s = $this->UTF8ToUTF16BE($s, true);
5166                                 }
5167                         }
5168                         if ($this->encrypted) {
5169                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
5170                         }
5171                         return '('. $this->_escape($s).')';
5172                 }
5173
5174                 /**
5175                 * Format an URI string
5176                 * @param string $s string to escape.
5177                 * @return string escaped string.
5178                 * @access protected
5179                 */
5180                 function _uristring($s) {
5181                         if ($this->encrypted) {
5182                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
5183                         }
5184                         return '('.$this->_escape($s).')';
5185                 }
5186
5187                 /**
5188                 * Format a text string
5189                 * @param string $s string to escape.
5190                 * @return string escaped string.
5191                 * @access protected
5192                 */
5193                 function _escapetext($s) {
5194                         if ($this->isunicode) {
5195                                 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5196                                         $s = $this->UTF8ToLatin1($s);
5197                                 } else {
5198                                         //Convert string to UTF-16BE and reverse RTL language
5199                                         $s = $this->utf8StrRev($s, false, $this->tmprtl);
5200                                 }
5201                         }
5202                         return $this->_escape($s);
5203                 }
5204
5205                 /**
5206                 * Add "\" before "\", "(" and ")"
5207                 * @param string $s string to escape.
5208                 * @return string escaped string.
5209                 * @access protected
5210                 */
5211                 function _escape($s) {
5212                         // the chr(13) substitution fixes the Bugs item #1421290.
5213                         return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
5214                 }
5215
5216                 /**
5217                 * Output a stream.
5218                 * @param string $s string to output.
5219                 * @access protected
5220                 */
5221                 function _putstream($s) {
5222                         if ($this->encrypted) {
5223                                 $s = $this->_RC4($this->_objectkey($this->n), $s);
5224                         }
5225                         $this->_out('stream');
5226                         $this->_out($s);
5227                         $this->_out('endstream');
5228                 }
5229
5230                 /**
5231                 * Output a string to the document.
5232                 * @param string $s string to output.
5233                 * @access protected
5234                 */
5235                 function _out($s) {
5236                         if ($this->state == 2) {
5237                                 if (isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
5238                                         // puts data before page footer
5239                                         $page = substr($this->pages[$this->page], 0, -$this->footerlen[$this->page]);
5240                                         $footer = substr($this->pages[$this->page], -$this->footerlen[$this->page]);
5241                                         $this->pages[$this->page] = $page." ".$s."\n".$footer;
5242                                 } else {
5243                                         $this->pages[$this->page] .= $s."\n";
5244                                 }
5245                         } else {
5246                                 $this->buffer .= $s."\n";
5247                         }
5248                 }
5249
5250                 /**
5251                 * Adds unicode fonts.<br>
5252                 * Based on PDF Reference 1.3 (section 5)
5253                 * @access protected
5254                 * @author Nicola Asuni
5255                 * @since 1.52.0.TC005 (2005-01-05)
5256                 */
5257                 function _puttruetypeunicode($font) {
5258                         // Type0 Font
5259                         // A composite font composed of other fonts, organized hierarchically
5260                         $this->_newobj();
5261                         $this->_out('<</Type /Font');
5262                         $this->_out('/Subtype /Type0');
5263                         $this->_out('/BaseFont /'.$font['name'].'');
5264                         $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.
5265                         $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]');
5266                         $this->_out('/ToUnicode '.($this->n + 2).' 0 R');
5267                         $this->_out('>>');
5268                         $this->_out('endobj');
5269                         // CIDFontType2
5270                         // A CIDFont whose glyph descriptions are based on TrueType font technology
5271                         $this->_newobj();
5272                         $this->_out('<</Type /Font');
5273                         $this->_out('/Subtype /CIDFontType2');
5274                         $this->_out('/BaseFont /'.$font['name'].'');
5275                         $this->_out('/CIDSystemInfo '.($this->n + 2).' 0 R');
5276                         $this->_out('/FontDescriptor '.($this->n + 3).' 0 R');
5277                         if (isset($font['desc']['MissingWidth'])){
5278                                 $this->_out('/DW '.$font['desc']['MissingWidth'].''); // The default width for glyphs in the CIDFont MissingWidth
5279                         }
5280                         $w = "";
5281                         foreach ($font['cw'] as $cid => $width) {
5282                                 $w .= ''.$cid.' ['.$width.'] '; // define a specific width for each individual CID
5283                         }
5284                         $this->_out('/W ['.$w.']'); // A description of the widths for the glyphs in the CIDFont
5285                         $this->_out('/CIDToGIDMap '.($this->n + 4).' 0 R');
5286                         $this->_out('>>');
5287                         $this->_out('endobj');
5288                         // ToUnicode
5289                         // is a stream object that contains the definition of the CMap
5290                         // (PDF Reference 1.3 chap. 5.9)
5291                         $this->_newobj();
5292                         $this->_out('<</Length 345>>');
5293                         $this->_out('stream');
5294                         $this->_out('/CIDInit /ProcSet findresource begin');
5295                         $this->_out('12 dict begin');
5296                         $this->_out('begincmap');
5297                         $this->_out('/CIDSystemInfo');
5298                         $this->_out('<</Registry (Adobe)');
5299                         $this->_out('/Ordering (UCS)');
5300                         $this->_out('/Supplement 0');
5301                         $this->_out('>> def');
5302                         $this->_out('/CMapName /Adobe-Identity-UCS def');
5303                         $this->_out('/CMapType 2 def');
5304                         $this->_out('1 begincodespacerange');
5305                         $this->_out('<0000> <FFFF>');
5306                         $this->_out('endcodespacerange');
5307                         $this->_out('1 beginbfrange');
5308                         $this->_out('<0000> <FFFF> <0000>');
5309                         $this->_out('endbfrange');
5310                         $this->_out('endcmap');
5311                         $this->_out('CMapName currentdict /CMap defineresource pop');
5312                         $this->_out('end');
5313                         $this->_out('end');
5314                         $this->_out('endstream');
5315                         $this->_out('endobj');
5316                         // CIDSystemInfo dictionary
5317                         // A dictionary containing entries that define the character collection of the CIDFont.
5318                         $this->_newobj();
5319                         $this->_out('<</Registry (Adobe)'); // A string identifying an issuer of character collections
5320                         $this->_out('/Ordering (UCS)'); // A string that uniquely names a character collection issued by a specific registry
5321                         $this->_out('/Supplement 0'); // The supplement number of the character collection.
5322                         $this->_out('>>');
5323                         $this->_out('endobj');
5324                         // Font descriptor
5325                         // A font descriptor describing the CIDFont default metrics other than its glyph widths
5326                         $this->_newobj();
5327                         $this->_out('<</Type /FontDescriptor');
5328                         $this->_out('/FontName /'.$font['name']);
5329                         foreach ($font['desc'] as $key => $value) {
5330                                 $this->_out('/'.$key.' '.$value);
5331                         }
5332                         if ($font['file']) {
5333                                 // A stream containing a TrueType font program
5334                                 $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R');
5335                         }
5336                         $this->_out('>>');
5337                         $this->_out('endobj');
5338                         // Embed CIDToGIDMap
5339                         // A specification of the mapping from CIDs to glyph indices
5340                         $this->_newobj();
5341                         $ctgfile = $this->_getfontpath().strtolower($font['ctg']);
5342                         if (!file_exists($ctgfile)) {
5343                                 $this->Error('Font file not found: '.$ctgfile);
5344                         }
5345                         $size = filesize($ctgfile);
5346                         $this->_out('<</Length '.$size.'');
5347                         if (substr($ctgfile, -2) == '.z') { // check file extension
5348                                 /* Decompresses data encoded using the public-domain
5349                                 zlib/deflate compression method, reproducing the
5350                                 original text or binary data */
5351                                 $this->_out('/Filter /FlateDecode');
5352                         }
5353                         $this->_out('>>');
5354                         $this->_putstream(file_get_contents($ctgfile));
5355                         $this->_out('endobj');
5356                 }
5357
5358                  /**
5359                  * Converts UTF-8 strings to codepoints array.<br>
5360                  * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
5361                  * Based on: http://www.faqs.org/rfcs/rfc3629.html
5362                  * <pre>
5363                  *        Char. number range  |        UTF-8 octet sequence
5364                  *       (hexadecimal)    |              (binary)
5365                  *    --------------------+-----------------------------------------------
5366                  *    0000 0000-0000 007F | 0xxxxxxx
5367                  *    0000 0080-0000 07FF | 110xxxxx 10xxxxxx
5368                  *    0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
5369                  *    0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
5370                  *    ---------------------------------------------------------------------
5371                  *
5372                  *   ABFN notation:
5373                  *   ---------------------------------------------------------------------
5374                  *   UTF8-octets = *( UTF8-char )
5375                  *   UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
5376                  *   UTF8-1      = %x00-7F
5377                  *   UTF8-2      = %xC2-DF UTF8-tail
5378                  *
5379                  *   UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
5380                  *                 %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
5381                  *   UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
5382                  *                 %xF4 %x80-8F 2( UTF8-tail )
5383                  *   UTF8-tail   = %x80-BF
5384                  *   ---------------------------------------------------------------------
5385                  * </pre>
5386                  * @param string $str string to process.
5387                  * @return array containing codepoints (UTF-8 characters values)
5388                  * @access protected
5389                  * @author Nicola Asuni
5390                  * @since 1.53.0.TC005 (2005-01-05)
5391                  */
5392                 function UTF8StringToArray($str) {
5393                         if (!$this->isunicode) {
5394                                 // split string into array of equivalent codes
5395                                 $strarr = array();
5396                                 $strlen = strlen($str);
5397                                 for($i=0; $i < $strlen; $i++) {
5398                                         $strarr[] = ord($str{$i});
5399                                 }
5400                                 return $strarr;
5401                         }
5402                         $unicode = array(); // array containing unicode values
5403                         $bytes  = array(); // array containing single character byte sequences
5404                         $numbytes  = 1; // number of octetc needed to represent the UTF-8 character
5405                         $str .= ""; // force $str to be a string
5406                         $length = strlen($str);
5407                         for($i = 0; $i < $length; $i++) {
5408                                 $char = ord($str{$i}); // get one string character at time
5409                                 if (count($bytes) == 0) { // get starting octect
5410                                         if ($char <= 0x7F) {
5411                                                 $unicode[] = $char; // use the character "as is" because is ASCII
5412                                                 $numbytes = 1;
5413                                         } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
5414                                                 $bytes[] = ($char - 0xC0) << 0x06;
5415                                                 $numbytes = 2;
5416                                         } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
5417                                                 $bytes[] = ($char - 0xE0) << 0x0C;
5418                                                 $numbytes = 3;
5419                                         } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
5420                                                 $bytes[] = ($char - 0xF0) << 0x12;
5421                                                 $numbytes = 4;
5422                                         } else {
5423                                                 // use replacement character for other invalid sequences
5424                                                 $unicode[] = 0xFFFD;
5425                                                 $bytes = array();
5426                                                 $numbytes = 1;
5427                                         }
5428                                 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
5429                                         $bytes[] = $char - 0x80;
5430                                         if (count($bytes) == $numbytes) {
5431                                                 // compose UTF-8 bytes to a single unicode value
5432                                                 $char = $bytes[0];
5433                                                 for($j = 1; $j < $numbytes; $j++) {
5434                                                         $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
5435                                                 }
5436                                                 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
5437                                                         /* The definition of UTF-8 prohibits encoding character numbers between
5438                                                         U+D800 and U+DFFF, which are reserved for use with the UTF-16
5439                                                         encoding form (as surrogate pairs) and do not directly represent
5440                                                         characters. */
5441                                                         $unicode[] = 0xFFFD; // use replacement character
5442                                                 } else {
5443                                                         $unicode[] = $char; // add char to array
5444                                                 }
5445                                                 // reset data for next char
5446                                                 $bytes = array();
5447                                                 $numbytes = 1;
5448                                         }
5449                                 } else {
5450                                         // use replacement character for other invalid sequences
5451                                         $unicode[] = 0xFFFD;
5452                                         $bytes = array();
5453                                         $numbytes = 1;
5454                                 }
5455                         }
5456                         return $unicode;
5457                 }
5458
5459                 /**
5460                  * Converts UTF-8 strings to UTF16-BE.<br>
5461                  * @param string $str string to process.
5462                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5463                  * @return string
5464                  * @access protected
5465                  * @author Nicola Asuni
5466                  * @since 1.53.0.TC005 (2005-01-05)
5467                  * @uses UTF8StringToArray(), arrUTF8ToUTF16BE()
5468                  */
5469                 function UTF8ToUTF16BE($str, $setbom=true) {
5470                         if (!$this->isunicode) {
5471                                 return $str; // string is not in unicode
5472                         }
5473                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5474                         return $this->arrUTF8ToUTF16BE($unicode, $setbom);
5475                 }
5476
5477                 /**
5478                  * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
5479                  * @param string $str string to process.
5480                  * @return string
5481                  * @author Andrew Whitehead, Nicola Asuni
5482                  * @access protected
5483                  * @since 3.2.000 (2008-06-23)
5484                  */
5485                 function UTF8ToLatin1($str) {
5486                         if (!$this->isunicode) {
5487                                 return $str; // string is not in unicode
5488                         }
5489                         $outstr = ""; // string to be returned
5490                         $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
5491                         foreach ($unicode as $char) {
5492                                 if ($char == 0xFFFD) {
5493                                         // skip
5494                                 } elseif ($char == 0x2022) {
5495                                         // fix for middot
5496                                         $outstr .= chr(183);
5497                                 } elseif ($char < 256) {
5498                                         $outstr .= chr($char);
5499                                 } else {
5500                                         $outstr .= '?';
5501                                 }
5502                         }
5503                         return $outstr;
5504                 }
5505
5506                 /**
5507                  * Converts array of UTF-8 characters to UTF16-BE string.<br>
5508                  * Based on: http://www.faqs.org/rfcs/rfc2781.html
5509                  * <pre>
5510                  *   Encoding UTF-16:
5511                  *
5512                  *   Encoding of a single character from an ISO 10646 character value to
5513                  *    UTF-16 proceeds as follows. Let U be the character number, no greater
5514                  *    than 0x10FFFF.
5515                  *
5516                  *    1) If U < 0x10000, encode U as a 16-bit unsigned integer and
5517                  *       terminate.
5518                  *
5519                  *    2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
5520                  *       U' must be less than or equal to 0xFFFFF. That is, U' can be
5521                  *       represented in 20 bits.
5522                  *
5523                  *    3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
5524                  *       0xDC00, respectively. These integers each have 10 bits free to
5525                  *       encode the character value, for a total of 20 bits.
5526                  *
5527                  *    4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
5528                  *       bits of W1 and the 10 low-order bits of U' to the 10 low-order
5529                  *       bits of W2. Terminate.
5530                  *
5531                  *    Graphically, steps 2 through 4 look like:
5532                  *    U' = yyyyyyyyyyxxxxxxxxxx
5533                  *    W1 = 110110yyyyyyyyyy
5534                  *    W2 = 110111xxxxxxxxxx
5535                  * </pre>
5536                  * @param array $unicode array containing UTF-8 unicode values
5537                  * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF)
5538                  * @return string
5539                  * @access protected
5540                  * @author Nicola Asuni
5541                  * @since 2.1.000 (2008-01-08)
5542                  * @see UTF8ToUTF16BE()
5543                  */
5544                 function arrUTF8ToUTF16BE($unicode, $setbom=true) {
5545                         $outstr = ""; // string to be returned
5546                         if ($setbom) {
5547                                 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
5548                         }
5549                         foreach($unicode as $char) {
5550                                 if ($char == 0xFFFD) {
5551                                         $outstr .= "\xFF\xFD"; // replacement character
5552                                 } elseif ($char < 0x10000) {
5553                                         $outstr .= chr($char >> 0x08);
5554                                         $outstr .= chr($char & 0xFF);
5555                                 } else {
5556                                         $char -= 0x10000;
5557                                         $w1 = 0xD800 | ($char >> 0x10);
5558                                         $w2 = 0xDC00 | ($char & 0x3FF);
5559                                         $outstr .= chr($w1 >> 0x08);
5560                                         $outstr .= chr($w1 & 0xFF);
5561                                         $outstr .= chr($w2 >> 0x08);
5562                                         $outstr .= chr($w2 & 0xFF);
5563                                 }
5564                         }
5565                         return $outstr;
5566                 }
5567                 // ====================================================
5568
5569                 /**
5570                  * Set header font.
5571                  * @param array $font font
5572                  * @since 1.1
5573                  */
5574                 function setHeaderFont($font) {
5575                         $this->header_font = $font;
5576                 }
5577
5578                 /**
5579                  * Get header font.
5580                  * @return array()
5581                  * @since 4.0.012 (2008-07-24)
5582                  */
5583                 function getHeaderFont() {
5584                         return $this->header_font;
5585                 }
5586
5587                 /**
5588                  * Set footer font.
5589                  * @param array $font font
5590                  * @since 1.1
5591                  */
5592                 function setFooterFont($font) {
5593                         $this->footer_font = $font;
5594                 }
5595
5596                 /**
5597                  * Get Footer font.
5598                  * @return array()
5599                  * @since 4.0.012 (2008-07-24)
5600                  */
5601                 function getFooterFont() {
5602                         return $this->footer_font;
5603                 }
5604
5605                 /**
5606                  * Set language array.
5607                  * @param array $language
5608                  * @since 1.1
5609                  */
5610                 function setLanguageArray($language) {
5611                         $this->l = $language;
5612                         $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
5613                 }
5614
5615                 /**
5616                  * Returns the PDF data.
5617                  */
5618                 function getPDFData() {
5619                         if ($this->state < 3) {
5620                                 $this->Close();
5621                         }
5622                         return $this->buffer;
5623                 }
5624
5625                 /**
5626                  * Sets font style.
5627                  * @param string $tag tag name in lowercase. Supported tags are:<ul>
5628                  * <li>b : bold text</li>
5629                  * <li>i : italic</li>
5630                  * <li>u : underlined</li>
5631                  * <li>d : line-through</li></ul>
5632                  * @param boolean $enable
5633                  * @access protected
5634                  */
5635                 function setStyle($tag, $enable) {
5636                         $this->$tag += ($enable ? 1 : -1);
5637                         $style = '';
5638                         foreach(array('b', 'i', 'u', 'd') as $s) {
5639                                 if ($this->$s > 0) {
5640                                         $style .= $s;
5641                                 }
5642                         }
5643                         $this->SetFont('', $style);
5644                 }
5645
5646                 /**
5647                  * Output anchor link.
5648                  * @param string $url link URL
5649                  * @param string $name link name
5650                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
5651                  * @param boolean $firstline if true prints only the first line and return the remaining string.
5652                  * @return the number of cells used or the remaining text if $firstline = true;
5653                  * @access public
5654                  */
5655                 function addHtmlLink($url, $name, $fill=0, $firstline=false) {
5656                         $prevcolor = $this->fgcolor;
5657                         $this->SetTextColor(0, 0, 255);
5658                         $this->setStyle('u', true);
5659                         $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline);
5660                         $this->setStyle('u', false);
5661                         $this->SetTextColorArray($prevcolor);
5662                         return $ret;
5663                 }
5664
5665                 /**
5666                  * 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).
5667                  * @param string $color html color
5668                  * @return array
5669                  * @access protected
5670                  */
5671                 function convertHTMLColorToDec($color="#000000") {
5672                         global $webcolor;
5673                         $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces
5674                         // set default color to be returned in case of error
5675                         $returncolor = array ('R' => 0, 'G' => 0, 'B' => 0);
5676                         if (empty($color)) {
5677                                 return $returncolor;
5678                         }
5679                         if (substr(strtolower($color), 0, 3) == 'rgb') {
5680                                 $codes = substr($color, 4);
5681                                 $codes = str_replace(')', '', $codes);
5682                                 $returncolor = explode(',', $codes, 3);
5683                                 return $returncolor;    
5684                         }
5685                         if (substr($color, 0, 1) != "#") {
5686                                 // decode color name
5687                                 if (isset($webcolor[strtolower($color)])) {
5688                                         $color_code = $webcolor[strtolower($color)];
5689                                 } else {
5690                                         return $returncolor;
5691                                 }
5692                         } else {
5693                                 $color_code = substr($color, 1);
5694                         }
5695                         switch (strlen($color_code)) {
5696                                 case 3: {
5697                                         // three-digit hexadecimal representation
5698                                         $r = substr($color_code, 0, 1);
5699                                         $g = substr($color_code, 1, 1);
5700                                         $b = substr($color_code, 2, 1);
5701                                         $returncolor['R'] = hexdec($r.$r);
5702                                         $returncolor['G'] = hexdec($g.$g);
5703                                         $returncolor['B'] = hexdec($b.$b);
5704                                         break;
5705                                 }
5706                                 case 6: {
5707                                         // six-digit hexadecimal representation
5708                                         $returncolor['R'] = hexdec(substr($color_code, 0, 2));
5709                                         $returncolor['G'] = hexdec(substr($color_code, 2, 2));
5710                                         $returncolor['B'] = hexdec(substr($color_code, 4, 2));
5711                                         break;
5712                                 }
5713                         }
5714                         return $returncolor;
5715                 }
5716
5717                 /**
5718                  * Converts pixels to Units.
5719                  * @param int $px pixels
5720                  * @return float millimeters
5721                  * @access public
5722                  */
5723                 function pixelsToUnits($px){
5724                         return $px / $this->k;
5725                 }
5726
5727                 /**
5728                  * Reverse function for htmlentities.
5729                  * Convert entities in UTF-8.
5730                  * @param $text_to_convert Text to convert.
5731                  * @return string converted
5732                  */
5733                 function unhtmlentities($text_to_convert) {
5734                         return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
5735                 }
5736
5737                 // ENCRYPTION METHODS ----------------------------------
5738                 // SINCE 2.0.000 (2008-01-02)
5739                 /**
5740                 * Compute encryption key depending on object number where the encrypted data is stored
5741                 * @param int $n object number
5742                 * @since 2.0.000 (2008-01-02)
5743                 */
5744                 function _objectkey($n) {
5745                         return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);
5746                 }
5747
5748                 /**
5749                  * Put encryption on PDF document.
5750                  * @since 2.0.000 (2008-01-02)
5751                  */
5752                 function _putencryption() {
5753                         $this->_out('/Filter /Standard');
5754                         $this->_out('/V 1');
5755                         $this->_out('/R 2');
5756                         $this->_out('/O ('.$this->_escape($this->Ovalue).')');
5757                         $this->_out('/U ('.$this->_escape($this->Uvalue).')');
5758                         $this->_out('/P '.$this->Pvalue);
5759                 }
5760
5761                 /**
5762                 * Returns the input text exrypted using RC4 algorithm and the specified key.
5763                 * RC4 is the standard encryption algorithm used in PDF format
5764                 * @param string $key encryption key
5765                 * @param String $text input text to be encrypted
5766                 * @return String encrypted text
5767                 * @since 2.0.000 (2008-01-02)
5768                 * @author Klemen Vodopivec
5769                 */
5770                 function _RC4($key, $text) {
5771                         if ($this->last_rc4_key != $key) {
5772                                 $k = str_repeat($key, 256/strlen($key)+1);
5773                                 $rc4 = range(0,255);
5774                                 $j = 0;
5775                                 for ($i=0; $i < 256; $i++) {
5776                                         $t = $rc4[$i];
5777                                         $j = ($j + $t + ord($k{$i})) % 256;
5778                                         $rc4[$i] = $rc4[$j];
5779                                         $rc4[$j] = $t;
5780                                 }
5781                                 $this->last_rc4_key = $key;
5782                                 $this->last_rc4_key_c = $rc4;
5783                         } else {
5784                                 $rc4 = $this->last_rc4_key_c;
5785                         }
5786                         $len = strlen($text);
5787                         $a = 0;
5788                         $b = 0;
5789                         $out = '';
5790                         for ($i=0; $i < $len; $i++) {
5791                                 $a = ($a + 1) % 256;
5792                                 $t = $rc4[$a];
5793                                 $b = ($b + $t) % 256;
5794                                 $rc4[$a] = $rc4[$b];
5795                                 $rc4[$b] = $t;
5796                                 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
5797                                 $out .= chr(ord($text{$i}) ^ $k);
5798                         }
5799                         return $out;
5800                 }
5801
5802                 /**
5803                 * Encrypts a string using MD5 and returns it's value as a binary string.
5804                 * @param string $str input string
5805                 * @return String MD5 encrypted binary string
5806                 * @since 2.0.000 (2008-01-02)
5807                 * @author Klemen Vodopivec
5808                 */
5809                 function _md5_16($str) {
5810                         return pack('H*',md5($str));
5811                 }
5812
5813                 /**
5814                 * Compute O value (used for RC4 encryption)
5815                 * @param String $user_pass user password
5816                 * @param String $owner_pass user password
5817                 * @return String O value
5818                 * @since 2.0.000 (2008-01-02)
5819                 * @author Klemen Vodopivec
5820                 */
5821                 function _Ovalue($user_pass, $owner_pass) {
5822                         $tmp = $this->_md5_16($owner_pass);
5823                         $owner_RC4_key = substr($tmp,0,5);
5824                         return $this->_RC4($owner_RC4_key, $user_pass);
5825                 }
5826
5827                 /**
5828                 * Compute U value (used for RC4 encryption)
5829                 * @return String U value
5830                 * @since 2.0.000 (2008-01-02)
5831                 * @author Klemen Vodopivec
5832                 */
5833                 function _Uvalue() {
5834                         return $this->_RC4($this->encryption_key, $this->padding);
5835                 }
5836
5837                 /**
5838                 * Compute encryption key
5839                 * @param String $user_pass user password
5840                 * @param String $owner_pass user password
5841                 * @param String $protection protection type
5842                 * @since 2.0.000 (2008-01-02)
5843                 * @author Klemen Vodopivec
5844                 */
5845                 function _generateencryptionkey($user_pass, $owner_pass, $protection) {
5846                         // Pad passwords
5847                         $user_pass = substr($user_pass.$this->padding,0,32);
5848                         $owner_pass = substr($owner_pass.$this->padding,0,32);
5849                         // Compute O value
5850                         $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
5851                         // Compute encyption key
5852                         $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");
5853                         $this->encryption_key = substr($tmp,0,5);
5854                         // Compute U value
5855                         $this->Uvalue = $this->_Uvalue();
5856                         // Compute P value
5857                         $this->Pvalue = -(($protection^255)+1);
5858                 }
5859
5860                 /**
5861                 * Set document protection
5862                 * The permission array is composed of values taken from the following ones:
5863                 * - copy: copy text and images to the clipboard
5864                 * - print: print the document
5865                 * - modify: modify it (except for annotations and forms)
5866                 * - annot-forms: add annotations and forms
5867                 * Remark: the protection against modification is for people who have the full Acrobat product.
5868                 * 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.
5869                 * 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.
5870                 * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms)
5871                 * @param String $user_pass user password. Empty by default.
5872                 * @param String $owner_pass owner password. If not specified, a random value is used.
5873                 * @since 2.0.000 (2008-01-02)
5874                 * @author Klemen Vodopivec
5875                 */
5876                 function SetProtection($permissions=array(), $user_pass='', $owner_pass=null) {
5877                         $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
5878                         $protection = 192;
5879                         foreach($permissions as $permission) {
5880                                 if (!isset($options[$permission])) {
5881                                         $this->Error('Incorrect permission: '.$permission);
5882                                 }
5883                                 $protection += $options[$permission];
5884                         }
5885                         if ($owner_pass === null) {
5886                                 $owner_pass = uniqid(rand());
5887                         }
5888                         $this->encrypted = true;
5889                         $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
5890                 }
5891
5892                 // END OF ENCRYPTION FUNCTIONS -------------------------
5893
5894                 // START TRANSFORMATIONS SECTION -----------------------
5895                 // authors: Moritz Wagner, Andreas Wurmser, Nicola Asuni
5896
5897                 /**
5898                 * Starts a 2D tranformation saving current graphic state.
5899                 * This function must be called before scaling, mirroring, translation, rotation and skewing.
5900                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5901                 * @since 2.1.000 (2008-01-07)
5902                 * @see StartTransform(), StopTransform()
5903                 */
5904                 function StartTransform() {
5905                         $this->_out('q');
5906                 }
5907
5908                 /**
5909                 * Stops a 2D tranformation restoring previous graphic state.
5910                 * This function must be called after scaling, mirroring, translation, rotation and skewing.
5911                 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
5912                 * @since 2.1.000 (2008-01-07)
5913                 * @see StartTransform(), StopTransform()
5914                 */
5915                 function StopTransform() {
5916                         $this->_out('Q');
5917                 }
5918                 /**
5919                 * Horizontal Scaling.
5920                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5921                 * @param int $x abscissa of the scaling center. Default is current x position
5922                 * @param int $y ordinate of the scaling center. Default is current y position
5923                 * @since 2.1.000 (2008-01-07)
5924                 * @see StartTransform(), StopTransform()
5925                 */
5926                 function ScaleX($s_x, $x='', $y=''){
5927                         $this->Scale($s_x, 100, $x, $y);
5928                 }
5929
5930                 /**
5931                 * Vertical Scaling.
5932                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5933                 * @param int $x abscissa of the scaling center. Default is current x position
5934                 * @param int $y ordinate of the scaling center. Default is current y position
5935                 * @since 2.1.000 (2008-01-07)
5936                 * @see StartTransform(), StopTransform()
5937                 */
5938                 function ScaleY($s_y, $x='', $y=''){
5939                         $this->Scale(100, $s_y, $x, $y);
5940                 }
5941
5942                 /**
5943                 * Vertical and horizontal proportional Scaling.
5944                 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
5945                 * @param int $x abscissa of the scaling center. Default is current x position
5946                 * @param int $y ordinate of the scaling center. Default is current y position
5947                 * @since 2.1.000 (2008-01-07)
5948                 * @see StartTransform(), StopTransform()
5949                 */
5950                 function ScaleXY($s, $x='', $y=''){
5951                         $this->Scale($s, $s, $x, $y);
5952                 }
5953
5954                 /**
5955                 * Vertical and horizontal non-proportional Scaling.
5956                 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
5957                 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
5958                 * @param int $x abscissa of the scaling center. Default is current x position
5959                 * @param int $y ordinate of the scaling center. Default is current y position
5960                 * @since 2.1.000 (2008-01-07)
5961                 * @see StartTransform(), StopTransform()
5962                 */
5963                 function Scale($s_x, $s_y, $x='', $y=''){
5964                         if ($x === '') {
5965                                 $x=$this->x;
5966                         }
5967                         if ($y === '') {
5968                                 $y=$this->y;
5969                         }
5970                         if ($this->rtl) {
5971                                 $x = $this->w - $x;
5972                         }
5973                         if (($s_x == 0) OR ($s_y == 0)) {
5974                                 $this->Error('Please do not use values equal to zero for scaling');
5975                         }
5976                         $y = ($this->h - $y) * $this->k;
5977                         $x *= $this->k;
5978                         //calculate elements of transformation matrix
5979                         $s_x /= 100;
5980                         $s_y /= 100;
5981                         $tm[0] = $s_x;
5982                         $tm[1] = 0;
5983                         $tm[2] = 0;
5984                         $tm[3] = $s_y;
5985                         $tm[4] = $x * (1 - $s_x);
5986                         $tm[5] = $y * (1 - $s_y);
5987                         //scale the coordinate system
5988                         $this->Transform($tm);
5989                 }
5990
5991                 /**
5992                 * Horizontal Mirroring.
5993                 * @param int $x abscissa of the point. Default is current x position
5994                 * @since 2.1.000 (2008-01-07)
5995                 * @see StartTransform(), StopTransform()
5996                 */
5997                 function MirrorH($x=''){
5998                         $this->Scale(-100, 100, $x);
5999                 }
6000
6001                 /**
6002                 * Verical Mirroring.
6003                 * @param int $y ordinate of the point. Default is current y position
6004                 * @since 2.1.000 (2008-01-07)
6005                 * @see StartTransform(), StopTransform()
6006                 */
6007                 function MirrorV($y=''){
6008                         $this->Scale(100, -100, '', $y);
6009                 }
6010
6011                 /**
6012                 * Point reflection mirroring.
6013                 * @param int $x abscissa of the point. Default is current x position
6014                 * @param int $y ordinate of the point. Default is current y position
6015                 * @since 2.1.000 (2008-01-07)
6016                 * @see StartTransform(), StopTransform()
6017                 */
6018                 function MirrorP($x='',$y=''){
6019                         $this->Scale(-100, -100, $x, $y);
6020                 }
6021
6022                 /**
6023                 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
6024                 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
6025                 * @param int $x abscissa of the point. Default is current x position
6026                 * @param int $y ordinate of the point. Default is current y position
6027                 * @since 2.1.000 (2008-01-07)
6028                 * @see StartTransform(), StopTransform()
6029                 */
6030                 function MirrorL($angle=0, $x='',$y=''){
6031                         $this->Scale(-100, 100, $x, $y);
6032                         $this->Rotate(-2*($angle-90), $x, $y);
6033                 }
6034
6035                 /**
6036                 * Translate graphic object horizontally.
6037                 * @param int $t_x movement to the right (or left for RTL)
6038                 * @since 2.1.000 (2008-01-07)
6039                 * @see StartTransform(), StopTransform()
6040                 */
6041                 function TranslateX($t_x){
6042                         $this->Translate($t_x, 0);
6043                 }
6044
6045                 /**
6046                 * Translate graphic object vertically.
6047                 * @param int $t_y movement to the bottom
6048                 * @since 2.1.000 (2008-01-07)
6049                 * @see StartTransform(), StopTransform()
6050                 */
6051                 function TranslateY($t_y){
6052                         $this->Translate(0, $t_y);
6053                 }
6054
6055                 /**
6056                 * Translate graphic object horizontally and vertically.
6057                 * @param int $t_x movement to the right
6058                 * @param int $t_y movement to the bottom
6059                 * @since 2.1.000 (2008-01-07)
6060                 * @see StartTransform(), StopTransform()
6061                 */
6062                 function Translate($t_x, $t_y){
6063                         if ($this->rtl) {
6064                                 $t_x = -$t_x;
6065                         }
6066                         //calculate elements of transformation matrix
6067                         $tm[0] = 1;
6068                         $tm[1] = 0;
6069                         $tm[2] = 0;
6070                         $tm[3] = 1;
6071                         $tm[4] = $t_x * $this->k;
6072                         $tm[5] = -$t_y * $this->k;
6073                         //translate the coordinate system
6074                         $this->Transform($tm);
6075                 }
6076
6077                 /**
6078                 * Rotate object.
6079                 * @param float $angle angle in degrees for counter-clockwise rotation
6080                 * @param int $x abscissa of the rotation center. Default is current x position
6081                 * @param int $y ordinate of the rotation center. Default is current y position
6082                 * @since 2.1.000 (2008-01-07)
6083                 * @see StartTransform(), StopTransform()
6084                 */
6085                 function Rotate($angle, $x='', $y=''){
6086                         if ($x === '') {
6087                                 $x=$this->x;
6088                         }
6089                         if ($y === '') {
6090                                 $y=$this->y;
6091                         }
6092                         if ($this->rtl) {
6093                                 $x = $this->w - $x;
6094                                 $angle = -$angle;
6095                         }
6096                         $y = ($this->h - $y) * $this->k;
6097                         $x *= $this->k;
6098                         //calculate elements of transformation matrix
6099                         $tm[0] = cos(deg2rad($angle));
6100                         $tm[1] = sin(deg2rad($angle));
6101                         $tm[2] = -$tm[1];
6102                         $tm[3] = $tm[0];
6103                         $tm[4] = $x + $tm[1] * $y - $tm[0] * $x;
6104                         $tm[5] = $y - $tm[0] * $y - $tm[1] * $x;
6105                         //rotate the coordinate system around ($x,$y)
6106                         $this->Transform($tm);
6107                 }
6108
6109                 /**
6110                 * Skew horizontally.
6111                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6112                 * @param int $x abscissa of the skewing center. default is current x position
6113                 * @param int $y ordinate of the skewing center. default is current y position
6114                 * @since 2.1.000 (2008-01-07)
6115                 * @see StartTransform(), StopTransform()
6116                 */
6117                 function SkewX($angle_x, $x='', $y=''){
6118                         $this->Skew($angle_x, 0, $x, $y);
6119                 }
6120
6121                 /**
6122                 * Skew vertically.
6123                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6124                 * @param int $x abscissa of the skewing center. default is current x position
6125                 * @param int $y ordinate of the skewing center. default is current y position
6126                 * @since 2.1.000 (2008-01-07)
6127                 * @see StartTransform(), StopTransform()
6128                 */
6129                 function SkewY($angle_y, $x='', $y=''){
6130                         $this->Skew(0, $angle_y, $x, $y);
6131                 }
6132
6133                 /**
6134                 * Skew.
6135                 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
6136                 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
6137                 * @param int $x abscissa of the skewing center. default is current x position
6138                 * @param int $y ordinate of the skewing center. default is current y position
6139                 * @since 2.1.000 (2008-01-07)
6140                 * @see StartTransform(), StopTransform()
6141                 */
6142                 function Skew($angle_x, $angle_y, $x='', $y=''){
6143                         if ($x === '') {
6144                                 $x = $this->x;
6145                         }
6146                         if ($y === '') {
6147                                 $y = $this->y;
6148                         }
6149                         if ($this->rtl) {
6150                                 $x = $this->w - $x;
6151                                 $angle_x = -$angle_x;
6152                         }
6153                         if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
6154                                 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
6155                         }
6156                         $x *= $this->k;
6157                         $y = ($this->h - $y) * $this->k;
6158                         //calculate elements of transformation matrix
6159                         $tm[0] = 1;
6160                         $tm[1] = tan(deg2rad($angle_y));
6161                         $tm[2] = tan(deg2rad($angle_x));
6162                         $tm[3] = 1;
6163                         $tm[4] = -$tm[2] * $y;
6164                         $tm[5] = -$tm[1] * $x;
6165                         //skew the coordinate system
6166                         $this->Transform($tm);
6167                 }
6168
6169                 /**
6170                 * Apply graphic transformations.
6171                 * @since 2.1.000 (2008-01-07)
6172                 * @see StartTransform(), StopTransform()
6173                 */
6174                 function Transform($tm){
6175                         $this->_out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
6176                 }
6177
6178                 // END TRANSFORMATIONS SECTION -------------------------
6179
6180
6181                 // START GRAPHIC FUNCTIONS SECTION ---------------------
6182                 // The following section is based on the code provided by David Hernandez Sanz
6183
6184                 /**
6185                 * 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.
6186                 * @param float $width The width.
6187                 * @since 1.0
6188                 * @see Line(), Rect(), Cell(), MultiCell()
6189                 */
6190                 function SetLineWidth($width) {
6191                         //Set line width
6192                         $this->LineWidth = $width;
6193                         //$this->linestyleWidth = sprintf('%.2f w', ($width * $this->k));
6194                         // FrontAccounting fix
6195                         // My PHP 5.2.6 environment gave an "Unsupported operand types"
6196                         // error for the multiplication on the next line some of the
6197                         // time when this method is called - I debugged and sometimes
6198                         // the $width parameter is some sort of weird array.  I don't
6199                         // understand what's going on, but casting it to a (float) seems
6200                         // to "fix" the problem.  -Jason Maas, 2009/09/25
6201                         $this->linestyleWidth = sprintf('%.2f w', ((float) $width * (float) $this->k));
6202                         $this->_out($this->linestyleWidth);
6203                 }
6204
6205                 /**
6206                 * Returns the current the line width.
6207                 * @return int Line width
6208                 * @since 2.1.000 (2008-01-07)
6209                 * @see Line(), SetLineWidth()
6210                 */
6211                 function GetLineWidth() {
6212                         return $this->LineWidth;
6213                 }
6214
6215                 /**
6216                 * Set line style.
6217                 * @param array $style Line style. Array with keys among the following:
6218                 * <ul>
6219                 *        <li>width (float): Width of the line in user units.</li>
6220                 *        <li>cap (string): Type of cap to put on the line. Possible values are:
6221                 * butt, round, square. The difference between "square" and "butt" is that
6222                 * "square" projects a flat end past the end of the line.</li>
6223                 *        <li>join (string): Type of join. Possible values are: miter, round,
6224                 * bevel.</li>
6225                 *        <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
6226                 * series of length values, which are the lengths of the on and off dashes.
6227                 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
6228                 * 1 off, 2 on, 1 off, ...</li>
6229                 *        <li>phase (integer): Modifier on the dash pattern which is used to shift
6230                 * the point at which the pattern starts.</li>
6231                 *        <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
6232                 * </ul>
6233                 * @access public
6234                 * @since 2.1.000 (2008-01-08)
6235                 */
6236                 function SetLineStyle($style) {
6237                         extract($style);
6238                         if (isset($width)) {
6239                                 $width_prev = $this->LineWidth;
6240                                 $this->SetLineWidth($width);
6241                                 $this->LineWidth = $width_prev;
6242                         }
6243                         if (isset($cap)) {
6244                                 $ca = array("butt" => 0, "round"=> 1, "square" => 2);
6245                                 if (isset($ca[$cap])) {
6246                                         $this->linestyleCap = $ca[$cap]." J";
6247                                         $this->_out($this->linestyleCap);
6248                                 }
6249                         }
6250                         if (isset($join)) {
6251                                 $ja = array("miter" => 0, "round" => 1, "bevel" => 2);
6252                                 if (isset($ja[$join])) {
6253                                         $this->linestyleJoin = $ja[$join]." j";
6254                                         $this->_out($this->linestyleJoin);
6255                                 }
6256                         }
6257                         if (isset($dash)) {
6258                                 $dash_string = "";
6259                                 if ($dash) {
6260                                         if (preg_match("/^.+,/", $dash)) {
6261                                                 $tab = explode(",", $dash);
6262                                         } else {
6263                                                 $tab = array($dash);
6264                                         }
6265                                         $dash_string = "";
6266                                         foreach ($tab as $i => $v) {
6267                                                 if ($i) {
6268                                                         $dash_string .= " ";
6269                                                 }
6270                                                 $dash_string .= sprintf("%.2f", $v);
6271                                         }
6272                                 }
6273                                 if (!isset($phase) OR !$dash) {
6274                                         $phase = 0;
6275                                 }
6276                                 $this->linestyleDash = sprintf("[%s] %.2f d", $dash_string, $phase);
6277                                 $this->_out($this->linestyleDash);
6278                         }
6279                         if (isset($color)) {
6280                                 $this->SetDrawColorArray($color);
6281                         }
6282                 }
6283
6284                 /*
6285                 * Set a draw point.
6286                 * @param float $x Abscissa of point.
6287                 * @param float $y Ordinate of point.
6288                 * @access protected
6289                 * @since 2.1.000 (2008-01-08)
6290                 */
6291                 function _outPoint($x, $y) {
6292                         if ($this->rtl) {
6293                                 $x = $this->w - $x;
6294                         }
6295                         $this->_out(sprintf("%.2f %.2f m", $x * $this->k, ($this->h - $y) * $this->k));
6296                 }
6297
6298                 /*
6299                 * Draws a line from last draw point.
6300                 * @param float $x Abscissa of end point.
6301                 * @param float $y Ordinate of end point.
6302                 * @access protected
6303                 * @since 2.1.000 (2008-01-08)
6304                 */
6305                 function _outLine($x, $y) {
6306                         if ($this->rtl) {
6307                                 $x = $this->w - $x;
6308                         }
6309                         $this->_out(sprintf("%.2f %.2f l", $x * $this->k, ($this->h - $y) * $this->k));
6310                 }
6311
6312                 /**
6313                 * Draws a rectangle.
6314                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6315                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6316                 * @param float $w Width.
6317                 * @param float $h Height.
6318                 * @param string $op options
6319                 * @access protected
6320                 * @since 2.1.000 (2008-01-08)
6321                 */
6322                 function _outRect($x, $y, $w, $h, $op) {
6323                         if ($this->rtl) {
6324                                 $x = $this->w - $x - $w;
6325                         }
6326                         $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k, $op));
6327                 }
6328
6329                 /*
6330                 * Draws a Bezier curve from last draw point.
6331                 * The Bezier curve is a tangent to the line between the control points at either end of the curve.
6332                 * @param float $x1 Abscissa of control point 1.
6333                 * @param float $y1 Ordinate of control point 1.
6334                 * @param float $x2 Abscissa of control point 2.
6335                 * @param float $y2 Ordinate of control point 2.
6336                 * @param float $x3 Abscissa of end point.
6337                 * @param float $y3 Ordinate of end point.
6338                 * @access protected
6339                 * @since 2.1.000 (2008-01-08)
6340                 */
6341                 function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
6342                         if ($this->rtl) {
6343                                 $x1 = $this->w - $x1;
6344                                 $x2 = $this->w - $x2;
6345                                 $x3 = $this->w - $x3;
6346                         }
6347                         $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));
6348                 }
6349
6350                 /**
6351                 * Draws a line between two points.
6352                 * @param float $x1 Abscissa of first point.
6353                 * @param float $y1 Ordinate of first point.
6354                 * @param float $x2 Abscissa of second point.
6355                 * @param float $y2 Ordinate of second point.
6356                 * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6357                 * @access public
6358                 * @since 1.0
6359                 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
6360                 */
6361                 function Line($x1, $y1, $x2, $y2, $style=array()) {
6362                         if ($style) {
6363                                 $this->SetLineStyle($style);
6364                         }
6365                         $this->_outPoint($x1, $y1);
6366                         $this->_outLine($x2, $y2);
6367                         $this->_out(" S");
6368                 }
6369
6370                 /**
6371                 * Draws a rectangle.
6372                 * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language).
6373                 * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language).
6374                 * @param float $w Width.
6375                 * @param float $h Height.
6376                 * @param string $style Style of rendering. Possible values are:
6377                 * <ul>
6378                 *        <li>D or empty string: Draw (default).</li>
6379                 *        <li>F: Fill.</li>
6380                 *        <li>DF or FD: Draw and fill.</li>
6381                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6382                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6383                 * </ul>
6384                 * @param array $border_style Border style of rectangle. Array with keys among the following:
6385                 * <ul>
6386                 *        <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
6387                 *        <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
6388                 * </ul>
6389                 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
6390                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6391                 * @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).
6392                 * @access public
6393                 * @since 1.0
6394                 * @see SetLineStyle()
6395                 */
6396                 function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
6397                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6398                                 $this->SetFillColorArray($fill_color);
6399                         }
6400                         switch ($style) {
6401                                 case "F": {
6402                                         $op = 'f';
6403                                         $border_style = array();
6404                                         $this->_outRect($x, $y, $w, $h, $op);
6405                                         break;
6406                                 }
6407                                 case "DF":
6408                                 case "FD": {
6409                                         if ((!$border_style) OR (isset($border_style["all"]))) {
6410                                                 $op = 'B';
6411                                                 if (isset($border_style["all"])) {
6412                                                         $this->SetLineStyle($border_style["all"]);
6413                                                         $border_style = array();
6414                                                 }
6415                                         } else {
6416                                                 $op = 'f';
6417                                         }
6418                                         $this->_outRect($x, $y, $w, $h, $op);
6419                                         break;
6420                                 }
6421                                 case "CNZ": {
6422                                         $op = "W n";
6423                                         break;
6424                                 }
6425                                 case "CEO": {
6426                                         $op = "W* n";
6427                                         break;
6428                                 }
6429                                 default: {
6430                                         $op = 'S';
6431                                         if ((!$border_style) OR (isset($border_style["all"]))) {
6432                                                 if (isset($border_style["all"]) AND $border_style["all"]) {
6433                                                         $this->SetLineStyle($border_style["all"]);
6434                                                         $border_style = array();
6435                                                 }
6436                                                 $this->_outRect($x, $y, $w, $h, $op);
6437                                         }
6438                                         break;
6439                                 }
6440                         }
6441                         if ($border_style) {
6442                                 $border_style2 = array();
6443                                 foreach ($border_style as $line => $value) {
6444                                         $lenght = strlen($line);
6445                                         for ($i = 0; $i < $lenght; $i++) {
6446                                                 $border_style2[$line[$i]] = $value;
6447                                         }
6448                                 }
6449                                 $border_style = $border_style2;
6450                                 if (isset($border_style["L"]) AND $border_style["L"]) {
6451                                         $this->Line($x, $y, $x, $y + $h, $border_style["L"]);
6452                                 }
6453                                 if (isset($border_style["T"]) AND $border_style["T"]) {
6454                                         $this->Line($x, $y, $x + $w, $y, $border_style["T"]);
6455                                 }
6456                                 if (isset($border_style["R"]) AND $border_style["R"]) {
6457                                         $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style["R"]);
6458                                 }
6459                                 if (isset($border_style["B"]) AND $border_style["B"]) {
6460                                         $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style["B"]);
6461                                 }
6462                         }
6463                 }
6464
6465
6466                 /**
6467                 * Draws a Bezier curve.
6468                 * The Bezier curve is a tangent to the line between the control points at
6469                 * either end of the curve.
6470                 * @param float $x0 Abscissa of start point.
6471                 * @param float $y0 Ordinate of start point.
6472                 * @param float $x1 Abscissa of control point 1.
6473                 * @param float $y1 Ordinate of control point 1.
6474                 * @param float $x2 Abscissa of control point 2.
6475                 * @param float $y2 Ordinate of control point 2.
6476                 * @param float $x3 Abscissa of end point.
6477                 * @param float $y3 Ordinate of end point.
6478                 * @param string $style Style of rendering. Possible values are:
6479                 * <ul>
6480                 *        <li>D or empty string: Draw (default).</li>
6481                 *        <li>F: Fill.</li>
6482                 *        <li>DF or FD: Draw and fill.</li>
6483                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6484                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6485                 * </ul>
6486                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6487                 * @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).
6488                 * @access public
6489                 * @see SetLineStyle()
6490                 * @since 2.1.000 (2008-01-08)
6491                 */
6492                 function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style="", $line_style=array(), $fill_color=array()) {
6493                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6494                                 $this->SetFillColorArray($fill_color);
6495                         }
6496                         switch ($style) {
6497                                 case "F": {
6498                                         $op = "f";
6499                                         $line_style = array();
6500                                         break;
6501                                 }
6502                                 case "FD":
6503                                 case "DF": {
6504                                         $op = "B";
6505                                         break;
6506                                 }
6507                                 case "CNZ": {
6508                                         $op = "W n";
6509                                         break;
6510                                 }
6511                                 case "CEO": {
6512                                         $op = "W* n";
6513                                         break;
6514                                 }
6515                                 default: {
6516                                         $op = "S";
6517                                         break;
6518                                 }
6519                         }
6520                         if ($line_style) {
6521                                 $this->SetLineStyle($line_style);
6522                         }
6523                         $this->_outPoint($x0, $y0);
6524                         $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6525                         $this->_out($op);
6526                 }
6527
6528                 /**
6529                 * Draws a poly-Bezier curve.
6530                 * Each Bezier curve segment is a tangent to the line between the control points at
6531                 * either end of the curve.
6532                 * @param float $x0 Abscissa of start point.
6533                 * @param float $y0 Ordinate of start point.
6534                 * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
6535                 * @param string $style Style of rendering. Possible values are:
6536                 * <ul>
6537                 *        <li>D or empty string: Draw (default).</li>
6538                 *        <li>F: Fill.</li>
6539                 *        <li>DF or FD: Draw and fill.</li>
6540                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6541                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6542                 * </ul>
6543                 * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6544                 * @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).
6545                 * @access public
6546                 * @see SetLineStyle()
6547                 * @since 3.0008 (2008-05-12)
6548                 */
6549                 function Polycurve($x0, $y0, $segments, $style="", $line_style=array(), $fill_color=array()) {
6550                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6551                                 $this->SetFillColorArray($fill_color);
6552                         }
6553                         switch ($style) {
6554                                 case "F": {
6555                                         $op = "f";
6556                                         $line_style = array();
6557                                         break;
6558                                 }
6559                                 case "FD":
6560                                 case "DF": {
6561                                         $op = "B";
6562                                         break;
6563                                 }
6564                                 case "CNZ": {
6565                                         $op = "W n";
6566                                         break;
6567                                 }
6568                                 case "CEO": {
6569                                         $op = "W* n";
6570                                         break;
6571                                 }
6572                                 default: {
6573                                         $op = "S";
6574                                         break;
6575                                 }
6576                         }
6577                         if ($line_style) {
6578                                 $this->SetLineStyle($line_style);
6579                         }
6580                         $this->_outPoint($x0, $y0);
6581                         foreach ($segments as $segment) {
6582                                 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
6583                                 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
6584                         }
6585                         $this->_out($op);
6586                 }
6587
6588                 /**
6589                 * Draws an ellipse.
6590                 * An ellipse is formed from n Bezier curves.
6591                 * @param float $x0 Abscissa of center point.
6592                 * @param float $y0 Ordinate of center point.
6593                 * @param float $rx Horizontal radius.
6594                 * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0.
6595                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6596                 * @param float $astart: Angle start of draw line. Default value: 0.
6597                 * @param float $afinish: Angle finish of draw line. Default value: 360.
6598                 * @param string $style Style of rendering. Possible values are:
6599                 * <ul>
6600                 *        <li>D or empty string: Draw (default).</li>
6601                 *        <li>F: Fill.</li>
6602                 *        <li>DF or FD: Draw and fill.</li>
6603                 *        <li>C: Draw close.</li>
6604                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6605                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6606                 * </ul>
6607                 * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6608                 * @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).
6609                 * @param integer $nc Number of curves used in ellipse. Default value: 8.
6610                 * @access public
6611                 * @since 2.1.000 (2008-01-08)
6612                 */
6613                 function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6614                         if ($angle) {
6615                                 $this->StartTransform();
6616                                 $this->Rotate($angle, $x0, $y0);
6617                                 $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6618                                 $this->StopTransform();
6619                                 return;
6620                         }
6621                         if ($rx) {
6622                                 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6623                                         $this->SetFillColorArray($fill_color);
6624                                 }
6625                                 switch ($style) {
6626                                         case "F": {
6627                                                 $op = "f";
6628                                                 $line_style = array();
6629                                                 break;
6630                                         }
6631                                         case "FD":
6632                                         case "DF": {
6633                                                 $op = "B";
6634                                                 break;
6635                                         }
6636                                         case "C": {
6637                                                 $op = "s"; // Small "s" signifies closing the path as well
6638                                                 break;
6639                                         }
6640                                         case "CNZ": {
6641                                                 $op = "W n";
6642                                                 break;
6643                                         }
6644                                         case "CEO": {
6645                                                 $op = "W* n";
6646                                                 break;
6647                                         }
6648                                         default: {
6649                                                 $op = "S";
6650                                                 break;
6651                                         }
6652                                 }
6653                                 if ($line_style) {
6654                                         $this->SetLineStyle($line_style);
6655                                 }
6656                                 if (!$ry) {
6657                                         $ry = $rx;
6658                                 }
6659                                 $rx *= $this->k;
6660                                 $ry *= $this->k;
6661                                 if ($nc < 2){
6662                                         $nc = 2;
6663                                 }
6664                                 $astart = deg2rad((float) $astart);
6665                                 $afinish = deg2rad((float) $afinish);
6666                                 $total_angle = $afinish - $astart;
6667                                 $dt = $total_angle / $nc;
6668                                 $dtm = $dt / 3;
6669                                 $x0 *= $this->k;
6670                                 $y0 = ($this->h - $y0) * $this->k;
6671                                 $t1 = $astart;
6672                                 $a0 = $x0 + ($rx * cos($t1));
6673                                 $b0 = $y0 + ($ry * sin($t1));
6674                                 $c0 = -$rx * sin($t1);
6675                                 $d0 = $ry * cos($t1);
6676                                 $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k));
6677                                 for ($i = 1; $i <= $nc; $i++) {
6678                                         // Draw this bit of the total curve
6679                                         $t1 = ($i * $dt) + $astart;
6680                                         $a1 = $x0 + ($rx * cos($t1));
6681                                         $b1 = $y0 + ($ry * sin($t1));
6682                                         $c1 = -$rx * sin($t1);
6683                                         $d1 = $ry * cos($t1);
6684                                         $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));
6685                                         $a0 = $a1;
6686                                         $b0 = $b1;
6687                                         $c0 = $c1;
6688                                         $d0 = $d1;
6689                                 }
6690                                 $this->_out($op);
6691                         }
6692                 }
6693
6694                 /**
6695                 * Draws a circle.
6696                 * A circle is formed from n Bezier curves.
6697                 * @param float $x0 Abscissa of center point.
6698                 * @param float $y0 Ordinate of center point.
6699                 * @param float $r Radius.
6700                 * @param float $astart: Angle start of draw line. Default value: 0.
6701                 * @param float $afinish: Angle finish of draw line. Default value: 360.
6702                 * @param string $style Style of rendering. Possible values are:
6703                 * <ul>
6704                 *        <li>D or empty string: Draw (default).</li>
6705                 *        <li>F: Fill.</li>
6706                 *        <li>DF or FD: Draw and fill.</li>
6707                 *        <li>C: Draw close.</li>
6708                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6709                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6710                 * </ul>
6711                 * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6712                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6713                 * @param integer $nc Number of curves used in circle. Default value: 8.
6714                 * @access public
6715                 * @since 2.1.000 (2008-01-08)
6716                 */
6717                 function Circle($x0, $y0, $r, $astart=0, $afinish=360, $style="", $line_style=array(), $fill_color=array(), $nc=8) {
6718                         $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc);
6719                 }
6720
6721                 /**
6722                 * Draws a polygon.
6723                 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
6724                 * @param string $style Style of rendering. Possible values are:
6725                 * <ul>
6726                 *        <li>D or empty string: Draw (default).</li>
6727                 *        <li>F: Fill.</li>
6728                 *        <li>DF or FD: Draw and fill.</li>
6729                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6730                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6731                 * </ul>
6732                 * @param array $line_style Line style of polygon. Array with keys among the following:
6733                 * <ul>
6734                 *        <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li>
6735                 *        <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li>
6736                 * </ul>
6737                 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
6738                 * @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).
6739                 * @access public
6740                 * @since 2.1.000 (2008-01-08)
6741                 */
6742                 function Polygon($p, $style="", $line_style=array(), $fill_color=array()) {
6743                         $np = count($p) / 2;
6744                         if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6745                                 $this->SetFillColorArray($fill_color);
6746                         }
6747                         switch ($style) {
6748                                 case "F": {
6749                                         $line_style = array();
6750                                         $op = "f";
6751                                         break;
6752                                 }
6753                                 case "FD":
6754                                 case "DF": {
6755                                         $op = "B";
6756                                         break;
6757                                 }
6758                                 case "CNZ": {
6759                                         $op = "W n";
6760                                         break;
6761                                 }
6762                                 case "CEO": {
6763                                         $op = "W* n";
6764                                         break;
6765                                 }
6766                                 default: {
6767                                         $op = "S";
6768                                         break;
6769                                 }
6770                         }
6771                         $draw = true;
6772                         if ($line_style) {
6773                                 if (isset($line_style["all"])) {
6774                                         $this->SetLineStyle($line_style["all"]);
6775                                 } else { // 0 .. (np - 1), op = {B, S}
6776                                         $draw = false;
6777                                         if ("B" == $op) {
6778                                                 $op = "f";
6779                                                 $this->_outPoint($p[0], $p[1]);
6780                                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6781                                                         $this->_outLine($p[$i], $p[$i + 1]);
6782                                                 }
6783                                                 $this->_outLine($p[0], $p[1]);
6784                                                 $this->_out($op);
6785                                         }
6786                                         $p[($np * 2)] = $p[0];
6787                                         $p[(($np * 2) + 1)] = $p[1];
6788                                         for ($i = 0; $i < $np; $i++) {
6789                                                 if (isset($line_style[$i]) AND ($line_style[$i] != 0)) {
6790                                                         $this->Line($p[($i * 2)], $p[(($i * 2) + 1)], $p[(($i * 2) + 2)], $p[(($i * 2) + 3)], $line_style[$i]);
6791                                                 }
6792                                         }
6793                                 }
6794                         }
6795                         if ($draw) {
6796                                 $this->_outPoint($p[0], $p[1]);
6797                                 for ($i = 2; $i < ($np * 2); $i = $i + 2) {
6798                                         $this->_outLine($p[$i], $p[$i + 1]);
6799                                 }
6800                                 $this->_outLine($p[0], $p[1]);
6801                                 $this->_out($op);
6802                         }
6803                 }
6804
6805                 /**
6806                 * Draws a regular polygon.
6807                 * @param float $x0 Abscissa of center point.
6808                 * @param float $y0 Ordinate of center point.
6809                 * @param float $r: Radius of inscribed circle.
6810                 * @param integer $ns Number of sides.
6811                 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
6812                 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
6813                 * @param string $style Style of rendering. Possible values are:
6814                 * <ul>
6815                 *        <li>D or empty string: Draw (default).</li>
6816                 *        <li>F: Fill.</li>
6817                 *        <li>DF or FD: Draw and fill.</li>
6818                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6819                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6820                 * </ul>
6821                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6822                 * <ul>
6823                 *        <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li>
6824                 *        <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6825                 * </ul>
6826                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6827                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6828                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6829                 * <ul>
6830                 *        <li>D or empty string: Draw (default).</li>
6831                 *        <li>F: Fill.</li>
6832                 *        <li>DF or FD: Draw and fill.</li>
6833                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6834                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6835                 * </ul>
6836                 * @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).
6837                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6838                 * @access public
6839                 * @since 2.1.000 (2008-01-08)
6840                 */
6841                 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()) {
6842                         if (3 > $ns) {
6843                                 $ns = 3;
6844                         }
6845                         if ($draw_circle) {
6846                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6847                         }
6848                         $p = array();
6849                         for ($i = 0; $i < $ns; $i++) {
6850                                 $a = $angle + ($i * 360 / $ns);
6851                                 $a_rad = deg2rad((float) $a);
6852                                 $p[] = $x0 + ($r * sin($a_rad));
6853                                 $p[] = $y0 + ($r * cos($a_rad));
6854                         }
6855                         $this->Polygon($p, $style, $line_style, $fill_color);
6856                 }
6857
6858                 /**
6859                 * Draws a star polygon
6860                 * @param float $x0 Abscissa of center point.
6861                 * @param float $y0 Ordinate of center point.
6862                 * @param float $r Radius of inscribed circle.
6863                 * @param integer $nv Number of vertices.
6864                 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
6865                 * @param float $angle: Angle oriented (anti-clockwise). Default value: 0.
6866                 * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false.
6867                 * @param string $style Style of rendering. Possible values are:
6868                 * <ul>
6869                 *        <li>D or empty string: Draw (default).</li>
6870                 *        <li>F: Fill.</li>
6871                 *        <li>DF or FD: Draw and fill.</li>
6872                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6873                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6874                 * </ul>
6875                 * @param array $line_style Line style of polygon sides. Array with keys among the following:
6876                 * <ul>
6877                 *        <li>all: Line style of all sides. Array like for
6878                 * {@link SetLineStyle SetLineStyle}.</li>
6879                 *        <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li>
6880                 * </ul>
6881                 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
6882                 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
6883                 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
6884                 * <ul>
6885                 *        <li>D or empty string: Draw (default).</li>
6886                 *        <li>F: Fill.</li>
6887                 *        <li>DF or FD: Draw and fill.</li>
6888                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6889                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6890                 * </ul>
6891                 * @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).
6892                 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
6893                 * @access public
6894                 * @since 2.1.000 (2008-01-08)
6895                 */
6896                 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()) {
6897                         if (2 > $nv) {
6898                                 $nv = 2;
6899                         }
6900                         if ($draw_circle) {
6901                                 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
6902                         }
6903                         $p2 = array();
6904                         $visited = array();
6905                         for ($i = 0; $i < $nv; $i++) {
6906                                 $a = $angle + ($i * 360 / $nv);
6907                                 $a_rad = deg2rad((float) $a);
6908                                 $p2[] = $x0 + ($r * sin($a_rad));
6909                                 $p2[] = $y0 + ($r * cos($a_rad));
6910                                 $visited[] = false;
6911                         }
6912                         $p = array();
6913                         $i = 0;
6914                         do {
6915                                 $p[] = $p2[$i * 2];
6916                                 $p[] = $p2[($i * 2) + 1];
6917                                 $visited[$i] = true;
6918                                 $i += $ng;
6919                                 $i %= $nv;
6920                         } while (!$visited[$i]);
6921                         $this->Polygon($p, $style, $line_style, $fill_color);
6922                 }
6923
6924                 /**
6925                 * Draws a rounded rectangle.
6926                 * @param float $x Abscissa of upper-left corner.
6927                 * @param float $y Ordinate of upper-left corner.
6928                 * @param float $w Width.
6929                 * @param float $h Height.
6930                 * @param float $r Radius of the rounded corners.
6931                 * @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").
6932                 * @param string $style Style of rendering. Possible values are:
6933                 * <ul>
6934                 *        <li>D or empty string: Draw (default).</li>
6935                 *        <li>F: Fill.</li>
6936                 *        <li>DF or FD: Draw and fill.</li>
6937                 *        <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
6938                 *        <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
6939                 * </ul>
6940                 * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
6941                 * @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).
6942                 * @access public
6943                 * @since 2.1.000 (2008-01-08)
6944                 */
6945                 function RoundedRect($x, $y, $w, $h, $r, $round_corner="1111", $style="", $border_style=array(), $fill_color=array()) {
6946                         if ("0000" == $round_corner) { // Not rounded
6947                                 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
6948                         } else { // Rounded
6949                                 if (!(false === strpos($style, "F")) AND isset($fill_color)) {
6950                                         $this->SetFillColorArray($fill_color);
6951                                 }
6952                                 switch ($style) {
6953                                         case "F": {
6954                                                 $border_style = array();
6955                                                 $op = "f";
6956                                                 break;
6957                                         }
6958                                         case "FD":
6959                                         case "DF": {
6960                                                 $op = "B";
6961                                                 break;
6962                                         }
6963                                         case "CNZ": {
6964                                                 $op = "W n";
6965                                                 break;
6966                                         }
6967                                         case "CEO": {
6968                                                 $op = "W* n";
6969                                                 break;
6970                                         }
6971                                         default: {
6972                                                 $op = "S";
6973                                                 break;
6974                                         }
6975                                 }
6976                                 if ($border_style) {
6977                                         $this->SetLineStyle($border_style);
6978                                 }
6979                                 $MyArc = 4 / 3 * (sqrt(2) - 1);
6980                                 $this->_outPoint($x + $r, $y);
6981                                 $xc = $x + $w - $r;
6982                                 $yc = $y + $r;
6983                                 $this->_outLine($xc, $y);
6984                                 if ($round_corner[0]) {
6985                                         $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc);
6986                                 } else {
6987                                         $this->_outLine($x + $w, $y);
6988                                 }
6989                                 $xc = $x + $w - $r;
6990                                 $yc = $y + $h - $r;
6991                                 $this->_outLine($x + $w, $yc);
6992                                 if ($round_corner[1]) {
6993                                         $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r);
6994                                 } else {
6995                                         $this->_outLine($x + $w, $y + $h);
6996                                 }
6997                                 $xc = $x + $r;
6998                                 $yc = $y + $h - $r;
6999                                 $this->_outLine($xc, $y + $h);
7000                                 if ($round_corner[2]) {
7001                                         $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc);
7002                                 } else {
7003                                         $this->_outLine($x, $y + $h);
7004                                 }
7005                                 $xc = $x + $r;
7006                                 $yc = $y + $r;
7007                                 $this->_outLine($x, $yc);
7008                                 if ($round_corner[3]) {
7009                                         $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r);
7010                                 } else {
7011                                         $this->_outLine($x, $y);
7012                                         $this->_outLine($x + $r, $y);
7013                                 }
7014                                 $this->_out($op);
7015                         }
7016                 }
7017
7018                 // END GRAPHIC FUNCTIONS SECTION -----------------------
7019
7020                 // BIDIRECTIONAL TEXT SECTION --------------------------
7021                 /**
7022                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7023                  * @param string $str string to manipulate.
7024                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7025                  * @return string
7026                  * @author Nicola Asuni
7027                  * @since 2.1.000 (2008-01-08)
7028                 */
7029                 function utf8StrRev($str, $setbom=false, $forcertl=false) {
7030                         return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $forcertl), $setbom);
7031                 }
7032
7033                 /**
7034                  * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
7035                  * @param array $ta array of characters composing the string.
7036                  * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR
7037                  * @return string
7038                  * @author Nicola Asuni
7039                  * @since 2.4.000 (2008-03-06)
7040                 */
7041                 function utf8Bidi($ta, $forcertl=false) {
7042                         global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics;
7043                         // paragraph embedding level
7044                         $pel = 0;
7045                         // max level
7046                         $maxlevel = 0;
7047                         // create string from array
7048                         $str = $this->UTF8ArrSubString($ta);
7049                         // check if string contains arabic text
7050                         if (preg_match(K_RE_PATTERN_ARABIC, $str)) {
7051                                 $arabic = true;
7052                         } else {
7053                                 $arabic = false;
7054                         }
7055                         // check if string contains RTL text
7056                         if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) {
7057                                 return $ta;
7058                         }
7059                         
7060                         // get number of chars
7061                         $numchars = count($ta);
7062                         
7063                         if ($forcertl == 'R') {
7064                                         $pel = 1;
7065                         } elseif ($forcertl == 'L') {
7066                                         $pel = 0;
7067                         } else {
7068                                 // P2. In each paragraph, find the first character of type L, AL, or R.
7069                                 // 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.
7070                                 for ($i=0; $i < $numchars; $i++) {
7071                                         $type = $unicode[$ta[$i]];
7072                                         if ($type == 'L') {
7073                                                 $pel = 0;
7074                                                 break;
7075                                         } elseif (($type == 'AL') OR ($type == 'R')) {
7076                                                 $pel = 1;
7077                                                 break;
7078                                         }
7079                                 }
7080                         }
7081                         
7082                         // Current Embedding Level
7083                         $cel = $pel;
7084                         // directional override status
7085                         $dos = 'N';
7086                         $remember = array();
7087                         // start-of-level-run
7088                         $sor = $pel % 2 ? 'R' : 'L';
7089                         $eor = $sor;
7090
7091                         //$levels = array(array('level' => $cel, 'sor' => $sor, 'eor' => '', 'chars' => array()));
7092                         //$current_level = &$levels[count( $levels )-1];
7093
7094                         // Array of characters data
7095                         $chardata = Array();
7096
7097                         // 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.
7098                         //      In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
7099                         for ($i=0; $i < $numchars; $i++) {
7100                                 if ($ta[$i] == K_RLE) {
7101                                         // X2. With each RLE, compute the least greater odd embedding level.
7102                                         //      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.
7103                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7104                                         $next_level = $cel + ($cel % 2) + 1;
7105                                         if ($next_level < 62) {
7106                                                 $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos);
7107                                                 $cel = $next_level;
7108                                                 $dos = 'N';
7109                                                 $sor = $eor;
7110                                                 $eor = $cel % 2 ? 'R' : 'L';
7111                                         }
7112                                 } elseif ($ta[$i] == K_LRE) {
7113                                         // X3. With each LRE, compute the least greater even embedding level.
7114                                         //      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.
7115                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7116                                         $next_level = $cel + 2 - ($cel % 2);
7117                                         if ( $next_level < 62 ) {
7118                                                 $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos);
7119                                                 $cel = $next_level;
7120                                                 $dos = 'N';
7121                                                 $sor = $eor;
7122                                                 $eor = $cel % 2 ? 'R' : 'L';
7123                                         }
7124                                 } elseif ($ta[$i] == K_RLO) {
7125                                         // X4. With each RLO, compute the least greater odd embedding level.
7126                                         //      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.
7127                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7128                                         $next_level = $cel + ($cel % 2) + 1;
7129                                         if ($next_level < 62) {
7130                                                 $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos);
7131                                                 $cel = $next_level;
7132                                                 $dos = 'R';
7133                                                 $sor = $eor;
7134                                                 $eor = $cel % 2 ? 'R' : 'L';
7135                                         }
7136                                 } elseif ($ta[$i] == K_LRO) {
7137                                         // X5. With each LRO, compute the least greater even embedding level.
7138                                         //      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.
7139                                         //      b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
7140                                         $next_level = $cel + 2 - ($cel % 2);
7141                                         if ( $next_level < 62 ) {
7142                                                 $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos);
7143                                                 $cel = $next_level;
7144                                                 $dos = 'L';
7145                                                 $sor = $eor;
7146                                                 $eor = $cel % 2 ? 'R' : 'L';
7147                                         }
7148                                 } elseif ($ta[$i] == K_PDF) {
7149                                         // 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.
7150                                         if (count($remember)) {
7151                                                 $last = count($remember ) - 1;
7152                                                 if (($remember[$last]['num'] == K_RLE) OR
7153                                                           ($remember[$last]['num'] == K_LRE) OR
7154                                                           ($remember[$last]['num'] == K_RLO) OR
7155                                                           ($remember[$last]['num'] == K_LRO)) {
7156                                                         $match = array_pop($remember);
7157                                                         $cel = $match['cel'];
7158                                                         $dos = $match['dos'];
7159                                                         $sor = $eor;
7160                                                         $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
7161                                                 }
7162                                         }
7163                                 } elseif (($ta[$i] != K_RLE) AND
7164                                                                  ($ta[$i] != K_LRE) AND
7165                                                                  ($ta[$i] != K_RLO) AND
7166                                                                  ($ta[$i] != K_LRO) AND
7167                                                                  ($ta[$i] != K_PDF)) {
7168                                         // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
7169                                         //      a. Set the level of the current character to the current embedding level.
7170                                         //      b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
7171                                         if ($dos != 'N') {
7172                                                 $chardir = $dos;
7173                                         } else {
7174                                                 $chardir = $unicode[$ta[$i]];
7175                                         }
7176                                         // stores string characters and other information
7177                                         $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
7178                                 }
7179                         } // end for each char
7180
7181                         // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
7182                         // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
7183                         // 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.
7184
7185                         // 3.3.3 Resolving Weak Types
7186                         // 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.
7187                         // Nonspacing marks are now resolved based on the previous characters.
7188                         $numchars = count($chardata);
7189
7190                         // 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.
7191                         $prevlevel = -1; // track level changes
7192                         $levcount = 0; // counts consecutive chars at the same level
7193                         for ($i=0; $i < $numchars; $i++) {
7194                                 if ($chardata[$i]['type'] == 'NSM') {
7195                                         if ($levcount) {
7196                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7197                                         } elseif ($i > 0) {
7198                                                 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
7199                                         }
7200                                 }
7201                                 if ($chardata[$i]['level'] != $prevlevel) {
7202                                         $levcount = 0;
7203                                 } else {
7204                                         $levcount++;
7205                                 }
7206                                 $prevlevel = $chardata[$i]['level'];
7207                         }
7208
7209                         // 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.
7210                         $prevlevel = -1;
7211                         $levcount = 0;
7212                         for ($i=0; $i < $numchars; $i++) {
7213                                 if ($chardata[$i]['char'] == 'EN') {
7214                                         for ($j=$levcount; $j >= 0; $j--) {
7215                                                 if ($chardata[$j]['type'] == 'AL') {
7216                                                         $chardata[$i]['type'] = 'AN';
7217                                                 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
7218                                                         break;
7219                                                 }
7220                                         }
7221                                 }
7222                                 if ($chardata[$i]['level'] != $prevlevel) {
7223                                         $levcount = 0;
7224                                 } else {
7225                                         $levcount++;
7226                                 }
7227                                 $prevlevel = $chardata[$i]['level'];
7228                         }
7229
7230                         // W3. Change all ALs to R.
7231                         for ($i=0; $i < $numchars; $i++) {
7232                                 if ($chardata[$i]['type'] == 'AL') {
7233                                         $chardata[$i]['type'] = 'R';
7234                                 }
7235                         }
7236
7237                         // 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.
7238                         $prevlevel = -1;
7239                         $levcount = 0;
7240                         for ($i=0; $i < $numchars; $i++) {
7241                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7242                                         if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7243                                                 $chardata[$i]['type'] = 'EN';
7244                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
7245                                                 $chardata[$i]['type'] = 'EN';
7246                                         } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
7247                                                 $chardata[$i]['type'] = 'AN';
7248                                         }
7249                                 }
7250                                 if ($chardata[$i]['level'] != $prevlevel) {
7251                                         $levcount = 0;
7252                                 } else {
7253                                         $levcount++;
7254                                 }
7255                                 $prevlevel = $chardata[$i]['level'];
7256                         }
7257
7258                         // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
7259                         $prevlevel = -1;
7260                         $levcount = 0;
7261                         for ($i=0; $i < $numchars; $i++) {
7262                                 if ($chardata[$i]['type'] == 'ET') {
7263                                         if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
7264                                                 $chardata[$i]['type'] = 'EN';
7265                                         } else {
7266                                                 $j = $i+1;
7267                                                 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
7268                                                         if ($chardata[$j]['type'] == 'EN') {
7269                                                                 $chardata[$i]['type'] = 'EN';
7270                                                                 break;
7271                                                         } elseif ($chardata[$j]['type'] != 'ET') {
7272                                                                 break;
7273                                                         }
7274                                                         $j++;
7275                                                 }
7276                                         }
7277                                 }
7278                                 if ($chardata[$i]['level'] != $prevlevel) {
7279                                         $levcount = 0;
7280                                 } else {
7281                                         $levcount++;
7282                                 }
7283                                 $prevlevel = $chardata[$i]['level'];
7284                         }
7285
7286                         // W6. Otherwise, separators and terminators change to Other Neutral.
7287                         $prevlevel = -1;
7288                         $levcount = 0;
7289                         for ($i=0; $i < $numchars; $i++) {
7290                                 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
7291                                         $chardata[$i]['type'] = 'ON';
7292                                 }
7293                                 if ($chardata[$i]['level'] != $prevlevel) {
7294                                         $levcount = 0;
7295                                 } else {
7296                                         $levcount++;
7297                                 }
7298                                 $prevlevel = $chardata[$i]['level'];
7299                         }
7300
7301                         //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.
7302                         $prevlevel = -1;
7303                         $levcount = 0;
7304                         for ($i=0; $i < $numchars; $i++) {
7305                                 if ($chardata[$i]['char'] == 'EN') {
7306                                         for ($j=$levcount; $j >= 0; $j--) {
7307                                                 if ($chardata[$j]['type'] == 'L') {
7308                                                         $chardata[$i]['type'] = 'L';
7309                                                 } elseif ($chardata[$j]['type'] == 'R') {
7310                                                         break;
7311                                                 }
7312                                         }
7313                                 }
7314                                 if ($chardata[$i]['level'] != $prevlevel) {
7315                                         $levcount = 0;
7316                                 } else {
7317                                         $levcount++;
7318                                 }
7319                                 $prevlevel = $chardata[$i]['level'];
7320                         }
7321
7322                         // 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.
7323                         $prevlevel = -1;
7324                         $levcount = 0;
7325                         for ($i=0; $i < $numchars; $i++) {
7326                                 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7327                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7328                                                 $chardata[$i]['type'] = 'L';
7329                                         } elseif (($chardata[$i]['type'] == 'N') AND
7330                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7331                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7332                                                 $chardata[$i]['type'] = 'R';
7333                                         } elseif ($chardata[$i]['type'] == 'N') {
7334                                                 // N2. Any remaining neutrals take the embedding direction
7335                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7336                                         }
7337                                 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
7338                                         // first char
7339                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
7340                                                 $chardata[$i]['type'] = 'L';
7341                                         } elseif (($chardata[$i]['type'] == 'N') AND
7342                                          (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
7343                                          (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
7344                                                 $chardata[$i]['type'] = 'R';
7345                                         } elseif ($chardata[$i]['type'] == 'N') {
7346                                                 // N2. Any remaining neutrals take the embedding direction
7347                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7348                                         }
7349                                 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
7350                                         //last char
7351                                         if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
7352                                                 $chardata[$i]['type'] = 'L';
7353                                         } elseif (($chardata[$i]['type'] == 'N') AND
7354                                          (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
7355                                          (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
7356                                                 $chardata[$i]['type'] = 'R';
7357                                         } elseif ($chardata[$i]['type'] == 'N') {
7358                                                 // N2. Any remaining neutrals take the embedding direction
7359                                                 $chardata[$i]['type'] = $chardata[$i]['sor'];
7360                                         }
7361                                 } elseif ($chardata[$i]['type'] == 'N') {
7362                                         // N2. Any remaining neutrals take the embedding direction
7363                                         $chardata[$i]['type'] = $chardata[$i]['sor'];
7364                                 }
7365                                 if ($chardata[$i]['level'] != $prevlevel) {
7366                                         $levcount = 0;
7367                                 } else {
7368                                         $levcount++;
7369                                 }
7370                                 $prevlevel = $chardata[$i]['level'];
7371                         }
7372
7373                         // 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.
7374                         // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
7375                         for ($i=0; $i < $numchars; $i++) {
7376                                 $odd = $chardata[$i]['level'] % 2;
7377                                 if ($odd) {
7378                                         if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7379                                                 $chardata[$i]['level'] += 1;
7380                                         }
7381                                 } else {
7382                                         if ($chardata[$i]['type'] == 'R') {
7383                                                 $chardata[$i]['level'] += 1;
7384                                         } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){
7385                                                 $chardata[$i]['level'] += 2;
7386                                         }
7387                                 }
7388                                 $maxlevel = max($chardata[$i]['level'],$maxlevel);
7389                         }
7390
7391                         // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
7392                         //      1. Segment separators,
7393                         //      2. Paragraph separators,
7394                         //      3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
7395                         //      4. Any sequence of white space characters at the end of the line.
7396                         for ($i=0; $i < $numchars; $i++) {
7397                                 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
7398                                         $chardata[$i]['level'] = $pel;
7399                                 } elseif ($chardata[$i]['type'] == 'WS') {
7400                                         $j = $i+1;
7401                                         while ($j < $numchars) {
7402                                                 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
7403                                                         (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
7404                                                         $chardata[$i]['level'] = $pel;
7405                                                         break;
7406                                                 } elseif ($chardata[$j]['type'] != 'WS') {
7407                                                         break;
7408                                                 }
7409                                                 $j++;
7410                                         }
7411                                 }
7412                         }
7413
7414                         // Arabic Shaping
7415                         // 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.
7416                         if ($arabic) {
7417                                 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
7418                                 $alfletter = array(1570,1571,1573,1575);
7419                                 $chardata2 = $chardata;
7420                                 $laaletter = false;
7421                                 $charAL = array();
7422                                 $x = 0;
7423                                 for ($i=0; $i < $numchars; $i++) {
7424                                         if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
7425                                                 $charAL[$x] = $chardata[$i];
7426                                                 $charAL[$x]['i'] = $i;
7427                                                 $chardata[$i]['x'] = $x;
7428                                                 $x++;
7429                                         }
7430                                 }
7431                                 $numAL = $x;
7432                                 for ($i=0; $i < $numchars; $i++) {
7433                                         $thischar = $chardata[$i];
7434                                         if ($i > 0) {
7435                                                 $prevchar = $chardata[($i-1)];
7436                                         } else {
7437                                                 $prevchar = false;
7438                                         }
7439                                         if (($i+1) < $numchars) {
7440                                                 $nextchar = $chardata[($i+1)];
7441                                         } else {
7442                                                 $nextchar = false;
7443                                         }
7444                                         if ($unicode[$thischar['char']] == 'AL') {
7445                                                 $x = $thischar['x'];
7446                                                 if ($x > 0) {
7447                                                         $prevchar = $charAL[($x-1)];
7448                                                 } else {
7449                                                         $prevchar = false;
7450                                                 }
7451                                                 if (($x+1) < $numAL) {
7452                                                         $nextchar = $charAL[($x+1)];
7453                                                 } else {
7454                                                         $nextchar = false;
7455                                                 }
7456                                                 // if laa letter
7457                                                 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
7458                                                         $arabicarr = $laa_array;
7459                                                         $laaletter = true;
7460                                                         if ($x > 1) {
7461                                                                 $prevchar = $charAL[($x-2)];
7462                                                         } else {
7463                                                                 $prevchar = false;
7464                                                         }
7465                                                 } else {
7466                                                         $arabicarr = $unicode_arlet;
7467                                                         $laaletter = false;
7468                                                 }
7469                                                 if (($prevchar !== false) AND ($nextchar !== false) AND
7470                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7471                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7472                                                         ($prevchar['type'] == $thischar['type']) AND
7473                                                         ($nextchar['type'] == $thischar['type']) AND
7474                                                         ($nextchar['char'] != 1567)) {
7475                                                         if (in_array($prevchar['char'], $endedletter)) {
7476                                                                 if (isset($arabicarr[$thischar['char']][2])) {
7477                                                                         // initial
7478                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7479                                                                 }
7480                                                         } else {
7481                                                                 if (isset($arabicarr[$thischar['char']][3])) {
7482                                                                         // medial
7483                                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
7484                                                                 }
7485                                                         }
7486                                                 } elseif (($nextchar !== false) AND
7487                                                         (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND
7488                                                         ($nextchar['type'] == $thischar['type']) AND
7489                                                         ($nextchar['char'] != 1567)) {
7490                                                         if (isset($arabicarr[$chardata[$i]['char']][2])) {
7491                                                                 // initial
7492                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
7493                                                         }
7494                                                 } elseif ((($prevchar !== false) AND
7495                                                         (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND
7496                                                         ($prevchar['type'] == $thischar['type'])) OR
7497                                                         (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
7498                                                         // final
7499                                                         if (($i > 1) AND ($thischar['char'] == 1607) AND
7500                                                                 ($chardata[$i-1]['char'] == 1604) AND
7501                                                                 ($chardata[$i-2]['char'] == 1604)) {
7502                                                                 //Allah Word
7503                                                                 // mark characters to delete with false
7504                                                                 $chardata2[$i-2]['char'] = false;
7505                                                                 $chardata2[$i-1]['char'] = false;
7506                                                                 $chardata2[$i]['char'] = 65010;
7507                                                         } else {
7508                                                                 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
7509                                                                         if (isset($arabicarr[$thischar['char']][0])) {
7510                                                                                 // isolated
7511                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7512                                                                         }
7513                                                                 } else {
7514                                                                         if (isset($arabicarr[$thischar['char']][1])) {
7515                                                                                 // final
7516                                                                                 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
7517                                                                         }
7518                                                                 }
7519                                                         }
7520                                                 } elseif (isset($arabicarr[$thischar['char']][0])) {
7521                                                         // isolated
7522                                                         $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
7523                                                 }
7524                                                 // if laa letter
7525                                                 if ($laaletter) {
7526                                                         // mark characters to delete with false
7527                                                         $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
7528                                                 }
7529                                         } // end if AL (Arabic Letter)
7530                                 } // end for each char
7531                                 /*
7532                                  * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594.
7533                                  * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
7534                                  */
7535                                 $cw = &$this->CurrentFont['cw'];
7536                                 for ($i=0; $i < ($numchars-1); $i++) {
7537                                         if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) {
7538                                                 // check if the subtitution font is defined on current font
7539                                                 if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) {
7540                                                         $chardata2[$i]['char'] = false;
7541                                                         $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])];
7542                                                 }
7543                                         }
7544                                 }
7545                                 // remove marked characters
7546                                 foreach($chardata2 as $key => $value) {
7547                                         if ($value['char'] === false) {
7548                                                 unset($chardata2[$key]);
7549                                         }
7550                                 }
7551                                 $chardata = array_values($chardata2);
7552                                 $numchars = count($chardata);
7553                                 unset($chardata2);
7554                                 unset($arabicarr);
7555                                 unset($laaletter);
7556                                 unset($charAL);
7557                         }
7558
7559                         // 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.
7560                         for ($j=$maxlevel; $j > 0; $j--) {
7561                                 $ordarray = Array();
7562                                 $revarr = Array();
7563                                 $onlevel = false;
7564                                 for ($i=0; $i < $numchars; $i++) {
7565                                         if ($chardata[$i]['level'] >= $j) {
7566                                                 $onlevel = true;
7567                                                 if (isset($unicode_mirror[$chardata[$i]['char']])) {
7568                                                         // 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.
7569                                                         $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']];
7570                                                 }
7571                                                 $revarr[] = $chardata[$i];
7572                                         } else {
7573                                                 if ($onlevel) {
7574                                                         $revarr = array_reverse($revarr);
7575                                                         $ordarray = array_merge($ordarray, $revarr);
7576                                                         $revarr = Array();
7577                                                         $onlevel = false;
7578                                                 }
7579                                                 $ordarray[] = $chardata[$i];
7580                                         }
7581                                 }
7582                                 if ($onlevel) {
7583                                         $revarr = array_reverse($revarr);
7584                                         $ordarray = array_merge($ordarray, $revarr);
7585                                 }
7586                                 $chardata = $ordarray;
7587                         }
7588
7589                         $ordarray = array();
7590                         for ($i=0; $i < $numchars; $i++) {
7591                                 $ordarray[] = $chardata[$i]['char'];
7592                         }
7593
7594                         return $ordarray;
7595                 }
7596
7597                 // END OF BIDIRECTIONAL TEXT SECTION -------------------
7598
7599                 /*
7600                 * Adds a bookmark.
7601                 * @param string $txt bookmark description.
7602                 * @param int $level bookmark level (minimum value is 0).
7603                 * @param float $y Ordinate of the boorkmark position (default = -1 = current position).
7604                 * @access public
7605                 * @author Olivier Plathey, Nicola Asuni
7606                 * @since 2.1.002 (2008-02-12)
7607                 */
7608                 function Bookmark($txt, $level=0, $y=-1) {
7609                         if ($level < 0) {
7610                                 $level = 0;
7611                         }
7612                         if (isset($this->outlines[0])) {
7613                                 $lastoutline = end($this->outlines);
7614                                 $maxlevel = $lastoutline['l'] + 1;
7615                         } else {
7616                                 $maxlevel = 0;
7617                         }
7618                         if ($level > $maxlevel) {
7619                                 $level = $maxlevel;
7620                         }
7621                         if ($y == -1) {
7622                                 $y = $this->GetY();
7623                         }
7624                         $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $this->PageNo());
7625                 }
7626
7627                 /*
7628                 * Create a bookmark PDF string.
7629                 * @access protected
7630                 * @author Olivier Plathey, Nicola Asuni
7631                 * @since 2.1.002 (2008-02-12)
7632                 */
7633                 function _putbookmarks() {
7634                         $nb = count($this->outlines);
7635                         if ($nb == 0) {
7636                                 return;
7637                         }
7638                         $lru = array();
7639                         $level = 0;
7640                         foreach($this->outlines as $i => $o) {
7641                                 if ($o['l'] > 0) {
7642                                         $parent = $lru[($o['l'] - 1)];
7643                                         //Set parent and last pointers
7644                                         $this->outlines[$i]['parent'] = $parent;
7645                                         $this->outlines[$parent]['last'] = $i;
7646                                         if ($o['l'] > $level) {
7647                                                 //Level increasing: set first pointer
7648                                                 $this->outlines[$parent]['first'] = $i;
7649                                         }
7650                                 } else {
7651                                         $this->outlines[$i]['parent'] = $nb;
7652                                 }
7653                                 if (($o['l'] <= $level) AND ($i > 0)) {
7654                                         //Set prev and next pointers
7655                                         $prev = $lru[$o['l']];
7656                                         $this->outlines[$prev]['next'] = $i;
7657                                         $this->outlines[$i]['prev'] = $prev;
7658                                 }
7659                                 $lru[$o['l']] = $i;
7660                                 $level = $o['l'];
7661                         }
7662                         //Outline items
7663                         $n = $this->n + 1;
7664                         foreach($this->outlines as $i => $o) {
7665                                 $this->_newobj();
7666                                 $this->_out('<</Title '.$this->_textstring($o['t']));
7667                                 $this->_out('/Parent '.($n+$o['parent']).' 0 R');
7668                                 if (isset($o['prev']))
7669                                 $this->_out('/Prev '.($n+$o['prev']).' 0 R');
7670                                 if (isset($o['next']))
7671                                 $this->_out('/Next '.($n+$o['next']).' 0 R');
7672                                 if (isset($o['first']))
7673                                 $this->_out('/First '.($n+$o['first']).' 0 R');
7674                                 if (isset($o['last']))
7675                                 $this->_out('/Last '.($n+$o['last']).' 0 R');
7676                                 $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]', 1+2*$o['p'], ($this->h-$o['y'])*$this->k));
7677                                 $this->_out('/Count 0>>');
7678                                 $this->_out('endobj');
7679                         }
7680                         //Outline root
7681                         $this->_newobj();
7682                         $this->OutlineRoot=$this->n;
7683                         $this->_out('<</Type /Outlines /First '.$n.' 0 R');
7684                         $this->_out('/Last '.($n+$lru[0]).' 0 R>>');
7685                         $this->_out('endobj');
7686                 }
7687
7688
7689                 // --- JAVASCRIPT - FORMS ------------------------------
7690
7691                 /*
7692                 * Adds a javascript
7693                 * @access public
7694                 * @author Johannes Güntert, Nicola Asuni
7695                 * @since 2.1.002 (2008-02-12)
7696                 */
7697                 function IncludeJS($script) {
7698                         $this->javascript .= $script;
7699                 }
7700
7701                 /*
7702                 * Create a javascript PDF string.
7703                 * @access protected
7704                 * @author Johannes Güntert, Nicola Asuni
7705                 * @since 2.1.002 (2008-02-12)
7706                 */
7707                 function _putjavascript() {
7708                         if (empty($this->javascript)) {
7709                                 return;
7710                         }
7711                         // the following two lines are uded to avoid form fields duplication after saving
7712                         $js1 = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2f,%.2f,%.2f,%.2f]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
7713                         $js2 = "getField('tcpdfdocsaved').value = 'saved';";
7714                         $this->_newobj();
7715                         $this->n_js = $this->n;
7716                         $this->_out('<<');
7717                         $this->_out('/Names [(EmbeddedJS) '.($this->n + 1).' 0 R ]');
7718                         $this->_out('>>');
7719                         $this->_out('endobj');
7720                         $this->_newobj();
7721                         $this->_out('<<');
7722                         $this->_out('/S /JavaScript');
7723                         $this->_out('/JS '.$this->_textstring($js1."\n".$this->javascript."\n".$js2));
7724                         $this->_out('>>');
7725                         $this->_out('endobj');
7726                 }
7727
7728                 /*
7729                 * Convert color to javascript color.
7730                 * @param string $color color name or #RRGGBB
7731                 * @access protected
7732                 * @author Denis Van Nuffelen, Nicola Asuni
7733                 * @since 2.1.002 (2008-02-12)
7734                 */
7735                 function _JScolor($color) {
7736                         static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
7737                         if (substr($color,0,1) == '#') {
7738                                 return sprintf("['RGB',%.3f,%.3f,%.3f]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
7739                         }
7740                         if (!in_array($color,$aColors)) {
7741                                 $this->Error('Invalid color: '.$color);
7742                         }
7743                         return 'color.'.$color;
7744                 }
7745
7746                 /*
7747                 * Adds a javascript form field.
7748                 * @param string $type field type
7749                 * @param string $name field name
7750                 * @param int $x horizontal position
7751                 * @param int $y vertical position
7752                 * @param int $w width
7753                 * @param int $h height
7754                 * @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>
7755                 * @access protected
7756                 * @author Denis Van Nuffelen, Nicola Asuni
7757                 * @since 2.1.002 (2008-02-12)
7758                 */
7759                 function _addfield($type, $name, $x, $y, $w, $h, $prop) {
7760                         // the followind avoid fields duplication after saving the document
7761                         $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {";
7762                         $k = $this->k;
7763                         $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";
7764                         $this->javascript .= "f".$name.".textSize=".$this->FontSizePt.";\n";
7765                         foreach ($prop as $key => $val) {
7766                                 if (strcmp(substr($key,-5),"Color") == 0) {
7767                                         $val = $this->_JScolor($val);
7768                                 } else {
7769                                         $val = "'".$val."'";
7770                                 }
7771                                 $this->javascript .= "f".$name.".".$key."=".$val.";\n";
7772                         }
7773                         $this->x += $w;
7774                         $this->javascript .= "}";
7775                 }
7776
7777                 /*
7778                 * Creates a text field
7779                 * @param string $name field name
7780                 * @param int $w width
7781                 * @param int $h height
7782                 * @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>
7783                 * @access public
7784                 * @author Denis Van Nuffelen, Nicola Asuni
7785                 * @since 2.1.002 (2008-02-12)
7786                 */
7787                 function TextField($name, $w, $h, $prop=array()) {
7788                         $this->_addfield('text', $name, $this->x, $this->y, $w, $h, $prop);
7789                 }
7790
7791                 /*
7792                 * Creates a RadioButton field
7793                 * @param string $name field name
7794                 * @param int $w width
7795                 * @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>
7796                 * @access public
7797                 * @author Nicola Asuni
7798                 * @since 2.2.003 (2008-03-03)
7799                 */
7800                 function RadioButton($name, $w, $prop=array()) {
7801                         if (!isset($prop['strokeColor'])) {
7802                                 $prop['strokeColor']='black';
7803                         }
7804                         $this->_addfield('radiobutton', $name, $this->x, $this->y, $w, $w, $prop);
7805                 }
7806
7807                 /*
7808                 * Creates a List-box field
7809                 * @param string $name field name
7810                 * @param int $w width
7811                 * @param int $h height
7812                 * @param array $values array containing the list of values.
7813                 * @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>
7814                 * @access public
7815                 * @author Nicola Asuni
7816                 * @since 2.2.003 (2008-03-03)
7817                 */
7818                 function ListBox($name, $w, $h, $values, $prop=array()) {
7819                         if (!isset($prop['strokeColor'])) {
7820                                 $prop['strokeColor'] = 'ltGray';
7821                         }
7822                         $this->_addfield('listbox', $name, $this->x, $this->y, $w, $h, $prop);
7823                         $s = '';
7824                         foreach($values as $value) {
7825                                 $s .= "'".addslashes($value)."',";
7826                         }
7827                         $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7828                 }
7829
7830                 /*
7831                 * Creates a Combo-box field
7832                 * @param string $name field name
7833                 * @param int $w width
7834                 * @param int $h height
7835                 * @param array $values array containing the list of values.
7836                 * @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>
7837                 * @access public
7838                 * @author Denis Van Nuffelen, Nicola Asuni
7839                 * @since 2.1.002 (2008-02-12)
7840                 */
7841                 function ComboBox($name, $w, $h, $values, $prop=array()) {
7842                         $this->_addfield('combobox', $name, $this->x, $this->y, $w, $h, $prop);
7843                         $s = '';
7844                         foreach($values as $value) {
7845                                 $s .= "'".addslashes($value)."',";
7846                         }
7847                         $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n";
7848                 }
7849
7850                 /*
7851                 * Creates a CheckBox field
7852                 * @param string $name field name
7853                 * @param int $w width
7854                 * @param boolean $checked define the initial state (default = false).
7855                 * @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>
7856                 * @access public
7857                 * @author Denis Van Nuffelen, Nicola Asuni
7858                 * @since 2.1.002 (2008-02-12)
7859                 */
7860                 function CheckBox($name, $w, $checked=false, $prop=array()) {
7861                         $prop['value'] = ($checked ? 'Yes' : 'Off');
7862                         if (!isset($prop['strokeColor'])) {
7863                                 $prop['strokeColor'] = 'black';
7864                         }
7865                         $this->_addfield('checkbox', $name, $this->x, $this->y, $w, $w, $prop);
7866                 }
7867
7868                 /*
7869                 * Creates a button field
7870                 * @param string $name field name
7871                 * @param int $w width
7872                 * @param int $h height
7873                 * @param string $caption caption.
7874                 * @param string $action action triggered by the button (JavaScript code).
7875                 * @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>
7876                 * @access public
7877                 * @author Denis Van Nuffelen, Nicola Asuni
7878                 * @since 2.1.002 (2008-02-12)
7879                 */
7880                 function Button($name, $w, $h, $caption, $action, $prop=array()) {
7881                         if (!isset($prop['strokeColor'])) {
7882                                 $prop['strokeColor'] = 'black';
7883                         }
7884                         if (!isset($prop['borderStyle'])) {
7885                                 $prop['borderStyle'] = 'beveled';
7886                         }
7887                         $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
7888                         $this->javascript .= "f".$name.".buttonSetCaption('".addslashes($caption)."');\n";
7889                         $this->javascript .= "f".$name.".setAction('MouseUp','".addslashes($action)."');\n";
7890                         $this->javascript .= "f".$name.".highlight='push';\n";
7891                         $this->javascript .= "f".$name.".print=false;\n";
7892                 }
7893
7894                 // END JAVASCRIPT - FORMS ------------------------------
7895
7896                 /*
7897                 * Enable Write permissions for PDF Reader.
7898                 * @access protected
7899                 * @author Nicola Asuni
7900                 * @since 2.9.000 (2008-03-26)
7901                 */
7902                 function _putuserrights() {
7903                         if (!$this->ur) {
7904                                 return;
7905                         }
7906                         $this->_out('/Perms');
7907                         $this->_out('<<');
7908                         $this->_out('/UR3');
7909                         $this->_out('<<');
7910                         //$this->_out('/SubFilter/adbe.pkcs7.detached/Filter/Adobe.PPKLite/Contents');
7911                         //$this->_out('<0>');
7912                         //$this->_out('/ByteRange[0 3]');
7913                         $this->_out('/M '.$this->_datestring('D:'.date('YmdHis')));
7914                         $this->_out('/Name(TCPDF)');
7915                         $this->_out('/Reference[');
7916                         $this->_out('<<');
7917                         $this->_out('/TransformParams');
7918                         $this->_out('<<');
7919                         $this->_out('/Type/TransformParams');
7920                         $this->_out('/V/2.2');
7921                         if (!empty($this->ur_document)) {
7922                                 $this->_out('/Document['.$this->ur_document.']');
7923                         }
7924                         if (!empty($this->ur_annots)) {
7925                                 $this->_out('/Annots['.$this->ur_annots.']');
7926                         }
7927                         if (!empty($this->ur_form)) {
7928                                 $this->_out('/Form['.$this->ur_form.']');
7929                         }
7930                         if (!empty($this->ur_signature)) {
7931                                 $this->_out('/Signature['.$this->ur_signature.']');
7932                         }
7933                         $this->_out('>>');
7934                         $this->_out('/TransformMethod/UR3');
7935                         $this->_out('/Type/SigRef');
7936                         $this->_out('>>');
7937                         $this->_out(']');
7938                         $this->_out('/Type/Sig');
7939                         $this->_out('>>');
7940                         $this->_out('>>');
7941                 }
7942
7943                 /*
7944                 * Set User's Rights for PDF Reader
7945                 * Check the PDF Reference 8.7.1 Transform Methods,
7946                 * Table 8.105 Entries in the UR transform parameters dictionary
7947                 * @param boolean $enable if true enable user's rights on PDF reader
7948                 * @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.
7949                 * @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.
7950                 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
7951                 * @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.
7952                 * @access public
7953                 * @author Nicola Asuni
7954                 * @since 2.9.000 (2008-03-26)
7955                 */
7956                 function setUserRights(
7957                                 $enable=true,
7958                                 $document="/FullSave",
7959                                 $annots="/Create/Delete/Modify/Copy/Import/Export",
7960                                 $form="/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate",
7961                                 $signature="/Modify") {
7962                         $this->ur = $enable;
7963                         $this->ur_document = $document;
7964                         $this->ur_annots = $annots;
7965                         $this->ur_form = $form;
7966                         $this->ur_signature = $signature;
7967                 }
7968
7969                 /*
7970                 * Create a new page group.
7971                 * NOTE: call this function before calling AddPage()
7972                 * @access public
7973                 * @since 3.0.000 (2008-03-27)
7974                 */
7975                 function startPageGroup() {
7976                         $this->newpagegroup = true;
7977                 }
7978
7979                 /*
7980                 * Return the current page in the group.
7981                 * @return current page in the group
7982                 * @access public
7983                 * @since 3.0.000 (2008-03-27)
7984                 */
7985                 function getGroupPageNo() {
7986                         return $this->pagegroups[$this->currpagegroup];
7987                 }
7988
7989                 /*
7990                 * Return the alias of the current page group
7991         * If the current font is unicode type, the returned string is surrounded by additional curly braces.
7992                 * (will be replaced by the total number of pages in this group).
7993                 * @return alias of the current page group
7994                 * @access public
7995                 * @since 3.0.000 (2008-03-27)
7996                 */
7997                 function getPageGroupAlias() {
7998                         if (strpos(strtolower($this->CurrentFont['type']), 'unicode')) {
7999                                 return "{".$this->currpagegroup."}";
8000             }
8001                         return $this->currpagegroup;
8002                 }
8003
8004                 /*
8005                 * Put visibility settings.
8006                 * @access protected
8007                 * @since 3.0.000 (2008-03-27)
8008                 */
8009                 function _putocg() {
8010                         $this->_newobj();
8011                         $this->n_ocg_print = $this->n;
8012                         $this->_out('<</Type /OCG /Name '.$this->_textstring('print'));
8013                         $this->_out('/Usage <</Print <</PrintState /ON>> /View <</ViewState /OFF>>>>>>');
8014                         $this->_out('endobj');
8015                         $this->_newobj();
8016                         $this->n_ocg_view=$this->n;
8017                         $this->_out('<</Type /OCG /Name '.$this->_textstring('view'));
8018                         $this->_out('/Usage <</Print <</PrintState /OFF>> /View <</ViewState /ON>>>>>>');
8019                         $this->_out('endobj');
8020                 }
8021
8022                 /*
8023                 * Set the visibility of the successive elements.
8024                 * This can be useful, for instance, to put a background
8025                 * image or color that will show on screen but won't print.
8026                 * @param string $v visibility mode. Legal values are: all, print, screen.
8027                 * @access public
8028                 * @since 3.0.000 (2008-03-27)
8029                 */
8030                 function setVisibility($v) {
8031                         if ($this->openMarkedContent) {
8032                                 // close existing open marked-content
8033                                 $this->_out('EMC');
8034                                 $this->openMarkedContent = false;
8035                         }
8036                         switch($v) {
8037                                 case "print": {
8038                                         $this->_out('/OC /OC1 BDC');
8039                                         $this->openMarkedContent = true;
8040                                         break;
8041                                 }
8042                                 case "screen": {
8043                                         $this->_out('/OC /OC2 BDC');
8044                                         $this->openMarkedContent = true;
8045                                         break;
8046                                 }
8047                                 case "all": {
8048                                         $this->_out('');
8049                                         break;
8050                                 }
8051                                 default: {
8052                                         $this->Error('Incorrect visibility: '.$v);
8053                                         break;
8054                                 }
8055                         }
8056                         $this->visibility = $v;
8057                 }
8058
8059                 /*
8060                 * Add transparency parameters to the current extgstate
8061                 * @param array $params parameters
8062                 * @return the number of extgstates
8063                 * @access protected
8064                 * @since 3.0.000 (2008-03-27)
8065                 */
8066                 function addExtGState($parms) {
8067                         $n = count($this->extgstates) + 1;
8068                         $this->extgstates[$n]['parms'] = $parms;
8069                         return $n;
8070                 }
8071
8072                 /*
8073                 * Add an extgstate
8074                 * @param array $gs extgstate
8075                 * @access protected
8076                 * @since 3.0.000 (2008-03-27)
8077                 */
8078                 function setExtGState($gs) {
8079                         $this->_out(sprintf('/GS%d gs', $gs));
8080                 }
8081
8082                 /*
8083                 * Put extgstates for object transparency
8084                 * @param array $gs extgstate
8085                 * @access protected
8086                 * @since 3.0.000 (2008-03-27)
8087                 */
8088                 function _putextgstates() {
8089                         $ne = count($this->extgstates);
8090                         for ($i = 1; $i <= $ne; $i++) {
8091                                 $this->_newobj();
8092                                 $this->extgstates[$i]['n'] = $this->n;
8093                                 $this->_out('<</Type /ExtGState');
8094                                 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
8095                                         $this->_out('/'.$k.' '.$v);
8096                                 }
8097                                 $this->_out('>>');
8098                                 $this->_out('endobj');
8099                         }
8100                 }
8101
8102                 /*
8103                 * Set alpha for stroking (CA) and non-stroking (ca) operations.
8104                 * @param float $alpha real value from 0 (transparent) to 1 (opaque)
8105                 * @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
8106                 * @access public
8107                 * @since 3.0.000 (2008-03-27)
8108                 */
8109                 function setAlpha($alpha, $bm='Normal') {
8110                         $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm));
8111                         $this->setExtGState($gs);
8112                 }
8113
8114                 /*
8115                 * Set the default JPEG compression quality (1-100)
8116                 * @param int $quality JPEG quality, integer between 1 and 100
8117                 * @access public
8118                 * @since 3.0.000 (2008-03-27)
8119                 */
8120                 function setJPEGQuality($quality) {
8121                         if (($quality < 1) OR ($quality > 100)) {
8122                                 $quality = 75;
8123                         }
8124                         $this->jpeg_quality = intval($quality);
8125                 }
8126
8127                 /*
8128                 * Set the default number of columns in a row for HTML tables.
8129                 * @param int $cols number of columns
8130                 * @access public
8131                 * @since 3.0.014 (2008-06-04)
8132                 */
8133                 function setDefaultTableColumns($cols=4) {
8134                         $this->default_table_columns = intval($cols);
8135                 }
8136
8137                 /*
8138                 * Set the height of cell repect font height.
8139                 * @param int $h cell proportion respect font height (typical value = 1.25).
8140                 * @access public
8141                 * @since 3.0.014 (2008-06-04)
8142                 */
8143                 function setCellHeightRatio($h) {
8144                         $this->cell_height_ratio = $h;
8145                 }
8146
8147                 /*
8148                 * return the height of cell repect font height.
8149                 * @access public
8150                 * @since 4.0.012 (2008-07-24)
8151                 */
8152                 function getCellHeightRatio() {
8153                         return $this->cell_height_ratio;
8154                 }
8155
8156                 /*
8157                 * Set the PDF version (check PDF reference for valid values).
8158                 * Default value is 1.t
8159                 * @access public
8160                 * @since 3.1.000 (2008-06-09)
8161                 */
8162                 function setPDFVersion($version="1.7") {
8163                         $this->PDFVersion = $version;
8164                 }
8165
8166                 /*
8167                 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
8168                 * (see Section 8.1 of PDF reference, "Viewer Preferences").
8169                 * <ul>
8170                 * <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>
8171                 * <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>
8172                 * <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>
8173                 * <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>
8174                 * <li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li>
8175                 * <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>
8176                 * <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>
8177                 * <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>
8178                 * <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>
8179                 * <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>
8180                 * <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>
8181                 * <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>
8182                 * <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>
8183                 * <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>
8184                 * <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>
8185                 * <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>
8186                 * </ul>
8187                 * @param array $preferences array of options.
8188                 * @author Nicola Asuni
8189                 * @access public
8190                 * @since 3.1.000 (2008-06-09)
8191                 */
8192                 function setViewerPreferences($preferences) {
8193                         $this->viewer_preferences = $preferences;
8194                 }
8195
8196                 /**
8197                 * Paints a linear colour gradient.
8198                 * @param float $x abscissa of the top left corner of the rectangle.
8199                 * @param float $y ordinate of the top left corner of the rectangle.
8200                 * @param float $w width of the rectangle.
8201                 * @param float $h height of the rectangle.
8202                 * @param array $col1 first color (RGB components).
8203                 * @param array $col2 second color (RGB components).
8204                 * @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).
8205                 * @author Andreas Würmser, Nicola Asuni
8206                 * @since 3.1.000 (2008-06-09)
8207                 * @access public
8208                 */
8209                 function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
8210                         $this->Clip($x, $y, $w, $h);
8211                         $this->Gradient(2, $col1, $col2, $coords);
8212                 }
8213
8214                 /**
8215                 * Paints a radial colour gradient.
8216                 * @param float $x abscissa of the top left corner of the rectangle.
8217                 * @param float $y ordinate of the top left corner of the rectangle.
8218                 * @param float $w width of the rectangle.
8219                 * @param float $h height of the rectangle.
8220                 * @param array $col1 first color (RGB components).
8221                 * @param array $col2 second color (RGB components).
8222                 * @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.
8223                 * @author Andreas Würmser, Nicola Asuni
8224                 * @since 3.1.000 (2008-06-09)
8225                 * @access public
8226                 */
8227                 function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
8228                         $this->Clip($x, $y, $w, $h);
8229                         $this->Gradient(3, $col1, $col2, $coords);
8230                 }
8231
8232                 /**
8233                 * Paints a coons patch mesh.
8234                 * @param float $x abscissa of the top left corner of the rectangle.
8235                 * @param float $y ordinate of the top left corner of the rectangle.
8236                 * @param float $w width of the rectangle.
8237                 * @param float $h height of the rectangle.
8238                 * @param array $col1 first color (lower left corner) (RGB components).
8239                 * @param array $col2 second color (lower right corner) (RGB components).
8240                 * @param array $col3 third color (upper right corner) (RGB components).
8241                 * @param array $col4 fourth color (upper left corner) (RGB components).
8242                 * @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>
8243                 * @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
8244                 * @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
8245                 * @author Andreas Würmser, Nicola Asuni
8246                 * @since 3.1.000 (2008-06-09)
8247                 * @access public
8248                 */
8249                 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) {
8250                         $this->Clip($x, $y, $w, $h);
8251                         $n = count($this->gradients) + 1;
8252                         $this->gradients[$n]['type'] = 6; //coons patch mesh
8253                         //check the coords array if it is the simple array or the multi patch array
8254                         if (!isset($coords[0]['f'])){
8255                                 //simple array -> convert to multi patch array
8256                                 if (!isset($col1[1])) {
8257                                         $col1[1] = $col1[2] = $col1[0];
8258                                 }
8259                                 if (!isset($col2[1])) {
8260                                         $col2[1] = $col2[2] = $col2[0];
8261                                 }
8262                                 if (!isset($col3[1])) {
8263                                         $col3[1] = $col3[2] = $col3[0];
8264                                 }
8265                                 if (!isset($col4[1])) {
8266                                         $col4[1] = $col4[2] = $col4[0];
8267                                 }
8268                                 $patch_array[0]['f'] = 0;
8269                                 $patch_array[0]['points'] = $coords;
8270                                 $patch_array[0]['colors'][0]['r'] = $col1[0];
8271                                 $patch_array[0]['colors'][0]['g'] = $col1[1];
8272                                 $patch_array[0]['colors'][0]['b'] = $col1[2];
8273                                 $patch_array[0]['colors'][1]['r'] = $col2[0];
8274                                 $patch_array[0]['colors'][1]['g'] = $col2[1];
8275                                 $patch_array[0]['colors'][1]['b'] = $col2[2];
8276                                 $patch_array[0]['colors'][2]['r'] = $col3[0];
8277                                 $patch_array[0]['colors'][2]['g'] = $col3[1];
8278                                 $patch_array[0]['colors'][2]['b'] = $col3[2];
8279                                 $patch_array[0]['colors'][3]['r'] = $col4[0];
8280                                 $patch_array[0]['colors'][3]['g'] = $col4[1];
8281                                 $patch_array[0]['colors'][3]['b'] = $col4[2];
8282                         } else {
8283                                 //multi patch array
8284                                 $patch_array = $coords;
8285                         }
8286                         $bpcd = 65535; //16 BitsPerCoordinate
8287                         //build the data stream
8288                         $this->gradients[$n]['stream'] = "";
8289                         for($i=0; $i < count($patch_array); $i++) {
8290                                 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
8291                                 for($j=0; $j < count($patch_array[$i]['points']); $j++) {
8292                                         //each point as 16 bit
8293                                         $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j]-$coords_min)/($coords_max-$coords_min))*$bpcd;
8294                                         if ($patch_array[$i]['points'][$j] < 0) {
8295                                                 $patch_array[$i]['points'][$j] = 0;
8296                                         }
8297                                         if ($patch_array[$i]['points'][$j] > $bpcd) {
8298                                                 $patch_array[$i]['points'][$j] = $bpcd;
8299                                         }
8300                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]/256));
8301                                         $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j]%256));
8302                                 }
8303                                 for($j=0; $j < count($patch_array[$i]['colors']); $j++) {
8304                                         //each color component as 8 bit
8305                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
8306                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
8307                                         $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
8308                                 }
8309                         }
8310                         //paint the gradient
8311                         $this->_out('/Sh'.$n.' sh');
8312                         //restore previous Graphic State
8313                         $this->_out('Q');
8314                 }
8315
8316                 /**
8317                 * Set a rectangular clipping area.
8318                 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
8319                 * @param float $y ordinate of the top left corner of the rectangle.
8320                 * @param float $w width of the rectangle.
8321                 * @param float $h height of the rectangle.
8322                 * @author Andreas Würmser, Nicola Asuni
8323                 * @since 3.1.000 (2008-06-09)
8324                 * @access protected
8325                 */
8326                 function Clip($x, $y, $w, $h){
8327                         if ($this->rtl) {
8328                                 $x = $this->w - $x - $w;
8329                         }
8330                         //save current Graphic State
8331                         $s = 'q';
8332                         //set clipping area
8333                         $s .= sprintf(' %.2f %.2f %.2f %.2f re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
8334                         //set up transformation matrix for gradient
8335                         $s .= sprintf(' %.3f 0 0 %.3f %.3f %.3f cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
8336                         $this->_out($s);
8337                 }
8338
8339                 /**
8340                 * Output gradient.
8341                 * @param int $type type of gradient.
8342                 * @param array $col1 first color (RGB components).
8343                 * @param array $col2 second color (RGB components).
8344                 * @param array $coords array of coordinates.
8345                 * @author Andreas Würmser, Nicola Asuni
8346                 * @since 3.1.000 (2008-06-09)
8347                 * @access protected
8348                 */
8349                 function Gradient($type, $col1, $col2, $coords){
8350                         $n = count($this->gradients) + 1;
8351                         $this->gradients[$n]['type'] = $type;
8352                         if (!isset($col1[1])) {
8353                                 $col1[1]=$col1[2]=$col1[0];
8354                         }
8355                         $this->gradients[$n]['col1'] = sprintf('%.3f %.3f %.3f', ($col1[0]/255), ($col1[1]/255), ($col1[2]/255));
8356                         if (!isset($col2[1])) {
8357                                 $col2[1] = $col2[2] = $col2[0];
8358                         }
8359                         $this->gradients[$n]['col2'] = sprintf('%.3f %.3f %.3f', ($col2[0]/255), ($col2[1]/255), ($col2[2]/255));
8360                         $this->gradients[$n]['coords'] = $coords;
8361                         //paint the gradient
8362                         $this->_out('/Sh'.$n.' sh');
8363                         //restore previous Graphic State
8364                         $this->_out('Q');
8365                 }
8366
8367                 /**
8368                 * Output shaders.
8369                 * @author Andreas Würmser, Nicola Asuni
8370                 * @since 3.1.000 (2008-06-09)
8371                 * @access protected
8372                 */
8373                 function _putshaders() {
8374                         foreach($this->gradients as $id => $grad) {
8375                                 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
8376                                         $this->_newobj();
8377                                         $this->_out('<<');
8378                                         $this->_out('/FunctionType 2');
8379                                         $this->_out('/Domain [0.0 1.0]');
8380                                         $this->_out('/C0 ['.$grad['col1'].']');
8381                                         $this->_out('/C1 ['.$grad['col2'].']');
8382                                         $this->_out('/N 1');
8383                                         $this->_out('>>');
8384                                         $this->_out('endobj');
8385                                         $f1 = $this->n;
8386                                 }
8387                                 $this->_newobj();
8388                                 $this->_out('<<');
8389                                 $this->_out('/ShadingType '.$grad['type']);
8390                                 $this->_out('/ColorSpace /DeviceRGB');
8391                                 if ($grad['type'] == 2) {
8392                                         $this->_out(sprintf('/Coords [%.3f %.3f %.3f %.3f]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]));
8393                                         $this->_out('/Function '.$f1.' 0 R');
8394                                         $this->_out('/Extend [true true] ');
8395                                         $this->_out('>>');
8396                                 } elseif ($grad['type'] == 3) {
8397                                         //x0, y0, r0, x1, y1, r1
8398                                         //at this this time radius of inner circle is 0
8399                                         $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]));
8400                                         $this->_out('/Function '.$f1.' 0 R');
8401                                         $this->_out('/Extend [true true] ');
8402                                         $this->_out('>>');
8403                                 } elseif ($grad['type'] == 6) {
8404                                         $this->_out('/BitsPerCoordinate 16');
8405                                         $this->_out('/BitsPerComponent 8');
8406                                         $this->_out('/Decode[0 1 0 1 0 1 0 1 0 1]');
8407                                         $this->_out('/BitsPerFlag 8');
8408                                         $this->_out('/Length '.strlen($grad['stream']));
8409                                         $this->_out('>>');
8410                                         $this->_putstream($grad['stream']);
8411                                 }
8412                                 $this->_out('endobj');
8413                                 $this->gradients[$id]['id'] = $this->n;
8414                         }
8415                 }
8416
8417                 /**
8418                 * Output an arc
8419                 * @author Maxime Delorme, Nicola Asuni
8420                 * @since 3.1.000 (2008-06-09)
8421                 * @access protected
8422                 */
8423                 function _outarc($x1, $y1, $x2, $y2, $x3, $y3 ) {
8424                         $h = $this->h;
8425                         $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));
8426                 }
8427
8428                 /**
8429                 * Draw the sector of a circle.
8430                 * It can be used for instance to render pie charts.
8431                 * @param float $xc abscissa of the center.
8432                 * @param float $yc ordinate of the center.
8433                 * @param float $r radius.
8434                 * @param float $a start angle (in degrees).
8435                 * @param float $b end angle (in degrees).
8436                 * @param string $style: D, F, FD or DF (draw, fill, fill and draw). Default: FD.
8437                 * @param float $cw: indicates whether to go clockwise (default: true).
8438                 * @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.
8439                 * @author Maxime Delorme, Nicola Asuni
8440                 * @since 3.1.000 (2008-06-09)
8441                 * @access public
8442                 */
8443                 function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
8444                         if ($this->rtl) {
8445                                 $xc = $this->w - $xc - $w;
8446                         }
8447                         if ($cw) {
8448                                 $d = $b;
8449                                 $b = $o - $a;
8450                                 $a = $o - $d;
8451                         } else {
8452                                 $b += $o;
8453                                 $a += $o;
8454                         }
8455                         $a = ($a % 360) + 360;
8456                         $b = ($b % 360) + 360;
8457                         if ($a > $b) {
8458                                 $b +=360;
8459                         }
8460                         $b = $b / 360 * 2 * M_PI;
8461                         $a = $a / 360 * 2 * M_PI;
8462                         $d = $b - $a;
8463                         if ($d == 0 ) {
8464                                 $d = 2 * M_PI;
8465                         }
8466                         $k = $this->k;
8467                         $hp = $this->h;
8468                         if ($style=='F') {
8469                                 $op = 'f';
8470                         } elseif ($style=='FD' or $style=='DF') {
8471                                 $op = 'b';
8472                         } else {
8473                                 $op = 's';
8474                         }
8475                         if (sin($d/2)) {
8476                                 $MyArc = 4/3 * (1 - cos($d/2)) / sin($d/2) * $r;
8477                         }
8478                         //first put the center
8479                         $this->_out(sprintf('%.2f %.2f m', ($xc)*$k, ($hp-$yc)*$k));
8480                         //put the first point
8481                         $this->_out(sprintf('%.2f %.2f l', ($xc+$r*cos($a))*$k, (($hp-($yc-$r*sin($a)))*$k)));
8482                         //draw the arc
8483                         if ($d < (M_PI/2)) {
8484                                 $this->_outarc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a), $yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a), $xc+$r*cos($b)+$MyArc*cos($b-M_PI/2), $yc-$r*sin($b)-$MyArc*sin($b-M_PI/2), $xc+$r*cos($b), $yc-$r*sin($b));
8485                         } else {
8486                                 $b = $a + $d/4;
8487                                 $MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
8488                                 $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));
8489                                 $a = $b;
8490                                 $b = $a + $d/4;
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                         }
8499                         //terminate drawing
8500                         $this->_out($op);
8501                 }
8502
8503                 /**
8504                 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
8505                 * Only vector drawing is supported, not text or bitmap.
8506                 * 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).
8507                 * @param string $file Name of the file containing the image.
8508                 * @param float $x Abscissa of the upper-left corner.
8509                 * @param float $y Ordinate of the upper-left corner.
8510                 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
8511                 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
8512                 * @param mixed $link URL or identifier returned by AddLink().
8513                 * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
8514                 * @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>
8515                 * @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>
8516                 * @author Valentin Schmidt, Nicola Asuni
8517                 * @since 3.1.000 (2008-06-09)
8518                 * @access public
8519                 */
8520                 function ImageEps($file, $x, $y, $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='') {
8521                         $data = file_get_contents($file);
8522                         if ($data === false) {
8523                                 $this->Error('EPS file not found: '.$file);
8524                         }
8525                         $regs = array();
8526                         // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
8527                         preg_match ('/%%Creator:([^\r\n]+)/', $data, $regs); # find Creator
8528                         if (count($regs) > 1) {
8529                                 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
8530                                 if (strpos($version_str, 'Adobe Illustrator') !== false) {
8531                                         $versexp = explode(' ', $version_str);
8532                                         $version = (float)array_pop($versexp);
8533                                         if ($version >= 9) {
8534                                                 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
8535                                         }
8536                                 }
8537                         }
8538                         // strip binary bytes in front of PS-header
8539                         $start = strpos($data, '%!PS-Adobe');
8540                         if ($start > 0) {
8541                                 $data = substr($data, $start);
8542                         }
8543                         // find BoundingBox params
8544                         preg_match ("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
8545                         if (count($regs) > 1) {
8546                                 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
8547                         } else {
8548                                 $this->Error('No BoundingBox found in EPS file: '.$file);
8549                         }
8550                         $start = strpos($data, '%%EndSetup');
8551                         if ($start === false) {
8552                                 $start = strpos($data, '%%EndProlog');
8553                         }
8554                         if ($start === false) {
8555                                 $start = strpos($data, '%%BoundingBox');
8556                         }
8557                         $data = substr($data, $start);
8558                         $end = strpos($data, '%%PageTrailer');
8559                         if ($end===false) {
8560                                 $end = strpos($data, 'showpage');
8561                         }
8562                         if ($end) {
8563                                 $data = substr($data, 0, $end);
8564                         }
8565                         $k = $this->k;
8566                         if ($w > 0) {
8567                                 $scale_x = $w/(($x2-$x1)/$k);
8568                                 if ($h > 0) {
8569                                         $scale_y = $h/(($y2-$y1)/$k);
8570                                 } else {
8571                                         $scale_y = $scale_x;
8572                                         $h = ($y2-$y1)/$k * $scale_y;
8573                                 }
8574                         } else {
8575                                 if ($h > 0) {
8576                                         $scale_y = $h/(($y2-$y1)/$k);
8577                                         $scale_x = $scale_y;
8578                                         $w = ($x2-$x1)/$k * $scale_x;
8579                                 } else {
8580                                         $w = ($x2 - $x1) / $k;
8581                                         $h = ($y2 - $y1) / $k;
8582                                 }
8583                         }
8584                         // Check whether we need a new page first as this does not fit
8585                         if ((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) {
8586                                 // Automatic page break
8587                                 $this->AddPage($this->CurOrientation);
8588                                 // Reset coordinates to top fo next page
8589                                 //$x = $this->GetX();
8590                                 $y = $this->GetY() + $this->cMargin;
8591                         }
8592                         // set bottomcoordinates
8593                         $this->img_rb_y = $y + $h;
8594                         // set alignment
8595                         if ($this->rtl) {
8596                                 if ($palign == 'L') {
8597                                         $ximg = $this->lMargin;
8598                                         // set right side coordinate
8599                                         $this->img_rb_x = $ximg + $w;
8600                                 } elseif ($palign == 'C') {
8601                                         $ximg = ($this->w - $x - $w) / 2;
8602                                         // set right side coordinate
8603                                         $this->img_rb_x = $ximg + $w;
8604                                 } else {
8605                                         $ximg = $this->w - $x - $w;
8606                                         // set left side coordinate
8607                                         $this->img_rb_x = $ximg;
8608                                 }
8609                         } else {
8610                                 if ($palign == 'R') {
8611                                         $ximg = $this->w - $this->rMargin - $w;
8612                                         // set left side coordinate
8613                                         $this->img_rb_x = $ximg;
8614                                 } elseif ($palign == 'C') {
8615                                         $ximg = ($this->w - $x - $w) / 2;
8616                                         // set right side coordinate
8617                                         $this->img_rb_x = $ximg + $w;
8618                                 } else {
8619                                         $ximg = $x;
8620                                         // set right side coordinate
8621                                         $this->img_rb_x = $ximg + $w;
8622                                 }
8623                         }
8624                         if ($useBoundingBox){
8625                                 $dx = $ximg * $k - $x1;
8626                                 $dy = $y * $k - $y1;
8627                         } else {
8628                                 $dx = $ximg * $k;
8629                                 $dy = $y * $k;
8630                         }
8631                         // save the current graphic state
8632                         $this->_out('q');
8633                         // translate
8634                         $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy+($this->hPt - 2*$y*$k - ($y2-$y1))));
8635                         // scale
8636                         if (isset($scale_x)) {
8637                                 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1*(1-$scale_x), $y2*(1-$scale_y)));
8638                         }
8639                         // handle pc/unix/mac line endings
8640                         $lines = preg_split("/\r\n|[\r\n]/", $data);
8641                         $u=0;
8642                         $cnt = count($lines);
8643                         for ($i=0; $i < $cnt; $i++) {
8644                                 $line = $lines[$i];
8645                                 if (($line == '') OR ($line{0} == '%')) {
8646                                         continue;
8647                                 }
8648                                 $len = strlen($line);
8649                                 $chunks = explode(' ', $line);
8650                                 $cmd = array_pop($chunks);
8651                                 // RGB
8652                                 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
8653                                         $b = array_pop($chunks);
8654                                         $g = array_pop($chunks);
8655                                         $r = array_pop($chunks);
8656                                         $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!
8657                                         continue;
8658                                 }
8659                                 switch ($cmd) {
8660                                         case 'm':
8661                                         case 'l':
8662                                         case 'v':
8663                                         case 'y':
8664                                         case 'c':
8665                                         case 'k':
8666                                         case 'K':
8667                                         case 'g':
8668                                         case 'G':
8669                                         case 's':
8670                                         case 'S':
8671                                         case 'J':
8672                                         case 'j':
8673                                         case 'w':
8674                                         case 'M':
8675                                         case 'd':
8676                                         case 'n':
8677                                         case 'v': {
8678                                                 $this->_out($line);
8679                                                 break;
8680                                         }
8681                                         case 'x': {// custom fill color
8682                                                 list($c,$m,$y,$k) = $chunks;
8683                                                 $this->_out("$c $m $y $k k");
8684                                                 break;
8685                                         }
8686                                         case 'X': { // custom stroke color
8687                                                 list($c,$m,$y,$k) = $chunks;
8688                                                 $this->_out("$c $m $y $k K");
8689                                                 break;
8690                                         }
8691                                         case 'Y':
8692                                         case 'N':
8693                                         case 'V':
8694                                         case 'L':
8695                                         case 'C': {
8696                                                 $line{$len-1} = strtolower($cmd);
8697                                                 $this->_out($line);
8698                                                 break;
8699                                         }
8700                                         case 'b':
8701                                         case 'B': {
8702                                                 $this->_out($cmd . '*');
8703                                                 break;
8704                                         }
8705                                         case 'f':
8706                                         case 'F': {
8707                                                 if ($u > 0) {
8708                                                         $isU = false;
8709                                                         $max = min($i+5, $cnt);
8710                                                         for ($j=$i+1; $j < $max; $j++)
8711                                                           $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
8712                                                         if ($isU) {
8713                                                                 $this->_out("f*");
8714                                                         }
8715                                                 } else {
8716                                                         $this->_out("f*");
8717                                                 }
8718                                                 break;
8719                                         }
8720                                         case '*u': {
8721                                                 $u++;
8722                                                 break;
8723                                         }
8724                                         case '*U': {
8725                                                 $u--;
8726                                                 break;
8727                                         }
8728                                 }
8729                         }
8730                         // restore previous graphic state
8731                         $this->_out('Q');
8732                         if ($link) {
8733                                 $this->Link($ximg, $y, $w, $h, $link);
8734                         }
8735                         // set pointer to align the successive text/objects
8736                         switch($align) {
8737                                 case 'T':{
8738                                         $this->y = $y;
8739                                         $this->x = $this->img_rb_x;
8740                                         break;
8741                                 }
8742                                 case 'M':{
8743                                         $this->y = $y + round($h/2);
8744                                         $this->x = $this->img_rb_x;
8745                                         break;
8746                                 }
8747                                 case 'B':{
8748                                         $this->y = $this->img_rb_y;
8749                                         $this->x = $this->img_rb_x;
8750                                         break;
8751                                 }
8752                                 case 'N':{
8753                                         $this->SetY($this->img_rb_y);
8754                                         break;
8755                                 }
8756                                 default:{
8757                                         break;
8758                                 }
8759                         }
8760                         $this->endlinex = $this->img_rb_x;
8761                 }
8762
8763                 /**
8764                  * Set document barcode.
8765                  * @param string $bc barcode
8766                  */
8767                 function setBarcode($bc="") {
8768                         $this->barcode = $bc;
8769                 }
8770
8771                 /**
8772                  * Get current barcode.
8773                  * @return string
8774                  * @since 4.0.012 (2008-07-24)
8775                  */
8776                 function getBarcode() {
8777                         return $this->barcode;
8778                 }
8779
8780                 /**
8781                  * Print Barcode.
8782                  * @param string $code code to print
8783                  * @param string $type type of barcode.
8784                  * @param int $x x position in user units
8785                  * @param int $y y position in user units
8786                  * @param int $w width in user units
8787                  * @param int $h height position in user units
8788                  * @param float $xres width of the smallest bar in user units
8789                  * @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>
8790                  * @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>
8791                  * @author Nicola Asuni
8792                  * @since 3.1.000 (2008-06-09)
8793                  * @access public
8794                  */
8795                 function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres=0.4, $style='', $align='') {
8796                         if (empty($code)) {
8797                                 return;
8798                         }
8799                         $barcodeobj = new TCPDFbarcode($code, $type);
8800                         $arrcode = $barcodeobj->getBarcodeArray();
8801                         if ($arrcode === false) {
8802                                 $this->Error('Error in barcode string');
8803                         }
8804                         // set default values
8805                         if (!isset($style["position"])) {
8806                                 if ($this->rtl) {
8807                                         $style["position"] = "R";
8808                                 } else {
8809                                         $style["position"] = "L";
8810                                 }
8811                         }
8812                         if (!isset($style["padding"])) {
8813                                 $style["padding"] = 0;
8814                         }
8815                         if (!isset($style["fgcolor"])) {
8816                                 $style["fgcolor"] = array(0,0,0); // default black
8817                         }
8818                         if (!isset($style["bgcolor"])) {
8819                                 $style["bgcolor"] = false; // default transparent
8820                         }
8821                         if (!isset($style["border"])) {
8822                                 $style["border"] = false;
8823                         }
8824                         if (!isset($style["text"])) {
8825                                 $style["text"] = false;
8826                                 $fontsize = 0;
8827                         }
8828                         if ($style["text"] AND isset($style["font"])) {
8829                                 $prevFontFamily = $this->FontFamily;
8830                                 $prevFontStyle = $this->FontStyle;
8831                                 $prevFontSizePt = $this->FontSizePt;
8832                                 if (isset($style["fontsize"])) {
8833                                         $fontsize = $style["fontsize"];
8834                                 } else {
8835                                         $fontsize = 0;
8836                                 }
8837                                 $this->SetFont($style["font"], '', $fontsize);
8838                         }
8839                         if (!isset($style["stretchtext"])) {
8840                                 $style["stretchtext"] = 4;
8841                         }
8842                         // set foreground color
8843                         $prevDrawColor = $this->DrawColor;
8844                         $prevTextColor = $this->TextColor;
8845                         $this->SetDrawColorArray($style["fgcolor"]);
8846                         $this->SetTextColorArray($style["fgcolor"]);
8847                         if (empty($w) OR ($w <= 0)) {
8848                                 if ($this->rtl) {
8849                                         $w = $this->x - $this->lMargin;
8850                                 } else {
8851                                         $w = $this->w - $this->rMargin - $this->x;
8852                                 }
8853                         }
8854                         if (empty($x)) {
8855                                 $x = $this->GetX();
8856                         }
8857                         if ($this->rtl) {
8858                                 $x = $this->w - $x;
8859                         }
8860                         if (empty($y)) {
8861                                 $y = $this->GetY();
8862                         }
8863                         if (empty($xres)) {
8864                                 $xres = 0.4;
8865                         }
8866                         $fbw = ($arrcode["maxw"] * $xres) + (2 * $style["padding"]);
8867                         $extraspace = ($this->cell_height_ratio * $fontsize / $this->k) + (2 * $style["padding"]);
8868                         if (empty($h)) {
8869                                 $h = 10 + $extraspace;
8870                         }
8871                         if ((($y + $h) > $this->PageBreakTrigger) AND (empty($this->InFooter)) AND ($this->AcceptPageBreak())) {
8872                                 //Automatic page break
8873                                 $x = $this->x;
8874                                 $ws = $this->ws;
8875                                 if ($ws > 0) {
8876                                         $this->ws = 0;
8877                                         $this->_out('0 Tw');
8878                                 }
8879                                 $this->AddPage($this->CurOrientation);
8880                                 if ($ws > 0) {
8881                                         $this->ws = $ws;
8882                                         $this->_out(sprintf('%.3f Tw',$ws * $k));
8883                                 }
8884                                 $this->x = $x;
8885                                 $y = $this->y;
8886                         }
8887                         // maximum bar heigth
8888                         $barh = $h - $extraspace;
8889                         switch ($style["position"]) {
8890                                 case "L": { // left
8891                                         if ($this->rtl) {
8892                                                 $xpos = $x - $w;
8893                                         } else {
8894                                                 $xpos = $x;
8895                                         }
8896                                         break;
8897                                 }
8898                                 case "C": { // center
8899                                         $xdiff = (($w - $fbw) / 2);
8900                                         if ($this->rtl) {
8901                                                 $xpos = $x - $w + $xdiff;
8902                                         } else {
8903                                                 $xpos = $x + $xdiff;
8904                                         }
8905                                         break;
8906                                 }
8907                                 case "R": { // right
8908                                         if ($this->rtl) {
8909                                                 $xpos = $x - $fbw;
8910                                         } else {
8911                                                 $xpos = $x + $w - $fbw;
8912                                         }
8913                                         break;
8914                                 }
8915                                 case "S": { // stretch
8916                                         $fbw = $w;
8917                                         $xres = ($w - (2 * $style["padding"])) / $arrcode["maxw"];
8918                                         if ($this->rtl) {
8919                                                 $xpos = $x - $w;
8920                                         } else {
8921                                                 $xpos = $x;
8922                                         }
8923                                         break;
8924                                 }
8925                         }
8926                         $xpos_rect = $xpos;
8927                         $xpos = $xpos_rect + $style["padding"];
8928                         $xpos_text = $xpos;
8929                         // barcode is always printed in LTR direction
8930                         $tempRTL = $this->rtl;
8931                         $this->rtl = false;
8932                         // print background color
8933                         if ($style["bgcolor"]) {
8934                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'DF', '', $style["bgcolor"]);
8935                         } elseif ($style["border"]) {
8936                                 $this->Rect($xpos_rect, $y, $fbw, $h, 'D');
8937                         }
8938                         // print bars
8939                         if ($arrcode !== false) {
8940                                 foreach ($arrcode["bcode"] as $k => $v) {
8941                                         $bw = ($v["w"] * $xres);
8942                                         if ($v["t"]) {
8943                                                 // braw a vertical bar
8944                                                 $ypos = $y + $style["padding"] + ($v["p"] * $barh / $arrcode["maxh"]);
8945                                                 $this->Rect($xpos, $ypos, $bw, ($v["h"] * $barh  / $arrcode["maxh"]), 'DF', array("L"=>0,"T"=>0,"R"=>0,"B"=>0), $style["fgcolor"]);
8946                                         }
8947                                         $xpos += $bw;
8948                                 }
8949                         }
8950                         // print text
8951                         if ($style["text"]) {
8952                                 // print text
8953                                 $this->x = $xpos_text;
8954                                 $this->y = $y + $style["padding"] + $barh;
8955                                 $this->Cell(($arrcode["maxw"] * $xres), ($this->cell_height_ratio * $fontsize / $this->k), $code, 0, 0, 'C', 0, '', $style["stretchtext"]);
8956                         }
8957                         // restore original direction
8958                         $this->rtl = $tempRTL;
8959                         // restore previous font
8960                         if ($style["text"] AND isset($style["font"])) {
8961                                 $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
8962                         }
8963                         // restore colors
8964                         $this->DrawColor = $prevDrawColor;
8965                         $this->TextColor = $prevTextColor;
8966                         // set bottomcoordinates
8967                         $this->img_rb_y = $y + $h;
8968                         if ($this->rtl) {
8969                                 // set left side coordinate
8970                                 $this->img_rb_x = ($this->w - $x - $w);
8971                         } else {
8972                                 // set right side coordinate
8973                                 $this->img_rb_x = $x + $w;
8974                         }
8975                         // set pointer to align the successive text/objects
8976                         switch($align) {
8977                                 case 'T':{
8978                                         $this->y = $y;
8979                                         $this->x = $this->img_rb_x;
8980                                         break;
8981                                 }
8982                                 case 'M':{
8983                                         $this->y = $y + round($h/2);
8984                                         $this->x = $this->img_rb_x;
8985                                         break;
8986                                 }
8987                                 case 'B':{
8988                                         $this->y = $this->img_rb_y;
8989                                         $this->x = $this->img_rb_x;
8990                                         break;
8991                                 }
8992                                 case 'N':{
8993                                         $this->SetY($this->img_rb_y);
8994                                         break;
8995                                 }
8996                                 default:{
8997                                         break;
8998                                 }
8999                         }
9000                 }
9001
9002                 /**
9003                  * This function is DEPRECATED, please use the new write1DBarcode() function.
9004                  * @param int $x x position in user units
9005                  * @param int $y y position in user units
9006                  * @param int $w width in user units
9007                  * @param int $h height position in user units
9008                  * @param string $type type of barcode (I25, C128A, C128B, C128C, C39)
9009                  * @param string $style barcode style
9010                  * @param string $font font for text
9011                  * @param int $xres x resolution
9012                  * @param string $code code to print
9013                  * @deprecated deprecated since version 3.1.000 (2008-06-10)
9014                  * @see write1DBarcode()
9015                  */
9016                 function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
9017                         // convert old settings for the new write1DBarcode() function.
9018                         $xres = 1 / $xres;
9019                         $newstyle = array(
9020                                 "position" => "L",
9021                                 "border" => false,
9022                                 "padding" => 0,
9023                                 "fgcolor" => array(0,0,0),
9024                                 "bgcolor" => false,
9025                                 "text" => true,
9026                                 "font" => $font,
9027                                 "fontsize" => 8,
9028                                 "stretchtext" => 4
9029                         );
9030                         if ($style & 1) {
9031                                 $newstyle["border"] = true;
9032                         }
9033                         if ($style & 2) {
9034                                 $newstyle["bgcolor"] = false;
9035                         }
9036                         if ($style & 4) {
9037                                 $newstyle["position"] = "C";
9038                         } elseif ($style & 8) {
9039                                 $newstyle["position"] = "L";
9040                         } elseif ($style & 16) {
9041                                 $newstyle["position"] = "R";
9042                         }
9043                         if ($style & 128) {
9044                                 $newstyle["text"] = true;
9045                         }
9046                         if ($style & 256) {
9047                                 $newstyle["stretchtext"] = 4;
9048                         }
9049                         $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
9050                 }
9051
9052                 /**
9053                  * Returns an array containing current margins:
9054                  * <ul>
9055                                 <li>$ret['left'] = left  margin</li>
9056                                 <li>$ret['right'] = right margin</li>
9057                                 <li>$ret['top'] = top margin</li>
9058                                 <li>$ret['bottom'] = bottom margin</li>
9059                                 <li>$ret['header'] = header margin</li>
9060                                 <li>$ret['footer'] = footer margin</li>
9061                                 <li>$ret['cell'] = cell margin</li>
9062                  * </ul>
9063                  * @return array containing all margins measures
9064                  * @since 3.2.000 (2008-06-23)
9065                  */
9066                 function getMargins() {
9067                         $ret = array(
9068                                 'left' => $this->lMargin,
9069                                 'right' => $this->rMargin,
9070                                 'top' => $this->tMargin,
9071                                 'bottom' => $this->bMargin,
9072                                 'header' => $this->header_margin,
9073                                 'footer' => $this->footer_margin,
9074                                 'cell' => $this->cMargin,
9075                         );
9076                         return $ret;
9077                 }
9078
9079                 /**
9080                  * Returns an array containing original margins:
9081                  * <ul>
9082                                 <li>$ret['left'] = left  margin</li>
9083                                 <li>$ret['right'] = right margin</li>
9084                  * </ul>
9085                  * @return array containing all margins measures
9086                  * @since 4.0.012 (2008-07-24)
9087                  */
9088                 function getOriginalMargins() {
9089                         $ret = array(
9090                                 'left' => $this->original_lMargin,
9091                                 'right' => $this->original_rMargin
9092                         );
9093                         return $ret;
9094                 }
9095
9096                 /**
9097                  * Returns the current font size.
9098                  * @return current font size
9099                  * @since 3.2.000 (2008-06-23)
9100                  */
9101                 function getFontSize() {
9102                         return $this->FontSize;
9103                 }
9104
9105                 /**
9106                  * Returns the current font size in points unit.
9107                  * @return current font size in points unit
9108                  * @since 3.2.000 (2008-06-23)
9109                  */
9110                 function getFontSizePt() {
9111                         return $this->FontSizePt;
9112                 }
9113
9114                 /**
9115                  * Prints a cell (rectangular area) with optional borders, background color and html text string.
9116                  * 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 />
9117                  * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
9118                  * @param float $w Cell width. If 0, the cell extends up to the right margin.
9119                  * @param float $h Cell minimum height. The cell extends automatically if needed.
9120                  * @param float $x upper-left corner X coordinate
9121                  * @param float $y upper-left corner Y coordinate
9122                  * @param string $html html text to print. Default value: empty string.
9123                  * @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>
9124                  * @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>
9125         Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
9126                  * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
9127                  * @param boolean $reseth if true reset the last cell height (default true).
9128                  * @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>
9129                  * @uses MultiCell()
9130                  * @see Multicell(), writeHTML()
9131                  */
9132                 function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='') {
9133                         return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true);
9134                 }
9135
9136                 /**
9137                  * Returns the HTML DOM array.
9138                  * <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>
9139                  * @param string $html html code
9140                  * @return array
9141                  * @since 3.2.000 (2008-06-20)
9142                  */
9143                 function getHtmlDomArray($html) {
9144                         // remove all unsupported tags (the line below lists all supported tags)
9145                         $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>");
9146                         //replace carriage returns, newlines and tabs
9147                         $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ", "\\" => "\\\\");
9148                         $html = strtr($html, $repTable);
9149                         // remove extra spaces from tables
9150                         $html = preg_replace('/[\s]*<\/table>[\s]*/', '</table>', $html);
9151                         $html = preg_replace('/[\s]*<\/tr>[\s]*/', '</tr>', $html);
9152                         $html = preg_replace('/[\s]*<tr/', '<tr', $html);
9153                         $html = preg_replace('/[\s]*<\/th>[\s]*/', '</th>', $html);
9154                         $html = preg_replace('/[\s]*<th/', '<th', $html);
9155                         $html = preg_replace('/[\s]*<\/td>[\s]*/', '</td>', $html);
9156                         $html = preg_replace('/[\s]*<td/', '<td', $html);
9157                         $html = preg_replace('/<\/th>/', '<span></span></th>', $html);
9158                         $html = preg_replace('/<\/td>/', '<span></span></td>', $html);
9159                         // pattern for generic tag
9160                         $tagpattern = '/(<[^>]+>)/Uu';
9161                         // explodes the string
9162                         $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
9163                         // count elements
9164                         $maxel = count($a);
9165                         $key = 0;
9166                         // create an array of elements
9167                         $dom = array();
9168                         $dom[$key] = array();
9169                         // set first void element
9170                         $dom[$key]['tag'] = false;
9171                         $dom[$key]['value'] = "";
9172                         $dom[$key]['parent'] = 0;
9173                         $dom[$key]['fontname'] = $this->FontFamily;
9174                         $dom[$key]['fontstyle'] = $this->FontStyle;
9175                         $dom[$key]['fontsize'] = $this->FontSizePt;
9176                         $dom[$key]['bgcolor'] = false;
9177                         $dom[$key]['fgcolor'] = $this->fgcolor;
9178                         $dom[$key]['align'] = '';
9179                         $key++;
9180                         $level = array();
9181                         array_push($level, 0); // root
9182                         while ($key <= $maxel) {
9183                                 if ($key > 0) {
9184                                         $dom[$key] = array();
9185                                 }
9186                                 $element = $a[($key-1)];
9187                                 if (preg_match($tagpattern, $element)) {
9188                                         // html tag
9189                                         $dom[$key]['tag'] = true;
9190                                         $element = substr($element, 1, -1);
9191                                         // get tag name
9192                                         preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
9193                                         $dom[$key]['value'] = strtolower($tag[1]);
9194                                         if ($element{0} == '/') {
9195                                                 // closing html tag
9196                                                 $dom[$key]['opening'] = false;
9197                                                 $dom[$key]['parent'] = end($level);
9198                                                 array_pop($level);
9199                                                 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
9200                                                 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
9201                                                 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
9202                                                 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
9203                                                 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
9204                                                 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
9205                                                 // set the number of columns in table tag
9206                                                 if (($dom[$key]['value'] == "tr") AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
9207                                                         $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
9208                                                 }
9209                                                 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9210                                                         $dom[($dom[$key]['parent'])]['content'] = "";
9211                                                         for ($i = ($dom[$key]['parent'] + 1); $i < $key; $i++) {
9212                                                                 $dom[($dom[$key]['parent'])]['content'] .= $a[($i-1)];
9213                                                         }
9214                                                         $key = $i;
9215                                                 }
9216                                         } else {
9217                                                 // opening html tag
9218                                                 $dom[$key]['opening'] = true;
9219                                                 $dom[$key]['parent'] = end($level);
9220                                                 if (substr($element, -1, 1) != '/') {
9221                                                         // not self-closing tag
9222                                                         array_push($level, $key);
9223                                                         $dom[$key]['self'] = false;
9224                                                 } else {
9225                                                         $dom[$key]['self'] = true;
9226                                                 }
9227                                                 // copy some values from parent
9228                                                 if ($key > 0) {
9229                                                         $dom[$key]['fontname'] = $dom[($dom[$key]['parent'])]['fontname'];
9230                                                         $dom[$key]['fontstyle'] = $dom[($dom[$key]['parent'])]['fontstyle'];
9231                                                         $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'];
9232                                                         $dom[$key]['bgcolor'] = $dom[($dom[$key]['parent'])]['bgcolor'];
9233                                                         $dom[$key]['fgcolor'] = $dom[($dom[$key]['parent'])]['fgcolor'];
9234                                                         $dom[$key]['align'] = $dom[($dom[$key]['parent'])]['align'];
9235                                                 }
9236                                                 // get attributes
9237                                                 preg_match_all('/([^=\s]*)=["\']?([^"\']*)["\']?/', $element, $attr_array, PREG_PATTERN_ORDER);
9238                                                 $dom[$key]['attribute'] = array(); // reset attribute array
9239                                                 foreach ($attr_array[1] as $id => $name) {
9240                                                         $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
9241                                                 }
9242                                                 // split style attributes
9243                                                 if (isset($dom[$key]['attribute']['style'])) {
9244                                                         // get style attributes
9245                                                         preg_match_all('/([^:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
9246                                                         $dom[$key]['style'] = array(); // reset style attribute array
9247                                                         foreach ($style_array[1] as $id => $name) {
9248                                                                 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
9249                                                         }
9250                                                         // --- get some style attributes ---
9251                                                         if (isset($dom[$key]['style']['font-family'])) {
9252                                                                 // font family
9253                                                                 if (isset($dom[$key]['style']['font-family'])) {
9254                                                                         $fontslist = preg_split("/,/", strtolower($dom[$key]['style']['font-family']));
9255                                                                         foreach($fontslist as $font) {
9256                                                                                 $font = trim(strtolower($font));
9257                                                                                 if (in_array($font, $this->fontlist)){
9258                                                                                         $dom[$key]['fontname'] = $font;
9259                                                                                         break;
9260                                                                                 }
9261                                                                         }
9262                                                                 }
9263                                                         }
9264                                                         // font size
9265                                                         if (isset($dom[$key]['style']['font-size'])) {
9266                                                                 $fsize = trim($dom[$key]['style']['font-size']);
9267                                                                 switch ($fsize) {
9268                                                                         case 'xx-small': {
9269                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
9270                                                                                 break;
9271                                                                         }
9272                                                                         case 'x-small': {
9273                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
9274                                                                                 break;
9275                                                                         }
9276                                                                         case 'small': {
9277                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
9278                                                                                 break;
9279                                                                         }
9280                                                                         case 'medium': {
9281                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
9282                                                                                 break;
9283                                                                         }
9284                                                                         case 'large': {
9285                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
9286                                                                                 break;
9287                                                                         }
9288                                                                         case 'x-large': {
9289                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
9290                                                                                 break;
9291                                                                         }
9292                                                                         case 'xx-large': {
9293                                                                                 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
9294                                                                                 break;
9295                                                                         }
9296                                                                         default: {
9297                                                                                 $dom[$key]['fontsize'] = intval($fsize);
9298                                                                         }
9299                                                                 }
9300                                                         }
9301                                                         // font style
9302                                                         $dom[$key]['fontstyle'] = "";
9303                                                         if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == "b")) {
9304                                                                 $dom[$key]['fontstyle'] .= "B";
9305                                                         }
9306                                                         if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == "i")) {
9307                                                                 $dom[$key]['fontstyle'] .= "I";
9308                                                         }
9309                                                         // font color
9310                                                         if (isset($dom[$key]['style']['color']) AND (!empty($dom[$key]['style']['color']))) {
9311                                                                 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
9312                                                         }
9313                                                         // background color
9314                                                         if (isset($dom[$key]['style']['background-color']) AND (!empty($dom[$key]['style']['background-color']))) {
9315                                                                 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
9316                                                         }
9317                                                         // text-decoration
9318                                                         if (isset($dom[$key]['style']['text-decoration'])) {
9319                                                                 $decors = explode(" ", strtolower($dom[$key]['style']['text-decoration']));
9320                                                                 foreach ($decors as $dec) {
9321                                                                         $dec = trim($dec);
9322                                                                         if ($dec{0} == "u") {
9323                                                                                 $dom[$key]['fontstyle'] .= "U";
9324                                                                         } elseif ($dec{0} == "l") {
9325                                                                                 $dom[$key]['fontstyle'] .= "D";
9326                                                                         }
9327                                                                 }
9328                                                         }
9329                                                         // check for width attribute
9330                                                         if (isset($dom[$key]['style']['width'])) {
9331                                                                 $dom[$key]['width'] = intval($dom[$key]['style']['width']);
9332                                                         }
9333                                                         // check for height attribute
9334                                                         if (isset($dom[$key]['style']['height'])) {
9335                                                                 $dom[$key]['height'] = intval($dom[$key]['style']['height']);
9336                                                         }
9337                                                         // check for text alignment
9338                                                         if (isset($dom[$key]['style']['text-align'])) {
9339                                                                 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
9340                                                         }
9341                                                 }
9342                                                 // check for font tag
9343                                                 if ($dom[$key]['value'] == "font") {
9344                                                         // font family
9345                                                         if (isset($dom[$key]['attribute']['face'])) {
9346                                                                 $fontslist = preg_split("/,/", strtolower($dom[$key]['attribute']['face']));
9347                                                                 foreach($fontslist as $font) {
9348                                                                         $font = trim(strtolower($font));
9349                                                                         if (in_array($font, $this->fontlist)){
9350                                                                                 $dom[$key]['fontname'] = $font;
9351                                                                                 break;
9352                                                                         }
9353                                                                 }
9354                                                         }
9355                                                         // font size
9356                                                         if (isset($dom[$key]['attribute']['size'])) {
9357                                                                 if ($key > 0) {
9358                                                                         if ($dom[$key]['attribute']['size']{0} == "+") {
9359                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
9360                                                                         } elseif ($dom[$key]['attribute']['size']{0} == "-") {
9361                                                                                 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
9362                                                                         } else {
9363                                                                                 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9364                                                                         }
9365                                                                 } else {
9366                                                                         $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
9367                                                                 }
9368                                                         }
9369                                                 }
9370                                                 if (($dom[$key]['value'] == "ul") OR ($dom[$key]['value'] == "ol") OR ($dom[$key]['value'] == "dl")) {
9371                                                         // force natural alignment for lists
9372                                                         if ($this->rtl) {
9373                                                                 $dom[$key]['align'] = "R";
9374                                                         } else {
9375                                                                 $dom[$key]['align'] = "L";
9376                                                         }
9377                                                 }
9378                                                 if (($dom[$key]['value'] == "small") OR ($dom[$key]['value'] == "sup") OR ($dom[$key]['value'] == "sub")) {
9379                                                         $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
9380                                                 }
9381                                                 if (($dom[$key]['value'] == "strong") OR ($dom[$key]['value'] == "b")) {
9382                                                         $dom[$key]['fontstyle'] .= "B";
9383                                                 }
9384                                                 if (($dom[$key]['value'] == "em") OR ($dom[$key]['value'] == "i")) {
9385                                                         $dom[$key]['fontstyle'] .= "I";
9386                                                 }
9387                                                 if (($dom[$key]['value']{0} == "h") AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
9388                                                         $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
9389                                                         $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
9390                                                         $dom[$key]['fontstyle'] .= "B";
9391                                                 }
9392                                                 if (($dom[$key]['value'] == "table")) {
9393                                                         $dom[$key]['rows'] = 0; // number of rows
9394                                                         $dom[$key]['trids'] = array(); // IDs of TR elements
9395                                                 }
9396                                                 if (($dom[$key]['value'] == "tr")) {
9397                                                         $dom[$key]['cols'] = 0;
9398                                                         // store the number of rows on table element
9399                                                         $dom[($dom[$key]['parent'])]['rows']++;
9400                                                         // store the TR elements IDs on table element
9401                                                         array_push($dom[($dom[$key]['parent'])]['trids'], $key);
9402                                                 }
9403                                                 if (($dom[$key]['value'] == "th") OR ($dom[$key]['value'] == "td")) {
9404                                                         if (isset($dom[$key]['attribute']['colspan'])) {
9405                                                                 $colspan = intval($dom[$key]['attribute']['colspan']);
9406                                                         } else {
9407                                                                 $colspan = 1;
9408                                                         }
9409                                                         $dom[$key]['attribute']['colspan'] = $colspan;
9410                                                         $dom[($dom[$key]['parent'])]['cols'] += $colspan;
9411                                                 }
9412                                                 // set foreground color attribute
9413                                                 if (isset($dom[$key]['attribute']['color']) AND (!empty($dom[$key]['attribute']['color']))) {
9414                                                         $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
9415                                                 }
9416                                                 // set background color attribute
9417                                                 if (isset($dom[$key]['attribute']['bgcolor']) AND (!empty($dom[$key]['attribute']['bgcolor']))) {
9418                                                         $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
9419                                                 }
9420                                                 // check for width attribute
9421                                                 if (isset($dom[$key]['attribute']['width'])) {
9422                                                         $dom[$key]['width'] = intval($dom[$key]['attribute']['width']);
9423                                                 }
9424                                                 // check for height attribute
9425                                                 if (isset($dom[$key]['attribute']['height'])) {
9426                                                         $dom[$key]['height'] = intval($dom[$key]['attribute']['height']);
9427                                                 }
9428                                                 // check for text alignment
9429                                                 if (isset($dom[$key]['attribute']['align']) AND (!empty($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
9430                                                         $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
9431                                                 }
9432                                         } // end opening tag
9433                                 } else {
9434                                         // text
9435                                         $dom[$key]['tag'] = false;
9436                                         $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
9437                                         $dom[$key]['parent'] = end($level);
9438                                         // calculate text width
9439                                         //$dom[$key]['width'] = $this->GetStringWidth($dom[$key]['value'], $dom[($dom[$key]['parent'])]['fontname'], $dom[($dom[$key]['parent'])]['fontstyle'], $dom[($dom[$key]['parent'])]['fontsize']);
9440                                 }
9441                                 $key++;
9442                         }
9443                         return $dom;
9444                 }
9445
9446                 /**
9447                  * Allows to preserve some HTML formatting (limited support).<br />
9448                  * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
9449                  * 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,
9450                  * @param string $html text to display
9451                  * @param boolean $ln if true add a new line after text (default = true)
9452                  * @param int $fill Indicates if the background must be painted (true) or transparent (false).
9453                  * @param boolean $reseth if true reset the last cell height (default false).
9454                  * @param boolean $cell if true add the default cMargin space to each Write (default false).
9455                  * @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>
9456                  */
9457                 function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
9458                         // store current values
9459                         $prevlMargin = $this->lMargin;
9460                         $prevrMargin = $this->rMargin;
9461                         $prevcMargin = $this->cMargin;
9462                         $prevFontFamily = $this->FontFamily;
9463                         $prevFontStyle = $this->FontStyle;
9464                         $prevFontSizePt = $this->FontSizePt;
9465                         $curfontname = $prevFontFamily;
9466                         $curfontstyle = $prevFontStyle;
9467                         $curfontsize = $prevFontSizePt;
9468                         $prevbgcolor = $this->bgcolor;
9469                         $prevfgcolor = $this->fgcolor;
9470                         $this->newline = true;
9471                         $minstartliney = $this->y;
9472                         $yshift = 0;
9473                         $startlinepage = $this->page;
9474                         $newline = true;
9475                         if (isset($this->footerlen[$this->page])) {
9476                                 $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9477                         } else {
9478                                 $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9479                         }
9480                         $startlinepos = $this->footerpos[$this->page];
9481                         $lalign = $align;
9482                         $plalign = $align;
9483                         if ($this->rtl) {
9484                                 $w = $this->x - $this->lMargin;
9485                         } else {
9486                                 $w = $this->w - $this->rMargin - $this->x;
9487                         }
9488                         $w -= (2 * $this->cMargin);
9489                         if ($cell) {
9490                                 if ($this->rtl) {
9491                                         $this->x -= $this->cMargin;
9492                                 } else {
9493                                         $this->x += $this->cMargin;
9494                                 }
9495                         }
9496                         $this->listindent = $this->GetStringWidth("0000");
9497                         $this->listnum = 0;
9498                         if ((empty($this->lasth))OR ($reseth)) {
9499                                 //set row height
9500                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9501                         }
9502                         $dom = $this->getHtmlDomArray($html);
9503                         $maxel = count($dom);
9504                         $key = 0;
9505                         while ($key < $maxel) {
9506                                 if ($dom[$key]['tag'] OR ($key == 0)) {
9507                                         if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
9508                                                 $dom[$key]['align'] = ($this->rtl)?'R':'L';
9509                                         }
9510                                         // vertically align image in line
9511                                         if ((!$this->newline) AND ($dom[$key]['value'] == 'img') 
9512                                                 AND (isset($dom[$key]['attribute']['height']))
9513                                                 AND ($dom[$key]['attribute']['height'] > 0)
9514                                                 ) {
9515                                                 $this->y += (($curfontsize / $this->k) - $this->pixelsToUnits($dom[$key]['attribute']['height']));
9516                                                 $minstartliney = min($this->y, $minstartliney);
9517                                         } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize'])) {
9518                                                 // account for different font size
9519                                                 $pfontname = $curfontname;
9520                                                 $pfontstyle = $curfontstyle;
9521                                                 $pfontsize = $curfontsize;
9522                                                 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
9523                                                 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
9524                                                 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
9525                                                 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)) {
9526                                                         $this->SetFont($fontname, $fontstyle, $fontsize);
9527                                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
9528                                                         if (is_numeric($fontsize) AND ($fontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($fontsize != $curfontsize) AND (!$this->newline)) {
9529                                                                 $this->y += (($curfontsize - $fontsize) / $this->k);
9530                                                                 $minstartliney = min($this->y, $minstartliney);
9531                                                         }
9532                                                         $curfontname = $fontname;
9533                                                         $curfontstyle = $fontstyle;
9534                                                         $curfontsize = $fontsize;
9535                                                 }
9536                                         }
9537                                         if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
9538                                                 $this->SetFillColorArray($dom[$key]['bgcolor']);
9539                                                 $wfill = true;
9540                                         } else {
9541                                                 $wfill = $fill | false;
9542                                         }
9543                                         if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
9544                                                 $this->SetTextColorArray($dom[$key]['fgcolor']);
9545                                         }
9546                                         if (isset($dom[$key]['align'])) {
9547                                                 $lalign = $dom[$key]['align'];
9548                                         }
9549                                         if (empty($lalign)) {
9550                                                 $lalign = $align;
9551                                         }
9552                                 }
9553                                 // align lines
9554                                 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
9555                                         $newline = true;
9556                                         // we are at the beginning of a new line
9557                                         if (isset($startlinex)) {
9558                                                 $yshift = $minstartliney - $startliney;
9559                                                 if ($yshift > 0) {
9560                                                         $yshift = 0;
9561                                                 }
9562                                                 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9563                                                         // the last line must be shifted to be aligned as requested
9564                                                         $linew = abs($this->endlinex - $startlinex);
9565                                                         $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9566                                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9567                                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9568                                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9569                                                         } elseif (isset($opentagpos)) {
9570                                                                 $midpos = $opentagpos;
9571                                                         } elseif (isset($this->footerlen[$startlinepage])) {
9572                                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9573                                                                 $midpos = $this->footerpos[$startlinepage];
9574                                                         } else {
9575                                                                 $midpos = 0;
9576                                                         }
9577                                                         if ($midpos > 0) {
9578                                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9579                                                                 $pend = substr($this->pages[$startlinepage], $midpos);
9580                                                         } else {
9581                                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9582                                                                 $pend = "";
9583                                                         }
9584                                                         // calculate shifting amount
9585                                                         $mdiff = abs($w - $linew);
9586                                                         if ($plalign == "C") {
9587                                                                 if ($this->rtl) {
9588                                                                         $t_x = -($mdiff / 2);
9589                                                                 } else {
9590                                                                         $t_x = ($mdiff / 2);
9591                                                                 }
9592                                                         }       elseif (($plalign == "R") AND (!$this->rtl)) {
9593                                                                 // right alignment on LTR document
9594                                                                 $t_x = $mdiff;
9595                                                         }       elseif (($plalign == "L") AND ($this->rtl)) {
9596                                                                 // left alignment on RTL document
9597                                                                 $t_x = -$mdiff;
9598                                                         } else {
9599                                                                 $t_x = 0;
9600                                                         }
9601                                                         if (($t_x != 0) OR ($yshift < 0)) {
9602                                                                 // shift the line
9603                                                                 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9604                                                                 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9605                                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9606                                                                 // shift the annotations and links
9607                                                                 if (isset($this->PageAnnots[$this->page])) {
9608                                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9609                                                                                 if ($pac['y'] >= $minstartliney) {
9610                                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9611                                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9612                                                                                 }
9613                                                                         }
9614                                                                 }
9615                                                                 $this->y -= $yshift;
9616                                                         }
9617                                                 }
9618                                         }
9619                                         $this->checkPageBreak($this->lasth);
9620                                         $this->SetFont($fontname, $fontstyle, $fontsize);
9621                                         if ($wfill) {
9622                                                 $this->SetFillColorArray($this->bgcolor);
9623                                         }
9624                                         $startlinex = $this->x;
9625                                         $startliney = $this->y;
9626                                         $minstartliney = $this->y;
9627                                         $startlinepage = $this->page;
9628                                         if (isset($endlinepos)) {
9629                                                 $startlinepos = $endlinepos;
9630                                                 unset($endlinepos);
9631                                         } else {
9632                                                 if (isset($this->footerlen[$this->page])) {
9633                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9634                                                 } else {
9635                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9636                                                 }
9637                                                 $startlinepos = $this->footerpos[$this->page];
9638                                         }
9639                                         $plalign = $lalign;
9640                                         $this->newline = false;
9641                                 }
9642                                 if (isset($opentagpos)) {
9643                                         unset($opentagpos);
9644                                 }
9645                                 if ($dom[$key]['tag']) {
9646                                         if ($dom[$key]['opening']) {
9647                                                 // table content is handled in a special way
9648                                                 if (($dom[$key]['value'] == "td") OR ($dom[$key]['value'] == "th")) {
9649                                                         $trid = $dom[$key]['parent'];
9650                                                         $table_el = $dom[$trid]['parent'];
9651                                                         if (!isset($dom[$table_el]['cols'])) {
9652                                                                 $dom[$table_el]['cols'] = $trid['cols'];
9653                                                         }
9654                                                         // calculate cell width
9655                                                         if (isset($dom[($dom[$key]['parent'])]['width'])) {
9656                                                                 $table_width = $this->pixelsToUnits($dom[($dom[$key]['parent'])]['width']);
9657                                                         } else {
9658                                                                 $table_width = $w;
9659                                                         }
9660                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
9661                                                                 $currentcmargin = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding']);
9662                                                         } else {
9663                                                                 $currentcmargin = 0;
9664                                                         }
9665                                                         $this->cMargin = $currentcmargin;
9666                                                         if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellspacing'])) {
9667                                                                 $cellspacing = $this->pixelsToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellspacing']);
9668                                                         } else {
9669                                                                 $cellspacing = 0;
9670                                                         }
9671                                                         if ($this->rtl) {
9672                                                                 $cellspacingx = -$cellspacing;
9673                                                         } else {
9674                                                                 $cellspacingx = $cellspacing;
9675                                                         }
9676                                                         $colspan = $dom[$key]['attribute']['colspan'];
9677                                                         if (isset($dom[$key]['width'])) {
9678                                                                 $cellw = $this->pixelsToUnits($dom[$key]['width']);
9679                                                         } else {
9680                                                                 $cellw = ($colspan * ($table_width / $dom[$table_el]['cols']));
9681                                                         }
9682                                                         $cellw -= $cellspacing;
9683                                                         if (isset($dom[$key]['content'])) {
9684                                                                 $cell_content = $dom[$key]['content'];
9685                                                         } else {
9686                                                                 $cell_content = "&nbsp;";
9687                                                         }
9688                                                         $tagtype = $dom[$key]['value'];
9689                                                         $parentid = $key;
9690                                                         while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
9691                                                                 // move $key index forward
9692                                                                 $key++;
9693                                                         }
9694                                                         if (!isset($dom[$trid]['startpage'])) {
9695                                                                 $dom[$trid]['startpage'] = $this->page;
9696                                                         } else {
9697                                                                 $this->setPage($dom[$trid]['startpage']);
9698                                                         }
9699                                                         if (!isset($dom[$trid]['starty'])) {
9700                                                                 $dom[$trid]['starty'] = $this->y;
9701                                                         } else {
9702                                                                 $this->y = $dom[$trid]['starty'];
9703                                                         }
9704                                                         if (!isset($dom[$trid]['startx'])) {
9705                                                                 $dom[$trid]['startx'] = $this->x;
9706                                                         }
9707                                                         $this->x += ($cellspacingx / 2);
9708                                                         if (isset($dom[$parentid]['attribute']['rowspan'])) {
9709                                                                 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
9710                                                         }       else {
9711                                                                 $rowspan = 1;
9712                                                         }
9713                                                         // skip row-spanned cells started on the previous rows
9714                                                         if (isset($dom[$table_el]['rowspans'])) {
9715                                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9716                                                                         if  (($trwsp['startx'] == $this->x) AND (($trwsp['starty'] < $this->y) OR ($trwsp['startpage'] < $this->page)) AND ($trwsp['rowspan'] > 0)) {
9717                                                                                 $this->x = $trwsp['endx'] + $cellspacingx;
9718                                                                         }
9719                                                                 }
9720                                                         }
9721                                                         // add rowspan information to table element
9722                                                         if ($rowspan > 1) {
9723                                                                 if (isset($this->footerlen[$this->page])) {
9724                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9725                                                                 } else {
9726                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9727                                                                 }
9728                                                                 $trintmrkpos = $this->footerpos[$this->page];
9729                                                                 $trsid = array_push($dom[$table_el]['rowspans'], array('rowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startx' => $this->x, 'starty' => $this->y, 'intmrkpos' => $trintmrkpos));
9730                                                         }
9731                                                         $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
9732                                                         if ($rowspan > 1) {
9733                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
9734                                                         }
9735                                                         // push background colors
9736                                                         if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
9737                                                                 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
9738                                                         }
9739
9740                                                         // write the cell content
9741                                                         $this->MultiCell($cellw, 0, $cell_content, false, $lalign, false, 2, '', '', true, 0, true);
9742
9743                                                         $this->cMargin = $currentcmargin;
9744                                                         $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
9745                                                         
9746                                                         // update the end of row position
9747                                                         if ($rowspan <= 1) {
9748                                                                 if (isset($dom[$trid]['endy'])) {
9749                                                                         if ($this->page == $dom[$trid]['endpage']) {
9750                                                                                 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
9751                                                                         } elseif ($this->page > $dom[$trid]['endpage']) {
9752                                                                                 $dom[$trid]['endy'] = $this->y;
9753                                                                         }
9754                                                                 } else {
9755                                                                         $dom[$trid]['endy'] = $this->y;
9756                                                                 }
9757                                                                 if (isset($dom[$trid]['endpage'])) {
9758                                                                         $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
9759                                                                 } else {
9760                                                                         $dom[$trid]['endpage'] = $this->page;
9761                                                                 }
9762                                                         } else {
9763                                                         // account for row-spanned cells
9764                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
9765                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
9766                                                                 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
9767                                                         }
9768                                                         if (isset($dom[$table_el]['rowspans'])) {
9769                                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
9770                                                                         if ($trwsp['rowspan'] > 0) {
9771                                                                                 if (isset($dom[$trid]['endpage'])) {
9772                                                                                         if ($trwsp['endpage'] == $dom[$trid]['endpage']) {
9773                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
9774                                                                                         } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[$trid]['endpage']) {
9775                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $trwsp['endy'];
9776                                                                                         } else {
9777                                                                                                 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
9778                                                                                                 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
9779                                                                                         }
9780                                                                                 }
9781                                                                         }
9782                                                                 }
9783                                                         }
9784                                                         $this->x += ($cellspacingx / 2);
9785                                                 } else {
9786                                                         // opening tag (or self-closing tag)
9787                                                         if (!isset($opentagpos)) {
9788                                                                 if (isset($this->footerlen[$this->page])) {
9789                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]) - $this->footerlen[$this->page];
9790                                                                 } else {
9791                                                                         $this->footerpos[$this->page] = strlen($this->pages[$this->page]);
9792                                                                 }
9793                                                                 $opentagpos = $this->footerpos[$this->page];
9794                                                         }
9795                                                         $this->openHTMLTagHandler($dom, $key, $cell);
9796                                                 }
9797                                         } else {
9798                                                 // closing tag
9799                                                 $this->closeHTMLTagHandler($dom, $key, $cell);
9800                                         }
9801                                 } elseif (strlen($dom[$key]['value']) > 0) {
9802                                         // print list-item
9803                                         if (!empty($this->lispacer)) {
9804                                                 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
9805                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9806                                                 $minstartliney = $this->y;
9807                                                 $tmpx = $this->x;
9808                                                 $lspace = $this->GetStringWidth($this->lispacer."  ");
9809                                                 if ($this->rtl) {
9810                                                         $this->x += $lspace;
9811                                                 } else {
9812                                                         $this->x -= $lspace;
9813                                                 }
9814                                                 $this->Write($this->lasth, $this->lispacer, '', false, '', false, 0, false);
9815                                                 $this->x = $tmpx;
9816                                                 $this->lispacer = "";
9817                                                 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
9818                                                 $this->lasth = $this->FontSize * $this->cell_height_ratio;
9819                                                 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
9820                                                         $this->y += (($pfontsize - $curfontsize) / $this->k);
9821                                                         $minstartliney = min($this->y, $minstartliney);
9822                                                 }
9823                                         }
9824                                         // text
9825                                         $this->htmlvspace = 0;
9826                                         if ($newline) {
9827                                                 if ($this->rtl OR $this->tmprtl) {
9828                                                         $dom[$key]['value'] = rtrim($dom[$key]['value']);
9829                                                 } else {
9830                                                         $dom[$key]['value'] = ltrim($dom[$key]['value']);
9831                                                 }
9832                                                 $newline = false;
9833                                         }
9834                                         if ($this->HREF) {
9835                                                 // HTML <a> Link
9836                                                 $strrest = $this->addHtmlLink($this->HREF, $dom[$key]['value'], $wfill, true);
9837                                         } else {
9838                                                 $ctmpmargin = $this->cMargin;
9839                                                 $this->cMargin = 0;
9840                                                 // write only until the end of the line and get the rest
9841                                                 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, "", false, 0, true);
9842                                                 $this->cMargin = $ctmpmargin;
9843                                         }
9844                                         if (strlen($strrest) > 0) {
9845                                                 // store the remaining string on the previous $key position
9846                                                 $this->newline = true;
9847                                                 if ($cell) {
9848                                                         if ($this->rtl) {
9849                                                                 $this->x -= $this->cMargin;
9850                                                         } else {
9851                                                                 $this->x += $this->cMargin;
9852                                                         }
9853                                                 }
9854                                                 $dom[$key]['value'] = ltrim($strrest);
9855                                                 $key--;
9856                                         }
9857                                 }
9858                                 $key++;
9859                         } // end for each $key
9860                         // align the last line
9861                         if (isset($startlinex)) {
9862                                 $yshift = $minstartliney - $startliney;
9863                                 if ($yshift > 0) {
9864                                         $yshift = 0;
9865                                 }
9866                                 if ((isset($plalign) AND ((($plalign == "C") OR (($plalign == "R") AND (!$this->rtl)) OR (($plalign == "L") AND ($this->rtl))))) OR ($yshift < 0)){
9867                                         // the last line must be shifted to be aligned as requested
9868                                         $linew = abs($this->endlinex - $startlinex);
9869                                         $pstart = substr($this->pages[$startlinepage], 0, $startlinepos);
9870                                         if (isset($opentagpos) AND isset($this->footerlen[$startlinepage])) {
9871                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9872                                                 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
9873                                         } elseif (isset($opentagpos)) {
9874                                                 $midpos = $opentagpos;
9875                                         } elseif (isset($this->footerlen[$startlinepage])) {
9876                                                 $this->footerpos[$startlinepage] = strlen($this->pages[$startlinepage]) - $this->footerlen[$startlinepage];
9877                                                 $midpos = $this->footerpos[$startlinepage];
9878                                         } else {
9879                                                 $midpos = 0;
9880                                         }
9881                                         if ($midpos > 0) {
9882                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos, ($midpos - $startlinepos));
9883                                                 $pend = substr($this->pages[$startlinepage], $midpos);
9884                                         } else {
9885                                                 $pmid = substr($this->pages[$startlinepage], $startlinepos);
9886                                                 $pend = "";
9887                                         }
9888                                         // calculate shifting amount
9889                                         $mdiff = abs($w - $linew);
9890                                         if ($plalign == "C") {
9891                                                 if ($this->rtl) {
9892                                                         $t_x = -($mdiff / 2);
9893                                                 } else {
9894                                                         $t_x = ($mdiff / 2);
9895                                                 }
9896                                         }       elseif (($plalign == "R") AND (!$this->rtl)) {
9897                                                 // right alignment on LTR document
9898                                                 $t_x = $mdiff;
9899                                         }       elseif (($plalign == "L") AND ($this->rtl)) {
9900                                                 // left alignment on RTL document
9901                                                 $t_x = -$mdiff;
9902                                         } else {
9903                                                 $t_x = 0;
9904                                         }
9905                                         if (($t_x != 0) OR ($yshift < 0)) {
9906                                                 // shift the line
9907                                                 $trx = sprintf('1 0 0 1 %.3f %.3f cm', ($t_x * $this->k), ($yshift * $this->k));
9908                                                 $this->pages[$startlinepage] = $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend;
9909                                                 $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n");
9910                                                 // shift the annotations and links
9911                                                 if (isset($this->PageAnnots[$this->page])) {
9912                                                         foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
9913                                                                 if ($pac['y'] >= $minstartliney) {
9914                                                                         $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
9915                                                                         $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
9916                                                                 }
9917                                                         }
9918                                                 }
9919                                                 $this->y -= $yshift;
9920                                         }
9921                                 }
9922                         }
9923                         if ($ln AND (!($cell AND ($dom[$key-1]['value'] == "table")))) {
9924                                 $this->Ln($this->lasth);
9925                         }
9926                         // restore previous values
9927                         $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
9928                         $this->SetFillColorArray($prevbgcolor);
9929                         $this->SetTextColorArray($prevfgcolor);
9930                         $this->lMargin = $prevlMargin;
9931                         $this->rMargin = $prevrMargin;
9932                         $this->cMargin = $prevcMargin;
9933                         unset($dom);
9934                 }
9935
9936                 /**
9937                  * Process opening tags.
9938                  * @param array $dom html dom array
9939                  * @param int $key current element id
9940                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
9941                  * @access protected
9942                  */
9943                 function openHTMLTagHandler(&$dom, $key, $cell=false) {
9944                         $tag = $dom[$key];
9945                         $parent = $dom[($dom[$key]['parent'])];
9946                         // check for text direction attribute
9947                         if (isset($tag['attribute']['dir'])) {
9948                                 $this->tmprtl = $tag['attribute']['dir'] == 'rtl' ? 'R' : 'L';
9949                         } else {
9950                                 $this->tmprtl = false;
9951                         }
9952                         //Opening tag
9953                         switch($tag['value']) {
9954                                 case 'table': {
9955                                         $dom[$key]['rowspans'] = array();
9956                                         if (isset($tag['attribute']['cellpadding'])) {
9957                                                 $this->oldcMargin = $this->cMargin;
9958                                                 $this->cMargin = $this->pixelsToUnits($tag['attribute']['cellpadding']);
9959                                         }
9960                                         break;
9961                                 }
9962                                 case 'tr': {
9963                                         // array of columns positions
9964                                         $dom[$key]['cellpos'] = array();
9965                                         break;
9966                                 }
9967                                 case 'td':
9968                                 case 'th': {
9969                                         break;
9970                                 }
9971                                 case 'hr': {
9972                                         $this->addHTMLVertSpace(1, $cell);
9973                                         $this->htmlvspace = 0;
9974                                         if ((isset($tag['attribute']['width'])) AND ($tag['attribute']['width'] != '')) {
9975                                                 $hrWidth = $this->pixelsToUnits($tag['attribute']['width']);
9976                                         } else {
9977                                                 $hrWidth = $this->w - $this->lMargin - $this->rMargin;
9978                                         }
9979                                         $x = $this->GetX();
9980                                         $y = $this->GetY();
9981                                         $prevlinewidth = $this->GetLineWidth();
9982                                         $this->Line($x, $y, $x + $hrWidth, $y);
9983                                         $this->SetLineWidth($prevlinewidth);
9984                                         $this->addHTMLVertSpace(1, $cell);
9985                                         break;
9986                                 }
9987                                 case 'b': {
9988                                         $this->setStyle('b', true);
9989                                         break;
9990                                 }
9991                                 case 'i': {
9992                                         $this->setStyle('i', true);
9993                                         break;
9994                                 }
9995                                 case 'u': {
9996                                         $this->setStyle('u', true);
9997                                         break;
9998                                 }
9999                                 case 'del': {
10000                                         $this->setStyle('d', true);
10001                                         break;
10002                                 }
10003                                 case 'a': {
10004                                         if (array_key_exists('href', $tag['attribute'])) {
10005                                                 $this->HREF = $tag['attribute']['href'];
10006                                         }
10007                                         break;
10008                                 }
10009                                 case 'img': {
10010                                         if (isset($tag['attribute']['src'])) {
10011                                                 // replace relative path with real server path
10012                                                 if ($tag['attribute']['src'][0] == '/') {
10013                                                         $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
10014                                                 }
10015                                                 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
10016                                                 if (!isset($tag['attribute']['width'])) {
10017                                                         $tag['attribute']['width'] = 0;
10018                                                 }
10019                                                 if (!isset($tag['attribute']['height'])) {
10020                                                         $tag['attribute']['height'] = 0;
10021                                                 }
10022                                                 //if (!isset($tag['attribute']['align'])) {
10023                                                         // the only alignment supported is "bottom"
10024                                                         // further development is required for other modes.
10025                                                         $tag['attribute']['align'] = 'bottom';
10026                                                 //} 
10027                                                 switch($tag['attribute']['align']) {
10028                                                         case 'top': {
10029                                                                 $align = 'T';
10030                                                                 break;
10031                                                         }
10032                                                         case 'middle': {
10033                                                                 $align = 'M';
10034                                                                 break;
10035                                                         }
10036                                                         case 'bottom': {
10037                                                                 $align = 'B';
10038                                                                 break;
10039                                                         }
10040                                                         default: {
10041                                                                 $align = 'B';
10042                                                                 break;
10043                                                         }
10044                                                 }
10045                                                 $fileinfo = pathinfo($tag['attribute']['src']);
10046                                                 if (isset($fileinfo['extension']) AND (!empty($fileinfo['extension']))) {
10047                                                         $type = strtolower($fileinfo['extension']);
10048                                                 }
10049                                                 $prevy = $this->y;
10050                                                 if (($type == "eps") OR ($type == "ai")) {
10051                                                         $this->ImageEps($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', true, $align);
10052                                                 } else {
10053                                                         $this->Image($tag['attribute']['src'], $this->GetX(), $this->GetY(), $this->pixelsToUnits($tag['attribute']['width']), $this->pixelsToUnits($tag['attribute']['height']), '', '', $align);
10054                                                 }
10055                                                 switch($align) {
10056                                                         case 'T': {
10057                                                                 $this->y = $prevy;
10058                                                                 break;
10059                                                         }
10060                                                         case 'M': {
10061                                                                 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
10062                                                                 break;
10063                                                         }
10064                                                         case 'B': {
10065                                                                 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
10066                                                                 break;
10067                                                         }
10068                                                 }
10069                                         }
10070                                         break;
10071                                 }
10072                                 case 'dl': {
10073                                         $this->listnum++;
10074                                         break;
10075                                 }
10076                                 case 'dt': {
10077                                         $this->addHTMLVertSpace(1, $cell);
10078                                         break;
10079                                 }
10080                                 case 'dd': {
10081                                         if ($this->rtl) {
10082                                                 $this->rMargin += $this->listindent;
10083                                         } else {
10084                                                 $this->lMargin += $this->listindent;
10085                                         }
10086                                         $this->addHTMLVertSpace(1, $cell);
10087                                         break;
10088                                 }
10089                                 case 'ul':
10090                                 case 'ol': {
10091                                         $this->listnum++;
10092                                         if ($tag['value'] == "ol") {
10093                                                 $this->listordered[$this->listnum] = true;
10094                                         } else {
10095                                                 $this->listordered[$this->listnum] = false;
10096                                         }
10097                                         $this->listcount[$this->listnum] = 0;
10098                                         if ($this->rtl) {
10099                                                 $this->rMargin += $this->listindent;
10100                                         } else {
10101                                                 $this->lMargin += $this->listindent;
10102                                         }
10103                                         break;
10104                                 }
10105                                 case 'li': {
10106                                         $this->Ln('', $cell);
10107                                         if ($tag['value'] == 'li') {
10108                                                 if ($this->listordered[$this->listnum]) {
10109                                                         if (isset($tag['attribute']['value'])) {
10110                                                                 $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
10111                                                         }
10112                                                         $this->listcount[$this->listnum]++;
10113                                                         if ($this->rtl) {
10114                                                                 $this->lispacer = ".".($this->listcount[$this->listnum]);
10115                                                         } else {
10116                                                                 $this->lispacer = ($this->listcount[$this->listnum]).".";
10117                                                         }
10118                                                 } else {
10119                                                         //unordered list symbol
10120                                                         $this->lispacer = "-";
10121                                                 }
10122                                         } else {
10123                                                 $this->lispacer = "";
10124                                         }
10125                                         break;
10126                                 }
10127                                 case 'blockquote': {
10128                                         if ($this->rtl) {
10129                                                 $this->rMargin += $this->listindent;
10130                                         } else {
10131                                                 $this->lMargin += $this->listindent;
10132                                         }
10133                                         $this->addHTMLVertSpace(2, $cell);
10134                                         break;
10135                                 }
10136                                 case 'br': {
10137                                         $this->Ln('', $cell);
10138                                         break;
10139                                 }
10140                                 case 'div': {
10141                                         $this->addHTMLVertSpace(2, $cell);
10142                                         break;
10143                                 }
10144                                 case 'p': {
10145                                         $this->addHTMLVertSpace(2, $cell);
10146                                         break;
10147                                 }
10148                                 case 'sup': {
10149                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
10150                                         break;
10151                                 }
10152                                 case 'sub': {
10153                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
10154                                         break;
10155                                 }
10156                                 case 'h1':
10157                                 case 'h2':
10158                                 case 'h3':
10159                                 case 'h4':
10160                                 case 'h5':
10161                                 case 'h6': {
10162                                         $this->addHTMLVertSpace(1, $cell, ($tag['fontsize'] * 1.5) / $this->k);
10163                                         break;
10164                                 }
10165                                 default: {
10166                                         break;
10167                                 }
10168                         }
10169                 }
10170
10171                 /**
10172                  * Process closing tags.
10173                  * @param array $dom html dom array
10174                  * @param int $key current element id
10175                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
10176                  * @access protected
10177                  */
10178                 function closeHTMLTagHandler(&$dom, $key, $cell=false) {
10179                         $tag = $dom[$key];
10180                         $parent = $dom[($dom[$key]['parent'])];
10181                         //Closing tag
10182                         switch($tag['value']) {
10183                                 case 'td':
10184                                 case 'th': {
10185                                         break;
10186                                 }
10187                                 case 'tr': {
10188                                         $table_el = $dom[($dom[$key]['parent'])]['parent'];
10189                                         // update row-spanned cells
10190                                         if (isset($dom[$table_el]['rowspans'])) {
10191                                                 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
10192                                                         $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
10193                                                         if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
10194                                                                 if ($dom[$table_el]['rowspans'][$k]['endpage'] == $dom[($dom[$key]['parent'])]['endpage']) {
10195                                                                         $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
10196                                                                 } elseif ($dom[$table_el]['rowspans'][$k]['endpage'] > $dom[($dom[$key]['parent'])]['endpage']) {
10197                                                                         $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
10198                                                                         $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
10199                                                                 }
10200                                                         }
10201                                                 }
10202                                         }
10203                                         $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
10204                                         $this->y = $dom[($dom[$key]['parent'])]['endy'];
10205                                         if (isset($dom[$table_el]['attribute']['cellspacing'])) {
10206                                                 $cellspacing = $this->pixelsToUnits($dom[$table_el]['attribute']['cellspacing']);
10207                                                 $this->y += $cellspacing;
10208                                         }                               
10209                                         $this->Ln(0, $cell);
10210                                         $this->x = $dom[($dom[$key]['parent'])]['startx'];
10211                                         break;
10212                                 }
10213                                 case 'table': {
10214                                         // draw borders
10215                                         $table_el = $parent;
10216                                         if ((isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0))
10217                                                 OR (isset($table_el['style']['border']) AND ($table_el['style']['border'] > 0))) {
10218                                                         $border = 1;
10219                                         } else {
10220                                                 $border = 0;
10221                                         }
10222                                         // for each row
10223                                         foreach ($table_el['trids'] as $j => $trkey) {
10224                                                 $parent = $dom[$trkey];
10225                                                 $restspace = $this->getPageHeight() - $this->y - $this->getBreakMargin();
10226                                                 // for each cell on the row
10227                                                 foreach ($parent['cellpos'] as $k => $cellpos) {
10228                                                         if (isset($cellpos['rowspanid'])) {
10229                                                                 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
10230                                                                 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
10231                                                                 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
10232                                                                 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
10233                                                                 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
10234                                                         } else {
10235                                                                 $endy = $parent['endy'];
10236                                                                 $startpage = $parent['startpage'];
10237                                                                 $endpage = $parent['endpage'];
10238                                                         }
10239                                                         $this->setPage($startpage);
10240                                                         $this->y = $parent['starty'];
10241                                                         if ($endpage > $startpage) {
10242                                                                 // design borders around HTML cells.
10243                                                                 for ($page=$startpage; $page <= $endpage; $page++) {
10244                                                                         $this->setPage($page);
10245                                                                         if ($page == $startpage) {
10246                                                                                 $this->y = $this->getPageHeight() - $restspace - $this->getBreakMargin();
10247                                                                                 $ch = $restspace;
10248                                                                         } elseif ($page == $endpage) {
10249                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of text
10250                                                                                 $ch = $endy - $this->tMargin;
10251                                                                         } else {
10252                                                                                 $this->y = $this->tMargin; // put cursor at the beginning of text
10253                                                                                 $ch = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin();
10254                                                                         }
10255
10256                                                                         if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10257                                                                                 $this->SetFillColorArray($cellpos['bgcolor']);
10258                                                                                 $fill = true;
10259                                                                         } else {
10260                                                                                 $fill = false;
10261                                                                         }
10262                                                                         $cw = abs($cellpos['endx'] - $cellpos['startx']);
10263                                                                         $this->x = $cellpos['startx'];
10264                                                                         // design a cell around the text
10265                                                                         $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10266                                                                         $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10267                                                                         $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10268                                                                         $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10269                                                                         $this->intmrk[$this->page] += strlen($ccode."\n");
10270                                                                 }
10271                                                         } else {
10272                                                                 $ch = $endy - $parent['starty'];
10273                                                                 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
10274                                                                         $this->SetFillColorArray($cellpos['bgcolor']);
10275                                                                         $fill = true;
10276                                                                 } else {
10277                                                                         $fill = false;
10278                                                                 }
10279                                                                 $cw = abs($cellpos['endx'] - $cellpos['startx']);
10280                                                                 $this->x = $cellpos['startx'];
10281                                                                 $this->y = $parent['starty'];
10282                                                                 // design a cell around the text
10283                                                                 $ccode = $this->FillColor."\n".$this->getCellCode($cw, $ch, "", $border, 1, '', $fill);
10284                                                                 $pstart = substr($this->pages[$this->page], 0, $this->intmrk[$this->page]);
10285                                                                 $pend = substr($this->pages[$this->page], $this->intmrk[$this->page]);
10286                                                                 $this->pages[$this->page] = $pstart.$ccode."\n".$pend;
10287                                                                 $this->intmrk[$this->page] += strlen($ccode."\n");
10288                                                         }
10289                                                 }
10290                                                 if (isset($table_el['attribute']['cellspacing'])) {
10291                                                         $cellspacing = $this->pixelsToUnits($table_el['attribute']['cellspacing']);
10292                                                         $this->y += $cellspacing;
10293                                                 }
10294                                                 $this->Ln(0, $cell);
10295                                                 $this->x = $parent['startx'];
10296                                         }
10297                                         if (isset($parent['cellpadding'])) {
10298                                                 $this->cMargin = $this->oldcMargin;
10299                                         }
10300                                         //set row height
10301                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
10302                                         break;
10303                                 }
10304                                 case 'b': {
10305                                         $this->setStyle('b', false);
10306                                         break;
10307                                 }
10308                                 case 'i': {
10309                                         $this->setStyle('i', false);
10310                                         break;
10311                                 }
10312                                 case 'u': {
10313                                         $this->setStyle('u', false);
10314                                         break;
10315                                 }
10316                                 case 'del': {
10317                                         $this->setStyle('d', false);
10318                                         break;
10319                                 }
10320                                 case 'a': {
10321                                         $this->HREF = '';
10322                                         break;
10323                                 }
10324                                 case 'sup': {
10325                                         $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
10326                                         break;
10327                                 }
10328                                 case 'sub': {
10329                                         $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
10330                                         break;
10331                                 }
10332                                 case 'div': {
10333                                         $this->addHTMLVertSpace(1, $cell);
10334                                         break;
10335                                 }
10336                                 case 'blockquote': {
10337                                         if ($this->rtl) {
10338                                                 $this->rMargin -= $this->listindent;
10339                                         } else {
10340                                                 $this->lMargin -= $this->listindent;
10341                                         }
10342                                         $this->addHTMLVertSpace(2, $cell);
10343                                         break;
10344                                 }
10345                                 case 'p': {
10346                                         $this->addHTMLVertSpace(2, $cell);
10347                                         break;
10348                                 }
10349                                 case 'dl': {
10350                                         $this->listnum--;
10351                                         if ($this->listnum <= 0) {
10352                                                 $this->listnum = 0;
10353                                                 $this->addHTMLVertSpace(2, $cell);
10354                                         }
10355                                         break;
10356                                 }
10357                                 case 'dt': {
10358                                         $this->lispacer = "";
10359                                         break;
10360                                 }
10361                                 case 'dd': {
10362                                         $this->lispacer = "";
10363                                         if ($this->rtl) {
10364                                                 $this->rMargin -= $this->listindent;
10365                                         } else {
10366                                                 $this->lMargin -= $this->listindent;
10367                                         }
10368                                         break;
10369                                 }
10370                                 case 'ul':
10371                                 case 'ol': {
10372                                         $this->listnum--;
10373                                         $this->lispacer = "";
10374                                         if ($this->rtl) {
10375                                                 $this->rMargin -= $this->listindent;
10376                                         } else {
10377                                                 $this->lMargin -= $this->listindent;
10378                                         }
10379                                         if ($this->listnum <= 0) {
10380                                                 $this->listnum = 0;
10381                                                 $this->addHTMLVertSpace(2, $cell);
10382                                         }
10383                                         $this->lasth = $this->FontSize * $this->cell_height_ratio;
10384                                         break;
10385                                 }
10386                                 case 'li': {
10387                                         $this->lispacer = "";
10388                                         break;
10389                                 }
10390                                 case 'h1':
10391                                 case 'h2':
10392                                 case 'h3':
10393                                 case 'h4':
10394                                 case 'h5':
10395                                 case 'h6': {
10396                                         $this->addHTMLVertSpace(1, $cell, ($parent['fontsize'] * 1.5) / $this->k);
10397                                         break;
10398                                 }
10399                                 default : {
10400                                         break;
10401                                 }
10402                         }
10403                         $this->tmprtl = false;
10404                 }
10405                 
10406                 /**
10407                  * Add vertical spaces if needed.
10408                  * @param int $n number of spaces to add
10409                  * @param boolean $cell if true add the default cMargin space to each new line (default false).
10410                  * @param string $h The height of the break. By default, the value equals the height of the last printed cell.
10411                  * @access protected
10412                  */
10413                 function addHTMLVertSpace($n, $cell=false, $h='') {
10414                         if (is_string($h)) {
10415                                 $vsize = $n * $this->lasth;
10416                         } else {
10417                                 $vsize = $n * $h;
10418                         }
10419                         if ($vsize > $this->htmlvspace) {
10420                                 $this->Ln(($vsize - $this->htmlvspace), $cell);
10421                                 $this->htmlvspace = $vsize;
10422             }
10423         }
10424                 
10425         } // END OF TCPDF CLASS
10426 }
10427 //============================================================+
10428 // END OF FILE
10429 //============================================================+