1<?php
2//============================================================+
3// File name   : tcpdf.php
4// Version     : 6.3.2
5// Begin       : 2002-08-03
6// Last Update : 2019-09-20
7// Author      : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
8// License     : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
9// -------------------------------------------------------------------
10// Copyright (C) 2002-2019 Nicola Asuni - Tecnick.com LTD
11//
12// This file is part of TCPDF software library.
13//
14// TCPDF is free software: you can redistribute it and/or modify it
15// under the terms of the GNU Lesser General Public License as
16// published by the Free Software Foundation, either version 3 of the
17// License, or (at your option) any later version.
18//
19// TCPDF is distributed in the hope that it will be useful, but
20// WITHOUT ANY WARRANTY; without even the implied warranty of
21// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
22// See the GNU Lesser General Public License for more details.
23//
24// You should have received a copy of the License
25// along with TCPDF. If not, see
26// <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
27//
28// See LICENSE.TXT file for more information.
29// -------------------------------------------------------------------
30//
31// Description :
32//   This is a PHP class for generating PDF documents without requiring external extensions.
33//
34// NOTE:
35//   This class was originally derived in 2002 from the Public
36//   Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
37//   but now is almost entirely rewritten and contains thousands of
38//   new lines of code and hundreds new features.
39//
40// Main features:
41//  * no external libraries are required for the basic functions;
42//  * all standard page formats, custom page formats, custom margins and units of measure;
43//  * UTF-8 Unicode and Right-To-Left languages;
44//  * TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;
45//  * font subsetting;
46//  * methods to publish some XHTML + CSS code, Javascript and Forms;
47//  * images, graphic (geometric figures) and transformation methods;
48//  * supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImageMagick (http://www.imagemagick.org/www/formats.html)
49//  * 1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;
50//  * JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;
51//  * automatic page header and footer management;
52//  * document encryption up to 256 bit and digital signature certifications;
53//  * transactions to UNDO commands;
54//  * PDF annotations, including links, text and file attachments;
55//  * text rendering modes (fill, stroke and clipping);
56//  * multiple columns mode;
57//  * no-write page regions;
58//  * bookmarks, named destinations and table of content;
59//  * text hyphenation;
60//  * text stretching and spacing (tracking);
61//  * automatic page break, line break and text alignments including justification;
62//  * automatic page numbering and page groups;
63//  * move and delete pages;
64//  * page compression (requires php-zlib extension);
65//  * XOBject Templates;
66//  * Layers and object visibility.
67//	* PDF/A-1b support
68//============================================================+
69
70/**
71 * @file
72 * This is a PHP class for generating PDF documents without requiring external extensions.<br>
73 * 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>
74 * <h3>TCPDF main features are:</h3>
75 * <ul>
76 * <li>no external libraries are required for the basic functions;</li>
77 * <li>all standard page formats, custom page formats, custom margins and units of measure;</li>
78 * <li>UTF-8 Unicode and Right-To-Left languages;</li>
79 * <li>TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;</li>
80 * <li>font subsetting;</li>
81 * <li>methods to publish some XHTML + CSS code, Javascript and Forms;</li>
82 * <li>images, graphic (geometric figures) and transformation methods;
83 * <li>supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImageMagick (http://www.imagemagick.org/www/formats.html)</li>
84 * <li>1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;</li>
85 * <li>JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
86 * <li>automatic page header and footer management;</li>
87 * <li>document encryption up to 256 bit and digital signature certifications;</li>
88 * <li>transactions to UNDO commands;</li>
89 * <li>PDF annotations, including links, text and file attachments;</li>
90 * <li>text rendering modes (fill, stroke and clipping);</li>
91 * <li>multiple columns mode;</li>
92 * <li>no-write page regions;</li>
93 * <li>bookmarks, named destinations and table of content;</li>
94 * <li>text hyphenation;</li>
95 * <li>text stretching and spacing (tracking);</li>
96 * <li>automatic page break, line break and text alignments including justification;</li>
97 * <li>automatic page numbering and page groups;</li>
98 * <li>move and delete pages;</li>
99 * <li>page compression (requires php-zlib extension);</li>
100 * <li>XOBject Templates;</li>
101 * <li>Layers and object visibility;</li>
102 * <li>PDF/A-1b support.</li>
103 * </ul>
104 * Tools to encode your unicode fonts are on fonts/utils directory.</p>
105 * @package com.tecnick.tcpdf
106 * @author Nicola Asuni
107 * @version 6.3.2
108 */
109
110// TCPDF configuration
111require_once(dirname(__FILE__).'/tcpdf_autoconfig.php');
112// TCPDF static font methods and data
113require_once(dirname(__FILE__).'/include/tcpdf_font_data.php');
114// TCPDF static font methods and data
115require_once(dirname(__FILE__).'/include/tcpdf_fonts.php');
116// TCPDF static color methods and data
117require_once(dirname(__FILE__).'/include/tcpdf_colors.php');
118// TCPDF static image methods and data
119require_once(dirname(__FILE__).'/include/tcpdf_images.php');
120// TCPDF static methods and data
121require_once(dirname(__FILE__).'/include/tcpdf_static.php');
122
123// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
124
125/**
126 * @class TCPDF
127 * PHP class for generating PDF documents without requiring external extensions.
128 * 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>
129 * @package com.tecnick.tcpdf
130 * @brief PHP class for generating PDF documents without requiring external extensions.
131 * @version 6.3.2
132 * @author Nicola Asuni - info@tecnick.com
133 * @IgnoreAnnotation("protected")
134 * @IgnoreAnnotation("public")
135 * @IgnoreAnnotation("pre")
136 */
137class TCPDF {
138
139	// Protected properties
140
141	/**
142	 * Current page number.
143	 * @protected
144	 */
145	protected $page;
146
147	/**
148	 * Current object number.
149	 * @protected
150	 */
151	protected $n;
152
153	/**
154	 * Array of object offsets.
155	 * @protected
156	 */
157	protected $offsets = array();
158
159	/**
160	 * Array of object IDs for each page.
161	 * @protected
162	 */
163	protected $pageobjects = array();
164
165	/**
166	 * Buffer holding in-memory PDF.
167	 * @protected
168	 */
169	protected $buffer;
170
171	/**
172	 * Array containing pages.
173	 * @protected
174	 */
175	protected $pages = array();
176
177	/**
178	 * Current document state.
179	 * @protected
180	 */
181	protected $state;
182
183	/**
184	 * Compression flag.
185	 * @protected
186	 */
187	protected $compress;
188
189	/**
190	 * Current page orientation (P = Portrait, L = Landscape).
191	 * @protected
192	 */
193	protected $CurOrientation;
194
195	/**
196	 * Page dimensions.
197	 * @protected
198	 */
199	protected $pagedim = array();
200
201	/**
202	 * Scale factor (number of points in user unit).
203	 * @protected
204	 */
205	protected $k;
206
207	/**
208	 * Width of page format in points.
209	 * @protected
210	 */
211	protected $fwPt;
212
213	/**
214	 * Height of page format in points.
215	 * @protected
216	 */
217	protected $fhPt;
218
219	/**
220	 * Current width of page in points.
221	 * @protected
222	 */
223	protected $wPt;
224
225	/**
226	 * Current height of page in points.
227	 * @protected
228	 */
229	protected $hPt;
230
231	/**
232	 * Current width of page in user unit.
233	 * @protected
234	 */
235	protected $w;
236
237	/**
238	 * Current height of page in user unit.
239	 * @protected
240	 */
241	protected $h;
242
243	/**
244	 * Left margin.
245	 * @protected
246	 */
247	protected $lMargin;
248
249	/**
250	 * Right margin.
251	 * @protected
252	 */
253	protected $rMargin;
254
255	/**
256	 * Cell left margin (used by regions).
257	 * @protected
258	 */
259	protected $clMargin;
260
261	/**
262	 * Cell right margin (used by regions).
263	 * @protected
264	 */
265	protected $crMargin;
266
267	/**
268	 * Top margin.
269	 * @protected
270	 */
271	protected $tMargin;
272
273	/**
274	 * Page break margin.
275	 * @protected
276	 */
277	protected $bMargin;
278
279	/**
280	 * Array of cell internal paddings ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
281	 * @since 5.9.000 (2010-10-03)
282	 * @protected
283	 */
284	protected $cell_padding = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
285
286	/**
287	 * Array of cell margins ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
288	 * @since 5.9.000 (2010-10-04)
289	 * @protected
290	 */
291	protected $cell_margin = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
292
293	/**
294	 * Current horizontal position in user unit for cell positioning.
295	 * @protected
296	 */
297	protected $x;
298
299	/**
300	 * Current vertical position in user unit for cell positioning.
301	 * @protected
302	 */
303	protected $y;
304
305	/**
306	 * Height of last cell printed.
307	 * @protected
308	 */
309	protected $lasth;
310
311	/**
312	 * Line width in user unit.
313	 * @protected
314	 */
315	protected $LineWidth;
316
317	/**
318	 * Array of standard font names.
319	 * @protected
320	 */
321	protected $CoreFonts;
322
323	/**
324	 * Array of used fonts.
325	 * @protected
326	 */
327	protected $fonts = array();
328
329	/**
330	 * Array of font files.
331	 * @protected
332	 */
333	protected $FontFiles = array();
334
335	/**
336	 * Array of encoding differences.
337	 * @protected
338	 */
339	protected $diffs = array();
340
341	/**
342	 * Array of used images.
343	 * @protected
344	 */
345	protected $images = array();
346
347	/**
348	 * Depth of the svg tag, to keep track if the svg tag is a subtag or the root tag.
349	 * @protected
350	 */
351	protected $svg_tag_depth = 0;
352
353	/**
354	 * Array of Annotations in pages.
355	 * @protected
356	 */
357	protected $PageAnnots = array();
358
359	/**
360	 * Array of internal links.
361	 * @protected
362	 */
363	protected $links = array();
364
365	/**
366	 * Current font family.
367	 * @protected
368	 */
369	protected $FontFamily;
370
371	/**
372	 * Current font style.
373	 * @protected
374	 */
375	protected $FontStyle;
376
377	/**
378	 * Current font ascent (distance between font top and baseline).
379	 * @protected
380	 * @since 2.8.000 (2007-03-29)
381	 */
382	protected $FontAscent;
383
384	/**
385	 * Current font descent (distance between font bottom and baseline).
386	 * @protected
387	 * @since 2.8.000 (2007-03-29)
388	 */
389	protected $FontDescent;
390
391	/**
392	 * Underlining flag.
393	 * @protected
394	 */
395	protected $underline;
396
397	/**
398	 * Overlining flag.
399	 * @protected
400	 */
401	protected $overline;
402
403	/**
404	 * Current font info.
405	 * @protected
406	 */
407	protected $CurrentFont;
408
409	/**
410	 * Current font size in points.
411	 * @protected
412	 */
413	protected $FontSizePt;
414
415	/**
416	 * Current font size in user unit.
417	 * @protected
418	 */
419	protected $FontSize;
420
421	/**
422	 * Commands for drawing color.
423	 * @protected
424	 */
425	protected $DrawColor;
426
427	/**
428	 * Commands for filling color.
429	 * @protected
430	 */
431	protected $FillColor;
432
433	/**
434	 * Commands for text color.
435	 * @protected
436	 */
437	protected $TextColor;
438
439	/**
440	 * Indicates whether fill and text colors are different.
441	 * @protected
442	 */
443	protected $ColorFlag;
444
445	/**
446	 * Automatic page breaking.
447	 * @protected
448	 */
449	protected $AutoPageBreak;
450
451	/**
452	 * Threshold used to trigger page breaks.
453	 * @protected
454	 */
455	protected $PageBreakTrigger;
456
457	/**
458	 * Flag set when processing page header.
459	 * @protected
460	 */
461	protected $InHeader = false;
462
463	/**
464	 * Flag set when processing page footer.
465	 * @protected
466	 */
467	protected $InFooter = false;
468
469	/**
470	 * Zoom display mode.
471	 * @protected
472	 */
473	protected $ZoomMode;
474
475	/**
476	 * Layout display mode.
477	 * @protected
478	 */
479	protected $LayoutMode;
480
481	/**
482	 * If true set the document information dictionary in Unicode.
483	 * @protected
484	 */
485	protected $docinfounicode = true;
486
487	/**
488	 * Document title.
489	 * @protected
490	 */
491	protected $title = '';
492
493	/**
494	 * Document subject.
495	 * @protected
496	 */
497	protected $subject = '';
498
499	/**
500	 * Document author.
501	 * @protected
502	 */
503	protected $author = '';
504
505	/**
506	 * Document keywords.
507	 * @protected
508	 */
509	protected $keywords = '';
510
511	/**
512	 * Document creator.
513	 * @protected
514	 */
515	protected $creator = '';
516
517	/**
518	 * Starting page number.
519	 * @protected
520	 */
521	protected $starting_page_number = 1;
522
523	/**
524	 * The right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image.
525	 * @since 2002-07-31
526	 * @author Nicola Asuni
527	 * @protected
528	 */
529	protected $img_rb_x;
530
531	/**
532	 * The right-bottom corner Y coordinate of last inserted image.
533	 * @since 2002-07-31
534	 * @author Nicola Asuni
535	 * @protected
536	 */
537	protected $img_rb_y;
538
539	/**
540	 * Adjusting factor to convert pixels to user units.
541	 * @since 2004-06-14
542	 * @author Nicola Asuni
543	 * @protected
544	 */
545	protected $imgscale = 1;
546
547	/**
548	 * Boolean flag set to true when the input text is unicode (require unicode fonts).
549	 * @since 2005-01-02
550	 * @author Nicola Asuni
551	 * @protected
552	 */
553	protected $isunicode = false;
554
555	/**
556	 * PDF version.
557	 * @since 1.5.3
558	 * @protected
559	 */
560	protected $PDFVersion = '1.7';
561
562	/**
563	 * ID of the stored default header template (-1 = not set).
564	 * @protected
565	 */
566	protected $header_xobjid = false;
567
568	/**
569	 * If true reset the Header Xobject template at each page
570	 * @protected
571	 */
572	protected $header_xobj_autoreset = false;
573
574	/**
575	 * Minimum distance between header and top page margin.
576	 * @protected
577	 */
578	protected $header_margin;
579
580	/**
581	 * Minimum distance between footer and bottom page margin.
582	 * @protected
583	 */
584	protected $footer_margin;
585
586	/**
587	 * Original left margin value.
588	 * @protected
589	 * @since 1.53.0.TC013
590	 */
591	protected $original_lMargin;
592
593	/**
594	 * Original right margin value.
595	 * @protected
596	 * @since 1.53.0.TC013
597	 */
598	protected $original_rMargin;
599
600	/**
601	 * Default font used on page header.
602	 * @protected
603	 */
604	protected $header_font;
605
606	/**
607	 * Default font used on page footer.
608	 * @protected
609	 */
610	protected $footer_font;
611
612	/**
613	 * Language templates.
614	 * @protected
615	 */
616	protected $l;
617
618	/**
619	 * Barcode to print on page footer (only if set).
620	 * @protected
621	 */
622	protected $barcode = false;
623
624	/**
625	 * Boolean flag to print/hide page header.
626	 * @protected
627	 */
628	protected $print_header = true;
629
630	/**
631	 * Boolean flag to print/hide page footer.
632	 * @protected
633	 */
634	protected $print_footer = true;
635
636	/**
637	 * Header image logo.
638	 * @protected
639	 */
640	protected $header_logo = '';
641
642	/**
643	 * Width of header image logo in user units.
644	 * @protected
645	 */
646	protected $header_logo_width = 30;
647
648	/**
649	 * Title to be printed on default page header.
650	 * @protected
651	 */
652	protected $header_title = '';
653
654	/**
655	 * String to pring on page header after title.
656	 * @protected
657	 */
658	protected $header_string = '';
659
660	/**
661	 * Color for header text (RGB array).
662	 * @since 5.9.174 (2012-07-25)
663	 * @protected
664	 */
665	protected $header_text_color = array(0,0,0);
666
667	/**
668	 * Color for header line (RGB array).
669	 * @since 5.9.174 (2012-07-25)
670	 * @protected
671	 */
672	protected $header_line_color = array(0,0,0);
673
674	/**
675	 * Color for footer text (RGB array).
676	 * @since 5.9.174 (2012-07-25)
677	 * @protected
678	 */
679	protected $footer_text_color = array(0,0,0);
680
681	/**
682	 * Color for footer line (RGB array).
683	 * @since 5.9.174 (2012-07-25)
684	 * @protected
685	 */
686	protected $footer_line_color = array(0,0,0);
687
688	/**
689	 * Text shadow data array.
690	 * @since 5.9.174 (2012-07-25)
691	 * @protected
692	 */
693	protected $txtshadow = array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal');
694
695	/**
696	 * Default number of columns for html table.
697	 * @protected
698	 */
699	protected $default_table_columns = 4;
700
701	// variables for html parser
702
703	/**
704	 * HTML PARSER: array to store current link and rendering styles.
705	 * @protected
706	 */
707	protected $HREF = array();
708
709	/**
710	 * List of available fonts on filesystem.
711	 * @protected
712	 */
713	protected $fontlist = array();
714
715	/**
716	 * Current foreground color.
717	 * @protected
718	 */
719	protected $fgcolor;
720
721	/**
722	 * HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
723	 * @protected
724	 */
725	protected $listordered = array();
726
727	/**
728	 * HTML PARSER: array count list items on nested lists.
729	 * @protected
730	 */
731	protected $listcount = array();
732
733	/**
734	 * HTML PARSER: current list nesting level.
735	 * @protected
736	 */
737	protected $listnum = 0;
738
739	/**
740	 * HTML PARSER: indent amount for lists.
741	 * @protected
742	 */
743	protected $listindent = 0;
744
745	/**
746	 * HTML PARSER: current list indententation level.
747	 * @protected
748	 */
749	protected $listindentlevel = 0;
750
751	/**
752	 * Current background color.
753	 * @protected
754	 */
755	protected $bgcolor;
756
757	/**
758	 * Temporary font size in points.
759	 * @protected
760	 */
761	protected $tempfontsize = 10;
762
763	/**
764	 * Spacer string for LI tags.
765	 * @protected
766	 */
767	protected $lispacer = '';
768
769	/**
770	 * Default encoding.
771	 * @protected
772	 * @since 1.53.0.TC010
773	 */
774	protected $encoding = 'UTF-8';
775
776	/**
777	 * PHP internal encoding.
778	 * @protected
779	 * @since 1.53.0.TC016
780	 */
781	protected $internal_encoding;
782
783	/**
784	 * Boolean flag to indicate if the document language is Right-To-Left.
785	 * @protected
786	 * @since 2.0.000
787	 */
788	protected $rtl = false;
789
790	/**
791	 * Boolean flag used to force RTL or LTR string direction.
792	 * @protected
793	 * @since 2.0.000
794	 */
795	protected $tmprtl = false;
796
797	// --- Variables used for document encryption:
798
799	/**
800	 * IBoolean flag indicating whether document is protected.
801	 * @protected
802	 * @since 2.0.000 (2008-01-02)
803	 */
804	protected $encrypted;
805
806	/**
807	 * Array containing encryption settings.
808	 * @protected
809	 * @since 5.0.005 (2010-05-11)
810	 */
811	protected $encryptdata = array();
812
813	/**
814	 * Last RC4 key encrypted (cached for optimisation).
815	 * @protected
816	 * @since 2.0.000 (2008-01-02)
817	 */
818	protected $last_enc_key;
819
820	/**
821	 * Last RC4 computed key.
822	 * @protected
823	 * @since 2.0.000 (2008-01-02)
824	 */
825	protected $last_enc_key_c;
826
827	/**
828	 * File ID (used on document trailer).
829	 * @protected
830	 * @since 5.0.005 (2010-05-12)
831	 */
832	protected $file_id;
833
834	// --- bookmark ---
835
836	/**
837	 * Outlines for bookmark.
838	 * @protected
839	 * @since 2.1.002 (2008-02-12)
840	 */
841	protected $outlines = array();
842
843	/**
844	 * Outline root for bookmark.
845	 * @protected
846	 * @since 2.1.002 (2008-02-12)
847	 */
848	protected $OutlineRoot;
849
850	// --- javascript and form ---
851
852	/**
853	 * Javascript code.
854	 * @protected
855	 * @since 2.1.002 (2008-02-12)
856	 */
857	protected $javascript = '';
858
859	/**
860	 * Javascript counter.
861	 * @protected
862	 * @since 2.1.002 (2008-02-12)
863	 */
864	protected $n_js;
865
866	/**
867	 * line through state
868	 * @protected
869	 * @since 2.8.000 (2008-03-19)
870	 */
871	protected $linethrough;
872
873	/**
874	 * Array with additional document-wide usage rights for the document.
875	 * @protected
876	 * @since 5.8.014 (2010-08-23)
877	 */
878	protected $ur = array();
879
880	/**
881	 * DPI (Dot Per Inch) Document Resolution (do not change).
882	 * @protected
883	 * @since 3.0.000 (2008-03-27)
884	 */
885	protected $dpi = 72;
886
887	/**
888	 * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
889	 * @protected
890	 * @since 3.0.000 (2008-03-27)
891	 */
892	protected $newpagegroup = array();
893
894	/**
895	 * Array that contains the number of pages in each page group.
896	 * @protected
897	 * @since 3.0.000 (2008-03-27)
898	 */
899	protected $pagegroups = array();
900
901	/**
902	 * Current page group number.
903	 * @protected
904	 * @since 3.0.000 (2008-03-27)
905	 */
906	protected $currpagegroup = 0;
907
908	/**
909	 * Array of transparency objects and parameters.
910	 * @protected
911	 * @since 3.0.000 (2008-03-27)
912	 */
913	protected $extgstates;
914
915	/**
916	 * Set the default JPEG compression quality (1-100).
917	 * @protected
918	 * @since 3.0.000 (2008-03-27)
919	 */
920	protected $jpeg_quality;
921
922	/**
923	 * Default cell height ratio.
924	 * @protected
925	 * @since 3.0.014 (2008-05-23)
926	 */
927	protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
928
929	/**
930	 * PDF viewer preferences.
931	 * @protected
932	 * @since 3.1.000 (2008-06-09)
933	 */
934	protected $viewer_preferences;
935
936	/**
937	 * A name object specifying how the document should be displayed when opened.
938	 * @protected
939	 * @since 3.1.000 (2008-06-09)
940	 */
941	protected $PageMode;
942
943	/**
944	 * Array for storing gradient information.
945	 * @protected
946	 * @since 3.1.000 (2008-06-09)
947	 */
948	protected $gradients = array();
949
950	/**
951	 * Array used to store positions inside the pages buffer (keys are the page numbers).
952	 * @protected
953	 * @since 3.2.000 (2008-06-26)
954	 */
955	protected $intmrk = array();
956
957	/**
958	 * Array used to store positions inside the pages buffer (keys are the page numbers).
959	 * @protected
960	 * @since 5.7.000 (2010-08-03)
961	 */
962	protected $bordermrk = array();
963
964	/**
965	 * Array used to store page positions to track empty pages (keys are the page numbers).
966	 * @protected
967	 * @since 5.8.007 (2010-08-18)
968	 */
969	protected $emptypagemrk = array();
970
971	/**
972	 * Array used to store content positions inside the pages buffer (keys are the page numbers).
973	 * @protected
974	 * @since 4.6.021 (2009-07-20)
975	 */
976	protected $cntmrk = array();
977
978	/**
979	 * Array used to store footer positions of each page.
980	 * @protected
981	 * @since 3.2.000 (2008-07-01)
982	 */
983	protected $footerpos = array();
984
985	/**
986	 * Array used to store footer length of each page.
987	 * @protected
988	 * @since 4.0.014 (2008-07-29)
989	 */
990	protected $footerlen = array();
991
992	/**
993	 * Boolean flag to indicate if a new line is created.
994	 * @protected
995	 * @since 3.2.000 (2008-07-01)
996	 */
997	protected $newline = true;
998
999	/**
1000	 * End position of the latest inserted line.
1001	 * @protected
1002	 * @since 3.2.000 (2008-07-01)
1003	 */
1004	protected $endlinex = 0;
1005
1006	/**
1007	 * PDF string for width value of the last line.
1008	 * @protected
1009	 * @since 4.0.006 (2008-07-16)
1010	 */
1011	protected $linestyleWidth = '';
1012
1013	/**
1014	 * PDF string for CAP value of the last line.
1015	 * @protected
1016	 * @since 4.0.006 (2008-07-16)
1017	 */
1018	protected $linestyleCap = '0 J';
1019
1020	/**
1021	 * PDF string for join value of the last line.
1022	 * @protected
1023	 * @since 4.0.006 (2008-07-16)
1024	 */
1025	protected $linestyleJoin = '0 j';
1026
1027	/**
1028	 * PDF string for dash value of the last line.
1029	 * @protected
1030	 * @since 4.0.006 (2008-07-16)
1031	 */
1032	protected $linestyleDash = '[] 0 d';
1033
1034	/**
1035	 * Boolean flag to indicate if marked-content sequence is open.
1036	 * @protected
1037	 * @since 4.0.013 (2008-07-28)
1038	 */
1039	protected $openMarkedContent = false;
1040
1041	/**
1042	 * Count the latest inserted vertical spaces on HTML.
1043	 * @protected
1044	 * @since 4.0.021 (2008-08-24)
1045	 */
1046	protected $htmlvspace = 0;
1047
1048	/**
1049	 * Array of Spot colors.
1050	 * @protected
1051	 * @since 4.0.024 (2008-09-12)
1052	 */
1053	protected $spot_colors = array();
1054
1055	/**
1056	 * Symbol used for HTML unordered list items.
1057	 * @protected
1058	 * @since 4.0.028 (2008-09-26)
1059	 */
1060	protected $lisymbol = '';
1061
1062	/**
1063	 * String used to mark the beginning and end of EPS image blocks.
1064	 * @protected
1065	 * @since 4.1.000 (2008-10-18)
1066	 */
1067	protected $epsmarker = 'x#!#EPS#!#x';
1068
1069	/**
1070	 * Array of transformation matrix.
1071	 * @protected
1072	 * @since 4.2.000 (2008-10-29)
1073	 */
1074	protected $transfmatrix = array();
1075
1076	/**
1077	 * Current key for transformation matrix.
1078	 * @protected
1079	 * @since 4.8.005 (2009-09-17)
1080	 */
1081	protected $transfmatrix_key = 0;
1082
1083	/**
1084	 * Booklet mode for double-sided pages.
1085	 * @protected
1086	 * @since 4.2.000 (2008-10-29)
1087	 */
1088	protected $booklet = false;
1089
1090	/**
1091	 * Epsilon value used for float calculations.
1092	 * @protected
1093	 * @since 4.2.000 (2008-10-29)
1094	 */
1095	protected $feps = 0.005;
1096
1097	/**
1098	 * Array used for custom vertical spaces for HTML tags.
1099	 * @protected
1100	 * @since 4.2.001 (2008-10-30)
1101	 */
1102	protected $tagvspaces = array();
1103
1104	/**
1105	 * HTML PARSER: custom indent amount for lists. Negative value means disabled.
1106	 * @protected
1107	 * @since 4.2.007 (2008-11-12)
1108	 */
1109	protected $customlistindent = -1;
1110
1111	/**
1112	 * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
1113	 * @protected
1114	 * @since 4.2.010 (2008-11-14)
1115	 */
1116	protected $opencell = true;
1117
1118	/**
1119	 * Array of files to embedd.
1120	 * @protected
1121	 * @since 4.4.000 (2008-12-07)
1122	 */
1123	protected $embeddedfiles = array();
1124
1125	/**
1126	 * Boolean flag to indicate if we are inside a PRE tag.
1127	 * @protected
1128	 * @since 4.4.001 (2008-12-08)
1129	 */
1130	protected $premode = false;
1131
1132	/**
1133	 * Array used to store positions of graphics transformation blocks inside the page buffer.
1134	 * keys are the page numbers
1135	 * @protected
1136	 * @since 4.4.002 (2008-12-09)
1137	 */
1138	protected $transfmrk = array();
1139
1140	/**
1141	 * Default color for html links.
1142	 * @protected
1143	 * @since 4.4.003 (2008-12-09)
1144	 */
1145	protected $htmlLinkColorArray = array(0, 0, 255);
1146
1147	/**
1148	 * Default font style to add to html links.
1149	 * @protected
1150	 * @since 4.4.003 (2008-12-09)
1151	 */
1152	protected $htmlLinkFontStyle = 'U';
1153
1154	/**
1155	 * Counts the number of pages.
1156	 * @protected
1157	 * @since 4.5.000 (2008-12-31)
1158	 */
1159	protected $numpages = 0;
1160
1161	/**
1162	 * Array containing page lengths in bytes.
1163	 * @protected
1164	 * @since 4.5.000 (2008-12-31)
1165	 */
1166	protected $pagelen = array();
1167
1168	/**
1169	 * Counts the number of pages.
1170	 * @protected
1171	 * @since 4.5.000 (2008-12-31)
1172	 */
1173	protected $numimages = 0;
1174
1175	/**
1176	 * Store the image keys.
1177	 * @protected
1178	 * @since 4.5.000 (2008-12-31)
1179	 */
1180	protected $imagekeys = array();
1181
1182	/**
1183	 * Length of the buffer in bytes.
1184	 * @protected
1185	 * @since 4.5.000 (2008-12-31)
1186	 */
1187	protected $bufferlen = 0;
1188
1189	/**
1190	 * Counts the number of fonts.
1191	 * @protected
1192	 * @since 4.5.000 (2009-01-02)
1193	 */
1194	protected $numfonts = 0;
1195
1196	/**
1197	 * Store the font keys.
1198	 * @protected
1199	 * @since 4.5.000 (2009-01-02)
1200	 */
1201	protected $fontkeys = array();
1202
1203	/**
1204	 * Store the font object IDs.
1205	 * @protected
1206	 * @since 4.8.001 (2009-09-09)
1207	 */
1208	protected $font_obj_ids = array();
1209
1210	/**
1211	 * Store the fage status (true when opened, false when closed).
1212	 * @protected
1213	 * @since 4.5.000 (2009-01-02)
1214	 */
1215	protected $pageopen = array();
1216
1217	/**
1218	 * Default monospace font.
1219	 * @protected
1220	 * @since 4.5.025 (2009-03-10)
1221	 */
1222	protected $default_monospaced_font = 'freemono';
1223
1224	/**
1225	 * Cloned copy of the current class object.
1226	 * @protected
1227	 * @since 4.5.029 (2009-03-19)
1228	 */
1229	protected $objcopy;
1230
1231	/**
1232	 * Array used to store the lengths of cache files.
1233	 * @protected
1234	 * @since 4.5.029 (2009-03-19)
1235	 */
1236	protected $cache_file_length = array();
1237
1238	/**
1239	 * Table header content to be repeated on each new page.
1240	 * @protected
1241	 * @since 4.5.030 (2009-03-20)
1242	 */
1243	protected $thead = '';
1244
1245	/**
1246	 * Margins used for table header.
1247	 * @protected
1248	 * @since 4.5.030 (2009-03-20)
1249	 */
1250	protected $theadMargins = array();
1251
1252	/**
1253	 * Boolean flag to enable document digital signature.
1254	 * @protected
1255	 * @since 4.6.005 (2009-04-24)
1256	 */
1257	protected $sign = false;
1258
1259	/**
1260	 * Digital signature data.
1261	 * @protected
1262	 * @since 4.6.005 (2009-04-24)
1263	 */
1264	protected $signature_data = array();
1265
1266	/**
1267	 * Digital signature max length.
1268	 * @protected
1269	 * @since 4.6.005 (2009-04-24)
1270	 */
1271	protected $signature_max_length = 11742;
1272
1273	/**
1274	 * Data for digital signature appearance.
1275	 * @protected
1276	 * @since 5.3.011 (2010-06-16)
1277	 */
1278	protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
1279
1280	/**
1281	 * Array of empty digital signature appearances.
1282	 * @protected
1283	 * @since 5.9.101 (2011-07-06)
1284	 */
1285	protected $empty_signature_appearance = array();
1286
1287	/**
1288	 * Boolean flag to enable document timestamping with TSA.
1289	 * @protected
1290	 * @since 6.0.085 (2014-06-19)
1291	 */
1292	protected $tsa_timestamp = false;
1293
1294	/**
1295	 * Timestamping data.
1296	 * @protected
1297	 * @since 6.0.085 (2014-06-19)
1298	 */
1299	protected $tsa_data = array();
1300
1301	/**
1302	 * Regular expression used to find blank characters (required for word-wrapping).
1303	 * @protected
1304	 * @since 4.6.006 (2009-04-28)
1305	 */
1306	protected $re_spaces = '/[^\S\xa0]/';
1307
1308	/**
1309	 * Array of $re_spaces parts.
1310	 * @protected
1311	 * @since 5.5.011 (2010-07-09)
1312	 */
1313	protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
1314
1315	/**
1316	 * Digital signature object ID.
1317	 * @protected
1318	 * @since 4.6.022 (2009-06-23)
1319	 */
1320	protected $sig_obj_id = 0;
1321
1322	/**
1323	 * ID of page objects.
1324	 * @protected
1325	 * @since 4.7.000 (2009-08-29)
1326	 */
1327	protected $page_obj_id = array();
1328
1329	/**
1330	 * List of form annotations IDs.
1331	 * @protected
1332	 * @since 4.8.000 (2009-09-07)
1333	 */
1334	protected $form_obj_id = array();
1335
1336	/**
1337	 * Deafult Javascript field properties. Possible values are described on official Javascript for Acrobat API reference. Annotation options can be directly specified using the 'aopt' entry.
1338	 * @protected
1339	 * @since 4.8.000 (2009-09-07)
1340	 */
1341	protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
1342
1343	/**
1344	 * Javascript objects array.
1345	 * @protected
1346	 * @since 4.8.000 (2009-09-07)
1347	 */
1348	protected $js_objects = array();
1349
1350	/**
1351	 * Current form action (used during XHTML rendering).
1352	 * @protected
1353	 * @since 4.8.000 (2009-09-07)
1354	 */
1355	protected $form_action = '';
1356
1357	/**
1358	 * Current form encryption type (used during XHTML rendering).
1359	 * @protected
1360	 * @since 4.8.000 (2009-09-07)
1361	 */
1362	protected $form_enctype = 'application/x-www-form-urlencoded';
1363
1364	/**
1365	 * Current method to submit forms.
1366	 * @protected
1367	 * @since 4.8.000 (2009-09-07)
1368	 */
1369	protected $form_mode = 'post';
1370
1371	/**
1372	 * List of fonts used on form fields (fontname => fontkey).
1373	 * @protected
1374	 * @since 4.8.001 (2009-09-09)
1375	 */
1376	protected $annotation_fonts = array();
1377
1378	/**
1379	 * List of radio buttons parent objects.
1380	 * @protected
1381	 * @since 4.8.001 (2009-09-09)
1382	 */
1383	protected $radiobutton_groups = array();
1384
1385	/**
1386	 * List of radio group objects IDs.
1387	 * @protected
1388	 * @since 4.8.001 (2009-09-09)
1389	 */
1390	protected $radio_groups = array();
1391
1392	/**
1393	 * Text indentation value (used for text-indent CSS attribute).
1394	 * @protected
1395	 * @since 4.8.006 (2009-09-23)
1396	 */
1397	protected $textindent = 0;
1398
1399	/**
1400	 * Store page number when startTransaction() is called.
1401	 * @protected
1402	 * @since 4.8.006 (2009-09-23)
1403	 */
1404	protected $start_transaction_page = 0;
1405
1406	/**
1407	 * Store Y position when startTransaction() is called.
1408	 * @protected
1409	 * @since 4.9.001 (2010-03-28)
1410	 */
1411	protected $start_transaction_y = 0;
1412
1413	/**
1414	 * True when we are printing the thead section on a new page.
1415	 * @protected
1416	 * @since 4.8.027 (2010-01-25)
1417	 */
1418	protected $inthead = false;
1419
1420	/**
1421	 * Array of column measures (width, space, starting Y position).
1422	 * @protected
1423	 * @since 4.9.001 (2010-03-28)
1424	 */
1425	protected $columns = array();
1426
1427	/**
1428	 * Number of colums.
1429	 * @protected
1430	 * @since 4.9.001 (2010-03-28)
1431	 */
1432	protected $num_columns = 1;
1433
1434	/**
1435	 * Current column number.
1436	 * @protected
1437	 * @since 4.9.001 (2010-03-28)
1438	 */
1439	protected $current_column = 0;
1440
1441	/**
1442	 * Starting page for columns.
1443	 * @protected
1444	 * @since 4.9.001 (2010-03-28)
1445	 */
1446	protected $column_start_page = 0;
1447
1448	/**
1449	 * Maximum page and column selected.
1450	 * @protected
1451	 * @since 5.8.000 (2010-08-11)
1452	 */
1453	protected $maxselcol = array('page' => 0, 'column' => 0);
1454
1455	/**
1456	 * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
1457	 * @protected
1458	 * @since 5.8.000 (2010-08-11)
1459	 */
1460	protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
1461
1462	/**
1463	 * Text rendering mode: 0 = Fill text; 1 = Stroke text; 2 = Fill, then stroke text; 3 = Neither fill nor stroke text (invisible); 4 = Fill text and add to path for clipping; 5 = Stroke text and add to path for clipping; 6 = Fill, then stroke text and add to path for clipping; 7 = Add text to path for clipping.
1464	 * @protected
1465	 * @since 4.9.008 (2010-04-03)
1466	 */
1467	protected $textrendermode = 0;
1468
1469	/**
1470	 * Text stroke width in doc units.
1471	 * @protected
1472	 * @since 4.9.008 (2010-04-03)
1473	 */
1474	protected $textstrokewidth = 0;
1475
1476	/**
1477	 * Current stroke color.
1478	 * @protected
1479	 * @since 4.9.008 (2010-04-03)
1480	 */
1481	protected $strokecolor;
1482
1483	/**
1484	 * Default unit of measure for document.
1485	 * @protected
1486	 * @since 5.0.000 (2010-04-22)
1487	 */
1488	protected $pdfunit = 'mm';
1489
1490	/**
1491	 * Boolean flag true when we are on TOC (Table Of Content) page.
1492	 * @protected
1493	 */
1494	protected $tocpage = false;
1495
1496	/**
1497	 * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
1498	 * @protected
1499	 * @since 5.0.000 (2010-04-26)
1500	 */
1501	protected $rasterize_vector_images = false;
1502
1503	/**
1504	 * Boolean flag: if true enables font subsetting by default.
1505	 * @protected
1506	 * @since 5.3.002 (2010-06-07)
1507	 */
1508	protected $font_subsetting = true;
1509
1510	/**
1511	 * Array of default graphic settings.
1512	 * @protected
1513	 * @since 5.5.008 (2010-07-02)
1514	 */
1515	protected $default_graphic_vars = array();
1516
1517	/**
1518	 * Array of XObjects.
1519	 * @protected
1520	 * @since 5.8.014 (2010-08-23)
1521	 */
1522	protected $xobjects = array();
1523
1524	/**
1525	 * Boolean value true when we are inside an XObject.
1526	 * @protected
1527	 * @since 5.8.017 (2010-08-24)
1528	 */
1529	protected $inxobj = false;
1530
1531	/**
1532	 * Current XObject ID.
1533	 * @protected
1534	 * @since 5.8.017 (2010-08-24)
1535	 */
1536	protected $xobjid = '';
1537
1538	/**
1539	 * Percentage of character stretching.
1540	 * @protected
1541	 * @since 5.9.000 (2010-09-29)
1542	 */
1543	protected $font_stretching = 100;
1544
1545	/**
1546	 * Increases or decreases the space between characters in a text by the specified amount (tracking).
1547	 * @protected
1548	 * @since 5.9.000 (2010-09-29)
1549	 */
1550	protected $font_spacing = 0;
1551
1552	/**
1553	 * Array of no-write regions.
1554	 * ('page' => page number or empy for current page, 'xt' => X top, 'yt' => Y top, 'xb' => X bottom, 'yb' => Y bottom, 'side' => page side 'L' = left or 'R' = right)
1555	 * @protected
1556	 * @since 5.9.003 (2010-10-14)
1557	 */
1558	protected $page_regions = array();
1559
1560	/**
1561	 * Boolean value true when page region check is active.
1562	 * @protected
1563	 */
1564	protected $check_page_regions = true;
1565
1566	/**
1567	 * Array of PDF layers data.
1568	 * @protected
1569	 * @since 5.9.102 (2011-07-13)
1570	 */
1571	protected $pdflayers = array();
1572
1573	/**
1574	 * A dictionary of names and corresponding destinations (Dests key on document Catalog).
1575	 * @protected
1576	 * @since 5.9.097 (2011-06-23)
1577	 */
1578	protected $dests = array();
1579
1580	/**
1581	 * Object ID for Named Destinations
1582	 * @protected
1583	 * @since 5.9.097 (2011-06-23)
1584	 */
1585	protected $n_dests;
1586
1587	/**
1588	 * Embedded Files Names
1589	 * @protected
1590	 * @since 5.9.204 (2013-01-23)
1591	 */
1592	protected $efnames = array();
1593
1594	/**
1595	 * Directory used for the last SVG image.
1596	 * @protected
1597	 * @since 5.0.000 (2010-05-05)
1598	 */
1599	protected $svgdir = '';
1600
1601	/**
1602	 *  Deafult unit of measure for SVG.
1603	 * @protected
1604	 * @since 5.0.000 (2010-05-02)
1605	 */
1606	protected $svgunit = 'px';
1607
1608	/**
1609	 * Array of SVG gradients.
1610	 * @protected
1611	 * @since 5.0.000 (2010-05-02)
1612	 */
1613	protected $svggradients = array();
1614
1615	/**
1616	 * ID of last SVG gradient.
1617	 * @protected
1618	 * @since 5.0.000 (2010-05-02)
1619	 */
1620	protected $svggradientid = 0;
1621
1622	/**
1623	 * Boolean value true when in SVG defs group.
1624	 * @protected
1625	 * @since 5.0.000 (2010-05-02)
1626	 */
1627	protected $svgdefsmode = false;
1628
1629	/**
1630	 * Array of SVG defs.
1631	 * @protected
1632	 * @since 5.0.000 (2010-05-02)
1633	 */
1634	protected $svgdefs = array();
1635
1636	/**
1637	 * Boolean value true when in SVG clipPath tag.
1638	 * @protected
1639	 * @since 5.0.000 (2010-04-26)
1640	 */
1641	protected $svgclipmode = false;
1642
1643	/**
1644	 * Array of SVG clipPath commands.
1645	 * @protected
1646	 * @since 5.0.000 (2010-05-02)
1647	 */
1648	protected $svgclippaths = array();
1649
1650	/**
1651	 * Array of SVG clipPath tranformation matrix.
1652	 * @protected
1653	 * @since 5.8.022 (2010-08-31)
1654	 */
1655	protected $svgcliptm = array();
1656
1657	/**
1658	 * ID of last SVG clipPath.
1659	 * @protected
1660	 * @since 5.0.000 (2010-05-02)
1661	 */
1662	protected $svgclipid = 0;
1663
1664	/**
1665	 * SVG text.
1666	 * @protected
1667	 * @since 5.0.000 (2010-05-02)
1668	 */
1669	protected $svgtext = '';
1670
1671	/**
1672	 * SVG text properties.
1673	 * @protected
1674	 * @since 5.8.013 (2010-08-23)
1675	 */
1676	protected $svgtextmode = array();
1677
1678	/**
1679	 * Array of SVG properties.
1680	 * @protected
1681	 * @since 5.0.000 (2010-05-02)
1682	 */
1683	protected $svgstyles = array(array(
1684		'alignment-baseline' => 'auto',
1685		'baseline-shift' => 'baseline',
1686		'clip' => 'auto',
1687		'clip-path' => 'none',
1688		'clip-rule' => 'nonzero',
1689		'color' => 'black',
1690		'color-interpolation' => 'sRGB',
1691		'color-interpolation-filters' => 'linearRGB',
1692		'color-profile' => 'auto',
1693		'color-rendering' => 'auto',
1694		'cursor' => 'auto',
1695		'direction' => 'ltr',
1696		'display' => 'inline',
1697		'dominant-baseline' => 'auto',
1698		'enable-background' => 'accumulate',
1699		'fill' => 'black',
1700		'fill-opacity' => 1,
1701		'fill-rule' => 'nonzero',
1702		'filter' => 'none',
1703		'flood-color' => 'black',
1704		'flood-opacity' => 1,
1705		'font' => '',
1706		'font-family' => 'helvetica',
1707		'font-size' => 'medium',
1708		'font-size-adjust' => 'none',
1709		'font-stretch' => 'normal',
1710		'font-style' => 'normal',
1711		'font-variant' => 'normal',
1712		'font-weight' => 'normal',
1713		'glyph-orientation-horizontal' => '0deg',
1714		'glyph-orientation-vertical' => 'auto',
1715		'image-rendering' => 'auto',
1716		'kerning' => 'auto',
1717		'letter-spacing' => 'normal',
1718		'lighting-color' => 'white',
1719		'marker' => '',
1720		'marker-end' => 'none',
1721		'marker-mid' => 'none',
1722		'marker-start' => 'none',
1723		'mask' => 'none',
1724		'opacity' => 1,
1725		'overflow' => 'auto',
1726		'pointer-events' => 'visiblePainted',
1727		'shape-rendering' => 'auto',
1728		'stop-color' => 'black',
1729		'stop-opacity' => 1,
1730		'stroke' => 'none',
1731		'stroke-dasharray' => 'none',
1732		'stroke-dashoffset' => 0,
1733		'stroke-linecap' => 'butt',
1734		'stroke-linejoin' => 'miter',
1735		'stroke-miterlimit' => 4,
1736		'stroke-opacity' => 1,
1737		'stroke-width' => 1,
1738		'text-anchor' => 'start',
1739		'text-decoration' => 'none',
1740		'text-rendering' => 'auto',
1741		'unicode-bidi' => 'normal',
1742		'visibility' => 'visible',
1743		'word-spacing' => 'normal',
1744		'writing-mode' => 'lr-tb',
1745		'text-color' => 'black',
1746		'transfmatrix' => array(1, 0, 0, 1, 0, 0)
1747		));
1748
1749	/**
1750	 * If true force sRGB color profile for all document.
1751	 * @protected
1752	 * @since 5.9.121 (2011-09-28)
1753	 */
1754	protected $force_srgb = false;
1755
1756	/**
1757	 * If true set the document to PDF/A mode.
1758	 * @protected
1759	 * @since 5.9.121 (2011-09-27)
1760	 */
1761	protected $pdfa_mode = false;
1762
1763	/**
1764	 * version of PDF/A mode (1 - 3).
1765	 * @protected
1766	 * @since 6.2.26 (2019-03-12)
1767	 */
1768	protected $pdfa_version = 1;
1769
1770	/**
1771	 * Document creation date-time
1772	 * @protected
1773	 * @since 5.9.152 (2012-03-22)
1774	 */
1775	protected $doc_creation_timestamp;
1776
1777	/**
1778	 * Document modification date-time
1779	 * @protected
1780	 * @since 5.9.152 (2012-03-22)
1781	 */
1782	protected $doc_modification_timestamp;
1783
1784	/**
1785	 * Custom XMP data.
1786	 * @protected
1787	 * @since 5.9.128 (2011-10-06)
1788	 */
1789	protected $custom_xmp = '';
1790
1791	/**
1792	 * Custom XMP RDF data.
1793	 * @protected
1794	 * @since 6.3.0 (2019-09-19)
1795	 */
1796	protected $custom_xmp_rdf = '';
1797
1798	/**
1799	 * Overprint mode array.
1800	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
1801	 * @protected
1802	 * @since 5.9.152 (2012-03-23)
1803	 */
1804	protected $overprint = array('OP' => false, 'op' => false, 'OPM' => 0);
1805
1806	/**
1807	 * Alpha mode array.
1808	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
1809	 * @protected
1810	 * @since 5.9.152 (2012-03-23)
1811	 */
1812	protected $alpha = array('CA' => 1, 'ca' => 1, 'BM' => '/Normal', 'AIS' => false);
1813
1814	/**
1815	 * Define the page boundaries boxes to be set on document.
1816	 * @protected
1817	 * @since 5.9.152 (2012-03-23)
1818	 */
1819	protected $page_boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
1820
1821	/**
1822	 * If true print TCPDF meta link.
1823	 * @protected
1824	 * @since 5.9.152 (2012-03-23)
1825	 */
1826	protected $tcpdflink = true;
1827
1828	/**
1829	 * Cache array for computed GD gamma values.
1830	 * @protected
1831	 * @since 5.9.1632 (2012-06-05)
1832	 */
1833	protected $gdgammacache = array();
1834
1835	//------------------------------------------------------------
1836	// METHODS
1837	//------------------------------------------------------------
1838
1839	/**
1840	 * This is the class constructor.
1841	 * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
1842	 *
1843	 * IMPORTANT: Please note that this method sets the mb_internal_encoding to ASCII, so if you are using the mbstring module functions with TCPDF you need to correctly set/unset the mb_internal_encoding when needed.
1844	 *
1845	 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul>
1846	 * @param $unit (string) 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.
1847	 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
1848	 * @param $unicode (boolean) TRUE means that the input text is unicode (default = true)
1849	 * @param $encoding (string) Charset encoding (used only when converting back html entities); default is UTF-8.
1850	 * @param $diskcache (boolean) DEPRECATED FEATURE
1851	 * @param $pdfa (integer) If not false, set the document to PDF/A mode and the good version (1 or 3).
1852	 * @public
1853	 * @see getPageSizeFromFormat(), setPageFormat()
1854	 */
1855	public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
1856		/* Set internal character encoding to ASCII */
1857		if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
1858			$this->internal_encoding = mb_internal_encoding();
1859			mb_internal_encoding('ASCII');
1860		}
1861		// set file ID for trailer
1862		$serformat = (is_array($format) ? json_encode($format) : $format);
1863		$this->file_id = md5(TCPDF_STATIC::getRandomSeed('TCPDF'.$orientation.$unit.$serformat.$encoding));
1864		$this->font_obj_ids = array();
1865		$this->page_obj_id = array();
1866		$this->form_obj_id = array();
1867
1868		// set pdf/a mode
1869		if ($pdfa != false) {
1870			$this->pdfa_mode = true;
1871			$this->pdfa_version = $pdfa;  // 1 or 3
1872		} else
1873			$this->pdfa_mode = false;
1874
1875		$this->force_srgb = false;
1876		// set language direction
1877		$this->rtl = false;
1878		$this->tmprtl = false;
1879		// some checks
1880		$this->_dochecks();
1881		// initialization of properties
1882		$this->isunicode = $unicode;
1883		$this->page = 0;
1884		$this->transfmrk[0] = array();
1885		$this->pagedim = array();
1886		$this->n = 2;
1887		$this->buffer = '';
1888		$this->pages = array();
1889		$this->state = 0;
1890		$this->fonts = array();
1891		$this->FontFiles = array();
1892		$this->diffs = array();
1893		$this->images = array();
1894		$this->links = array();
1895		$this->gradients = array();
1896		$this->InFooter = false;
1897		$this->lasth = 0;
1898		$this->FontFamily = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
1899		$this->FontStyle = '';
1900		$this->FontSizePt = 12;
1901		$this->underline = false;
1902		$this->overline = false;
1903		$this->linethrough = false;
1904		$this->DrawColor = '0 G';
1905		$this->FillColor = '0 g';
1906		$this->TextColor = '0 g';
1907		$this->ColorFlag = false;
1908		$this->pdflayers = array();
1909		// encryption values
1910		$this->encrypted = false;
1911		$this->last_enc_key = '';
1912		// standard Unicode fonts
1913		$this->CoreFonts = array(
1914			'courier'=>'Courier',
1915			'courierB'=>'Courier-Bold',
1916			'courierI'=>'Courier-Oblique',
1917			'courierBI'=>'Courier-BoldOblique',
1918			'helvetica'=>'Helvetica',
1919			'helveticaB'=>'Helvetica-Bold',
1920			'helveticaI'=>'Helvetica-Oblique',
1921			'helveticaBI'=>'Helvetica-BoldOblique',
1922			'times'=>'Times-Roman',
1923			'timesB'=>'Times-Bold',
1924			'timesI'=>'Times-Italic',
1925			'timesBI'=>'Times-BoldItalic',
1926			'symbol'=>'Symbol',
1927			'zapfdingbats'=>'ZapfDingbats'
1928		);
1929		// set scale factor
1930		$this->setPageUnit($unit);
1931		// set page format and orientation
1932		$this->setPageFormat($format, $orientation);
1933		// page margins (1 cm)
1934		$margin = 28.35 / $this->k;
1935		$this->SetMargins($margin, $margin);
1936		$this->clMargin = $this->lMargin;
1937		$this->crMargin = $this->rMargin;
1938		// internal cell padding
1939		$cpadding = $margin / 10;
1940		$this->setCellPaddings($cpadding, 0, $cpadding, 0);
1941		// cell margins
1942		$this->setCellMargins(0, 0, 0, 0);
1943		// line width (0.2 mm)
1944		$this->LineWidth = 0.57 / $this->k;
1945		$this->linestyleWidth = sprintf('%F w', ($this->LineWidth * $this->k));
1946		$this->linestyleCap = '0 J';
1947		$this->linestyleJoin = '0 j';
1948		$this->linestyleDash = '[] 0 d';
1949		// automatic page break
1950		$this->SetAutoPageBreak(true, (2 * $margin));
1951		// full width display mode
1952		$this->SetDisplayMode('fullwidth');
1953		// compression
1954		$this->SetCompression();
1955		// set default PDF version number
1956		$this->setPDFVersion();
1957		$this->tcpdflink = true;
1958		$this->encoding = $encoding;
1959		$this->HREF = array();
1960		$this->getFontsList();
1961		$this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
1962		$this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0);
1963		$this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
1964		$this->extgstates = array();
1965		$this->setTextShadow();
1966		// signature
1967		$this->sign = false;
1968		$this->tsa_timestamp = false;
1969		$this->tsa_data = array();
1970		$this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0', 'name' => 'Signature');
1971		$this->empty_signature_appearance = array();
1972		// user's rights
1973		$this->ur['enabled'] = false;
1974		$this->ur['document'] = '/FullSave';
1975		$this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
1976		$this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
1977		$this->ur['signature'] = '/Modify';
1978		$this->ur['ef'] = '/Create/Delete/Modify/Import';
1979		$this->ur['formex'] = '';
1980		// set default JPEG quality
1981		$this->jpeg_quality = 75;
1982		// initialize some settings
1983		TCPDF_FONTS::utf8Bidi(array(), '', false, $this->isunicode, $this->CurrentFont);
1984		// set default font
1985		$this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
1986		$this->setHeaderFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
1987		$this->setFooterFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
1988		// check if PCRE Unicode support is enabled
1989		if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) {
1990			// PCRE unicode support is turned ON
1991			// \s     : any whitespace character
1992			// \p{Z}  : any separator
1993			// \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
1994			// \xa0   : Unicode Character 'NO-BREAK SPACE' (U+00A0)
1995			//$this->setSpacesRE('/(?!\xa0)[\s\p{Z}\p{Lo}]/u');
1996			$this->setSpacesRE('/(?!\xa0)[\s\p{Z}]/u');
1997		} else {
1998			// PCRE unicode support is turned OFF
1999			$this->setSpacesRE('/[^\S\xa0]/');
2000		}
2001		$this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
2002		// set document creation and modification timestamp
2003		$this->doc_creation_timestamp = time();
2004		$this->doc_modification_timestamp = $this->doc_creation_timestamp;
2005		// get default graphic vars
2006		$this->default_graphic_vars = $this->getGraphicVars();
2007		$this->header_xobj_autoreset = false;
2008		$this->custom_xmp = '';
2009		$this->custom_xmp_rdf = '';
2010		// Call cleanup method after script execution finishes or exit() is called.
2011		// NOTE: This will not be executed if the process is killed with a SIGTERM or SIGKILL signal.
2012		register_shutdown_function(array($this, '_destroy'), true);
2013	}
2014
2015	/**
2016	 * Default destructor.
2017	 * @public
2018	 * @since 1.53.0.TC016
2019	 */
2020	public function __destruct() {
2021		// cleanup
2022		$this->_destroy(true);
2023	}
2024
2025	/**
2026	 * Set the units of measure for the document.
2027	 * @param $unit (string) 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.
2028	 * @public
2029	 * @since 3.0.015 (2008-06-06)
2030	 */
2031	public function setPageUnit($unit) {
2032		$unit = strtolower($unit);
2033		//Set scale factor
2034		switch ($unit) {
2035			// points
2036			case 'px':
2037			case 'pt': {
2038				$this->k = 1;
2039				break;
2040			}
2041			// millimeters
2042			case 'mm': {
2043				$this->k = $this->dpi / 25.4;
2044				break;
2045			}
2046			// centimeters
2047			case 'cm': {
2048				$this->k = $this->dpi / 2.54;
2049				break;
2050			}
2051			// inches
2052			case 'in': {
2053				$this->k = $this->dpi;
2054				break;
2055			}
2056			// unsupported unit
2057			default : {
2058				$this->Error('Incorrect unit: '.$unit);
2059				break;
2060			}
2061		}
2062		$this->pdfunit = $unit;
2063		if (isset($this->CurOrientation)) {
2064			$this->setPageOrientation($this->CurOrientation);
2065		}
2066	}
2067
2068	/**
2069	 * Change the format of the current page
2070	 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() documentation or an array of two numbers (width, height) or an array containing the following measures and options:<ul>
2071	 * <li>['format'] = page format name (one of the above);</li>
2072	 * <li>['Rotate'] : The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li>
2073	 * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
2074	 * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
2075	 * <li>['MediaBox']['llx'] : lower-left x coordinate</li>
2076	 * <li>['MediaBox']['lly'] : lower-left y coordinate</li>
2077	 * <li>['MediaBox']['urx'] : upper-right x coordinate</li>
2078	 * <li>['MediaBox']['ury'] : upper-right y coordinate</li>
2079	 * <li>['CropBox'] : the visible region of default user space:</li>
2080	 * <li>['CropBox']['llx'] : lower-left x coordinate</li>
2081	 * <li>['CropBox']['lly'] : lower-left y coordinate</li>
2082	 * <li>['CropBox']['urx'] : upper-right x coordinate</li>
2083	 * <li>['CropBox']['ury'] : upper-right y coordinate</li>
2084	 * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
2085	 * <li>['BleedBox']['llx'] : lower-left x coordinate</li>
2086	 * <li>['BleedBox']['lly'] : lower-left y coordinate</li>
2087	 * <li>['BleedBox']['urx'] : upper-right x coordinate</li>
2088	 * <li>['BleedBox']['ury'] : upper-right y coordinate</li>
2089	 * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
2090	 * <li>['TrimBox']['llx'] : lower-left x coordinate</li>
2091	 * <li>['TrimBox']['lly'] : lower-left y coordinate</li>
2092	 * <li>['TrimBox']['urx'] : upper-right x coordinate</li>
2093	 * <li>['TrimBox']['ury'] : upper-right y coordinate</li>
2094	 * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
2095	 * <li>['ArtBox']['llx'] : lower-left x coordinate</li>
2096	 * <li>['ArtBox']['lly'] : lower-left y coordinate</li>
2097	 * <li>['ArtBox']['urx'] : upper-right x coordinate</li>
2098	 * <li>['ArtBox']['ury'] : upper-right y coordinate</li>
2099	 * <li>['BoxColorInfo'] :specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for each of the possible page boundaries other than the MediaBox:</li>
2100	 * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
2101	 * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
2102	 * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
2103	 * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
2104	 * <li>['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation</li>
2105	 * <li>['trans']['Dur'] : The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li>
2106	 * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
2107	 * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
2108	 * <li>['trans']['Dm'] : (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li>
2109	 * <li>['trans']['M'] : (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li>
2110	 * <li>['trans']['Di'] : (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li>
2111	 * <li>['trans']['SS'] : (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0.</li>
2112	 * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
2113	 * </ul>
2114	 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul>
2115	 * <li>P or Portrait (default)</li>
2116	 * <li>L or Landscape</li>
2117	 * <li>'' (empty string) for automatic orientation</li>
2118	 * </ul>
2119	 * @protected
2120	 * @since 3.0.015 (2008-06-06)
2121	 * @see getPageSizeFromFormat()
2122	 */
2123	protected function setPageFormat($format, $orientation='P') {
2124		if (!empty($format) AND isset($this->pagedim[$this->page])) {
2125			// remove inherited values
2126			unset($this->pagedim[$this->page]);
2127		}
2128		if (is_string($format)) {
2129			// get page measures from format name
2130			$pf = TCPDF_STATIC::getPageSizeFromFormat($format);
2131			$this->fwPt = $pf[0];
2132			$this->fhPt = $pf[1];
2133		} else {
2134			// the boundaries of the physical medium on which the page shall be displayed or printed
2135			if (isset($format['MediaBox'])) {
2136				$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', $format['MediaBox']['llx'], $format['MediaBox']['lly'], $format['MediaBox']['urx'], $format['MediaBox']['ury'], false, $this->k, $this->pagedim);
2137				$this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k);
2138				$this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k);
2139			} else {
2140				if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
2141					$pf = array(($format[0] * $this->k), ($format[1] * $this->k));
2142				} else {
2143					if (!isset($format['format'])) {
2144						// default value
2145						$format['format'] = 'A4';
2146					}
2147					$pf = TCPDF_STATIC::getPageSizeFromFormat($format['format']);
2148				}
2149				$this->fwPt = $pf[0];
2150				$this->fhPt = $pf[1];
2151				$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
2152			}
2153			// the visible region of default user space
2154			if (isset($format['CropBox'])) {
2155				$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'CropBox', $format['CropBox']['llx'], $format['CropBox']['lly'], $format['CropBox']['urx'], $format['CropBox']['ury'], false, $this->k, $this->pagedim);
2156			}
2157			// the region to which the contents of the page shall be clipped when output in a production environment
2158			if (isset($format['BleedBox'])) {
2159				$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'BleedBox', $format['BleedBox']['llx'], $format['BleedBox']['lly'], $format['BleedBox']['urx'], $format['BleedBox']['ury'], false, $this->k, $this->pagedim);
2160			}
2161			// the intended dimensions of the finished page after trimming
2162			if (isset($format['TrimBox'])) {
2163				$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'TrimBox', $format['TrimBox']['llx'], $format['TrimBox']['lly'], $format['TrimBox']['urx'], $format['TrimBox']['ury'], false, $this->k, $this->pagedim);
2164			}
2165			// the page's meaningful content (including potential white space)
2166			if (isset($format['ArtBox'])) {
2167				$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'ArtBox', $format['ArtBox']['llx'], $format['ArtBox']['lly'], $format['ArtBox']['urx'], $format['ArtBox']['ury'], false, $this->k, $this->pagedim);
2168			}
2169			// specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
2170			if (isset($format['BoxColorInfo'])) {
2171				$this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo'];
2172			}
2173			if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) {
2174				// The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
2175				$this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']);
2176			}
2177			if (isset($format['PZ'])) {
2178				// The page's preferred zoom (magnification) factor
2179				$this->pagedim[$this->page]['PZ'] = floatval($format['PZ']);
2180			}
2181			if (isset($format['trans'])) {
2182				// The style and duration of the visual transition to use when moving from another page to the given page during a presentation
2183				if (isset($format['trans']['Dur'])) {
2184					// The page's display duration
2185					$this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']);
2186				}
2187				$stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
2188				if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
2189					// The transition style that shall be used when moving to this page from another during a presentation
2190					$this->pagedim[$this->page]['trans']['S'] = $format['trans']['S'];
2191					$valid_effect = array('Split', 'Blinds');
2192					$valid_vals = array('H', 'V');
2193					if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
2194						$this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm'];
2195					}
2196					$valid_effect = array('Split', 'Box', 'Fly');
2197					$valid_vals = array('I', 'O');
2198					if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
2199						$this->pagedim[$this->page]['trans']['M'] = $format['trans']['M'];
2200					}
2201					$valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
2202					if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
2203						if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
2204							OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
2205							OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
2206							$this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']);
2207						}
2208					}
2209					if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
2210						$this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']);
2211					}
2212					if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
2213						$this->pagedim[$this->page]['trans']['B'] = 'true';
2214					}
2215				} else {
2216					$this->pagedim[$this->page]['trans']['S'] = 'R';
2217				}
2218				if (isset($format['trans']['D'])) {
2219					// The duration of the transition effect, in seconds
2220					$this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']);
2221				} else {
2222					$this->pagedim[$this->page]['trans']['D'] = 1;
2223				}
2224			}
2225		}
2226		$this->setPageOrientation($orientation);
2227	}
2228
2229	/**
2230	 * Set page orientation.
2231	 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul>
2232	 * @param $autopagebreak (boolean) Boolean indicating if auto-page-break mode should be on or off.
2233	 * @param $bottommargin (float) bottom margin of the page.
2234	 * @public
2235	 * @since 3.0.015 (2008-06-06)
2236	 */
2237	public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
2238		if (!isset($this->pagedim[$this->page]['MediaBox'])) {
2239			// the boundaries of the physical medium on which the page shall be displayed or printed
2240			$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
2241		}
2242		if (!isset($this->pagedim[$this->page]['CropBox'])) {
2243			// the visible region of default user space
2244			$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'CropBox', $this->pagedim[$this->page]['MediaBox']['llx'], $this->pagedim[$this->page]['MediaBox']['lly'], $this->pagedim[$this->page]['MediaBox']['urx'], $this->pagedim[$this->page]['MediaBox']['ury'], true, $this->k, $this->pagedim);
2245		}
2246		if (!isset($this->pagedim[$this->page]['BleedBox'])) {
2247			// the region to which the contents of the page shall be clipped when output in a production environment
2248			$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'BleedBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
2249		}
2250		if (!isset($this->pagedim[$this->page]['TrimBox'])) {
2251			// the intended dimensions of the finished page after trimming
2252			$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'TrimBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
2253		}
2254		if (!isset($this->pagedim[$this->page]['ArtBox'])) {
2255			// the page's meaningful content (including potential white space)
2256			$this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'ArtBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
2257		}
2258		if (!isset($this->pagedim[$this->page]['Rotate'])) {
2259			// The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
2260			$this->pagedim[$this->page]['Rotate'] = 0;
2261		}
2262		if (!isset($this->pagedim[$this->page]['PZ'])) {
2263			// The page's preferred zoom (magnification) factor
2264			$this->pagedim[$this->page]['PZ'] = 1;
2265		}
2266		if ($this->fwPt > $this->fhPt) {
2267			// landscape
2268			$default_orientation = 'L';
2269		} else {
2270			// portrait
2271			$default_orientation = 'P';
2272		}
2273		$valid_orientations = array('P', 'L');
2274		if (empty($orientation)) {
2275			$orientation = $default_orientation;
2276		} else {
2277			$orientation = strtoupper($orientation[0]);
2278		}
2279		if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
2280			$this->CurOrientation = $orientation;
2281			$this->wPt = $this->fhPt;
2282			$this->hPt = $this->fwPt;
2283		} else {
2284			$this->CurOrientation = $default_orientation;
2285			$this->wPt = $this->fwPt;
2286			$this->hPt = $this->fhPt;
2287		}
2288		if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){
2289			// swap X and Y coordinates (change page orientation)
2290			$this->pagedim = TCPDF_STATIC::swapPageBoxCoordinates($this->page, $this->pagedim);
2291		}
2292		$this->w = ($this->wPt / $this->k);
2293		$this->h = ($this->hPt / $this->k);
2294		if (TCPDF_STATIC::empty_string($autopagebreak)) {
2295			if (isset($this->AutoPageBreak)) {
2296				$autopagebreak = $this->AutoPageBreak;
2297			} else {
2298				$autopagebreak = true;
2299			}
2300		}
2301		if (TCPDF_STATIC::empty_string($bottommargin)) {
2302			if (isset($this->bMargin)) {
2303				$bottommargin = $this->bMargin;
2304			} else {
2305				// default value = 2 cm
2306				$bottommargin = 2 * 28.35 / $this->k;
2307			}
2308		}
2309		$this->SetAutoPageBreak($autopagebreak, $bottommargin);
2310		// store page dimensions
2311		$this->pagedim[$this->page]['w'] = $this->wPt;
2312		$this->pagedim[$this->page]['h'] = $this->hPt;
2313		$this->pagedim[$this->page]['wk'] = $this->w;
2314		$this->pagedim[$this->page]['hk'] = $this->h;
2315		$this->pagedim[$this->page]['tm'] = $this->tMargin;
2316		$this->pagedim[$this->page]['bm'] = $bottommargin;
2317		$this->pagedim[$this->page]['lm'] = $this->lMargin;
2318		$this->pagedim[$this->page]['rm'] = $this->rMargin;
2319		$this->pagedim[$this->page]['pb'] = $autopagebreak;
2320		$this->pagedim[$this->page]['or'] = $this->CurOrientation;
2321		$this->pagedim[$this->page]['olm'] = $this->original_lMargin;
2322		$this->pagedim[$this->page]['orm'] = $this->original_rMargin;
2323	}
2324
2325	/**
2326	 * Set regular expression to detect withespaces or word separators.
2327	 * The pattern delimiter must be the forward-slash character "/".
2328	 * Some example patterns are:
2329	 * <pre>
2330	 * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
2331	 * Unicode and PCRE unicode support: "/(?!\xa0)[\s\p{Z}]/u"
2332	 * Unicode and PCRE unicode support in Chinese mode: "/(?!\xa0)[\s\p{Z}\p{Lo}]/u"
2333	 * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
2334	 *      \s     : any whitespace character
2335	 *      \p{Z}  : any separator
2336	 *      \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
2337	 *      \xa0   : Unicode Character 'NO-BREAK SPACE' (U+00A0)
2338	 * </pre>
2339	 * @param $re (string) regular expression (leave empty for default).
2340	 * @public
2341	 * @since 4.6.016 (2009-06-15)
2342	 */
2343	public function setSpacesRE($re='/[^\S\xa0]/') {
2344		$this->re_spaces = $re;
2345		$re_parts = explode('/', $re);
2346		// get pattern parts
2347		$this->re_space = array();
2348		if (isset($re_parts[1]) AND !empty($re_parts[1])) {
2349			$this->re_space['p'] = $re_parts[1];
2350		} else {
2351			$this->re_space['p'] = '[\s]';
2352		}
2353		// set pattern modifiers
2354		if (isset($re_parts[2]) AND !empty($re_parts[2])) {
2355			$this->re_space['m'] = $re_parts[2];
2356		} else {
2357			$this->re_space['m'] = '';
2358		}
2359	}
2360
2361	/**
2362	 * Enable or disable Right-To-Left language mode
2363	 * @param $enable (Boolean) if true enable Right-To-Left language mode.
2364	 * @param $resetx (Boolean) if true reset the X position on direction change.
2365	 * @public
2366	 * @since 2.0.000 (2008-01-03)
2367	 */
2368	public function setRTL($enable, $resetx=true) {
2369		$enable = $enable ? true : false;
2370		$resetx = ($resetx AND ($enable != $this->rtl));
2371		$this->rtl = $enable;
2372		$this->tmprtl = false;
2373		if ($resetx) {
2374			$this->Ln(0);
2375		}
2376	}
2377
2378	/**
2379	 * Return the RTL status
2380	 * @return boolean
2381	 * @public
2382	 * @since 4.0.012 (2008-07-24)
2383	 */
2384	public function getRTL() {
2385		return $this->rtl;
2386	}
2387
2388	/**
2389	 * Force temporary RTL language direction
2390	 * @param $mode (mixed) can be false, 'L' for LTR or 'R' for RTL
2391	 * @public
2392	 * @since 2.1.000 (2008-01-09)
2393	 */
2394	public function setTempRTL($mode) {
2395		$newmode = false;
2396		switch (strtoupper($mode)) {
2397			case 'LTR':
2398			case 'L': {
2399				if ($this->rtl) {
2400					$newmode = 'L';
2401				}
2402				break;
2403			}
2404			case 'RTL':
2405			case 'R': {
2406				if (!$this->rtl) {
2407					$newmode = 'R';
2408				}
2409				break;
2410			}
2411			case false:
2412			default: {
2413				$newmode = false;
2414				break;
2415			}
2416		}
2417		$this->tmprtl = $newmode;
2418	}
2419
2420	/**
2421	 * Return the current temporary RTL status
2422	 * @return boolean
2423	 * @public
2424	 * @since 4.8.014 (2009-11-04)
2425	 */
2426	public function isRTLTextDir() {
2427		return ($this->rtl OR ($this->tmprtl == 'R'));
2428	}
2429
2430	/**
2431	 * Set the last cell height.
2432	 * @param $h (float) cell height.
2433	 * @author Nicola Asuni
2434	 * @public
2435	 * @since 1.53.0.TC034
2436	 */
2437	public function setLastH($h) {
2438		$this->lasth = $h;
2439	}
2440
2441	/**
2442	 * Return the cell height
2443	 * @param $fontsize (int) Font size in internal units
2444	 * @param $padding (boolean) If true add cell padding
2445	 * @public
2446	 */
2447	public function getCellHeight($fontsize, $padding=TRUE) {
2448		$height = ($fontsize * $this->cell_height_ratio);
2449		if ($padding) {
2450			$height += ($this->cell_padding['T'] + $this->cell_padding['B']);
2451		}
2452		return round($height, 6);
2453	}
2454
2455	/**
2456	 * Reset the last cell height.
2457	 * @public
2458	 * @since 5.9.000 (2010-10-03)
2459	 */
2460	public function resetLastH() {
2461		$this->lasth = $this->getCellHeight($this->FontSize);
2462	}
2463
2464	/**
2465	 * Get the last cell height.
2466	 * @return last cell height
2467	 * @public
2468	 * @since 4.0.017 (2008-08-05)
2469	 */
2470	public function getLastH() {
2471		return $this->lasth;
2472	}
2473
2474	/**
2475	 * Set the adjusting factor to convert pixels to user units.
2476	 * @param $scale (float) adjusting factor to convert pixels to user units.
2477	 * @author Nicola Asuni
2478	 * @public
2479	 * @since 1.5.2
2480	 */
2481	public function setImageScale($scale) {
2482		$this->imgscale = $scale;
2483	}
2484
2485	/**
2486	 * Returns the adjusting factor to convert pixels to user units.
2487	 * @return float adjusting factor to convert pixels to user units.
2488	 * @author Nicola Asuni
2489	 * @public
2490	 * @since 1.5.2
2491	 */
2492	public function getImageScale() {
2493		return $this->imgscale;
2494	}
2495
2496	/**
2497	 * Returns an array of page dimensions:
2498	 * <ul><li>$this->pagedim[$this->page]['w'] = page width in points</li><li>$this->pagedim[$this->page]['h'] = height in points</li><li>$this->pagedim[$this->page]['wk'] = page width in user units</li><li>$this->pagedim[$this->page]['hk'] = page height in user units</li><li>$this->pagedim[$this->page]['tm'] = top margin</li><li>$this->pagedim[$this->page]['bm'] = bottom margin</li><li>$this->pagedim[$this->page]['lm'] = left margin</li><li>$this->pagedim[$this->page]['rm'] = right margin</li><li>$this->pagedim[$this->page]['pb'] = auto page break</li><li>$this->pagedim[$this->page]['or'] = page orientation</li><li>$this->pagedim[$this->page]['olm'] = original left margin</li><li>$this->pagedim[$this->page]['orm'] = original right margin</li><li>$this->pagedim[$this->page]['Rotate'] = The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li><li>$this->pagedim[$this->page]['PZ'] = The page's preferred zoom (magnification) factor.</li><li>$this->pagedim[$this->page]['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation<ul><li>$this->pagedim[$this->page]['trans']['Dur'] = The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li><li>$this->pagedim[$this->page]['trans']['S'] = transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li><li>$this->pagedim[$this->page]['trans']['D'] = The duration of the transition effect, in seconds.</li><li>$this->pagedim[$this->page]['trans']['Dm'] = (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li><li>$this->pagedim[$this->page]['trans']['M'] = (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li><li>$this->pagedim[$this->page]['trans']['Di'] = (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li><li>$this->pagedim[$this->page]['trans']['SS'] = (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0. </li><li>$this->pagedim[$this->page]['trans']['B'] = (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li></ul></li><li>$this->pagedim[$this->page]['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed<ul><li>$this->pagedim[$this->page]['MediaBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['CropBox'] : the visible region of default user space<ul><li>$this->pagedim[$this->page]['CropBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment<ul><li>$this->pagedim[$this->page]['BleedBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['TrimBox'] : the intended dimensions of the finished page after trimming<ul><li>$this->pagedim[$this->page]['TrimBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['ArtBox'] : the extent of the page's meaningful content<ul><li>$this->pagedim[$this->page]['ArtBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['ury'] = upper-right y coordinate in points</li></ul></li></ul>
2499	 * @param $pagenum (int) page number (empty = current page)
2500	 * @return array of page dimensions.
2501	 * @author Nicola Asuni
2502	 * @public
2503	 * @since 4.5.027 (2009-03-16)
2504	 */
2505	public function getPageDimensions($pagenum='') {
2506		if (empty($pagenum)) {
2507			$pagenum = $this->page;
2508		}
2509		return $this->pagedim[$pagenum];
2510	}
2511
2512	/**
2513	 * Returns the page width in units.
2514	 * @param $pagenum (int) page number (empty = current page)
2515	 * @return int page width.
2516	 * @author Nicola Asuni
2517	 * @public
2518	 * @since 1.5.2
2519	 * @see getPageDimensions()
2520	 */
2521	public function getPageWidth($pagenum='') {
2522		if (empty($pagenum)) {
2523			return $this->w;
2524		}
2525		return $this->pagedim[$pagenum]['w'];
2526	}
2527
2528	/**
2529	 * Returns the page height in units.
2530	 * @param $pagenum (int) page number (empty = current page)
2531	 * @return int page height.
2532	 * @author Nicola Asuni
2533	 * @public
2534	 * @since 1.5.2
2535	 * @see getPageDimensions()
2536	 */
2537	public function getPageHeight($pagenum='') {
2538		if (empty($pagenum)) {
2539			return $this->h;
2540		}
2541		return $this->pagedim[$pagenum]['h'];
2542	}
2543
2544	/**
2545	 * Returns the page break margin.
2546	 * @param $pagenum (int) page number (empty = current page)
2547	 * @return int page break margin.
2548	 * @author Nicola Asuni
2549	 * @public
2550	 * @since 1.5.2
2551	 * @see getPageDimensions()
2552	 */
2553	public function getBreakMargin($pagenum='') {
2554		if (empty($pagenum)) {
2555			return $this->bMargin;
2556		}
2557		return $this->pagedim[$pagenum]['bm'];
2558	}
2559
2560	/**
2561	 * Returns the scale factor (number of points in user unit).
2562	 * @return int scale factor.
2563	 * @author Nicola Asuni
2564	 * @public
2565	 * @since 1.5.2
2566	 */
2567	public function getScaleFactor() {
2568		return $this->k;
2569	}
2570
2571	/**
2572	 * Defines the left, top and right margins.
2573	 * @param $left (float) Left margin.
2574	 * @param $top (float) Top margin.
2575	 * @param $right (float) Right margin. Default value is the left one.
2576	 * @param $keepmargins (boolean) if true overwrites the default page margins
2577	 * @public
2578	 * @since 1.0
2579	 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
2580	 */
2581	public function SetMargins($left, $top, $right=-1, $keepmargins=false) {
2582		//Set left, top and right margins
2583		$this->lMargin = $left;
2584		$this->tMargin = $top;
2585		if ($right == -1) {
2586			$right = $left;
2587		}
2588		$this->rMargin = $right;
2589		if ($keepmargins) {
2590			// overwrite original values
2591			$this->original_lMargin = $this->lMargin;
2592			$this->original_rMargin = $this->rMargin;
2593		}
2594	}
2595
2596	/**
2597	 * 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.
2598	 * @param $margin (float) The margin.
2599	 * @public
2600	 * @since 1.4
2601	 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
2602	 */
2603	public function SetLeftMargin($margin) {
2604		//Set left margin
2605		$this->lMargin = $margin;
2606		if (($this->page > 0) AND ($this->x < $margin)) {
2607			$this->x = $margin;
2608		}
2609	}
2610
2611	/**
2612	 * Defines the top margin. The method can be called before creating the first page.
2613	 * @param $margin (float) The margin.
2614	 * @public
2615	 * @since 1.5
2616	 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
2617	 */
2618	public function SetTopMargin($margin) {
2619		//Set top margin
2620		$this->tMargin = $margin;
2621		if (($this->page > 0) AND ($this->y < $margin)) {
2622			$this->y = $margin;
2623		}
2624	}
2625
2626	/**
2627	 * Defines the right margin. The method can be called before creating the first page.
2628	 * @param $margin (float) The margin.
2629	 * @public
2630	 * @since 1.5
2631	 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
2632	 */
2633	public function SetRightMargin($margin) {
2634		$this->rMargin = $margin;
2635		if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
2636			$this->x = $this->w - $margin;
2637		}
2638	}
2639
2640	/**
2641	 * Set the same internal Cell padding for top, right, bottom, left-
2642	 * @param $pad (float) internal padding.
2643	 * @public
2644	 * @since 2.1.000 (2008-01-09)
2645	 * @see getCellPaddings(), setCellPaddings()
2646	 */
2647	public function SetCellPadding($pad) {
2648		if ($pad >= 0) {
2649			$this->cell_padding['L'] = $pad;
2650			$this->cell_padding['T'] = $pad;
2651			$this->cell_padding['R'] = $pad;
2652			$this->cell_padding['B'] = $pad;
2653		}
2654	}
2655
2656	/**
2657	 * Set the internal Cell paddings.
2658	 * @param $left (float) left padding
2659	 * @param $top (float) top padding
2660	 * @param $right (float) right padding
2661	 * @param $bottom (float) bottom padding
2662	 * @public
2663	 * @since 5.9.000 (2010-10-03)
2664	 * @see getCellPaddings(), SetCellPadding()
2665	 */
2666	public function setCellPaddings($left='', $top='', $right='', $bottom='') {
2667		if (($left !== '') AND ($left >= 0)) {
2668			$this->cell_padding['L'] = $left;
2669		}
2670		if (($top !== '') AND ($top >= 0)) {
2671			$this->cell_padding['T'] = $top;
2672		}
2673		if (($right !== '') AND ($right >= 0)) {
2674			$this->cell_padding['R'] = $right;
2675		}
2676		if (($bottom !== '') AND ($bottom >= 0)) {
2677			$this->cell_padding['B'] = $bottom;
2678		}
2679	}
2680
2681	/**
2682	 * Get the internal Cell padding array.
2683	 * @return array of padding values
2684	 * @public
2685	 * @since 5.9.000 (2010-10-03)
2686	 * @see setCellPaddings(), SetCellPadding()
2687	 */
2688	public function getCellPaddings() {
2689		return $this->cell_padding;
2690	}
2691
2692	/**
2693	 * Set the internal Cell margins.
2694	 * @param $left (float) left margin
2695	 * @param $top (float) top margin
2696	 * @param $right (float) right margin
2697	 * @param $bottom (float) bottom margin
2698	 * @public
2699	 * @since 5.9.000 (2010-10-03)
2700	 * @see getCellMargins()
2701	 */
2702	public function setCellMargins($left='', $top='', $right='', $bottom='') {
2703		if (($left !== '') AND ($left >= 0)) {
2704			$this->cell_margin['L'] = $left;
2705		}
2706		if (($top !== '') AND ($top >= 0)) {
2707			$this->cell_margin['T'] = $top;
2708		}
2709		if (($right !== '') AND ($right >= 0)) {
2710			$this->cell_margin['R'] = $right;
2711		}
2712		if (($bottom !== '') AND ($bottom >= 0)) {
2713			$this->cell_margin['B'] = $bottom;
2714		}
2715	}
2716
2717	/**
2718	 * Get the internal Cell margin array.
2719	 * @return array of margin values
2720	 * @public
2721	 * @since 5.9.000 (2010-10-03)
2722	 * @see setCellMargins()
2723	 */
2724	public function getCellMargins() {
2725		return $this->cell_margin;
2726	}
2727
2728	/**
2729	 * Adjust the internal Cell padding array to take account of the line width.
2730	 * @param $brd (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
2731	 * @return array of adjustments
2732	 * @public
2733	 * @since 5.9.000 (2010-10-03)
2734	 */
2735	protected function adjustCellPadding($brd=0) {
2736		if (empty($brd)) {
2737			return;
2738		}
2739		if (is_string($brd)) {
2740			// convert string to array
2741			$slen = strlen($brd);
2742			$newbrd = array();
2743			for ($i = 0; $i < $slen; ++$i) {
2744				$newbrd[$brd[$i]] = true;
2745			}
2746			$brd = $newbrd;
2747		} elseif (($brd === 1) OR ($brd === true) OR (is_numeric($brd) AND (intval($brd) > 0))) {
2748			$brd = array('LRTB' => true);
2749		}
2750		if (!is_array($brd)) {
2751			return;
2752		}
2753		// store current cell padding
2754		$cp = $this->cell_padding;
2755		// select border mode
2756		if (isset($brd['mode'])) {
2757			$mode = $brd['mode'];
2758			unset($brd['mode']);
2759		} else {
2760			$mode = 'normal';
2761		}
2762		// process borders
2763		foreach ($brd as $border => $style) {
2764			$line_width = $this->LineWidth;
2765			if (is_array($style) AND isset($style['width'])) {
2766				// get border width
2767				$line_width = $style['width'];
2768			}
2769			$adj = 0; // line width inside the cell
2770			switch ($mode) {
2771				case 'ext': {
2772					$adj = 0;
2773					break;
2774				}
2775				case 'int': {
2776					$adj = $line_width;
2777					break;
2778				}
2779				case 'normal':
2780				default: {
2781					$adj = ($line_width / 2);
2782					break;
2783				}
2784			}
2785			// correct internal cell padding if required to avoid overlap between text and lines
2786			if ((strpos($border,'T') !== false) AND ($this->cell_padding['T'] < $adj)) {
2787				$this->cell_padding['T'] = $adj;
2788			}
2789			if ((strpos($border,'R') !== false) AND ($this->cell_padding['R'] < $adj)) {
2790				$this->cell_padding['R'] = $adj;
2791			}
2792			if ((strpos($border,'B') !== false) AND ($this->cell_padding['B'] < $adj)) {
2793				$this->cell_padding['B'] = $adj;
2794			}
2795			if ((strpos($border,'L') !== false) AND ($this->cell_padding['L'] < $adj)) {
2796				$this->cell_padding['L'] = $adj;
2797			}
2798		}
2799		return array('T' => ($this->cell_padding['T'] - $cp['T']), 'R' => ($this->cell_padding['R'] - $cp['R']), 'B' => ($this->cell_padding['B'] - $cp['B']), 'L' => ($this->cell_padding['L'] - $cp['L']));
2800	}
2801
2802	/**
2803	 * 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.
2804	 * @param $auto (boolean) Boolean indicating if mode should be on or off.
2805	 * @param $margin (float) Distance from the bottom of the page.
2806	 * @public
2807	 * @since 1.0
2808	 * @see Cell(), MultiCell(), AcceptPageBreak()
2809	 */
2810	public function SetAutoPageBreak($auto, $margin=0) {
2811		$this->AutoPageBreak = $auto ? true : false;
2812		$this->bMargin = $margin;
2813		$this->PageBreakTrigger = $this->h - $margin;
2814	}
2815
2816	/**
2817	 * Return the auto-page-break mode (true or false).
2818	 * @return boolean auto-page-break mode
2819	 * @public
2820	 * @since 5.9.088
2821	 */
2822	public function getAutoPageBreak() {
2823		return $this->AutoPageBreak;
2824	}
2825
2826	/**
2827	 * Defines the way the document is to be displayed by the viewer.
2828	 * @param $zoom (mixed) 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>
2829	 * @param $layout (string) 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>
2830	 * @param $mode (string) 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>
2831	 * @public
2832	 * @since 1.2
2833	 */
2834	public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
2835		if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
2836			$this->ZoomMode = $zoom;
2837		} else {
2838			$this->Error('Incorrect zoom display mode: '.$zoom);
2839		}
2840		$this->LayoutMode = TCPDF_STATIC::getPageLayoutMode($layout);
2841		$this->PageMode = TCPDF_STATIC::getPageMode($mode);
2842	}
2843
2844	/**
2845	 * 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.
2846	 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
2847	 * @param $compress (boolean) Boolean indicating if compression must be enabled.
2848	 * @public
2849	 * @since 1.4
2850	 */
2851	public function SetCompression($compress=true) {
2852		$this->compress = false;
2853		if (function_exists('gzcompress')) {
2854			if ($compress) {
2855				if ( !$this->pdfa_mode) {
2856					$this->compress = true;
2857				}
2858			}
2859		}
2860	}
2861
2862	/**
2863	 * Set flag to force sRGB_IEC61966-2.1 black scaled ICC color profile for the whole document.
2864	 * @param $mode (boolean) If true force sRGB output intent.
2865	 * @public
2866	 * @since 5.9.121 (2011-09-28)
2867	 */
2868	public function setSRGBmode($mode=false) {
2869		$this->force_srgb = $mode ? true : false;
2870	}
2871
2872	/**
2873	 * Turn on/off Unicode mode for document information dictionary (meta tags).
2874	 * This has effect only when unicode mode is set to false.
2875	 * @param $unicode (boolean) if true set the meta information in Unicode
2876	 * @since 5.9.027 (2010-12-01)
2877	 * @public
2878	 */
2879	public function SetDocInfoUnicode($unicode=true) {
2880		$this->docinfounicode = $unicode ? true : false;
2881	}
2882
2883	/**
2884	 * Defines the title of the document.
2885	 * @param $title (string) The title.
2886	 * @public
2887	 * @since 1.2
2888	 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
2889	 */
2890	public function SetTitle($title) {
2891		$this->title = $title;
2892	}
2893
2894	/**
2895	 * Defines the subject of the document.
2896	 * @param $subject (string) The subject.
2897	 * @public
2898	 * @since 1.2
2899	 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
2900	 */
2901	public function SetSubject($subject) {
2902		$this->subject = $subject;
2903	}
2904
2905	/**
2906	 * Defines the author of the document.
2907	 * @param $author (string) The name of the author.
2908	 * @public
2909	 * @since 1.2
2910	 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
2911	 */
2912	public function SetAuthor($author) {
2913		$this->author = $author;
2914	}
2915
2916	/**
2917	 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
2918	 * @param $keywords (string) The list of keywords.
2919	 * @public
2920	 * @since 1.2
2921	 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
2922	 */
2923	public function SetKeywords($keywords) {
2924		$this->keywords = $keywords;
2925	}
2926
2927	/**
2928	 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
2929	 * @param $creator (string) The name of the creator.
2930	 * @public
2931	 * @since 1.2
2932	 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
2933	 */
2934	public function SetCreator($creator) {
2935		$this->creator = $creator;
2936	}
2937
2938	/**
2939	 * Throw an exception or print an error message and die if the K_TCPDF_PARSER_THROW_EXCEPTION_ERROR constant is set to true.
2940	 * @param $msg (string) The error message
2941	 * @public
2942	 * @since 1.0
2943	 */
2944	public function Error($msg) {
2945		// unset all class variables
2946		$this->_destroy(true);
2947		if (defined('K_TCPDF_THROW_EXCEPTION_ERROR') AND !K_TCPDF_THROW_EXCEPTION_ERROR) {
2948			die('<strong>TCPDF ERROR: </strong>'.$msg);
2949		} else {
2950			throw new Exception('TCPDF ERROR: '.$msg);
2951		}
2952	}
2953
2954	/**
2955	 * This method begins the generation of the PDF document.
2956	 * It is not necessary to call it explicitly because AddPage() does it automatically.
2957	 * Note: no page is created by this method
2958	 * @public
2959	 * @since 1.0
2960	 * @see AddPage(), Close()
2961	 */
2962	public function Open() {
2963		$this->state = 1;
2964	}
2965
2966	/**
2967	 * Terminates the PDF document.
2968	 * It is not necessary to call this method explicitly because Output() does it automatically.
2969	 * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
2970	 * @public
2971	 * @since 1.0
2972	 * @see Open(), Output()
2973	 */
2974	public function Close() {
2975		if ($this->state == 3) {
2976			return;
2977		}
2978		if ($this->page == 0) {
2979			$this->AddPage();
2980		}
2981		$this->endLayer();
2982		if ($this->tcpdflink) {
2983			// save current graphic settings
2984			$gvars = $this->getGraphicVars();
2985			$this->setEqualColumns();
2986			$this->lastpage(true);
2987			$this->SetAutoPageBreak(false);
2988			$this->x = 0;
2989			$this->y = $this->h - (1 / $this->k);
2990			$this->lMargin = 0;
2991			$this->_outSaveGraphicsState();
2992			$font = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
2993			$this->SetFont($font, '', 1);
2994			$this->setTextRenderingMode(0, false, false);
2995			$msg = "\x50\x6f\x77\x65\x72\x65\x64\x20\x62\x79\x20\x54\x43\x50\x44\x46\x20\x28\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67\x29";
2996			$lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
2997			$this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
2998			$this->_outRestoreGraphicsState();
2999			// restore graphic settings
3000			$this->setGraphicVars($gvars);
3001		}
3002		// close page
3003		$this->endPage();
3004		// close document
3005		$this->_enddoc();
3006		// unset all class variables (except critical ones)
3007		$this->_destroy(false);
3008	}
3009
3010	/**
3011	 * Move pointer at the specified document page and update page dimensions.
3012	 * @param $pnum (int) page number (1 ... numpages)
3013	 * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
3014	 * @public
3015	 * @since 2.1.000 (2008-01-07)
3016	 * @see getPage(), lastpage(), getNumPages()
3017	 */
3018	public function setPage($pnum, $resetmargins=false) {
3019		if (($pnum == $this->page) AND ($this->state == 2)) {
3020			return;
3021		}
3022		if (($pnum > 0) AND ($pnum <= $this->numpages)) {
3023			$this->state = 2;
3024			// save current graphic settings
3025			//$gvars = $this->getGraphicVars();
3026			$oldpage = $this->page;
3027			$this->page = $pnum;
3028			$this->wPt = $this->pagedim[$this->page]['w'];
3029			$this->hPt = $this->pagedim[$this->page]['h'];
3030			$this->w = $this->pagedim[$this->page]['wk'];
3031			$this->h = $this->pagedim[$this->page]['hk'];
3032			$this->tMargin = $this->pagedim[$this->page]['tm'];
3033			$this->bMargin = $this->pagedim[$this->page]['bm'];
3034			$this->original_lMargin = $this->pagedim[$this->page]['olm'];
3035			$this->original_rMargin = $this->pagedim[$this->page]['orm'];
3036			$this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
3037			$this->CurOrientation = $this->pagedim[$this->page]['or'];
3038			$this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
3039			// restore graphic settings
3040			//$this->setGraphicVars($gvars);
3041			if ($resetmargins) {
3042				$this->lMargin = $this->pagedim[$this->page]['olm'];
3043				$this->rMargin = $this->pagedim[$this->page]['orm'];
3044				$this->SetY($this->tMargin);
3045			} else {
3046				// account for booklet mode
3047				if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
3048					$deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
3049					$this->lMargin += $deltam;
3050					$this->rMargin -= $deltam;
3051				}
3052			}
3053		} else {
3054			$this->Error('Wrong page number on setPage() function: '.$pnum);
3055		}
3056	}
3057
3058	/**
3059	 * Reset pointer to the last document page.
3060	 * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
3061	 * @public
3062	 * @since 2.0.000 (2008-01-04)
3063	 * @see setPage(), getPage(), getNumPages()
3064	 */
3065	public function lastPage($resetmargins=false) {
3066		$this->setPage($this->getNumPages(), $resetmargins);
3067	}
3068
3069	/**
3070	 * Get current document page number.
3071	 * @return int page number
3072	 * @public
3073	 * @since 2.1.000 (2008-01-07)
3074	 * @see setPage(), lastpage(), getNumPages()
3075	 */
3076	public function getPage() {
3077		return $this->page;
3078	}
3079
3080	/**
3081	 * Get the total number of insered pages.
3082	 * @return int number of pages
3083	 * @public
3084	 * @since 2.1.000 (2008-01-07)
3085	 * @see setPage(), getPage(), lastpage()
3086	 */
3087	public function getNumPages() {
3088		return $this->numpages;
3089	}
3090
3091	/**
3092	 * Adds a new TOC (Table Of Content) page to the document.
3093	 * @param $orientation (string) page orientation.
3094	 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
3095	 * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
3096	 * @public
3097	 * @since 5.0.001 (2010-05-06)
3098	 * @see AddPage(), startPage(), endPage(), endTOCPage()
3099	 */
3100	public function addTOCPage($orientation='', $format='', $keepmargins=false) {
3101		$this->AddPage($orientation, $format, $keepmargins, true);
3102	}
3103
3104	/**
3105	 * Terminate the current TOC (Table Of Content) page
3106	 * @public
3107	 * @since 5.0.001 (2010-05-06)
3108	 * @see AddPage(), startPage(), endPage(), addTOCPage()
3109	 */
3110	public function endTOCPage() {
3111		$this->endPage(true);
3112	}
3113
3114	/**
3115	 * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer (if enabled). Then the page is added, the current position set to the top-left corner according to the left and top margins (or top-right if in RTL mode), and Header() is called to display the header (if enabled).
3116	 * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
3117	 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
3118	 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
3119	 * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
3120	 * @param $tocpage (boolean) if true set the tocpage state to true (the added page will be used to display Table Of Content).
3121	 * @public
3122	 * @since 1.0
3123	 * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
3124	 */
3125	public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
3126		if ($this->inxobj) {
3127			// we are inside an XObject template
3128			return;
3129		}
3130		if (!isset($this->original_lMargin) OR $keepmargins) {
3131			$this->original_lMargin = $this->lMargin;
3132		}
3133		if (!isset($this->original_rMargin) OR $keepmargins) {
3134			$this->original_rMargin = $this->rMargin;
3135		}
3136		// terminate previous page
3137		$this->endPage();
3138		// start new page
3139		$this->startPage($orientation, $format, $tocpage);
3140	}
3141
3142	/**
3143	 * Terminate the current page
3144	 * @param $tocpage (boolean) if true set the tocpage state to false (end the page used to display Table Of Content).
3145	 * @public
3146	 * @since 4.2.010 (2008-11-14)
3147	 * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
3148	 */
3149	public function endPage($tocpage=false) {
3150		// check if page is already closed
3151		if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
3152			return;
3153		}
3154		// print page footer
3155		$this->setFooter();
3156		// close page
3157		$this->_endpage();
3158		// mark page as closed
3159		$this->pageopen[$this->page] = false;
3160		if ($tocpage) {
3161			$this->tocpage = false;
3162		}
3163	}
3164
3165	/**
3166	 * Starts a new page to the document. The page must be closed using the endPage() function.
3167	 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
3168	 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
3169	 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
3170	 * @param $tocpage (boolean) if true the page is designated to contain the Table-Of-Content.
3171	 * @since 4.2.010 (2008-11-14)
3172	 * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
3173	 * @public
3174	 */
3175	public function startPage($orientation='', $format='', $tocpage=false) {
3176		if ($tocpage) {
3177			$this->tocpage = true;
3178		}
3179		// move page numbers of documents to be attached
3180		if ($this->tocpage) {
3181			// move reference to unexistent pages (used for page attachments)
3182			// adjust outlines
3183			$tmpoutlines = $this->outlines;
3184			foreach ($tmpoutlines as $key => $outline) {
3185				if (!$outline['f'] AND ($outline['p'] > $this->numpages)) {
3186					$this->outlines[$key]['p'] = ($outline['p'] + 1);
3187				}
3188			}
3189			// adjust dests
3190			$tmpdests = $this->dests;
3191			foreach ($tmpdests as $key => $dest) {
3192				if (!$dest['f'] AND ($dest['p'] > $this->numpages)) {
3193					$this->dests[$key]['p'] = ($dest['p'] + 1);
3194				}
3195			}
3196			// adjust links
3197			$tmplinks = $this->links;
3198			foreach ($tmplinks as $key => $link) {
3199				if (!$link['f'] AND ($link['p'] > $this->numpages)) {
3200					$this->links[$key]['p'] = ($link['p'] + 1);
3201				}
3202			}
3203		}
3204		if ($this->numpages > $this->page) {
3205			// this page has been already added
3206			$this->setPage($this->page + 1);
3207			$this->SetY($this->tMargin);
3208			return;
3209		}
3210		// start a new page
3211		if ($this->state == 0) {
3212			$this->Open();
3213		}
3214		++$this->numpages;
3215		$this->swapMargins($this->booklet);
3216		// save current graphic settings
3217		$gvars = $this->getGraphicVars();
3218		// start new page
3219		$this->_beginpage($orientation, $format);
3220		// mark page as open
3221		$this->pageopen[$this->page] = true;
3222		// restore graphic settings
3223		$this->setGraphicVars($gvars);
3224		// mark this point
3225		$this->setPageMark();
3226		// print page header
3227		$this->setHeader();
3228		// restore graphic settings
3229		$this->setGraphicVars($gvars);
3230		// mark this point
3231		$this->setPageMark();
3232		// print table header (if any)
3233		$this->setTableHeader();
3234		// set mark for empty page check
3235		$this->emptypagemrk[$this->page]= $this->pagelen[$this->page];
3236	}
3237
3238	/**
3239	 * Set start-writing mark on current page stream used to put borders and fills.
3240	 * Borders and fills are always created after content and inserted on the position marked by this method.
3241	 * This function must be called after calling Image() function for a background image.
3242	 * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
3243	 * @public
3244	 * @since 4.0.016 (2008-07-30)
3245	 */
3246	public function setPageMark() {
3247		$this->intmrk[$this->page] = $this->pagelen[$this->page];
3248		$this->bordermrk[$this->page] = $this->intmrk[$this->page];
3249		$this->setContentMark();
3250	}
3251
3252	/**
3253	 * Set start-writing mark on selected page.
3254	 * Borders and fills are always created after content and inserted on the position marked by this method.
3255	 * @param $page (int) page number (default is the current page)
3256	 * @protected
3257	 * @since 4.6.021 (2009-07-20)
3258	 */
3259	protected function setContentMark($page=0) {
3260		if ($page <= 0) {
3261			$page = $this->page;
3262		}
3263		if (isset($this->footerlen[$page])) {
3264			$this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page];
3265		} else {
3266			$this->cntmrk[$page] = $this->pagelen[$page];
3267		}
3268	}
3269
3270	/**
3271	 * Set header data.
3272	 * @param $ln (string) header image logo
3273	 * @param $lw (string) header image logo width in mm
3274	 * @param $ht (string) string to print as title on document header
3275	 * @param $hs (string) string to print on document header
3276	 * @param $tc (array) RGB array color for text.
3277	 * @param $lc (array) RGB array color for line.
3278	 * @public
3279	 */
3280	public function setHeaderData($ln='', $lw=0, $ht='', $hs='', $tc=array(0,0,0), $lc=array(0,0,0)) {
3281		$this->header_logo = $ln;
3282		$this->header_logo_width = $lw;
3283		$this->header_title = $ht;
3284		$this->header_string = $hs;
3285		$this->header_text_color = $tc;
3286		$this->header_line_color = $lc;
3287	}
3288
3289	/**
3290	 * Set footer data.
3291	 * @param $tc (array) RGB array color for text.
3292	 * @param $lc (array) RGB array color for line.
3293	 * @public
3294	 */
3295	public function setFooterData($tc=array(0,0,0), $lc=array(0,0,0)) {
3296		$this->footer_text_color = $tc;
3297		$this->footer_line_color = $lc;
3298	}
3299
3300	/**
3301	 * Returns header data:
3302	 * <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>
3303	 * @return array()
3304	 * @public
3305	 * @since 4.0.012 (2008-07-24)
3306	 */
3307	public function getHeaderData() {
3308		$ret = array();
3309		$ret['logo'] = $this->header_logo;
3310		$ret['logo_width'] = $this->header_logo_width;
3311		$ret['title'] = $this->header_title;
3312		$ret['string'] = $this->header_string;
3313		$ret['text_color'] = $this->header_text_color;
3314		$ret['line_color'] = $this->header_line_color;
3315		return $ret;
3316	}
3317
3318	/**
3319	 * Set header margin.
3320	 * (minimum distance between header and top page margin)
3321	 * @param $hm (int) distance in user units
3322	 * @public
3323	 */
3324	public function setHeaderMargin($hm=10) {
3325		$this->header_margin = $hm;
3326	}
3327
3328	/**
3329	 * Returns header margin in user units.
3330	 * @return float
3331	 * @since 4.0.012 (2008-07-24)
3332	 * @public
3333	 */
3334	public function getHeaderMargin() {
3335		return $this->header_margin;
3336	}
3337
3338	/**
3339	 * Set footer margin.
3340	 * (minimum distance between footer and bottom page margin)
3341	 * @param $fm (int) distance in user units
3342	 * @public
3343	 */
3344	public function setFooterMargin($fm=10) {
3345		$this->footer_margin = $fm;
3346	}
3347
3348	/**
3349	 * Returns footer margin in user units.
3350	 * @return float
3351	 * @since 4.0.012 (2008-07-24)
3352	 * @public
3353	 */
3354	public function getFooterMargin() {
3355		return $this->footer_margin;
3356	}
3357	/**
3358	 * Set a flag to print page header.
3359	 * @param $val (boolean) set to true to print the page header (default), false otherwise.
3360	 * @public
3361	 */
3362	public function setPrintHeader($val=true) {
3363		$this->print_header = $val ? true : false;
3364	}
3365
3366	/**
3367	 * Set a flag to print page footer.
3368	 * @param $val (boolean) set to true to print the page footer (default), false otherwise.
3369	 * @public
3370	 */
3371	public function setPrintFooter($val=true) {
3372		$this->print_footer = $val ? true : false;
3373	}
3374
3375	/**
3376	 * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
3377	 * @return float
3378	 * @public
3379	 */
3380	public function getImageRBX() {
3381		return $this->img_rb_x;
3382	}
3383
3384	/**
3385	 * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
3386	 * @return float
3387	 * @public
3388	 */
3389	public function getImageRBY() {
3390		return $this->img_rb_y;
3391	}
3392
3393	/**
3394	 * Reset the xobject template used by Header() method.
3395	 * @public
3396	 */
3397	public function resetHeaderTemplate() {
3398		$this->header_xobjid = false;
3399	}
3400
3401	/**
3402	 * Set a flag to automatically reset the xobject template used by Header() method at each page.
3403	 * @param $val (boolean) set to true to reset Header xobject template at each page, false otherwise.
3404	 * @public
3405	 */
3406	public function setHeaderTemplateAutoreset($val=true) {
3407		$this->header_xobj_autoreset = $val ? true : false;
3408	}
3409
3410	/**
3411	 * This method is used to render the page header.
3412	 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
3413	 * @public
3414	 */
3415	public function Header() {
3416		if ($this->header_xobjid === false) {
3417			// start a new XObject Template
3418			$this->header_xobjid = $this->startTemplate($this->w, $this->tMargin);
3419			$headerfont = $this->getHeaderFont();
3420			$headerdata = $this->getHeaderData();
3421			$this->y = $this->header_margin;
3422			if ($this->rtl) {
3423				$this->x = $this->w - $this->original_rMargin;
3424			} else {
3425				$this->x = $this->original_lMargin;
3426			}
3427			if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
3428				$imgtype = TCPDF_IMAGES::getImageFileType(K_PATH_IMAGES.$headerdata['logo']);
3429				if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
3430					$this->ImageEps(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
3431				} elseif ($imgtype == 'svg') {
3432					$this->ImageSVG(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
3433				} else {
3434					$this->Image(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
3435				}
3436				$imgy = $this->getImageRBY();
3437			} else {
3438				$imgy = $this->y;
3439			}
3440			$cell_height = $this->getCellHeight($headerfont[2] / $this->k);
3441			// set starting margin for text data cell
3442			if ($this->getRTL()) {
3443				$header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.1);
3444			} else {
3445				$header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.1);
3446			}
3447			$cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.1);
3448			$this->SetTextColorArray($this->header_text_color);
3449			// header title
3450			$this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
3451			$this->SetX($header_x);
3452			$this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
3453			// header string
3454			$this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
3455			$this->SetX($header_x);
3456			$this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
3457			// print an ending header line
3458			$this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $headerdata['line_color']));
3459			$this->SetY((2.835 / $this->k) + max($imgy, $this->y));
3460			if ($this->rtl) {
3461				$this->SetX($this->original_rMargin);
3462			} else {
3463				$this->SetX($this->original_lMargin);
3464			}
3465			$this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C');
3466			$this->endTemplate();
3467		}
3468		// print header template
3469		$x = 0;
3470		$dx = 0;
3471		if (!$this->header_xobj_autoreset AND $this->booklet AND (($this->page % 2) == 0)) {
3472			// adjust margins for booklet mode
3473			$dx = ($this->original_lMargin - $this->original_rMargin);
3474		}
3475		if ($this->rtl) {
3476			$x = $this->w + $dx;
3477		} else {
3478			$x = 0 + $dx;
3479		}
3480		$this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false);
3481		if ($this->header_xobj_autoreset) {
3482			// reset header xobject template at each page
3483			$this->header_xobjid = false;
3484		}
3485	}
3486
3487	/**
3488	 * This method is used to render the page footer.
3489	 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
3490	 * @public
3491	 */
3492	public function Footer() {
3493		$cur_y = $this->y;
3494		$this->SetTextColorArray($this->footer_text_color);
3495		//set style for cell border
3496		$line_width = (0.85 / $this->k);
3497		$this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $this->footer_line_color));
3498		//print document barcode
3499		$barcode = $this->getBarcode();
3500		if (!empty($barcode)) {
3501			$this->Ln($line_width);
3502			$barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin) / 3);
3503			$style = array(
3504				'position' => $this->rtl?'R':'L',
3505				'align' => $this->rtl?'R':'L',
3506				'stretch' => false,
3507				'fitwidth' => true,
3508				'cellfitalign' => '',
3509				'border' => false,
3510				'padding' => 0,
3511				'fgcolor' => array(0,0,0),
3512				'bgcolor' => false,
3513				'text' => false
3514			);
3515			$this->write1DBarcode($barcode, 'C128', '', $cur_y + $line_width, '', (($this->footer_margin / 3) - $line_width), 0.3, $style, '');
3516		}
3517		$w_page = isset($this->l['w_page']) ? $this->l['w_page'].' ' : '';
3518		if (empty($this->pagegroups)) {
3519			$pagenumtxt = $w_page.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
3520		} else {
3521			$pagenumtxt = $w_page.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
3522		}
3523		$this->SetY($cur_y);
3524		//Print page number
3525		if ($this->getRTL()) {
3526			$this->SetX($this->original_rMargin);
3527			$this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
3528		} else {
3529			$this->SetX($this->original_lMargin);
3530			$this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
3531		}
3532	}
3533
3534	/**
3535	 * This method is used to render the page header.
3536	 * @protected
3537	 * @since 4.0.012 (2008-07-24)
3538	 */
3539	protected function setHeader() {
3540		if (!$this->print_header OR ($this->state != 2)) {
3541			return;
3542		}
3543		$this->InHeader = true;
3544		$this->setGraphicVars($this->default_graphic_vars);
3545		$temp_thead = $this->thead;
3546		$temp_theadMargins = $this->theadMargins;
3547		$lasth = $this->lasth;
3548		$newline = $this->newline;
3549		$this->_outSaveGraphicsState();
3550		$this->rMargin = $this->original_rMargin;
3551		$this->lMargin = $this->original_lMargin;
3552		$this->SetCellPadding(0);
3553		//set current position
3554		if ($this->rtl) {
3555			$this->SetXY($this->original_rMargin, $this->header_margin);
3556		} else {
3557			$this->SetXY($this->original_lMargin, $this->header_margin);
3558		}
3559		$this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
3560		$this->Header();
3561		//restore position
3562		if ($this->rtl) {
3563			$this->SetXY($this->original_rMargin, $this->tMargin);
3564		} else {
3565			$this->SetXY($this->original_lMargin, $this->tMargin);
3566		}
3567		$this->_outRestoreGraphicsState();
3568		$this->lasth = $lasth;
3569		$this->thead = $temp_thead;
3570		$this->theadMargins = $temp_theadMargins;
3571		$this->newline = $newline;
3572		$this->InHeader = false;
3573	}
3574
3575	/**
3576	 * This method is used to render the page footer.
3577	 * @protected
3578	 * @since 4.0.012 (2008-07-24)
3579	 */
3580	protected function setFooter() {
3581		if ($this->state != 2) {
3582			return;
3583		}
3584		$this->InFooter = true;
3585		// save current graphic settings
3586		$gvars = $this->getGraphicVars();
3587		// mark this point
3588		$this->footerpos[$this->page] = $this->pagelen[$this->page];
3589		$this->_out("\n");
3590		if ($this->print_footer) {
3591			$this->setGraphicVars($this->default_graphic_vars);
3592			$this->current_column = 0;
3593			$this->num_columns = 1;
3594			$temp_thead = $this->thead;
3595			$temp_theadMargins = $this->theadMargins;
3596			$lasth = $this->lasth;
3597			$this->_outSaveGraphicsState();
3598			$this->rMargin = $this->original_rMargin;
3599			$this->lMargin = $this->original_lMargin;
3600			$this->SetCellPadding(0);
3601			//set current position
3602			$footer_y = $this->h - $this->footer_margin;
3603			if ($this->rtl) {
3604				$this->SetXY($this->original_rMargin, $footer_y);
3605			} else {
3606				$this->SetXY($this->original_lMargin, $footer_y);
3607			}
3608			$this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
3609			$this->Footer();
3610			//restore position
3611			if ($this->rtl) {
3612				$this->SetXY($this->original_rMargin, $this->tMargin);
3613			} else {
3614				$this->SetXY($this->original_lMargin, $this->tMargin);
3615			}
3616			$this->_outRestoreGraphicsState();
3617			$this->lasth = $lasth;
3618			$this->thead = $temp_thead;
3619			$this->theadMargins = $temp_theadMargins;
3620		}
3621		// restore graphic settings
3622		$this->setGraphicVars($gvars);
3623		$this->current_column = $gvars['current_column'];
3624		$this->num_columns = $gvars['num_columns'];
3625		// calculate footer length
3626		$this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
3627		$this->InFooter = false;
3628	}
3629
3630	/**
3631	 * Check if we are on the page body (excluding page header and footer).
3632	 * @return true if we are not in page header nor in page footer, false otherwise.
3633	 * @protected
3634	 * @since 5.9.091 (2011-06-15)
3635	 */
3636	protected function inPageBody() {
3637		return (($this->InHeader === false) AND ($this->InFooter === false));
3638	}
3639
3640	/**
3641	 * This method is used to render the table header on new page (if any).
3642	 * @protected
3643	 * @since 4.5.030 (2009-03-25)
3644	 */
3645	protected function setTableHeader() {
3646		if ($this->num_columns > 1) {
3647			// multi column mode
3648			return;
3649		}
3650		if (isset($this->theadMargins['top'])) {
3651			// restore the original top-margin
3652			$this->tMargin = $this->theadMargins['top'];
3653			$this->pagedim[$this->page]['tm'] = $this->tMargin;
3654			$this->y = $this->tMargin;
3655		}
3656		if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
3657			// set margins
3658			$prev_lMargin = $this->lMargin;
3659			$prev_rMargin = $this->rMargin;
3660			$prev_cell_padding = $this->cell_padding;
3661			$this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']);
3662			$this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']);
3663			$this->cell_padding = $this->theadMargins['cell_padding'];
3664			if ($this->rtl) {
3665				$this->x = $this->w - $this->rMargin;
3666			} else {
3667				$this->x = $this->lMargin;
3668			}
3669			// account for special "cell" mode
3670			if ($this->theadMargins['cell']) {
3671				if ($this->rtl) {
3672					$this->x -= $this->cell_padding['R'];
3673				} else {
3674					$this->x += $this->cell_padding['L'];
3675				}
3676			}
3677			$gvars = $this->getGraphicVars();
3678			if (!empty($this->theadMargins['gvars'])) {
3679				// set the correct graphic style
3680				$this->setGraphicVars($this->theadMargins['gvars']);
3681				$this->rMargin = $gvars['rMargin'];
3682				$this->lMargin = $gvars['lMargin'];
3683			}
3684			// print table header
3685			$this->writeHTML($this->thead, false, false, false, false, '');
3686			$this->setGraphicVars($gvars);
3687			// set new top margin to skip the table headers
3688			if (!isset($this->theadMargins['top'])) {
3689				$this->theadMargins['top'] = $this->tMargin;
3690			}
3691			// store end of header position
3692			if (!isset($this->columns[0]['th'])) {
3693				$this->columns[0]['th'] = array();
3694			}
3695			$this->columns[0]['th']['\''.$this->page.'\''] = $this->y;
3696			$this->tMargin = $this->y;
3697			$this->pagedim[$this->page]['tm'] = $this->tMargin;
3698			$this->lasth = 0;
3699			$this->lMargin = $prev_lMargin;
3700			$this->rMargin = $prev_rMargin;
3701			$this->cell_padding = $prev_cell_padding;
3702		}
3703	}
3704
3705	/**
3706	 * Returns the current page number.
3707	 * @return int page number
3708	 * @public
3709	 * @since 1.0
3710	 * @see getAliasNbPages()
3711	 */
3712	public function PageNo() {
3713		return $this->page;
3714	}
3715
3716	/**
3717	 * Returns the array of spot colors.
3718	 * @return (array) Spot colors array.
3719	 * @public
3720	 * @since 6.0.038 (2013-09-30)
3721	 */
3722	public function getAllSpotColors() {
3723		return $this->spot_colors;
3724	}
3725
3726	/**
3727	 * Defines a new spot color.
3728	 * It can be expressed in RGB components or gray scale.
3729	 * The method can be called before the first page is created and the value is retained from page to page.
3730	 * @param $name (string) Full name of the spot color.
3731	 * @param $c (float) Cyan color for CMYK. Value between 0 and 100.
3732	 * @param $m (float) Magenta color for CMYK. Value between 0 and 100.
3733	 * @param $y (float) Yellow color for CMYK. Value between 0 and 100.
3734	 * @param $k (float) Key (Black) color for CMYK. Value between 0 and 100.
3735	 * @public
3736	 * @since 4.0.024 (2008-09-12)
3737	 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
3738	 */
3739	public function AddSpotColor($name, $c, $m, $y, $k) {
3740		if (!isset($this->spot_colors[$name])) {
3741			$i = (1 + count($this->spot_colors));
3742			$this->spot_colors[$name] = array('C' => $c, 'M' => $m, 'Y' => $y, 'K' => $k, 'name' => $name, 'i' => $i);
3743		}
3744	}
3745
3746	/**
3747	 * Set the spot color for the specified type ('draw', 'fill', 'text').
3748	 * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
3749	 * @param $name (string) Name of the spot color.
3750	 * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
3751	 * @return (string) PDF color command.
3752	 * @public
3753	 * @since 5.9.125 (2011-10-03)
3754	 */
3755	public function setSpotColor($type, $name, $tint=100) {
3756		$spotcolor = TCPDF_COLORS::getSpotColor($name, $this->spot_colors);
3757		if ($spotcolor === false) {
3758			$this->Error('Undefined spot color: '.$name.', you must add it using the AddSpotColor() method.');
3759		}
3760		$tint = (max(0, min(100, $tint)) / 100);
3761		$pdfcolor = sprintf('/CS%d ', $this->spot_colors[$name]['i']);
3762		switch ($type) {
3763			case 'draw': {
3764				$pdfcolor .= sprintf('CS %F SCN', $tint);
3765				$this->DrawColor = $pdfcolor;
3766				$this->strokecolor = $spotcolor;
3767				break;
3768			}
3769			case 'fill': {
3770				$pdfcolor .= sprintf('cs %F scn', $tint);
3771				$this->FillColor = $pdfcolor;
3772				$this->bgcolor = $spotcolor;
3773				break;
3774			}
3775			case 'text': {
3776				$pdfcolor .= sprintf('cs %F scn', $tint);
3777				$this->TextColor = $pdfcolor;
3778				$this->fgcolor = $spotcolor;
3779				break;
3780			}
3781		}
3782		$this->ColorFlag = ($this->FillColor != $this->TextColor);
3783		if ($this->state == 2) {
3784			$this->_out($pdfcolor);
3785		}
3786		if ($this->inxobj) {
3787			// we are inside an XObject template
3788			$this->xobjects[$this->xobjid]['spot_colors'][$name] = $this->spot_colors[$name];
3789		}
3790		return $pdfcolor;
3791	}
3792
3793	/**
3794	 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
3795	 * @param $name (string) Name of the spot color.
3796	 * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
3797	 * @public
3798	 * @since 4.0.024 (2008-09-12)
3799	 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
3800	 */
3801	public function SetDrawSpotColor($name, $tint=100) {
3802		$this->setSpotColor('draw', $name, $tint);
3803	}
3804
3805	/**
3806	 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
3807	 * @param $name (string) Name of the spot color.
3808	 * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
3809	 * @public
3810	 * @since 4.0.024 (2008-09-12)
3811	 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
3812	 */
3813	public function SetFillSpotColor($name, $tint=100) {
3814		$this->setSpotColor('fill', $name, $tint);
3815	}
3816
3817	/**
3818	 * Defines the spot color used for text.
3819	 * @param $name (string) Name of the spot color.
3820	 * @param $tint (int) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
3821	 * @public
3822	 * @since 4.0.024 (2008-09-12)
3823	 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
3824	 */
3825	public function SetTextSpotColor($name, $tint=100) {
3826		$this->setSpotColor('text', $name, $tint);
3827	}
3828
3829	/**
3830	 * Set the color array for the specified type ('draw', 'fill', 'text').
3831	 * It can be expressed in RGB, CMYK or GRAY SCALE components.
3832	 * The method can be called before the first page is created and the value is retained from page to page.
3833	 * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
3834	 * @param $color (array) Array of colors (1=gray, 3=RGB, 4=CMYK or 5=spotcolor=CMYK+name values).
3835	 * @param $ret (boolean) If true do not send the PDF command.
3836	 * @return (string) The PDF command or empty string.
3837	 * @public
3838	 * @since 3.1.000 (2008-06-11)
3839	 */
3840	public function setColorArray($type, $color, $ret=false) {
3841		if (is_array($color)) {
3842			$color = array_values($color);
3843			// component: grey, RGB red or CMYK cyan
3844			$c = isset($color[0]) ? $color[0] : -1;
3845			// component: RGB green or CMYK magenta
3846			$m = isset($color[1]) ? $color[1] : -1;
3847			// component: RGB blue or CMYK yellow
3848			$y = isset($color[2]) ? $color[2] : -1;
3849			// component: CMYK black
3850			$k = isset($color[3]) ? $color[3] : -1;
3851			// color name
3852			$name = isset($color[4]) ? $color[4] : '';
3853			if ($c >= 0) {
3854				return $this->setColor($type, $c, $m, $y, $k, $ret, $name);
3855			}
3856		}
3857		return '';
3858	}
3859
3860	/**
3861	 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
3862	 * It can be expressed in RGB, CMYK or GRAY SCALE components.
3863	 * The method can be called before the first page is created and the value is retained from page to page.
3864	 * @param $color (array) Array of colors (1, 3 or 4 values).
3865	 * @param $ret (boolean) If true do not send the PDF command.
3866	 * @return string the PDF command
3867	 * @public
3868	 * @since 3.1.000 (2008-06-11)
3869	 * @see SetDrawColor()
3870	 */
3871	public function SetDrawColorArray($color, $ret=false) {
3872		return $this->setColorArray('draw', $color, $ret);
3873	}
3874
3875	/**
3876	 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
3877	 * It can be expressed in RGB, CMYK or GRAY SCALE components.
3878	 * The method can be called before the first page is created and the value is retained from page to page.
3879	 * @param $color (array) Array of colors (1, 3 or 4 values).
3880	 * @param $ret (boolean) If true do not send the PDF command.
3881	 * @public
3882	 * @since 3.1.000 (2008-6-11)
3883	 * @see SetFillColor()
3884	 */
3885	public function SetFillColorArray($color, $ret=false) {
3886		return $this->setColorArray('fill', $color, $ret);
3887	}
3888
3889	/**
3890	 * Defines the color used for text. It can be expressed in RGB components or gray scale.
3891	 * The method can be called before the first page is created and the value is retained from page to page.
3892	 * @param $color (array) Array of colors (1, 3 or 4 values).
3893	 * @param $ret (boolean) If true do not send the PDF command.
3894	 * @public
3895	 * @since 3.1.000 (2008-6-11)
3896	 * @see SetFillColor()
3897	 */
3898	public function SetTextColorArray($color, $ret=false) {
3899		return $this->setColorArray('text', $color, $ret);
3900	}
3901
3902	/**
3903	 * Defines the color used by the specified type ('draw', 'fill', 'text').
3904	 * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
3905	 * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
3906	 * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
3907	 * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
3908	 * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
3909	 * @param $ret (boolean) If true do not send the command.
3910	 * @param $name (string) spot color name (if any)
3911	 * @return (string) The PDF command or empty string.
3912	 * @public
3913	 * @since 5.9.125 (2011-10-03)
3914	 */
3915	public function setColor($type, $col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
3916		// set default values
3917		if (!is_numeric($col1)) {
3918			$col1 = 0;
3919		}
3920		if (!is_numeric($col2)) {
3921			$col2 = -1;
3922		}
3923		if (!is_numeric($col3)) {
3924			$col3 = -1;
3925		}
3926		if (!is_numeric($col4)) {
3927			$col4 = -1;
3928		}
3929		// set color by case
3930		$suffix = '';
3931		if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
3932			// Grey scale
3933			$col1 = max(0, min(255, $col1));
3934			$intcolor = array('G' => $col1);
3935			$pdfcolor = sprintf('%F ', ($col1 / 255));
3936			$suffix = 'g';
3937		} elseif ($col4 == -1) {
3938			// RGB
3939			$col1 = max(0, min(255, $col1));
3940			$col2 = max(0, min(255, $col2));
3941			$col3 = max(0, min(255, $col3));
3942			$intcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
3943			$pdfcolor = sprintf('%F %F %F ', ($col1 / 255), ($col2 / 255), ($col3 / 255));
3944			$suffix = 'rg';
3945		} else {
3946			$col1 = max(0, min(100, $col1));
3947			$col2 = max(0, min(100, $col2));
3948			$col3 = max(0, min(100, $col3));
3949			$col4 = max(0, min(100, $col4));
3950			if (empty($name)) {
3951				// CMYK
3952				$intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
3953				$pdfcolor = sprintf('%F %F %F %F ', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
3954				$suffix = 'k';
3955			} else {
3956				// SPOT COLOR
3957				$intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
3958				$this->AddSpotColor($name, $col1, $col2, $col3, $col4);
3959				$pdfcolor = $this->setSpotColor($type, $name, 100);
3960			}
3961		}
3962		switch ($type) {
3963			case 'draw': {
3964				$pdfcolor .= strtoupper($suffix);
3965				$this->DrawColor = $pdfcolor;
3966				$this->strokecolor = $intcolor;
3967				break;
3968			}
3969			case 'fill': {
3970				$pdfcolor .= $suffix;
3971				$this->FillColor = $pdfcolor;
3972				$this->bgcolor = $intcolor;
3973				break;
3974			}
3975			case 'text': {
3976				$pdfcolor .= $suffix;
3977				$this->TextColor = $pdfcolor;
3978				$this->fgcolor = $intcolor;
3979				break;
3980			}
3981		}
3982		$this->ColorFlag = ($this->FillColor != $this->TextColor);
3983		if (($type != 'text') AND ($this->state == 2)) {
3984			if (!$ret) {
3985				$this->_out($pdfcolor);
3986			}
3987			return $pdfcolor;
3988		}
3989		return '';
3990	}
3991
3992	/**
3993	 * 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.
3994	 * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
3995	 * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
3996	 * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
3997	 * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
3998	 * @param $ret (boolean) If true do not send the command.
3999	 * @param $name (string) spot color name (if any)
4000	 * @return string the PDF command
4001	 * @public
4002	 * @since 1.3
4003	 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
4004	 */
4005	public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
4006		return $this->setColor('draw', $col1, $col2, $col3, $col4, $ret, $name);
4007	}
4008
4009	/**
4010	 * 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.
4011	 * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
4012	 * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
4013	 * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
4014	 * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
4015	 * @param $ret (boolean) If true do not send the command.
4016	 * @param $name (string) Spot color name (if any).
4017	 * @return (string) The PDF command.
4018	 * @public
4019	 * @since 1.3
4020	 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
4021	 */
4022	public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
4023		return $this->setColor('fill', $col1, $col2, $col3, $col4, $ret, $name);
4024	}
4025
4026	/**
4027	 * 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.
4028	 * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
4029	 * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
4030	 * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
4031	 * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
4032	 * @param $ret (boolean) If true do not send the command.
4033	 * @param $name (string) Spot color name (if any).
4034	 * @return (string) Empty string.
4035	 * @public
4036	 * @since 1.3
4037	 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
4038	 */
4039	public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
4040		return $this->setColor('text', $col1, $col2, $col3, $col4, $ret, $name);
4041	}
4042
4043	/**
4044	 * Returns the length of a string in user unit. A font must be selected.<br>
4045	 * @param $s (string) The string whose length is to be computed
4046	 * @param $fontname (string) 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.
4047	 * @param $fontstyle (string) 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-through</li><li>O: overline</li></ul> or any combination. The default value is regular.
4048	 * @param $fontsize (float) Font size in points. The default value is the current size.
4049	 * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
4050	 * @return mixed int total string length or array of characted widths
4051	 * @author Nicola Asuni
4052	 * @public
4053	 * @since 1.2
4054	 */
4055	public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
4056		return $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont), $s, $this->tmprtl, $this->isunicode, $this->CurrentFont), $fontname, $fontstyle, $fontsize, $getarray);
4057	}
4058
4059	/**
4060	 * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
4061	 * @param $sa (string) The array of chars whose total length is to be computed
4062	 * @param $fontname (string) 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.
4063	 * @param $fontstyle (string) 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 through</li><li>O: overline</li></ul> or any combination. The default value is regular.
4064	 * @param $fontsize (float) Font size in points. The default value is the current size.
4065	 * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
4066	 * @return mixed int total string length or array of characted widths
4067	 * @author Nicola Asuni
4068	 * @public
4069	 * @since 2.4.000 (2008-03-06)
4070	 */
4071	public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
4072		// store current values
4073		if (!TCPDF_STATIC::empty_string($fontname)) {
4074			$prev_FontFamily = $this->FontFamily;
4075			$prev_FontStyle = $this->FontStyle;
4076			$prev_FontSizePt = $this->FontSizePt;
4077			$this->SetFont($fontname, $fontstyle, $fontsize, '', 'default', false);
4078		}
4079		// convert UTF-8 array to Latin1 if required
4080		if ($this->isunicode AND (!$this->isUnicodeFont())) {
4081			$sa = TCPDF_FONTS::UTF8ArrToLatin1Arr($sa);
4082		}
4083		$w = 0; // total width
4084		$wa = array(); // array of characters widths
4085		foreach ($sa as $ck => $char) {
4086			// character width
4087			$cw = $this->GetCharWidth($char, isset($sa[($ck + 1)]));
4088			$wa[] = $cw;
4089			$w += $cw;
4090		}
4091		// restore previous values
4092		if (!TCPDF_STATIC::empty_string($fontname)) {
4093			$this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt, '', 'default', false);
4094		}
4095		if ($getarray) {
4096			return $wa;
4097		}
4098		return $w;
4099	}
4100
4101	/**
4102	 * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking).
4103	 * @param $char (int) The char code whose length is to be returned
4104	 * @param $notlast (boolean) If false ignore the font-spacing.
4105	 * @return float char width
4106	 * @author Nicola Asuni
4107	 * @public
4108	 * @since 2.4.000 (2008-03-06)
4109	 */
4110	public function GetCharWidth($char, $notlast=true) {
4111		// get raw width
4112		$chw = $this->getRawCharWidth($char);
4113		if (($this->font_spacing < 0) OR (($this->font_spacing > 0) AND $notlast)) {
4114			// increase/decrease font spacing
4115			$chw += $this->font_spacing;
4116		}
4117		if ($this->font_stretching != 100) {
4118			// fixed stretching mode
4119			$chw *= ($this->font_stretching / 100);
4120		}
4121		return $chw;
4122	}
4123
4124	/**
4125	 * Returns the length of the char in user unit for the current font.
4126	 * @param $char (int) The char code whose length is to be returned
4127	 * @return float char width
4128	 * @author Nicola Asuni
4129	 * @public
4130	 * @since 5.9.000 (2010-09-28)
4131	 */
4132	public function getRawCharWidth($char) {
4133		if ($char == 173) {
4134			// SHY character will not be printed
4135			return (0);
4136		}
4137		if (isset($this->CurrentFont['cw'][$char])) {
4138			$w = $this->CurrentFont['cw'][$char];
4139		} elseif (isset($this->CurrentFont['dw'])) {
4140			// default width
4141			$w = $this->CurrentFont['dw'];
4142		} elseif (isset($this->CurrentFont['cw'][32])) {
4143			// default width
4144			$w = $this->CurrentFont['cw'][32];
4145		} else {
4146			$w = 600;
4147		}
4148		return $this->getAbsFontMeasure($w);
4149	}
4150
4151	/**
4152	 * Returns the numbero of characters in a string.
4153	 * @param $s (string) The input string.
4154	 * @return int number of characters
4155	 * @public
4156	 * @since 2.0.0001 (2008-01-07)
4157	 */
4158	public function GetNumChars($s) {
4159		if ($this->isUnicodeFont()) {
4160			return count(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont));
4161		}
4162		return strlen($s);
4163	}
4164
4165	/**
4166	 * Fill the list of available fonts ($this->fontlist).
4167	 * @protected
4168	 * @since 4.0.013 (2008-07-28)
4169	 */
4170	protected function getFontsList() {
4171		if (($fontsdir = opendir(TCPDF_FONTS::_getfontpath())) !== false) {
4172			while (($file = readdir($fontsdir)) !== false) {
4173				if (substr($file, -4) == '.php') {
4174					array_push($this->fontlist, strtolower(basename($file, '.php')));
4175				}
4176			}
4177			closedir($fontsdir);
4178		}
4179	}
4180
4181	/**
4182	 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
4183	 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
4184	 * 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.
4185	 * @param $family (string) Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
4186	 * @param $style (string) 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>
4187	 * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
4188	 * @return array containing the font data, or false in case of error.
4189	 * @param $subset (mixed) if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.
4190	 * @public
4191	 * @since 1.5
4192	 * @see SetFont(), setFontSubsetting()
4193	 */
4194	public function AddFont($family, $style='', $fontfile='', $subset='default') {
4195		if ($subset === 'default') {
4196			$subset = $this->font_subsetting;
4197		}
4198		if ($this->pdfa_mode) {
4199			$subset = false;
4200		}
4201		if (TCPDF_STATIC::empty_string($family)) {
4202			if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
4203				$family = $this->FontFamily;
4204			} else {
4205				$this->Error('Empty font family');
4206			}
4207		}
4208		// move embedded styles on $style
4209		if (substr($family, -1) == 'I') {
4210			$style .= 'I';
4211			$family = substr($family, 0, -1);
4212		}
4213		if (substr($family, -1) == 'B') {
4214			$style .= 'B';
4215			$family = substr($family, 0, -1);
4216		}
4217		// normalize family name
4218		$family = strtolower($family);
4219		if ((!$this->isunicode) AND ($family == 'arial')) {
4220			$family = 'helvetica';
4221		}
4222		if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
4223			$style = '';
4224		}
4225		if ($this->pdfa_mode AND (isset($this->CoreFonts[$family]))) {
4226			// all fonts must be embedded
4227			$family = 'pdfa'.$family;
4228		}
4229		$tempstyle = strtoupper($style);
4230		$style = '';
4231		// underline
4232		if (strpos($tempstyle, 'U') !== false) {
4233			$this->underline = true;
4234		} else {
4235			$this->underline = false;
4236		}
4237		// line-through (deleted)
4238		if (strpos($tempstyle, 'D') !== false) {
4239			$this->linethrough = true;
4240		} else {
4241			$this->linethrough = false;
4242		}
4243		// overline
4244		if (strpos($tempstyle, 'O') !== false) {
4245			$this->overline = true;
4246		} else {
4247			$this->overline = false;
4248		}
4249		// bold
4250		if (strpos($tempstyle, 'B') !== false) {
4251			$style .= 'B';
4252		}
4253		// oblique
4254		if (strpos($tempstyle, 'I') !== false) {
4255			$style .= 'I';
4256		}
4257		$bistyle = $style;
4258		$fontkey = $family.$style;
4259		$font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : '');
4260		$fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
4261		// check if the font has been already added
4262		$fb = $this->getFontBuffer($fontkey);
4263		if ($fb !== false) {
4264			if ($this->inxobj) {
4265				// we are inside an XObject template
4266				$this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i'];
4267			}
4268			return $fontdata;
4269		}
4270		// get specified font directory (if any)
4271		$fontdir = false;
4272		if (!TCPDF_STATIC::empty_string($fontfile)) {
4273			$fontdir = dirname($fontfile);
4274			if (TCPDF_STATIC::empty_string($fontdir) OR ($fontdir == '.')) {
4275				$fontdir = '';
4276			} else {
4277				$fontdir .= '/';
4278			}
4279		}
4280		// true when the font style variation is missing
4281		$missing_style = false;
4282		// search and include font file
4283		if (TCPDF_STATIC::empty_string($fontfile) OR (!@TCPDF_STATIC::file_exists($fontfile))) {
4284			// build a standard filenames for specified font
4285			$tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
4286			$fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
4287			if (TCPDF_STATIC::empty_string($fontfile)) {
4288				$missing_style = true;
4289				// try to remove the style part
4290				$tmp_fontfile = str_replace(' ', '', $family).'.php';
4291				$fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
4292			}
4293		}
4294		// include font file
4295		if (!TCPDF_STATIC::empty_string($fontfile) AND (@TCPDF_STATIC::file_exists($fontfile))) {
4296			include($fontfile);
4297		} else {
4298			$this->Error('Could not include font definition file: '.$family.'');
4299		}
4300		// check font parameters
4301		if ((!isset($type)) OR (!isset($cw))) {
4302			$this->Error('The font definition file has a bad format: '.$fontfile.'');
4303		}
4304		// SET default parameters
4305		if (!isset($file) OR TCPDF_STATIC::empty_string($file)) {
4306			$file = '';
4307		}
4308		if (!isset($enc) OR TCPDF_STATIC::empty_string($enc)) {
4309			$enc = '';
4310		}
4311		if (!isset($cidinfo) OR TCPDF_STATIC::empty_string($cidinfo)) {
4312			$cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
4313			$cidinfo['uni2cid'] = array();
4314		}
4315		if (!isset($ctg) OR TCPDF_STATIC::empty_string($ctg)) {
4316			$ctg = '';
4317		}
4318		if (!isset($desc) OR TCPDF_STATIC::empty_string($desc)) {
4319			$desc = array();
4320		}
4321		if (!isset($up) OR TCPDF_STATIC::empty_string($up)) {
4322			$up = -100;
4323		}
4324		if (!isset($ut) OR TCPDF_STATIC::empty_string($ut)) {
4325			$ut = 50;
4326		}
4327		if (!isset($cw) OR TCPDF_STATIC::empty_string($cw)) {
4328			$cw = array();
4329		}
4330		if (!isset($dw) OR TCPDF_STATIC::empty_string($dw)) {
4331			// set default width
4332			if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
4333				$dw = $desc['MissingWidth'];
4334			} elseif (isset($cw[32])) {
4335				$dw = $cw[32];
4336			} else {
4337				$dw = 600;
4338			}
4339		}
4340		++$this->numfonts;
4341		if ($type == 'core') {
4342			$name = $this->CoreFonts[$fontkey];
4343			$subset = false;
4344		} elseif (($type == 'TrueType') OR ($type == 'Type1')) {
4345			$subset = false;
4346		} elseif ($type == 'TrueTypeUnicode') {
4347			$enc = 'Identity-H';
4348		} elseif ($type == 'cidfont0') {
4349			if ($this->pdfa_mode) {
4350				$this->Error('All fonts must be embedded in PDF/A mode!');
4351			}
4352		} else {
4353			$this->Error('Unknow font type: '.$type.'');
4354		}
4355		// set name if unset
4356		if (!isset($name) OR empty($name)) {
4357			$name = $fontkey;
4358		}
4359		// create artificial font style variations if missing (only works with non-embedded fonts)
4360		if (($type != 'core') AND $missing_style) {
4361			// style variations
4362			$styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
4363			$name .= $styles[$bistyle];
4364			// artificial bold
4365			if (strpos($bistyle, 'B') !== false) {
4366				if (isset($desc['StemV'])) {
4367					// from normal to bold
4368					$desc['StemV'] = round($desc['StemV'] * 1.75);
4369				} else {
4370					// bold
4371					$desc['StemV'] = 123;
4372				}
4373			}
4374			// artificial italic
4375			if (strpos($bistyle, 'I') !== false) {
4376				if (isset($desc['ItalicAngle'])) {
4377					$desc['ItalicAngle'] -= 11;
4378				} else {
4379					$desc['ItalicAngle'] = -11;
4380				}
4381				if (isset($desc['Flags'])) {
4382					$desc['Flags'] |= 64; //bit 7
4383				} else {
4384					$desc['Flags'] = 64;
4385				}
4386			}
4387		}
4388		// check if the array of characters bounding boxes is defined
4389		if (!isset($cbbox)) {
4390			$cbbox = array();
4391		}
4392		// initialize subsetchars
4393		$subsetchars = array_fill(0, 255, true);
4394		$this->setFontBuffer($fontkey, array('fontkey' => $fontkey, 'i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'cbbox' => $cbbox, 'dw' => $dw, 'enc' => $enc, 'cidinfo' => $cidinfo, 'file' => $file, 'ctg' => $ctg, 'subset' => $subset, 'subsetchars' => $subsetchars));
4395		if ($this->inxobj) {
4396			// we are inside an XObject template
4397			$this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts;
4398		}
4399		if (isset($diff) AND (!empty($diff))) {
4400			//Search existing encodings
4401			$d = 0;
4402			$nb = count($this->diffs);
4403			for ($i=1; $i <= $nb; ++$i) {
4404				if ($this->diffs[$i] == $diff) {
4405					$d = $i;
4406					break;
4407				}
4408			}
4409			if ($d == 0) {
4410				$d = $nb + 1;
4411				$this->diffs[$d] = $diff;
4412			}
4413			$this->setFontSubBuffer($fontkey, 'diff', $d);
4414		}
4415		if (!TCPDF_STATIC::empty_string($file)) {
4416			if (!isset($this->FontFiles[$file])) {
4417				if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
4418					$this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
4419				} elseif ($type != 'core') {
4420					$this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
4421				}
4422			} else {
4423				// update fontkeys that are sharing this font file
4424				$this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset);
4425				if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) {
4426					$this->FontFiles[$file]['fontkeys'][] = $fontkey;
4427				}
4428			}
4429		}
4430		return $fontdata;
4431	}
4432
4433	/**
4434	 * Sets the font used to print character strings.
4435	 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
4436	 * The method can be called before the first page is created and the font is retained from page to page.
4437	 * If you just wish to change the current font size, it is simpler to call SetFontSize().
4438	 * 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 />
4439	 * @param $family (string) 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.
4440	 * @param $style (string) 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 through</li><li>O: overline</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.
4441	 * @param $size (float) 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
4442	 * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
4443	 * @param $subset (mixed) if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.
4444	 * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
4445	 * @author Nicola Asuni
4446	 * @public
4447	 * @since 1.0
4448	 * @see AddFont(), SetFontSize()
4449	 */
4450	public function SetFont($family, $style='', $size=null, $fontfile='', $subset='default', $out=true) {
4451		//Select a font; size given in points
4452		if ($size === null) {
4453			$size = $this->FontSizePt;
4454		}
4455		if ($size < 0) {
4456			$size = 0;
4457		}
4458		// try to add font (if not already added)
4459		$fontdata = $this->AddFont($family, $style, $fontfile, $subset);
4460		$this->FontFamily = $fontdata['family'];
4461		$this->FontStyle = $fontdata['style'];
4462		if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
4463			// save subset chars of the previous font
4464			$this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
4465		}
4466		$this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
4467		$this->SetFontSize($size, $out);
4468	}
4469
4470	/**
4471	 * Defines the size of the current font.
4472	 * @param $size (float) The font size in points.
4473	 * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
4474	 * @public
4475	 * @since 1.0
4476	 * @see SetFont()
4477	 */
4478	public function SetFontSize($size, $out=true) {
4479		$size = (float)$size;
4480		// font size in points
4481		$this->FontSizePt = $size;
4482		// font size in user units
4483		$this->FontSize = $size / $this->k;
4484		// calculate some font metrics
4485		if (isset($this->CurrentFont['desc']['FontBBox'])) {
4486			$bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
4487			$font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
4488		} else {
4489			$font_height = $size * 1.219;
4490		}
4491		if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
4492			$font_ascent = ($this->CurrentFont['desc']['Ascent'] * $size / 1000);
4493		}
4494		if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) {
4495			$font_descent = (- $this->CurrentFont['desc']['Descent'] * $size / 1000);
4496		}
4497		if (!isset($font_ascent) AND !isset($font_descent)) {
4498			// core font
4499			$font_ascent = 0.76 * $font_height;
4500			$font_descent = $font_height - $font_ascent;
4501		} elseif (!isset($font_descent)) {
4502			$font_descent = $font_height - $font_ascent;
4503		} elseif (!isset($font_ascent)) {
4504			$font_ascent = $font_height - $font_descent;
4505		}
4506		$this->FontAscent = ($font_ascent / $this->k);
4507		$this->FontDescent = ($font_descent / $this->k);
4508		if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i'])) AND ($this->state == 2)) {
4509			$this->_out(sprintf('BT /F%d %F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
4510		}
4511	}
4512
4513	/**
4514	 * Returns the bounding box of the current font in user units.
4515	 * @return array
4516	 * @public
4517	 * @since 5.9.152 (2012-03-23)
4518	 */
4519	public function getFontBBox() {
4520		$fbbox = array();
4521		if (isset($this->CurrentFont['desc']['FontBBox'])) {
4522			$tmpbbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
4523			$fbbox = array_map(array($this,'getAbsFontMeasure'), $tmpbbox);
4524		} else {
4525			// Find max width
4526			if (isset($this->CurrentFont['desc']['MaxWidth'])) {
4527				$maxw = $this->getAbsFontMeasure(intval($this->CurrentFont['desc']['MaxWidth']));
4528			} else {
4529				$maxw = 0;
4530				if (isset($this->CurrentFont['desc']['MissingWidth'])) {
4531					$maxw = max($maxw, $this->CurrentFont['desc']['MissingWidth']);
4532				}
4533				if (isset($this->CurrentFont['desc']['AvgWidth'])) {
4534					$maxw = max($maxw, $this->CurrentFont['desc']['AvgWidth']);
4535				}
4536				if (isset($this->CurrentFont['dw'])) {
4537					$maxw = max($maxw, $this->CurrentFont['dw']);
4538				}
4539				foreach ($this->CurrentFont['cw'] as $char => $w) {
4540					$maxw = max($maxw, $w);
4541				}
4542				if ($maxw == 0) {
4543					$maxw = 600;
4544				}
4545				$maxw = $this->getAbsFontMeasure($maxw);
4546			}
4547			$fbbox = array(0, (0 - $this->FontDescent), $maxw, $this->FontAscent);
4548		}
4549		return $fbbox;
4550	}
4551
4552	/**
4553	 * Convert a relative font measure into absolute value.
4554	 * @param $s (int) Font measure.
4555	 * @return float Absolute measure.
4556	 * @since 5.9.186 (2012-09-13)
4557	 */
4558	public function getAbsFontMeasure($s) {
4559		return ($s * $this->FontSize / 1000);
4560	}
4561
4562	/**
4563	 * Returns the glyph bounding box of the specified character in the current font in user units.
4564	 * @param $char (int) Input character code.
4565	 * @return mixed array(xMin, yMin, xMax, yMax) or FALSE if not defined.
4566	 * @since 5.9.186 (2012-09-13)
4567	 */
4568	public function getCharBBox($char) {
4569		$c = intval($char);
4570		if (isset($this->CurrentFont['cw'][$c])) {
4571			// glyph is defined ... use zero width & height for glyphs without outlines
4572			$result = array(0,0,0,0);
4573			if (isset($this->CurrentFont['cbbox'][$c])) {
4574				$result = $this->CurrentFont['cbbox'][$c];
4575			}
4576			return array_map(array($this,'getAbsFontMeasure'), $result);
4577		}
4578		return false;
4579	}
4580
4581	/**
4582	 * Return the font descent value
4583	 * @param $font (string) font name
4584	 * @param $style (string) font style
4585	 * @param $size (float) The size (in points)
4586	 * @return int font descent
4587	 * @public
4588	 * @author Nicola Asuni
4589	 * @since 4.9.003 (2010-03-30)
4590	 */
4591	public function getFontDescent($font, $style='', $size=0) {
4592		$fontdata = $this->AddFont($font, $style);
4593		$fontinfo = $this->getFontBuffer($fontdata['fontkey']);
4594		if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
4595			$descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
4596		} else {
4597			$descent = (1.219 * 0.24 * $size);
4598		}
4599		return ($descent / $this->k);
4600	}
4601
4602	/**
4603	 * Return the font ascent value.
4604	 * @param $font (string) font name
4605	 * @param $style (string) font style
4606	 * @param $size (float) The size (in points)
4607	 * @return int font ascent
4608	 * @public
4609	 * @author Nicola Asuni
4610	 * @since 4.9.003 (2010-03-30)
4611	 */
4612	public function getFontAscent($font, $style='', $size=0) {
4613		$fontdata = $this->AddFont($font, $style);
4614		$fontinfo = $this->getFontBuffer($fontdata['fontkey']);
4615		if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
4616			$ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
4617		} else {
4618			$ascent = 1.219 * 0.76 * $size;
4619		}
4620		return ($ascent / $this->k);
4621	}
4622
4623	/**
4624	 * Return true in the character is present in the specified font.
4625	 * @param $char (mixed) Character to check (integer value or string)
4626	 * @param $font (string) Font name (family name).
4627	 * @param $style (string) Font style.
4628	 * @return (boolean) true if the char is defined, false otherwise.
4629	 * @public
4630	 * @since 5.9.153 (2012-03-28)
4631	 */
4632	public function isCharDefined($char, $font='', $style='') {
4633		if (is_string($char)) {
4634			// get character code
4635			$char = TCPDF_FONTS::UTF8StringToArray($char, $this->isunicode, $this->CurrentFont);
4636			$char = $char[0];
4637		}
4638		if (TCPDF_STATIC::empty_string($font)) {
4639			if (TCPDF_STATIC::empty_string($style)) {
4640				return (isset($this->CurrentFont['cw'][intval($char)]));
4641			}
4642			$font = $this->FontFamily;
4643		}
4644		$fontdata = $this->AddFont($font, $style);
4645		$fontinfo = $this->getFontBuffer($fontdata['fontkey']);
4646		return (isset($fontinfo['cw'][intval($char)]));
4647	}
4648
4649	/**
4650	 * Replace missing font characters on selected font with specified substitutions.
4651	 * @param $text (string) Text to process.
4652	 * @param $font (string) Font name (family name).
4653	 * @param $style (string) Font style.
4654	 * @param $subs (array) Array of possible character substitutions. The key is the character to check (integer value) and the value is a single intege value or an array of possible substitutes.
4655	 * @return (string) Processed text.
4656	 * @public
4657	 * @since 5.9.153 (2012-03-28)
4658	 */
4659	public function replaceMissingChars($text, $font='', $style='', $subs=array()) {
4660		if (empty($subs)) {
4661			return $text;
4662		}
4663		if (TCPDF_STATIC::empty_string($font)) {
4664			$font = $this->FontFamily;
4665		}
4666		$fontdata = $this->AddFont($font, $style);
4667		$fontinfo = $this->getFontBuffer($fontdata['fontkey']);
4668		$uniarr = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
4669		foreach ($uniarr as $k => $chr) {
4670			if (!isset($fontinfo['cw'][$chr])) {
4671				// this character is missing on the selected font
4672				if (isset($subs[$chr])) {
4673					// we have available substitutions
4674					if (is_array($subs[$chr])) {
4675						foreach($subs[$chr] as $s) {
4676							if (isset($fontinfo['cw'][$s])) {
4677								$uniarr[$k] = $s;
4678								break;
4679							}
4680						}
4681					} elseif (isset($fontinfo['cw'][$subs[$chr]])) {
4682						$uniarr[$k] = $subs[$chr];
4683					}
4684				}
4685			}
4686		}
4687		return TCPDF_FONTS::UniArrSubString(TCPDF_FONTS::UTF8ArrayToUniArray($uniarr, $this->isunicode));
4688	}
4689
4690	/**
4691	 * Defines the default monospaced font.
4692	 * @param $font (string) Font name.
4693	 * @public
4694	 * @since 4.5.025
4695	 */
4696	public function SetDefaultMonospacedFont($font) {
4697		$this->default_monospaced_font = $font;
4698	}
4699
4700	/**
4701	 * 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 />
4702	 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
4703	 * @public
4704	 * @since 1.5
4705	 * @see Cell(), Write(), Image(), Link(), SetLink()
4706	 */
4707	public function AddLink() {
4708		// create a new internal link
4709		$n = count($this->links) + 1;
4710		$this->links[$n] = array('p' => 0, 'y' => 0, 'f' => false);
4711		return $n;
4712	}
4713
4714	/**
4715	 * Defines the page and position a link points to.
4716	 * @param $link (int) The link identifier returned by AddLink()
4717	 * @param $y (float) Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
4718	 * @param $page (int) Number of target page; -1 indicates the current page (default value). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
4719	 * @public
4720	 * @since 1.5
4721	 * @see AddLink()
4722	 */
4723	public function SetLink($link, $y=0, $page=-1) {
4724		$fixed = false;
4725		if (!empty($page) AND ($page[0] == '*')) {
4726			$page = intval(substr($page, 1));
4727			// this page number will not be changed when moving/add/deleting pages
4728			$fixed = true;
4729		}
4730		if ($page < 0) {
4731			$page = $this->page;
4732		}
4733		if ($y == -1) {
4734			$y = $this->y;
4735		}
4736		$this->links[$link] = array('p' => $page, 'y' => $y, 'f' => $fixed);
4737	}
4738
4739	/**
4740	 * Puts a link on a rectangular area of the page.
4741	 * 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.
4742	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
4743	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
4744	 * @param $w (float) Width of the rectangle
4745	 * @param $h (float) Height of the rectangle
4746	 * @param $link (mixed) URL or identifier returned by AddLink()
4747	 * @param $spaces (int) number of spaces on the text to link
4748	 * @public
4749	 * @since 1.5
4750	 * @see AddLink(), Annotation(), Cell(), Write(), Image()
4751	 */
4752	public function Link($x, $y, $w, $h, $link, $spaces=0) {
4753		$this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
4754	}
4755
4756	/**
4757	 * Puts a markup annotation on a rectangular area of the page.
4758	 * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
4759	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
4760	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
4761	 * @param $w (float) Width of the rectangle
4762	 * @param $h (float) Height of the rectangle
4763	 * @param $text (string) annotation text or alternate content
4764	 * @param $opt (array) array of options (see section 8.4 of PDF reference 1.7).
4765	 * @param $spaces (int) number of spaces on the text to link
4766	 * @public
4767	 * @since 4.0.018 (2008-08-06)
4768	 */
4769	public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
4770		if ($this->inxobj) {
4771			// store parameters for later use on template
4772			$this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
4773			return;
4774		}
4775		if ($x === '') {
4776			$x = $this->x;
4777		}
4778		if ($y === '') {
4779			$y = $this->y;
4780		}
4781		// check page for no-write regions and adapt page margins if necessary
4782		list($x, $y) = $this->checkPageRegions($h, $x, $y);
4783		// recalculate coordinates to account for graphic transformations
4784		if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) {
4785			for ($i=$this->transfmatrix_key; $i > 0; --$i) {
4786				$maxid = count($this->transfmatrix[$i]) - 1;
4787				for ($j=$maxid; $j >= 0; --$j) {
4788					$ctm = $this->transfmatrix[$i][$j];
4789					if (isset($ctm['a'])) {
4790						$x = $x * $this->k;
4791						$y = ($this->h - $y) * $this->k;
4792						$w = $w * $this->k;
4793						$h = $h * $this->k;
4794						// top left
4795						$xt = $x;
4796						$yt = $y;
4797						$x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
4798						$y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
4799						// top right
4800						$xt = $x + $w;
4801						$yt = $y;
4802						$x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
4803						$y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
4804						// bottom left
4805						$xt = $x;
4806						$yt = $y - $h;
4807						$x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
4808						$y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
4809						// bottom right
4810						$xt = $x + $w;
4811						$yt = $y - $h;
4812						$x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
4813						$y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
4814						// new coordinates (rectangle area)
4815						$x = min($x1, $x2, $x3, $x4);
4816						$y = max($y1, $y2, $y3, $y4);
4817						$w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
4818						$h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
4819						$x = $x / $this->k;
4820						$y = $this->h - ($y / $this->k);
4821					}
4822				}
4823			}
4824		}
4825		if ($this->page <= 0) {
4826			$page = 1;
4827		} else {
4828			$page = $this->page;
4829		}
4830		if (!isset($this->PageAnnots[$page])) {
4831			$this->PageAnnots[$page] = array();
4832		}
4833		$this->PageAnnots[$page][] = array('n' => ++$this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
4834		if (!$this->pdfa_mode || ($this->pdfa_mode && $this->pdfa_version == 3)) {
4835			if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!TCPDF_STATIC::empty_string($opt['FS']))
4836				AND (@TCPDF_STATIC::file_exists($opt['FS']) OR TCPDF_STATIC::isValidURL($opt['FS']))
4837				AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
4838				$this->embeddedfiles[basename($opt['FS'])] = array('f' => ++$this->n, 'n' => ++$this->n, 'file' => $opt['FS']);
4839			}
4840		}
4841		// Add widgets annotation's icons
4842		if (isset($opt['mk']['i']) AND @TCPDF_STATIC::file_exists($opt['mk']['i'])) {
4843			$this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
4844		}
4845		if (isset($opt['mk']['ri']) AND @TCPDF_STATIC::file_exists($opt['mk']['ri'])) {
4846			$this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
4847		}
4848		if (isset($opt['mk']['ix']) AND @TCPDF_STATIC::file_exists($opt['mk']['ix'])) {
4849			$this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
4850		}
4851	}
4852
4853	/**
4854	 * Embedd the attached files.
4855	 * @since 4.4.000 (2008-12-07)
4856	 * @protected
4857	 * @see Annotation()
4858	 */
4859	protected function _putEmbeddedFiles() {
4860		if ($this->pdfa_mode && $this->pdfa_version != 3)  {
4861			// embedded files are not allowed in PDF/A mode version 1 and 2
4862			return;
4863		}
4864		reset($this->embeddedfiles);
4865		foreach ($this->embeddedfiles as $filename => $filedata) {
4866			$data = TCPDF_STATIC::fileGetContents($filedata['file']);
4867			if ($data !== FALSE) {
4868				$rawsize = strlen($data);
4869				if ($rawsize > 0) {
4870					// update name tree
4871					$this->efnames[$filename] = $filedata['f'].' 0 R';
4872					// embedded file specification object
4873					$out = $this->_getobj($filedata['f'])."\n";
4874					$out .= '<</Type /Filespec /F '.$this->_datastring($filename, $filedata['f']);
4875					$out .= ' /UF '.$this->_datastring($filename, $filedata['f']);
4876					$out .= ' /AFRelationship /Source';
4877					$out .= ' /EF <</F '.$filedata['n'].' 0 R>> >>';
4878					$out .= "\n".'endobj';
4879					$this->_out($out);
4880					// embedded file object
4881					$filter = '';
4882					if ($this->compress) {
4883						$data = gzcompress($data);
4884						$filter = ' /Filter /FlateDecode';
4885					}
4886
4887					if ($this->pdfa_version == 3) {
4888						$filter = ' /Subtype /text#2Fxml';
4889					}
4890
4891					$stream = $this->_getrawstream($data, $filedata['n']);
4892					$out = $this->_getobj($filedata['n'])."\n";
4893					$out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' /Params <</Size '.$rawsize.'>> >>';
4894					$out .= ' stream'."\n".$stream."\n".'endstream';
4895					$out .= "\n".'endobj';
4896					$this->_out($out);
4897				}
4898			}
4899		}
4900	}
4901
4902	/**
4903	 * Prints a text cell at the specified position.
4904	 * This method allows to place a string precisely on the page.
4905	 * @param $x (float) Abscissa of the cell origin
4906	 * @param $y (float) Ordinate of the cell origin
4907	 * @param $txt (string) String to print
4908	 * @param $fstroke (int) outline size in user units (false = disable)
4909	 * @param $fclip (boolean) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
4910	 * @param $ffill (boolean) if true fills the text
4911	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
4912	 * @param $ln (int) 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.
4913	 * @param $align (string) 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>
4914	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
4915	 * @param $link (mixed) URL or identifier returned by AddLink().
4916	 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
4917	 * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
4918	 * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li><li>B : cell bottom</li></ul>
4919	 * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
4920	 * @param $rtloff (boolean) if true uses the page top-left corner as origin of axis for $x and $y initial position.
4921	 * @public
4922	 * @since 1.0
4923	 * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
4924	 */
4925	public function Text($x, $y, $txt, $fstroke=false, $fclip=false, $ffill=true, $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M', $rtloff=false) {
4926		$textrendermode = $this->textrendermode;
4927		$textstrokewidth = $this->textstrokewidth;
4928		$this->setTextRenderingMode($fstroke, $ffill, $fclip);
4929		$this->SetXY($x, $y, $rtloff);
4930		$this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
4931		// restore previous rendering mode
4932		$this->textrendermode = $textrendermode;
4933		$this->textstrokewidth = $textstrokewidth;
4934	}
4935
4936	/**
4937	 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
4938	 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
4939	 * This method is called automatically and should not be called directly by the application.
4940	 * @return boolean
4941	 * @public
4942	 * @since 1.4
4943	 * @see SetAutoPageBreak()
4944	 */
4945	public function AcceptPageBreak() {
4946		if ($this->num_columns > 1) {
4947			// multi column mode
4948			if ($this->current_column < ($this->num_columns - 1)) {
4949				// go to next column
4950				$this->selectColumn($this->current_column + 1);
4951			} elseif ($this->AutoPageBreak) {
4952				// add a new page
4953				$this->AddPage();
4954				// set first column
4955				$this->selectColumn(0);
4956			}
4957			// avoid page breaking from checkPageBreak()
4958			return false;
4959		}
4960		return $this->AutoPageBreak;
4961	}
4962
4963	/**
4964	 * Add page if needed.
4965	 * @param $h (float) Cell height. Default value: 0.
4966	 * @param $y (mixed) starting y position, leave empty for current position.
4967	 * @param $addpage (boolean) if true add a page, otherwise only return the true/false state
4968	 * @return boolean true in case of page break, false otherwise.
4969	 * @since 3.2.000 (2008-07-01)
4970	 * @protected
4971	 */
4972	protected function checkPageBreak($h=0, $y='', $addpage=true) {
4973		if (TCPDF_STATIC::empty_string($y)) {
4974			$y = $this->y;
4975		}
4976		$current_page = $this->page;
4977		if ((($y + $h) > $this->PageBreakTrigger) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
4978			if ($addpage) {
4979				//Automatic page break
4980				$x = $this->x;
4981				$this->AddPage($this->CurOrientation);
4982				$this->y = $this->tMargin;
4983				$oldpage = $this->page - 1;
4984				if ($this->rtl) {
4985					if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
4986						$this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
4987					} else {
4988						$this->x = $x;
4989					}
4990				} else {
4991					if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
4992						$this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
4993					} else {
4994						$this->x = $x;
4995					}
4996				}
4997			}
4998			return true;
4999		}
5000		if ($current_page != $this->page) {
5001			// account for columns mode
5002			return true;
5003		}
5004		return false;
5005	}
5006
5007	/**
5008	 * 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 />
5009	 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
5010	 * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
5011	 * @param $h (float) Cell height. Default value: 0.
5012	 * @param $txt (string) String to print. Default value: empty string.
5013	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
5014	 * @param $ln (int) 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.
5015	 * @param $align (string) 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>
5016	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
5017	 * @param $link (mixed) URL or identifier returned by AddLink().
5018	 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
5019	 * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
5020	 * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul>
5021	 * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
5022	 * @public
5023	 * @since 1.0
5024	 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
5025	 */
5026	public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') {
5027		$prev_cell_margin = $this->cell_margin;
5028		$prev_cell_padding = $this->cell_padding;
5029		$this->adjustCellPadding($border);
5030		if (!$ignore_min_height) {
5031			$min_cell_height = $this->getCellHeight($this->FontSize);
5032			if ($h < $min_cell_height) {
5033				$h = $min_cell_height;
5034			}
5035		}
5036		$this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);
5037		// apply text shadow if enabled
5038		if ($this->txtshadow['enabled']) {
5039			// save data
5040			$x = $this->x;
5041			$y = $this->y;
5042			$bc = $this->bgcolor;
5043			$fc = $this->fgcolor;
5044			$sc = $this->strokecolor;
5045			$alpha = $this->alpha;
5046			// print shadow
5047			$this->x += $this->txtshadow['depth_w'];
5048			$this->y += $this->txtshadow['depth_h'];
5049			$this->SetFillColorArray($this->txtshadow['color']);
5050			$this->SetTextColorArray($this->txtshadow['color']);
5051			$this->SetDrawColorArray($this->txtshadow['color']);
5052			if ($this->txtshadow['opacity'] != $alpha['CA']) {
5053				$this->setAlpha($this->txtshadow['opacity'], $this->txtshadow['blend_mode']);
5054			}
5055			if ($this->state == 2) {
5056				$this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
5057			}
5058			//restore data
5059			$this->x = $x;
5060			$this->y = $y;
5061			$this->SetFillColorArray($bc);
5062			$this->SetTextColorArray($fc);
5063			$this->SetDrawColorArray($sc);
5064			if ($this->txtshadow['opacity'] != $alpha['CA']) {
5065				$this->setAlpha($alpha['CA'], $alpha['BM'], $alpha['ca'], $alpha['AIS']);
5066			}
5067		}
5068		if ($this->state == 2) {
5069			$this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
5070		}
5071		$this->cell_padding = $prev_cell_padding;
5072		$this->cell_margin = $prev_cell_margin;
5073	}
5074
5075	/**
5076	 * 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 />
5077	 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
5078	 * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
5079	 * @param $h (float) Cell height. Default value: 0.
5080	 * @param $txt (string) String to print. Default value: empty string.
5081	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
5082	 * @param $ln (int) 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.
5083	 * @param $align (string) 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>
5084	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
5085	 * @param $link (mixed) URL or identifier returned by AddLink().
5086	 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
5087	 * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
5088	 * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul>
5089	 * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>M : middle</li><li>B : bottom</li></ul>
5090	 * @return string containing cell code
5091	 * @protected
5092	 * @since 1.0
5093	 * @see Cell()
5094	 */
5095	protected function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') {
5096		// replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
5097		$txt = str_replace(TCPDF_FONTS::unichr(160, $this->isunicode), ' ', $txt);
5098		$prev_cell_margin = $this->cell_margin;
5099		$prev_cell_padding = $this->cell_padding;
5100		$txt = TCPDF_STATIC::removeSHY($txt, $this->isunicode);
5101		$rs = ''; //string to be returned
5102		$this->adjustCellPadding($border);
5103		if (!$ignore_min_height) {
5104			$min_cell_height = $this->getCellHeight($this->FontSize);
5105			if ($h < $min_cell_height) {
5106				$h = $min_cell_height;
5107			}
5108		}
5109		$k = $this->k;
5110		// check page for no-write regions and adapt page margins if necessary
5111		list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
5112		if ($this->rtl) {
5113			$x = $this->x - $this->cell_margin['R'];
5114		} else {
5115			$x = $this->x + $this->cell_margin['L'];
5116		}
5117		$y = $this->y + $this->cell_margin['T'];
5118		$prev_font_stretching = $this->font_stretching;
5119		$prev_font_spacing = $this->font_spacing;
5120		// cell vertical alignment
5121		switch ($calign) {
5122			case 'A': {
5123				// font top
5124				switch ($valign) {
5125					case 'T': {
5126						// top
5127						$y -= $this->cell_padding['T'];
5128						break;
5129					}
5130					case 'B': {
5131						// bottom
5132						$y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);
5133						break;
5134					}
5135					default:
5136					case 'C':
5137					case 'M': {
5138						// center
5139						$y -= (($h - $this->FontAscent - $this->FontDescent) / 2);
5140						break;
5141					}
5142				}
5143				break;
5144			}
5145			case 'L': {
5146				// font baseline
5147				switch ($valign) {
5148					case 'T': {
5149						// top
5150						$y -= ($this->cell_padding['T'] + $this->FontAscent);
5151						break;
5152					}
5153					case 'B': {
5154						// bottom
5155						$y -= ($h - $this->cell_padding['B'] - $this->FontDescent);
5156						break;
5157					}
5158					default:
5159					case 'C':
5160					case 'M': {
5161						// center
5162						$y -= (($h + $this->FontAscent - $this->FontDescent) / 2);
5163						break;
5164					}
5165				}
5166				break;
5167			}
5168			case 'D': {
5169				// font bottom
5170				switch ($valign) {
5171					case 'T': {
5172						// top
5173						$y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);
5174						break;
5175					}
5176					case 'B': {
5177						// bottom
5178						$y -= ($h - $this->cell_padding['B']);
5179						break;
5180					}
5181					default:
5182					case 'C':
5183					case 'M': {
5184						// center
5185						$y -= (($h + $this->FontAscent + $this->FontDescent) / 2);
5186						break;
5187					}
5188				}
5189				break;
5190			}
5191			case 'B': {
5192				// cell bottom
5193				$y -= $h;
5194				break;
5195			}
5196			case 'C':
5197			case 'M': {
5198				// cell center
5199				$y -= ($h / 2);
5200				break;
5201			}
5202			default:
5203			case 'T': {
5204				// cell top
5205				break;
5206			}
5207		}
5208		// text vertical alignment
5209		switch ($valign) {
5210			case 'T': {
5211				// top
5212				$yt = $y + $this->cell_padding['T'];
5213				break;
5214			}
5215			case 'B': {
5216				// bottom
5217				$yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;
5218				break;
5219			}
5220			default:
5221			case 'C':
5222			case 'M': {
5223				// center
5224				$yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);
5225				break;
5226			}
5227		}
5228		$basefonty = $yt + $this->FontAscent;
5229		if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
5230			if ($this->rtl) {
5231				$w = $x - $this->lMargin;
5232			} else {
5233				$w = $this->w - $this->rMargin - $x;
5234			}
5235		}
5236		$s = '';
5237		// fill and borders
5238		if (is_string($border) AND (strlen($border) == 4)) {
5239			// full border
5240			$border = 1;
5241		}
5242		if ($fill OR ($border == 1)) {
5243			if ($fill) {
5244				$op = ($border == 1) ? 'B' : 'f';
5245			} else {
5246				$op = 'S';
5247			}
5248			if ($this->rtl) {
5249				$xk = (($x - $w) * $k);
5250			} else {
5251				$xk = ($x * $k);
5252			}
5253			$s .= sprintf('%F %F %F %F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);
5254		}
5255		// draw borders
5256		$s .= $this->getCellBorder($x, $y, $w, $h, $border);
5257		if ($txt != '') {
5258			$txt2 = $txt;
5259			if ($this->isunicode) {
5260				if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5261					$txt2 = TCPDF_FONTS::UTF8ToLatin1($txt2, $this->isunicode, $this->CurrentFont);
5262				} else {
5263					$unicode = TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont); // array of UTF-8 unicode values
5264					$unicode = TCPDF_FONTS::utf8Bidi($unicode, '', $this->tmprtl, $this->isunicode, $this->CurrentFont);
5265					// replace thai chars (if any)
5266					if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {
5267						// number of chars
5268						$numchars = count($unicode);
5269						// po pla, for far, for fan
5270						$longtail = array(0x0e1b, 0x0e1d, 0x0e1f);
5271						// do chada, to patak
5272						$lowtail = array(0x0e0e, 0x0e0f);
5273						// mai hun arkad, sara i, sara ii, sara ue, sara uee
5274						$upvowel = array(0x0e31, 0x0e34, 0x0e35, 0x0e36, 0x0e37);
5275						// mai ek, mai tho, mai tri, mai chattawa, karan
5276						$tonemark = array(0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c);
5277						// sara u, sara uu, pinthu
5278						$lowvowel = array(0x0e38, 0x0e39, 0x0e3a);
5279						$output = array();
5280						for ($i = 0; $i < $numchars; $i++) {
5281							if (($unicode[$i] >= 0x0e00) && ($unicode[$i] <= 0x0e5b)) {
5282								$ch0 = $unicode[$i];
5283								$ch1 = ($i > 0) ? $unicode[($i - 1)] : 0;
5284								$ch2 = ($i > 1) ? $unicode[($i - 2)] : 0;
5285								$chn = ($i < ($numchars - 1)) ? $unicode[($i + 1)] : 0;
5286								if (in_array($ch0, $tonemark)) {
5287									if ($chn == 0x0e33) {
5288										// sara um
5289										if (in_array($ch1, $longtail)) {
5290											// tonemark at upper left
5291											$output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
5292										} else {
5293											// tonemark at upper right (normal position)
5294											$output[] = $ch0;
5295										}
5296									} elseif (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $lowvowel))) {
5297										// tonemark at lower left
5298										$output[] = $this->replaceChar($ch0, (0xf705 + $ch0 - 0x0e48));
5299									} elseif (in_array($ch1, $upvowel)) {
5300										if (in_array($ch2, $longtail)) {
5301											// tonemark at upper left
5302											$output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
5303										} else {
5304											// tonemark at upper right (normal position)
5305											$output[] = $ch0;
5306										}
5307									} else {
5308										// tonemark at lower right
5309										$output[] = $this->replaceChar($ch0, (0xf70a + $ch0 - 0x0e48));
5310									}
5311								} elseif (($ch0 == 0x0e33) AND (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $tonemark)))) {
5312									// add lower left nikhahit and sara aa
5313									if ($this->isCharDefined(0xf711) AND $this->isCharDefined(0x0e32)) {
5314										$output[] = 0xf711;
5315										$this->CurrentFont['subsetchars'][0xf711] = true;
5316										$output[] = 0x0e32;
5317										$this->CurrentFont['subsetchars'][0x0e32] = true;
5318									} else {
5319										$output[] = $ch0;
5320									}
5321								} elseif (in_array($ch1, $longtail)) {
5322									if ($ch0 == 0x0e31) {
5323										// lower left mai hun arkad
5324										$output[] = $this->replaceChar($ch0, 0xf710);
5325									} elseif (in_array($ch0, $upvowel)) {
5326										// lower left
5327										$output[] = $this->replaceChar($ch0, (0xf701 + $ch0 - 0x0e34));
5328									} elseif ($ch0 == 0x0e47) {
5329										// lower left mai tai koo
5330										$output[] = $this->replaceChar($ch0, 0xf712);
5331									} else {
5332										// normal character
5333										$output[] = $ch0;
5334									}
5335								} elseif (in_array($ch1, $lowtail) AND in_array($ch0, $lowvowel)) {
5336									// lower vowel
5337									$output[] = $this->replaceChar($ch0, (0xf718 + $ch0 - 0x0e38));
5338								} elseif (($ch0 == 0x0e0d) AND in_array($chn, $lowvowel)) {
5339									// yo ying without lower part
5340									$output[] = $this->replaceChar($ch0, 0xf70f);
5341								} elseif (($ch0 == 0x0e10) AND in_array($chn, $lowvowel)) {
5342									// tho santan without lower part
5343									$output[] = $this->replaceChar($ch0, 0xf700);
5344								} else {
5345									$output[] = $ch0;
5346								}
5347							} else {
5348								// non-thai character
5349								$output[] = $unicode[$i];
5350							}
5351						}
5352						$unicode = $output;
5353						// update font subsetchars
5354						$this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
5355					} // end of K_THAI_TOPCHARS
5356					$txt2 = TCPDF_FONTS::arrUTF8ToUTF16BE($unicode, false);
5357				}
5358			}
5359			$txt2 = TCPDF_STATIC::_escape($txt2);
5360			// get current text width (considering general font stretching and spacing)
5361			$txwidth = $this->GetStringWidth($txt);
5362			$width = $txwidth;
5363			// check for stretch mode
5364			if ($stretch > 0) {
5365				// calculate ratio between cell width and text width
5366				if ($width <= 0) {
5367					$ratio = 1;
5368				} else {
5369					$ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);
5370				}
5371				// check if stretching is required
5372				if (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {
5373					// the text will be stretched to fit cell width
5374					if ($stretch > 2) {
5375						// set new character spacing
5376						$this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));
5377					} else {
5378						// set new horizontal stretching
5379						$this->font_stretching *= $ratio;
5380					}
5381					// recalculate text width (the text fills the entire cell)
5382					$width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
5383					// reset alignment
5384					$align = '';
5385				}
5386			}
5387			if ($this->font_stretching != 100) {
5388				// apply font stretching
5389				$rs .= sprintf('BT %F Tz ET ', $this->font_stretching);
5390			}
5391			if ($this->font_spacing != 0) {
5392				// increase/decrease font spacing
5393				$rs .= sprintf('BT %F Tc ET ', ($this->font_spacing * $this->k));
5394			}
5395			if ($this->ColorFlag AND ($this->textrendermode < 4)) {
5396				$s .= 'q '.$this->TextColor.' ';
5397			}
5398			// rendering mode
5399			$s .= sprintf('BT %d Tr %F w ET ', $this->textrendermode, ($this->textstrokewidth * $this->k));
5400			// count number of spaces
5401			$ns = substr_count($txt, chr(32));
5402			// Justification
5403			$spacewidth = 0;
5404			if (($align == 'J') AND ($ns > 0)) {
5405				if ($this->isUnicodeFont()) {
5406					// get string width without spaces
5407					$width = $this->GetStringWidth(str_replace(' ', '', $txt));
5408					// calculate average space width
5409					$spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / ($this->FontSize?$this->FontSize:1);
5410					if ($this->font_stretching != 100) {
5411						// word spacing is affected by stretching
5412						$spacewidth /= ($this->font_stretching / 100);
5413					}
5414					// set word position to be used with TJ operator
5415					$txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacewidth).' (', $txt2);
5416					$unicode_justification = true;
5417				} else {
5418					// get string width
5419					$width = $txwidth;
5420					// new space width
5421					$spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;
5422					if ($this->font_stretching != 100) {
5423						// word spacing (Tw) is affected by stretching
5424						$spacewidth /= ($this->font_stretching / 100);
5425					}
5426					// set word spacing
5427					$rs .= sprintf('BT %F Tw ET ', $spacewidth);
5428				}
5429				$width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
5430			}
5431			// replace carriage return characters
5432			$txt2 = str_replace("\r", ' ', $txt2);
5433			switch ($align) {
5434				case 'C': {
5435					$dx = ($w - $width) / 2;
5436					break;
5437				}
5438				case 'R': {
5439					if ($this->rtl) {
5440						$dx = $this->cell_padding['R'];
5441					} else {
5442						$dx = $w - $width - $this->cell_padding['R'];
5443					}
5444					break;
5445				}
5446				case 'L': {
5447					if ($this->rtl) {
5448						$dx = $w - $width - $this->cell_padding['L'];
5449					} else {
5450						$dx = $this->cell_padding['L'];
5451					}
5452					break;
5453				}
5454				case 'J':
5455				default: {
5456					if ($this->rtl) {
5457						$dx = $this->cell_padding['R'];
5458					} else {
5459						$dx = $this->cell_padding['L'];
5460					}
5461					break;
5462				}
5463			}
5464			if ($this->rtl) {
5465				$xdx = $x - $dx - $width;
5466			} else {
5467				$xdx = $x + $dx;
5468			}
5469			$xdk = $xdx * $k;
5470			// print text
5471			$s .= sprintf('BT %F %F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
5472			if (isset($uniblock)) {
5473				// print overlapping characters as separate string
5474				$xshift = 0; // horizontal shift
5475				$ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);
5476				$spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));
5477				foreach ($uniblock as $uk => $uniarr) {
5478					if (($uk % 2) == 0) {
5479						// x space to skip
5480						if ($spacewidth != 0) {
5481							// justification shift
5482							$xshift += (count(array_keys($uniarr, 32)) * $spw);
5483						}
5484						$xshift += $this->GetArrStringWidth($uniarr); // + shift justification
5485					} else {
5486						// character to print
5487						$topchr = TCPDF_FONTS::arrUTF8ToUTF16BE($uniarr, false);
5488						$topchr = TCPDF_STATIC::_escape($topchr);
5489						$s .= sprintf(' BT %F %F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);
5490					}
5491				}
5492			}
5493			if ($this->underline) {
5494				$s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
5495			}
5496			if ($this->linethrough) {
5497				$s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
5498			}
5499			if ($this->overline) {
5500				$s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
5501			}
5502			if ($this->ColorFlag AND ($this->textrendermode < 4)) {
5503				$s .= ' Q';
5504			}
5505			if ($link) {
5506				$this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);
5507			}
5508		}
5509		// output cell
5510		if ($s) {
5511			// output cell
5512			$rs .= $s;
5513			if ($this->font_spacing != 0) {
5514				// reset font spacing mode
5515				$rs .= ' BT 0 Tc ET';
5516			}
5517			if ($this->font_stretching != 100) {
5518				// reset font stretching mode
5519				$rs .= ' BT 100 Tz ET';
5520			}
5521		}
5522		// reset word spacing
5523		if (!$this->isUnicodeFont() AND ($align == 'J')) {
5524			$rs .= ' BT 0 Tw ET';
5525		}
5526		// reset stretching and spacing
5527		$this->font_stretching = $prev_font_stretching;
5528		$this->font_spacing = $prev_font_spacing;
5529		$this->lasth = $h;
5530		if ($ln > 0) {
5531			//Go to the beginning of the next line
5532			$this->y = $y + $h + $this->cell_margin['B'];
5533			if ($ln == 1) {
5534				if ($this->rtl) {
5535					$this->x = $this->w - $this->rMargin;
5536				} else {
5537					$this->x = $this->lMargin;
5538				}
5539			}
5540		} else {
5541			// go left or right by case
5542			if ($this->rtl) {
5543				$this->x = $x - $w - $this->cell_margin['L'];
5544			} else {
5545				$this->x = $x + $w + $this->cell_margin['R'];
5546			}
5547		}
5548		$gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
5549		$rs = $gstyles.$rs;
5550		$this->cell_padding = $prev_cell_padding;
5551		$this->cell_margin = $prev_cell_margin;
5552		return $rs;
5553	}
5554
5555	/**
5556	 * Replace a char if is defined on the current font.
5557	 * @param $oldchar (int) Integer code (unicode) of the character to replace.
5558	 * @param $newchar (int) Integer code (unicode) of the new character.
5559	 * @return int the replaced char or the old char in case the new char i not defined
5560	 * @protected
5561	 * @since 5.9.167 (2012-06-22)
5562	 */
5563	protected function replaceChar($oldchar, $newchar) {
5564		if ($this->isCharDefined($newchar)) {
5565			// add the new char on the subset list
5566			$this->CurrentFont['subsetchars'][$newchar] = true;
5567			// return the new character
5568			return $newchar;
5569		}
5570		// return the old char
5571		return $oldchar;
5572	}
5573
5574	/**
5575	 * Returns the code to draw the cell border
5576	 * @param $x (float) X coordinate.
5577	 * @param $y (float) Y coordinate.
5578	 * @param $w (float) Cell width.
5579	 * @param $h (float) Cell height.
5580	 * @param $brd (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
5581	 * @return string containing cell border code
5582	 * @protected
5583	 * @see SetLineStyle()
5584	 * @since 5.7.000 (2010-08-02)
5585	 */
5586	protected function getCellBorder($x, $y, $w, $h, $brd) {
5587		$s = ''; // string to be returned
5588		if (empty($brd)) {
5589			return $s;
5590		}
5591		if ($brd == 1) {
5592			$brd = array('LRTB' => true);
5593		}
5594		// calculate coordinates for border
5595		$k = $this->k;
5596		if ($this->rtl) {
5597			$xeL = ($x - $w) * $k;
5598			$xeR = $x * $k;
5599		} else {
5600			$xeL = $x * $k;
5601			$xeR = ($x + $w) * $k;
5602		}
5603		$yeL = (($this->h - ($y + $h)) * $k);
5604		$yeT = (($this->h - $y) * $k);
5605		$xeT = $xeL;
5606		$xeB = $xeR;
5607		$yeR = $yeT;
5608		$yeB = $yeL;
5609		if (is_string($brd)) {
5610			// convert string to array
5611			$slen = strlen($brd);
5612			$newbrd = array();
5613			for ($i = 0; $i < $slen; ++$i) {
5614				$newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
5615			}
5616			$brd = $newbrd;
5617		}
5618		if (isset($brd['mode'])) {
5619			$mode = $brd['mode'];
5620			unset($brd['mode']);
5621		} else {
5622			$mode = 'normal';
5623		}
5624		foreach ($brd as $border => $style) {
5625			if (is_array($style) AND !empty($style)) {
5626				// apply border style
5627				$prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' ';
5628				$s .= $this->SetLineStyle($style, true)."\n";
5629			}
5630			switch ($mode) {
5631				case 'ext': {
5632					$off = (($this->LineWidth / 2) * $k);
5633					$xL = $xeL - $off;
5634					$xR = $xeR + $off;
5635					$yT = $yeT + $off;
5636					$yL = $yeL - $off;
5637					$xT = $xL;
5638					$xB = $xR;
5639					$yR = $yT;
5640					$yB = $yL;
5641					$w += $this->LineWidth;
5642					$h += $this->LineWidth;
5643					break;
5644				}
5645				case 'int': {
5646					$off = ($this->LineWidth / 2) * $k;
5647					$xL = $xeL + $off;
5648					$xR = $xeR - $off;
5649					$yT = $yeT - $off;
5650					$yL = $yeL + $off;
5651					$xT = $xL;
5652					$xB = $xR;
5653					$yR = $yT;
5654					$yB = $yL;
5655					$w -= $this->LineWidth;
5656					$h -= $this->LineWidth;
5657					break;
5658				}
5659				case 'normal':
5660				default: {
5661					$xL = $xeL;
5662					$xT = $xeT;
5663					$xB = $xeB;
5664					$xR = $xeR;
5665					$yL = $yeL;
5666					$yT = $yeT;
5667					$yB = $yeB;
5668					$yR = $yeR;
5669					break;
5670				}
5671			}
5672			// draw borders by case
5673			if (strlen($border) == 4) {
5674				$s .= sprintf('%F %F %F %F re S ', $xT, $yT, ($w * $k), (-$h * $k));
5675			} elseif (strlen($border) == 3) {
5676				if (strpos($border,'B') === false) { // LTR
5677					$s .= sprintf('%F %F m ', $xL, $yL);
5678					$s .= sprintf('%F %F l ', $xT, $yT);
5679					$s .= sprintf('%F %F l ', $xR, $yR);
5680					$s .= sprintf('%F %F l ', $xB, $yB);
5681					$s .= 'S ';
5682				} elseif (strpos($border,'L') === false) { // TRB
5683					$s .= sprintf('%F %F m ', $xT, $yT);
5684					$s .= sprintf('%F %F l ', $xR, $yR);
5685					$s .= sprintf('%F %F l ', $xB, $yB);
5686					$s .= sprintf('%F %F l ', $xL, $yL);
5687					$s .= 'S ';
5688				} elseif (strpos($border,'T') === false) { // RBL
5689					$s .= sprintf('%F %F m ', $xR, $yR);
5690					$s .= sprintf('%F %F l ', $xB, $yB);
5691					$s .= sprintf('%F %F l ', $xL, $yL);
5692					$s .= sprintf('%F %F l ', $xT, $yT);
5693					$s .= 'S ';
5694				} elseif (strpos($border,'R') === false) { // BLT
5695					$s .= sprintf('%F %F m ', $xB, $yB);
5696					$s .= sprintf('%F %F l ', $xL, $yL);
5697					$s .= sprintf('%F %F l ', $xT, $yT);
5698					$s .= sprintf('%F %F l ', $xR, $yR);
5699					$s .= 'S ';
5700				}
5701			} elseif (strlen($border) == 2) {
5702				if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
5703					$s .= sprintf('%F %F m ', $xL, $yL);
5704					$s .= sprintf('%F %F l ', $xT, $yT);
5705					$s .= sprintf('%F %F l ', $xR, $yR);
5706					$s .= 'S ';
5707				} elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
5708					$s .= sprintf('%F %F m ', $xT, $yT);
5709					$s .= sprintf('%F %F l ', $xR, $yR);
5710					$s .= sprintf('%F %F l ', $xB, $yB);
5711					$s .= 'S ';
5712				} elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
5713					$s .= sprintf('%F %F m ', $xR, $yR);
5714					$s .= sprintf('%F %F l ', $xB, $yB);
5715					$s .= sprintf('%F %F l ', $xL, $yL);
5716					$s .= 'S ';
5717				} elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
5718					$s .= sprintf('%F %F m ', $xB, $yB);
5719					$s .= sprintf('%F %F l ', $xL, $yL);
5720					$s .= sprintf('%F %F l ', $xT, $yT);
5721					$s .= 'S ';
5722				} elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
5723					$s .= sprintf('%F %F m ', $xL, $yL);
5724					$s .= sprintf('%F %F l ', $xT, $yT);
5725					$s .= 'S ';
5726					$s .= sprintf('%F %F m ', $xR, $yR);
5727					$s .= sprintf('%F %F l ', $xB, $yB);
5728					$s .= 'S ';
5729				} elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
5730					$s .= sprintf('%F %F m ', $xT, $yT);
5731					$s .= sprintf('%F %F l ', $xR, $yR);
5732					$s .= 'S ';
5733					$s .= sprintf('%F %F m ', $xB, $yB);
5734					$s .= sprintf('%F %F l ', $xL, $yL);
5735					$s .= 'S ';
5736				}
5737			} else { // strlen($border) == 1
5738				if (strpos($border,'L') !== false) { // L
5739					$s .= sprintf('%F %F m ', $xL, $yL);
5740					$s .= sprintf('%F %F l ', $xT, $yT);
5741					$s .= 'S ';
5742				} elseif (strpos($border,'T') !== false) { // T
5743					$s .= sprintf('%F %F m ', $xT, $yT);
5744					$s .= sprintf('%F %F l ', $xR, $yR);
5745					$s .= 'S ';
5746				} elseif (strpos($border,'R') !== false) { // R
5747					$s .= sprintf('%F %F m ', $xR, $yR);
5748					$s .= sprintf('%F %F l ', $xB, $yB);
5749					$s .= 'S ';
5750				} elseif (strpos($border,'B') !== false) { // B
5751					$s .= sprintf('%F %F m ', $xB, $yB);
5752					$s .= sprintf('%F %F l ', $xL, $yL);
5753					$s .= 'S ';
5754				}
5755			}
5756			if (is_array($style) AND !empty($style)) {
5757				// reset border style to previous value
5758				$s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n";
5759			}
5760		}
5761		return $s;
5762	}
5763
5764	/**
5765	 * This method allows printing text with line breaks.
5766	 * 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 />
5767	 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
5768	 * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
5769	 * @param $h (float) Cell minimum height. The cell extends automatically if needed.
5770	 * @param $txt (string) String to print
5771	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
5772	 * @param $align (string) 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>
5773	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
5774	 * @param $ln (int) 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>
5775	 * @param $x (float) x position in user units
5776	 * @param $y (float) y position in user units
5777	 * @param $reseth (boolean) if true reset the last cell height (default true).
5778	 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
5779	 * @param $ishtml (boolean) INTERNAL USE ONLY -- set to true if $txt is HTML content (default = false). Never set this parameter to true, use instead writeHTMLCell() or writeHTML() methods.
5780	 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
5781	 * @param $maxh (float) maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature. This feature works only when $ishtml=false.
5782	 * @param $valign (string) Vertical alignment of text (requires $maxh = $h > 0). Possible values are:<ul><li>T: TOP</li><li>M: middle</li><li>B: bottom</li></ul>. This feature works only when $ishtml=false and the cell must fit in a single page.
5783	 * @param $fitcell (boolean) if true attempt to fit all the text within the cell by reducing the font size (do not work in HTML mode). $maxh must be greater than 0 and equal to $h.
5784	 * @return int Return the number of cells or 1 for html mode.
5785	 * @public
5786	 * @since 1.3
5787	 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
5788	 */
5789	public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $valign='T', $fitcell=false) {
5790		$prev_cell_margin = $this->cell_margin;
5791		$prev_cell_padding = $this->cell_padding;
5792		// adjust internal padding
5793		$this->adjustCellPadding($border);
5794		$mc_padding = $this->cell_padding;
5795		$mc_margin = $this->cell_margin;
5796		$this->cell_padding['T'] = 0;
5797		$this->cell_padding['B'] = 0;
5798		$this->setCellMargins(0, 0, 0, 0);
5799		if (TCPDF_STATIC::empty_string($this->lasth) OR $reseth) {
5800			// reset row height
5801			$this->resetLastH();
5802		}
5803		if (!TCPDF_STATIC::empty_string($y)) {
5804			$this->SetY($y); // set y in order to convert negative y values to positive ones
5805		}
5806		$y = $this->GetY();
5807		$resth = 0;
5808		if (($h > 0) AND $this->inPageBody() AND (($y + $h + $mc_margin['T'] + $mc_margin['B']) > $this->PageBreakTrigger)) {
5809			// spit cell in more pages/columns
5810			$newh = ($this->PageBreakTrigger - $y);
5811			$resth = ($h - $newh); // cell to be printed on the next page/column
5812			$h = $newh;
5813		}
5814		// get current page number
5815		$startpage = $this->page;
5816		// get current column
5817		$startcolumn = $this->current_column;
5818		if (!TCPDF_STATIC::empty_string($x)) {
5819			$this->SetX($x);
5820		} else {
5821			$x = $this->GetX();
5822		}
5823		// check page for no-write regions and adapt page margins if necessary
5824		list($x, $y) = $this->checkPageRegions(0, $x, $y);
5825		// apply margins
5826		$oy = $y + $mc_margin['T'];
5827		if ($this->rtl) {
5828			$ox = ($this->w - $x - $mc_margin['R']);
5829		} else {
5830			$ox = ($x + $mc_margin['L']);
5831		}
5832		$this->x = $ox;
5833		$this->y = $oy;
5834		// set width
5835		if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
5836			if ($this->rtl) {
5837				$w = ($this->x - $this->lMargin - $mc_margin['L']);
5838			} else {
5839				$w = ($this->w - $this->x - $this->rMargin - $mc_margin['R']);
5840			}
5841		}
5842		// store original margin values
5843		$lMargin = $this->lMargin;
5844		$rMargin = $this->rMargin;
5845		if ($this->rtl) {
5846			$this->rMargin = ($this->w - $this->x);
5847			$this->lMargin = ($this->x - $w);
5848		} else {
5849			$this->lMargin = ($this->x);
5850			$this->rMargin = ($this->w - $this->x - $w);
5851		}
5852		$this->clMargin = $this->lMargin;
5853		$this->crMargin = $this->rMargin;
5854		if ($autopadding) {
5855			// add top padding
5856			$this->y += $mc_padding['T'];
5857		}
5858		if ($ishtml) { // ******* Write HTML text
5859			$this->writeHTML($txt, true, false, $reseth, true, $align);
5860			$nl = 1;
5861		} else { // ******* Write simple text
5862			$prev_FontSizePt = $this->FontSizePt;
5863			if ($fitcell) {
5864				// ajust height values
5865				$tobottom = ($this->h - $this->y - $this->bMargin - $this->cell_padding['T'] - $this->cell_padding['B']);
5866				$h = $maxh = max(min($h, $tobottom), min($maxh, $tobottom));
5867			}
5868			// vertical alignment
5869			if ($maxh > 0) {
5870				// get text height
5871				$text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
5872				if ($fitcell AND ($text_height > $maxh) AND ($this->FontSizePt > 1)) {
5873					// try to reduce font size to fit text on cell (use a quick search algorithm)
5874					$fmin = 1;
5875					$fmax = $this->FontSizePt;
5876					$diff_epsilon = (1 / $this->k); // one point (min resolution)
5877					$maxit = (2 * min(100, max(10, intval($fmax)))); // max number of iterations
5878					while ($maxit >= 0) {
5879						$fmid = (($fmax + $fmin) / 2);
5880						$this->SetFontSize($fmid, false);
5881						$this->resetLastH();
5882						$text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
5883						$diff = ($maxh - $text_height);
5884						if ($diff >= 0) {
5885							if ($diff <= $diff_epsilon) {
5886								break;
5887							}
5888							$fmin = $fmid;
5889						} else {
5890							$fmax = $fmid;
5891						}
5892						--$maxit;
5893					}
5894					if ($maxit < 0) {
5895						// premature exit, we get the minimum font value to fit the cell
5896						$this->SetFontSize($fmin);
5897						$this->resetLastH();
5898						$text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
5899					} else {
5900						$this->SetFontSize($fmid);
5901						$this->resetLastH();
5902					}
5903				}
5904				if ($text_height < $maxh) {
5905					if ($valign == 'M') {
5906						// text vertically centered
5907						$this->y += (($maxh - $text_height) / 2);
5908					} elseif ($valign == 'B') {
5909						// text vertically aligned on bottom
5910						$this->y += ($maxh - $text_height);
5911					}
5912				}
5913			}
5914			$nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
5915			if ($fitcell) {
5916				// restore font size
5917				$this->SetFontSize($prev_FontSizePt);
5918			}
5919		}
5920		if ($autopadding) {
5921			// add bottom padding
5922			$this->y += $mc_padding['B'];
5923		}
5924		// Get end-of-text Y position
5925		$currentY = $this->y;
5926		// get latest page number
5927		$endpage = $this->page;
5928		if ($resth > 0) {
5929			$skip = ($endpage - $startpage);
5930			$tmpresth = $resth;
5931			while ($tmpresth > 0) {
5932				if ($skip <= 0) {
5933					// add a page (or trig AcceptPageBreak() for multicolumn mode)
5934					$this->checkPageBreak($this->PageBreakTrigger + 1);
5935				}
5936				if ($this->num_columns > 1) {
5937					$tmpresth -= ($this->h - $this->y - $this->bMargin);
5938				} else {
5939					$tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
5940				}
5941				--$skip;
5942			}
5943			$currentY = $this->y;
5944			$endpage = $this->page;
5945		}
5946		// get latest column
5947		$endcolumn = $this->current_column;
5948		if ($this->num_columns == 0) {
5949			$this->num_columns = 1;
5950		}
5951		// disable page regions check
5952		$check_page_regions = $this->check_page_regions;
5953		$this->check_page_regions = false;
5954		// get border modes
5955		$border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
5956		$border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
5957		$border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
5958		// design borders around HTML cells.
5959		for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
5960			$ccode = '';
5961			$this->setPage($page);
5962			if ($this->num_columns < 2) {
5963				// single-column mode
5964				$this->SetX($x);
5965				$this->y = $this->tMargin;
5966			}
5967			// account for margin changes
5968			if ($page > $startpage) {
5969				if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
5970					$this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
5971				} elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
5972					$this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
5973				}
5974			}
5975			if ($startpage == $endpage) {
5976				// single page
5977				for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
5978					if ($column != $this->current_column) {
5979						$this->selectColumn($column);
5980					}
5981					if ($this->rtl) {
5982						$this->x -= $mc_margin['R'];
5983					} else {
5984						$this->x += $mc_margin['L'];
5985					}
5986					if ($startcolumn == $endcolumn) { // single column
5987						$cborder = $border;
5988						$h = max($h, ($currentY - $oy));
5989						$this->y = $oy;
5990					} elseif ($column == $startcolumn) { // first column
5991						$cborder = $border_start;
5992						$this->y = $oy;
5993						$h = $this->h - $this->y - $this->bMargin;
5994					} elseif ($column == $endcolumn) { // end column
5995						$cborder = $border_end;
5996						$h = $currentY - $this->y;
5997						if ($resth > $h) {
5998							$h = $resth;
5999						}
6000					} else { // middle column
6001						$cborder = $border_middle;
6002						$h = $this->h - $this->y - $this->bMargin;
6003						$resth -= $h;
6004					}
6005					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6006				} // end for each column
6007			} elseif ($page == $startpage) { // first page
6008				for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
6009					if ($column != $this->current_column) {
6010						$this->selectColumn($column);
6011					}
6012					if ($this->rtl) {
6013						$this->x -= $mc_margin['R'];
6014					} else {
6015						$this->x += $mc_margin['L'];
6016					}
6017					if ($column == $startcolumn) { // first column
6018						$cborder = $border_start;
6019						$this->y = $oy;
6020						$h = $this->h - $this->y - $this->bMargin;
6021					} else { // middle column
6022						$cborder = $border_middle;
6023						$h = $this->h - $this->y - $this->bMargin;
6024						$resth -= $h;
6025					}
6026					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6027				} // end for each column
6028			} elseif ($page == $endpage) { // last page
6029				for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
6030					if ($column != $this->current_column) {
6031						$this->selectColumn($column);
6032					}
6033					if ($this->rtl) {
6034						$this->x -= $mc_margin['R'];
6035					} else {
6036						$this->x += $mc_margin['L'];
6037					}
6038					if ($column == $endcolumn) {
6039						// end column
6040						$cborder = $border_end;
6041						$h = $currentY - $this->y;
6042						if ($resth > $h) {
6043							$h = $resth;
6044						}
6045					} else {
6046						// middle column
6047						$cborder = $border_middle;
6048						$h = $this->h - $this->y - $this->bMargin;
6049						$resth -= $h;
6050					}
6051					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6052				} // end for each column
6053			} else { // middle page
6054				for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
6055					$this->selectColumn($column);
6056					if ($this->rtl) {
6057						$this->x -= $mc_margin['R'];
6058					} else {
6059						$this->x += $mc_margin['L'];
6060					}
6061					$cborder = $border_middle;
6062					$h = $this->h - $this->y - $this->bMargin;
6063					$resth -= $h;
6064					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6065				} // end for each column
6066			}
6067			if ($cborder OR $fill) {
6068				$offsetlen = strlen($ccode);
6069				// draw border and fill
6070				if ($this->inxobj) {
6071					// we are inside an XObject template
6072					if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
6073						$pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
6074						$pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
6075						$this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
6076					} else {
6077						$pagemark = $this->xobjects[$this->xobjid]['intmrk'];
6078						$this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
6079					}
6080					$pagebuff = $this->xobjects[$this->xobjid]['outdata'];
6081					$pstart = substr($pagebuff, 0, $pagemark);
6082					$pend = substr($pagebuff, $pagemark);
6083					$this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
6084				} else {
6085					if (end($this->transfmrk[$this->page]) !== false) {
6086						$pagemarkkey = key($this->transfmrk[$this->page]);
6087						$pagemark = $this->transfmrk[$this->page][$pagemarkkey];
6088						$this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
6089					} elseif ($this->InFooter) {
6090						$pagemark = $this->footerpos[$this->page];
6091						$this->footerpos[$this->page] += $offsetlen;
6092					} else {
6093						$pagemark = $this->intmrk[$this->page];
6094						$this->intmrk[$this->page] += $offsetlen;
6095					}
6096					$pagebuff = $this->getPageBuffer($this->page);
6097					$pstart = substr($pagebuff, 0, $pagemark);
6098					$pend = substr($pagebuff, $pagemark);
6099					$this->setPageBuffer($this->page, $pstart.$ccode.$pend);
6100				}
6101			}
6102		} // end for each page
6103		// restore page regions check
6104		$this->check_page_regions = $check_page_regions;
6105		// Get end-of-cell Y position
6106		$currentY = $this->GetY();
6107		// restore previous values
6108		if ($this->num_columns > 1) {
6109			$this->selectColumn();
6110		} else {
6111			// restore original margins
6112			$this->lMargin = $lMargin;
6113			$this->rMargin = $rMargin;
6114			if ($this->page > $startpage) {
6115				// check for margin variations between pages (i.e. booklet mode)
6116				$dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$startpage]['olm']);
6117				$dr = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$startpage]['orm']);
6118				if (($dl != 0) OR ($dr != 0)) {
6119					$this->lMargin += $dl;
6120					$this->rMargin += $dr;
6121				}
6122			}
6123		}
6124		if ($ln > 0) {
6125			//Go to the beginning of the next line
6126			$this->SetY($currentY + $mc_margin['B']);
6127			if ($ln == 2) {
6128				$this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
6129			}
6130		} else {
6131			// go left or right by case
6132			$this->setPage($startpage);
6133			$this->y = $y;
6134			$this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
6135		}
6136		$this->setContentMark();
6137		$this->cell_padding = $prev_cell_padding;
6138		$this->cell_margin = $prev_cell_margin;
6139		$this->clMargin = $this->lMargin;
6140		$this->crMargin = $this->rMargin;
6141		return $nl;
6142	}
6143
6144	/**
6145	 * This method return the estimated number of lines for print a simple text string using Multicell() method.
6146	 * @param $txt (string) String for calculating his height
6147	 * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
6148	 * @param $reseth (boolean) if true reset the last cell height (default false).
6149	 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
6150	 * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
6151	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
6152	 * @return float Return the minimal height needed for multicell method for printing the $txt param.
6153	 * @author Alexander Escalona Fern\E1ndez, Nicola Asuni
6154	 * @public
6155	 * @since 4.5.011
6156	 */
6157	public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
6158		if ($txt === NULL) {
6159			return 0;
6160		}
6161		if ($txt === '') {
6162			// empty string
6163			return 1;
6164		}
6165		// adjust internal padding
6166		$prev_cell_padding = $this->cell_padding;
6167		$prev_lasth = $this->lasth;
6168		if (is_array($cellpadding)) {
6169			$this->cell_padding = $cellpadding;
6170		}
6171		$this->adjustCellPadding($border);
6172		if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
6173			if ($this->rtl) {
6174				$w = $this->x - $this->lMargin;
6175			} else {
6176				$w = $this->w - $this->rMargin - $this->x;
6177			}
6178		}
6179		$wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
6180		if ($reseth) {
6181			// reset row height
6182			$this->resetLastH();
6183		}
6184		$lines = 1;
6185		$sum = 0;
6186		$chars = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont), $txt, $this->tmprtl, $this->isunicode, $this->CurrentFont);
6187		$charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
6188		$length = count($chars);
6189		$lastSeparator = -1;
6190		for ($i = 0; $i < $length; ++$i) {
6191			$c = $chars[$i];
6192			$charWidth = $charsWidth[$i];
6193			if (($c != 160)
6194					AND (($c == 173)
6195						OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
6196						OR (($c == 45)
6197							AND ($i > 0) AND ($i < ($length - 1))
6198							AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i - 1)], $this->isunicode))
6199							AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
6200						)
6201					)
6202				) {
6203				$lastSeparator = $i;
6204			}
6205			if ((($sum + $charWidth) > $wmax) OR ($c == 10)) {
6206				++$lines;
6207				if ($c == 10) {
6208					$lastSeparator = -1;
6209					$sum = 0;
6210				} elseif ($lastSeparator != -1) {
6211					$i = $lastSeparator;
6212					$lastSeparator = -1;
6213					$sum = 0;
6214				} else {
6215					$sum = $charWidth;
6216				}
6217			} else {
6218				$sum += $charWidth;
6219			}
6220		}
6221		if ($chars[($length - 1)] == 10) {
6222			--$lines;
6223		}
6224		$this->cell_padding = $prev_cell_padding;
6225		$this->lasth = $prev_lasth;
6226		return $lines;
6227	}
6228
6229	/**
6230	 * This method return the estimated height needed for printing a simple text string using the Multicell() method.
6231	 * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
6232	 * @pre
6233	 *  // store current object
6234	 *  $pdf->startTransaction();
6235	 *  // store starting values
6236	 *  $start_y = $pdf->GetY();
6237	 *  $start_page = $pdf->getPage();
6238	 *  // call your printing functions with your parameters
6239	 *  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6240	 *  $pdf->MultiCell($w=0, $h=0, $txt, $border=1, $align='L', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0);
6241	 *  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6242	 *  // get the new Y
6243	 *  $end_y = $pdf->GetY();
6244	 *  $end_page = $pdf->getPage();
6245	 *  // calculate height
6246	 *  $height = 0;
6247	 *  if ($end_page == $start_page) {
6248	 *  	$height = $end_y - $start_y;
6249	 *  } else {
6250	 *  	for ($page=$start_page; $page <= $end_page; ++$page) {
6251	 *  		$this->setPage($page);
6252	 *  		if ($page == $start_page) {
6253	 *  			// first page
6254	 *  			$height += $this->h - $start_y - $this->bMargin;
6255	 *  		} elseif ($page == $end_page) {
6256	 *  			// last page
6257	 *  			$height += $end_y - $this->tMargin;
6258	 *  		} else {
6259	 *  			$height += $this->h - $this->tMargin - $this->bMargin;
6260	 *  		}
6261	 *  	}
6262	 *  }
6263	 *  // restore previous object
6264	 *  $pdf = $pdf->rollbackTransaction();
6265	 *
6266	 * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
6267	 * @param $txt (string) String for calculating his height
6268	 * @param $reseth (boolean) if true reset the last cell height (default false).
6269	 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
6270	 * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
6271	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
6272	 * @return float Return the minimal height needed for multicell method for printing the $txt param.
6273	 * @author Nicola Asuni, Alexander Escalona Fern\E1ndez
6274	 * @public
6275	 */
6276	public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
6277		// adjust internal padding
6278		$prev_cell_padding = $this->cell_padding;
6279		$prev_lasth = $this->lasth;
6280		if (is_array($cellpadding)) {
6281			$this->cell_padding = $cellpadding;
6282		}
6283		$this->adjustCellPadding($border);
6284		$lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
6285		$height = $this->getCellHeight(($lines * $this->FontSize), $autopadding);
6286		$this->cell_padding = $prev_cell_padding;
6287		$this->lasth = $prev_lasth;
6288		return $height;
6289	}
6290
6291	/**
6292	 * This method prints text from the current position.<br />
6293	 * @param $h (float) Line height
6294	 * @param $txt (string) String to print
6295	 * @param $link (mixed) URL or identifier returned by AddLink()
6296	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
6297	 * @param $align (string) 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>
6298	 * @param $ln (boolean) if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
6299	 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
6300	 * @param $firstline (boolean) if true prints only the first line and return the remaining string.
6301	 * @param $firstblock (boolean) if true the string is the starting of a line.
6302	 * @param $maxh (float) maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
6303	 * @param $wadj (float) first line width will be reduced by this amount (used in HTML mode).
6304	 * @param $margin (array) margin array of the parent container
6305	 * @return mixed Return the number of cells or the remaining string if $firstline = true.
6306	 * @public
6307	 * @since 1.5
6308	 */
6309	public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {
6310		// check page for no-write regions and adapt page margins if necessary
6311		list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
6312		if (strlen($txt) == 0) {
6313			// fix empty text
6314			$txt = ' ';
6315		}
6316		if ($margin === '') {
6317			// set default margins
6318			$margin = $this->cell_margin;
6319		}
6320		// remove carriage returns
6321		$s = str_replace("\r", '', $txt);
6322		// check if string contains arabic text
6323		if (preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $s)) {
6324			$arabic = true;
6325		} else {
6326			$arabic = false;
6327		}
6328		// check if string contains RTL text
6329		if ($arabic OR ($this->tmprtl == 'R') OR preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $s)) {
6330			$rtlmode = true;
6331		} else {
6332			$rtlmode = false;
6333		}
6334		// get a char width
6335		$chrwidth = $this->GetCharWidth(46); // dot character
6336		// get array of unicode values
6337		$chars = TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont);
6338		// calculate maximum width for a single character on string
6339		$chrw = $this->GetArrStringWidth($chars, '', '', 0, true);
6340		array_walk($chrw, array($this, 'getRawCharWidth'));
6341		$maxchwidth = max($chrw);
6342		// get array of chars
6343		$uchars = TCPDF_FONTS::UTF8ArrayToUniArray($chars, $this->isunicode);
6344		// get the number of characters
6345		$nb = count($chars);
6346		// replacement for SHY character (minus symbol)
6347		$shy_replacement = 45;
6348		$shy_replacement_char = TCPDF_FONTS::unichr($shy_replacement, $this->isunicode);
6349		// widht for SHY replacement
6350		$shy_replacement_width = $this->GetCharWidth($shy_replacement);
6351		// page width
6352		$pw = $w = $this->w - $this->lMargin - $this->rMargin;
6353		// calculate remaining line width ($w)
6354		if ($this->rtl) {
6355			$w = $this->x - $this->lMargin;
6356		} else {
6357			$w = $this->w - $this->rMargin - $this->x;
6358		}
6359		// max column width
6360		$wmax = ($w - $wadj);
6361		if (!$firstline) {
6362			$wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);
6363		}
6364		if ((!$firstline) AND (($chrwidth > $wmax) OR ($maxchwidth > $wmax))) {
6365			// the maximum width character do not fit on column
6366			return '';
6367		}
6368		// minimum row height
6369		$row_height = max($h, $this->getCellHeight($this->FontSize));
6370		// max Y
6371		$maxy = $this->y + $maxh - max($row_height, $h);
6372		$start_page = $this->page;
6373		$i = 0; // character position
6374		$j = 0; // current starting position
6375		$sep = -1; // position of the last blank space
6376		$prevsep = $sep; // previous separator
6377		$shy = false; // true if the last blank is a soft hypen (SHY)
6378		$prevshy = $shy; // previous shy mode
6379		$l = 0; // current string length
6380		$nl = 0; //number of lines
6381		$linebreak = false;
6382		$pc = 0; // previous character
6383		// for each character
6384		while ($i < $nb) {
6385			if (($maxh > 0) AND ($this->y > $maxy) ) {
6386				break;
6387			}
6388			//Get the current character
6389			$c = $chars[$i];
6390			if ($c == 10) { // 10 = "\n" = new line
6391				//Explicit line break
6392				if ($align == 'J') {
6393					if ($this->rtl) {
6394						$talign = 'R';
6395					} else {
6396						$talign = 'L';
6397					}
6398				} else {
6399					$talign = $align;
6400				}
6401				$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
6402				if ($firstline) {
6403					$startx = $this->x;
6404					$tmparr = array_slice($chars, $j, ($i - $j));
6405					if ($rtlmode) {
6406						$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
6407					}
6408					$linew = $this->GetArrStringWidth($tmparr);
6409					unset($tmparr);
6410					if ($this->rtl) {
6411						$this->endlinex = $startx - $linew;
6412					} else {
6413						$this->endlinex = $startx + $linew;
6414					}
6415					$w = $linew;
6416					$tmpcellpadding = $this->cell_padding;
6417					if ($maxh == 0) {
6418						$this->SetCellPadding(0);
6419					}
6420				}
6421				if ($firstblock AND $this->isRTLTextDir()) {
6422					$tmpstr = $this->stringRightTrim($tmpstr);
6423				}
6424				// Skip newlines at the beginning of a page or column
6425				if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {
6426					$this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
6427				}
6428				unset($tmpstr);
6429				if ($firstline) {
6430					$this->cell_padding = $tmpcellpadding;
6431					return (TCPDF_FONTS::UniArrSubString($uchars, $i));
6432				}
6433				++$nl;
6434				$j = $i + 1;
6435				$l = 0;
6436				$sep = -1;
6437				$prevsep = $sep;
6438				$shy = false;
6439				// account for margin changes
6440				if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
6441					$this->AcceptPageBreak();
6442					if ($this->rtl) {
6443						$this->x -= $margin['R'];
6444					} else {
6445						$this->x += $margin['L'];
6446					}
6447					$this->lMargin += $margin['L'];
6448					$this->rMargin += $margin['R'];
6449				}
6450				$w = $this->getRemainingWidth();
6451				$wmax = ($w - $this->cell_padding['L'] - $this->cell_padding['R']);
6452			} else {
6453				// 160 is the non-breaking space.
6454				// 173 is SHY (Soft Hypen).
6455				// \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
6456				// \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
6457				// \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
6458				if (($c != 160)
6459					AND (($c == 173)
6460						OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
6461						OR (($c == 45)
6462							AND ($i < ($nb - 1))
6463							AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($pc, $this->isunicode))
6464							AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
6465						)
6466					)
6467				) {
6468					// update last blank space position
6469					$prevsep = $sep;
6470					$sep = $i;
6471					// check if is a SHY
6472					if (($c == 173) OR ($c == 45)) {
6473						$prevshy = $shy;
6474						$shy = true;
6475						if ($pc == 45) {
6476							$tmp_shy_replacement_width = 0;
6477							$tmp_shy_replacement_char = '';
6478						} else {
6479							$tmp_shy_replacement_width = $shy_replacement_width;
6480							$tmp_shy_replacement_char = $shy_replacement_char;
6481						}
6482					} else {
6483						$shy = false;
6484					}
6485				}
6486				// update string length
6487				if ($this->isUnicodeFont() AND ($arabic)) {
6488					// with bidirectional algorithm some chars may be changed affecting the line length
6489					// *** very slow ***
6490					$l = $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl, $this->isunicode, $this->CurrentFont));
6491				} else {
6492					$l += $this->GetCharWidth($c);
6493				}
6494				if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) >= $wmax))) {
6495					if (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) {
6496						$sep = $prevsep;
6497						$shy = $prevshy;
6498					}
6499					// we have reached the end of column
6500					if ($sep == -1) {
6501						// check if the line was already started
6502						if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $this->cell_padding['R'] - $margin['R'] - $chrwidth)))
6503							OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $this->cell_padding['L'] + $margin['L'] + $chrwidth)))) {
6504							// print a void cell and go to next line
6505							$this->Cell($w, $h, '', 0, 1);
6506							$linebreak = true;
6507							if ($firstline) {
6508								return (TCPDF_FONTS::UniArrSubString($uchars, $j));
6509							}
6510						} else {
6511							// truncate the word because do not fit on column
6512							$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
6513							if ($firstline) {
6514								$startx = $this->x;
6515								$tmparr = array_slice($chars, $j, ($i - $j));
6516								if ($rtlmode) {
6517									$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
6518								}
6519								$linew = $this->GetArrStringWidth($tmparr);
6520								unset($tmparr);
6521								if ($this->rtl) {
6522									$this->endlinex = $startx - $linew;
6523								} else {
6524									$this->endlinex = $startx + $linew;
6525								}
6526								$w = $linew;
6527								$tmpcellpadding = $this->cell_padding;
6528								if ($maxh == 0) {
6529									$this->SetCellPadding(0);
6530								}
6531							}
6532							if ($firstblock AND $this->isRTLTextDir()) {
6533								$tmpstr = $this->stringRightTrim($tmpstr);
6534							}
6535							$this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
6536							unset($tmpstr);
6537							if ($firstline) {
6538								$this->cell_padding = $tmpcellpadding;
6539								return (TCPDF_FONTS::UniArrSubString($uchars, $i));
6540							}
6541							$j = $i;
6542							--$i;
6543						}
6544					} else {
6545						// word wrapping
6546						if ($this->rtl AND (!$firstblock) AND ($sep < $i)) {
6547							$endspace = 1;
6548						} else {
6549							$endspace = 0;
6550						}
6551						// check the length of the next string
6552						$strrest = TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace));
6553						$nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $this->stringTrim($strrest));
6554						if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
6555							// truncate the word because do not fit on a full page width
6556							$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
6557							if ($firstline) {
6558								$startx = $this->x;
6559								$tmparr = array_slice($chars, $j, ($i - $j));
6560								if ($rtlmode) {
6561									$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
6562								}
6563								$linew = $this->GetArrStringWidth($tmparr);
6564								unset($tmparr);
6565								if ($this->rtl) {
6566									$this->endlinex = ($startx - $linew);
6567								} else {
6568									$this->endlinex = ($startx + $linew);
6569								}
6570								$w = $linew;
6571								$tmpcellpadding = $this->cell_padding;
6572								if ($maxh == 0) {
6573									$this->SetCellPadding(0);
6574								}
6575							}
6576							if ($firstblock AND $this->isRTLTextDir()) {
6577								$tmpstr = $this->stringRightTrim($tmpstr);
6578							}
6579							$this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
6580							unset($tmpstr);
6581							if ($firstline) {
6582								$this->cell_padding = $tmpcellpadding;
6583								return (TCPDF_FONTS::UniArrSubString($uchars, $i));
6584							}
6585							$j = $i;
6586							--$i;
6587						} else {
6588							// word wrapping
6589							if ($shy) {
6590								// add hypen (minus symbol) at the end of the line
6591								$shy_width = $tmp_shy_replacement_width;
6592								if ($this->rtl) {
6593									$shy_char_left = $tmp_shy_replacement_char;
6594									$shy_char_right = '';
6595								} else {
6596									$shy_char_left = '';
6597									$shy_char_right = $tmp_shy_replacement_char;
6598								}
6599							} else {
6600								$shy_width = 0;
6601								$shy_char_left = '';
6602								$shy_char_right = '';
6603							}
6604							$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, ($sep + $endspace));
6605							if ($firstline) {
6606								$startx = $this->x;
6607								$tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));
6608								if ($rtlmode) {
6609									$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
6610								}
6611								$linew = $this->GetArrStringWidth($tmparr);
6612								unset($tmparr);
6613								if ($this->rtl) {
6614									$this->endlinex = $startx - $linew - $shy_width;
6615								} else {
6616									$this->endlinex = $startx + $linew + $shy_width;
6617								}
6618								$w = $linew;
6619								$tmpcellpadding = $this->cell_padding;
6620								if ($maxh == 0) {
6621									$this->SetCellPadding(0);
6622								}
6623							}
6624							// print the line
6625							if ($firstblock AND $this->isRTLTextDir()) {
6626								$tmpstr = $this->stringRightTrim($tmpstr);
6627							}
6628							$this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
6629							unset($tmpstr);
6630							if ($firstline) {
6631								if ($chars[$sep] == 45) {
6632									$endspace += 1;
6633								}
6634								// return the remaining text
6635								$this->cell_padding = $tmpcellpadding;
6636								return (TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace)));
6637							}
6638							$i = $sep;
6639							$sep = -1;
6640							$shy = false;
6641							$j = ($i + 1);
6642						}
6643					}
6644					// account for margin changes
6645					if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
6646						$this->AcceptPageBreak();
6647						if ($this->rtl) {
6648							$this->x -= $margin['R'];
6649						} else {
6650							$this->x += $margin['L'];
6651						}
6652						$this->lMargin += $margin['L'];
6653						$this->rMargin += $margin['R'];
6654					}
6655					$w = $this->getRemainingWidth();
6656					$wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
6657					if ($linebreak) {
6658						$linebreak = false;
6659					} else {
6660						++$nl;
6661						$l = 0;
6662					}
6663				}
6664			}
6665			// save last character
6666			$pc = $c;
6667			++$i;
6668		} // end while i < nb
6669		// print last substring (if any)
6670		if ($l > 0) {
6671			switch ($align) {
6672				case 'J':
6673				case 'C': {
6674					$w = $w;
6675					break;
6676				}
6677				case 'L': {
6678					if ($this->rtl) {
6679						$w = $w;
6680					} else {
6681						$w = $l;
6682					}
6683					break;
6684				}
6685				case 'R': {
6686					if ($this->rtl) {
6687						$w = $l;
6688					} else {
6689						$w = $w;
6690					}
6691					break;
6692				}
6693				default: {
6694					$w = $l;
6695					break;
6696				}
6697			}
6698			$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $nb);
6699			if ($firstline) {
6700				$startx = $this->x;
6701				$tmparr = array_slice($chars, $j, ($nb - $j));
6702				if ($rtlmode) {
6703					$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
6704				}
6705				$linew = $this->GetArrStringWidth($tmparr);
6706				unset($tmparr);
6707				if ($this->rtl) {
6708					$this->endlinex = $startx - $linew;
6709				} else {
6710					$this->endlinex = $startx + $linew;
6711				}
6712				$w = $linew;
6713				$tmpcellpadding = $this->cell_padding;
6714				if ($maxh == 0) {
6715					$this->SetCellPadding(0);
6716				}
6717			}
6718			if ($firstblock AND $this->isRTLTextDir()) {
6719				$tmpstr = $this->stringRightTrim($tmpstr);
6720			}
6721			$this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
6722			unset($tmpstr);
6723			if ($firstline) {
6724				$this->cell_padding = $tmpcellpadding;
6725				return (TCPDF_FONTS::UniArrSubString($uchars, $nb));
6726			}
6727			++$nl;
6728		}
6729		if ($firstline) {
6730			return '';
6731		}
6732		return $nl;
6733	}
6734
6735	/**
6736	 * Returns the remaining width between the current position and margins.
6737	 * @return int Return the remaining width
6738	 * @protected
6739	 */
6740	protected function getRemainingWidth() {
6741		list($this->x, $this->y) = $this->checkPageRegions(0, $this->x, $this->y);
6742		if ($this->rtl) {
6743			return ($this->x - $this->lMargin);
6744		} else {
6745			return ($this->w - $this->rMargin - $this->x);
6746		}
6747	}
6748
6749	/**
6750	 * Set the block dimensions accounting for page breaks and page/column fitting
6751	 * @param $w (float) width
6752	 * @param $h (float) height
6753	 * @param $x (float) X coordinate
6754	 * @param $y (float) Y coodiante
6755	 * @param $fitonpage (boolean) if true the block is resized to not exceed page dimensions.
6756	 * @return array($w, $h, $x, $y)
6757	 * @protected
6758	 * @since 5.5.009 (2010-07-05)
6759	 */
6760	protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
6761		if ($w <= 0) {
6762			// set maximum width
6763			$w = ($this->w - $this->lMargin - $this->rMargin);
6764			if ($w <= 0) {
6765				$w = 1;
6766			}
6767		}
6768		if ($h <= 0) {
6769			// set maximum height
6770			$h = ($this->PageBreakTrigger - $this->tMargin);
6771			if ($h <= 0) {
6772				$h = 1;
6773			}
6774		}
6775		// resize the block to be vertically contained on a single page or single column
6776		if ($fitonpage OR $this->AutoPageBreak) {
6777			$ratio_wh = ($w / $h);
6778			if ($h > ($this->PageBreakTrigger - $this->tMargin)) {
6779				$h = $this->PageBreakTrigger - $this->tMargin;
6780				$w = ($h * $ratio_wh);
6781			}
6782			// resize the block to be horizontally contained on a single page or single column
6783			if ($fitonpage) {
6784				$maxw = ($this->w - $this->lMargin - $this->rMargin);
6785				if ($w > $maxw) {
6786					$w = $maxw;
6787					$h = ($w / $ratio_wh);
6788				}
6789			}
6790		}
6791		// Check whether we need a new page or new column first as this does not fit
6792		$prev_x = $this->x;
6793		$prev_y = $this->y;
6794		if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) {
6795			$y = $this->y;
6796			if ($this->rtl) {
6797				$x += ($prev_x - $this->x);
6798			} else {
6799				$x += ($this->x - $prev_x);
6800			}
6801			$this->newline = true;
6802		}
6803		// resize the block to be contained on the remaining available page or column space
6804		if ($fitonpage) {
6805			$ratio_wh = ($w / $h);
6806			if (($y + $h) > $this->PageBreakTrigger) {
6807				$h = $this->PageBreakTrigger - $y;
6808				$w = ($h * $ratio_wh);
6809			}
6810			if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) {
6811				$w = $this->w - $this->rMargin - $x;
6812				$h = ($w / $ratio_wh);
6813			} elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) {
6814				$w = $x - $this->lMargin;
6815				$h = ($w / $ratio_wh);
6816			}
6817		}
6818		return array($w, $h, $x, $y);
6819	}
6820
6821	/**
6822	 * Puts an image in the page.
6823	 * The upper-left corner must be given.
6824	 * The dimensions can be specified in different ways:<ul>
6825	 * <li>explicit width and height (expressed in user unit)</li>
6826	 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
6827	 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
6828	 * 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;
6829	 * The format can be specified explicitly or inferred from the file extension.<br />
6830	 * It is possible to put a link on the image.<br />
6831	 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
6832	 * @param $file (string) Name of the file containing the image or a '@' character followed by the image data string. To link an image without embedding it on the document, set an asterisk character before the URL (i.e.: '*http://www.example.com/image.jpg').
6833	 * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
6834	 * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
6835	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
6836	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
6837	 * @param $type (string) 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.
6838	 * @param $link (mixed) URL or identifier returned by AddLink().
6839	 * @param $align (string) 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>
6840	 * @param $resize (mixed) If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling).
6841	 * @param $dpi (int) dot-per-inch resolution used on resize
6842	 * @param $palign (string) 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>
6843	 * @param $ismask (boolean) true if this image is a mask, false otherwise
6844	 * @param $imgmask (mixed) image object returned by this function or false
6845	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
6846	 * @param $fitbox (mixed) If not false scale image dimensions proportionally to fit within the ($w, $h) box. $fitbox can be true or a 2 characters string indicating the image alignment inside the box. The first character indicate the horizontal alignment (L = left, C = center, R = right) the second character indicate the vertical algnment (T = top, M = middle, B = bottom).
6847	 * @param $hidden (boolean) If true do not display the image.
6848	 * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
6849	 * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
6850	 * @param $altimgs (array) Array of alternate images IDs. Each alternative image must be an array with two values: an integer representing the image ID (the value returned by the Image method) and a boolean value to indicate if the image is the default for printing.
6851	 * @return image information
6852	 * @public
6853	 * @since 1.1
6854	 */
6855	public function Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false, $alt=false, $altimgs=array()) {
6856		if ($this->state != 2) {
6857			return;
6858		}
6859		if (strcmp($x, '') === 0) {
6860			$x = $this->x;
6861		}
6862		if (strcmp($y, '') === 0) {
6863			$y = $this->y;
6864		}
6865		// check page for no-write regions and adapt page margins if necessary
6866		list($x, $y) = $this->checkPageRegions($h, $x, $y);
6867		$exurl = ''; // external streams
6868		$imsize = FALSE;
6869		// check if we are passing an image as file or string
6870		if ($file[0] === '@') {
6871			// image from string
6872			$imgdata = substr($file, 1);
6873		} else { // image file
6874			if ($file[0] === '*') {
6875				// image as external stream
6876				$file = substr($file, 1);
6877				$exurl = $file;
6878			}
6879			// check if file exist and it is valid
6880			if (!@TCPDF_STATIC::file_exists($file)) {
6881				// DOL CHANGE If we keep this, the image is not visible on pages after the first one.
6882				//var_dump($file.' '.(!@TCPDF_STATIC::file_exists($file)));
6883				//return false;
6884			}
6885			if (($imsize = @getimagesize($file)) === FALSE) {
6886				if (in_array($file, $this->imagekeys)) {
6887					// get existing image data
6888					$info = $this->getImageBuffer($file);
6889					$imsize = array($info['w'], $info['h']);
6890				} elseif (strpos($file, '__tcpdf_'.$this->file_id.'_img') === FALSE) {
6891					$imgdata = TCPDF_STATIC::fileGetContents($file);
6892				}
6893			}
6894		}
6895		if (!empty($imgdata)) {
6896			// copy image to cache
6897			$original_file = $file;
6898			$file = TCPDF_STATIC::getObjFilename('img', $this->file_id);
6899			$fp = TCPDF_STATIC::fopenLocal($file, 'w');
6900			if (!$fp) {
6901				$this->Error('Unable to write file: '.$file);
6902			}
6903			fwrite($fp, $imgdata);
6904			fclose($fp);
6905			unset($imgdata);
6906			$imsize = @getimagesize($file);
6907			if ($imsize === FALSE) {
6908				unlink($file);
6909				$file = $original_file;
6910			}
6911		}
6912		if ($imsize === FALSE) {
6913			if (($w > 0) AND ($h > 0)) {
6914				// get measures from specified data
6915				$pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
6916				$ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
6917				$imsize = array($pw, $ph);
6918			} else {
6919				$this->Error('[Image] Unable to get the size of the image: '.$file);
6920			}
6921		}
6922		// file hash
6923		$filehash = md5($file);
6924		// get original image width and height in pixels
6925		list($pixw, $pixh) = $imsize;
6926		// calculate image width and height on document
6927		if (($w <= 0) AND ($h <= 0)) {
6928			// convert image size to document unit
6929			$w = $this->pixelsToUnits($pixw);
6930			$h = $this->pixelsToUnits($pixh);
6931		} elseif ($w <= 0) {
6932			$w = $h * $pixw / $pixh;
6933		} elseif ($h <= 0) {
6934			$h = $w * $pixh / $pixw;
6935		} elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
6936			if (strlen($fitbox) !== 2) {
6937				// set default alignment
6938				$fitbox = '--';
6939			}
6940			// scale image dimensions proportionally to fit within the ($w, $h) box
6941			if ((($w * $pixh) / ($h * $pixw)) < 1) {
6942				// store current height
6943				$oldh = $h;
6944				// calculate new height
6945				$h = $w * $pixh / $pixw;
6946				// height difference
6947				$hdiff = ($oldh - $h);
6948				// vertical alignment
6949				switch (strtoupper($fitbox[1])) {
6950					case 'T': {
6951						break;
6952					}
6953					case 'M': {
6954						$y += ($hdiff / 2);
6955						break;
6956					}
6957					case 'B': {
6958						$y += $hdiff;
6959						break;
6960					}
6961				}
6962			} else {
6963				// store current width
6964				$oldw = $w;
6965				// calculate new width
6966				$w = $h * $pixw / $pixh;
6967				// width difference
6968				$wdiff = ($oldw - $w);
6969				// horizontal alignment
6970				switch (strtoupper($fitbox[0])) {
6971					case 'L': {
6972						if ($this->rtl) {
6973							$x -= $wdiff;
6974						}
6975						break;
6976					}
6977					case 'C': {
6978						if ($this->rtl) {
6979							$x -= ($wdiff / 2);
6980						} else {
6981							$x += ($wdiff / 2);
6982						}
6983						break;
6984					}
6985					case 'R': {
6986						if (!$this->rtl) {
6987							$x += $wdiff;
6988						}
6989						break;
6990					}
6991				}
6992			}
6993		}
6994		// fit the image on available space
6995		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
6996		// calculate new minimum dimensions in pixels
6997		$neww = round($w * $this->k * $dpi / $this->dpi);
6998		$newh = round($h * $this->k * $dpi / $this->dpi);
6999		// check if resize is necessary (resize is used only to reduce the image)
7000		$newsize = ($neww * $newh);
7001		$pixsize = ($pixw * $pixh);
7002		if (intval($resize) == 2) {
7003			$resize = true;
7004		} elseif ($newsize >= $pixsize) {
7005			$resize = false;
7006		}
7007		// check if image has been already added on document
7008		$newimage = true;
7009		if (in_array($file, $this->imagekeys)) {
7010			$newimage = false;
7011			// get existing image data
7012			$info = $this->getImageBuffer($file);
7013			if (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE) {
7014				// check if the newer image is larger
7015				$oldsize = ($info['w'] * $info['h']);
7016				if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
7017					$newimage = true;
7018				}
7019			}
7020		} elseif (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)) {
7021			// create temp image file (without alpha channel)
7022			$tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
7023			// create temp alpha file
7024			$tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
7025			// check for cached images
7026			if (in_array($tempfile_plain, $this->imagekeys)) {
7027				// get existing image data
7028				$info = $this->getImageBuffer($tempfile_plain);
7029				// check if the newer image is larger
7030				$oldsize = ($info['w'] * $info['h']);
7031				if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
7032					$newimage = true;
7033				} else {
7034					$newimage = false;
7035					// embed mask image
7036					$imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
7037					// embed image, masked with previously embedded mask
7038					return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
7039				}
7040			}
7041		}
7042		if ($newimage) {
7043			//First use of image, get info
7044			$type = strtolower($type);
7045			if ($type == '') {
7046				$type = TCPDF_IMAGES::getImageFileType($file, $imsize);
7047			} elseif ($type == 'jpg') {
7048				$type = 'jpeg';
7049			}
7050			$mqr = TCPDF_STATIC::get_mqr();
7051			TCPDF_STATIC::set_mqr(false);
7052			// Specific image handlers (defined on TCPDF_IMAGES CLASS)
7053			$mtd = '_parse'.$type;
7054			// GD image handler function
7055			$gdfunction = 'imagecreatefrom'.$type;
7056			$info = false;
7057			if ((method_exists('TCPDF_IMAGES', $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
7058				// TCPDF image functions
7059				$info = TCPDF_IMAGES::$mtd($file);
7060				if (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)
7061					AND (($info === 'pngalpha') OR (isset($info['trns']) AND !empty($info['trns'])))) {
7062					return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
7063				}
7064			}
7065			if (($info === false) AND function_exists($gdfunction)) {
7066				try {
7067					// GD library
7068					$img = $gdfunction($file);
7069					if ($img !== false) {
7070						if ($resize) {
7071							$imgr = imagecreatetruecolor($neww, $newh);
7072							if (($type == 'gif') OR ($type == 'png')) {
7073								$imgr = TCPDF_IMAGES::setGDImageTransparency($imgr, $img);
7074							}
7075							imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
7076							$img = $imgr;
7077						}
7078						if (($type == 'gif') OR ($type == 'png')) {
7079							$info = TCPDF_IMAGES::_toPNG($img, TCPDF_STATIC::getObjFilename('img', $this->file_id));
7080						} else {
7081							$info = TCPDF_IMAGES::_toJPEG($img, $this->jpeg_quality, TCPDF_STATIC::getObjFilename('img', $this->file_id));
7082						}
7083					}
7084				} catch(Exception $e) {
7085					$info = false;
7086				}
7087			}
7088			if (($info === false) AND extension_loaded('imagick')) {
7089				try {
7090					// ImageMagick library
7091					$img = new Imagick();
7092					if ($type == 'svg') {
7093						if ($file[0] === '@') {
7094							// image from string
7095							$svgimg = substr($file, 1);
7096						} else {
7097							// get SVG file content
7098							$svgimg = TCPDF_STATIC::fileGetContents($file);
7099						}
7100						if ($svgimg !== FALSE) {
7101							// get width and height
7102							$regs = array();
7103							if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
7104								$svgtag = $regs[1];
7105								$tmp = array();
7106								if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
7107									$ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
7108									$owu = sprintf('%F', ($ow * $dpi / 72)).$this->pdfunit;
7109									$svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
7110								} else {
7111									$ow = $w;
7112								}
7113								$tmp = array();
7114								if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
7115									$oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
7116									$ohu = sprintf('%F', ($oh * $dpi / 72)).$this->pdfunit;
7117									$svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
7118								} else {
7119									$oh = $h;
7120								}
7121								$tmp = array();
7122								if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
7123									$vbw = ($ow * $this->imgscale * $this->k);
7124									$vbh = ($oh * $this->imgscale * $this->k);
7125									$vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
7126									$svgtag = $vbox.$svgtag;
7127								}
7128								$svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
7129							}
7130							$img->readImageBlob($svgimg);
7131						}
7132					} else {
7133						$img->readImage($file);
7134					}
7135					if ($resize) {
7136						$img->resizeImage($neww, $newh, 10, 1, false);
7137					}
7138					$img->setCompressionQuality($this->jpeg_quality);
7139					$img->setImageFormat('jpeg');
7140					$tempname = TCPDF_STATIC::getObjFilename('img', $this->file_id);
7141					$img->writeImage($tempname);
7142					$info = TCPDF_IMAGES::_parsejpeg($tempname);
7143					unlink($tempname);
7144					$img->destroy();
7145				} catch(Exception $e) {
7146					$info = false;
7147				}
7148			}
7149			if ($info === false) {
7150				// unable to process image
7151				return;
7152			}
7153			TCPDF_STATIC::set_mqr($mqr);
7154			if ($ismask) {
7155				// force grayscale
7156				$info['cs'] = 'DeviceGray';
7157			}
7158			if ($imgmask !== false) {
7159				$info['masked'] = $imgmask;
7160			}
7161			if (!empty($exurl)) {
7162				$info['exurl'] = $exurl;
7163			}
7164			// array of alternative images
7165			$info['altimgs'] = $altimgs;
7166			// add image to document
7167			$info['i'] = $this->setImageBuffer($file, $info);
7168		}
7169		// set alignment
7170		$this->img_rb_y = $y + $h;
7171		// set alignment
7172		if ($this->rtl) {
7173			if ($palign == 'L') {
7174				$ximg = $this->lMargin;
7175			} elseif ($palign == 'C') {
7176				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
7177			} elseif ($palign == 'R') {
7178				$ximg = $this->w - $this->rMargin - $w;
7179			} else {
7180				$ximg = $x - $w;
7181			}
7182			$this->img_rb_x = $ximg;
7183		} else {
7184			if ($palign == 'L') {
7185				$ximg = $this->lMargin;
7186			} elseif ($palign == 'C') {
7187				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
7188			} elseif ($palign == 'R') {
7189				$ximg = $this->w - $this->rMargin - $w;
7190			} else {
7191				$ximg = $x;
7192			}
7193			$this->img_rb_x = $ximg + $w;
7194		}
7195		if ($ismask OR $hidden) {
7196			// image is not displayed
7197			return $info['i'];
7198		}
7199		$xkimg = $ximg * $this->k;
7200		if (!$alt) {
7201			// only non-alternative immages will be set
7202			$this->_out(sprintf('q %F 0 0 %F %F %F cm /I%u Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
7203		}
7204		if (!empty($border)) {
7205			$bx = $this->x;
7206			$by = $this->y;
7207			$this->x = $ximg;
7208			if ($this->rtl) {
7209				$this->x += $w;
7210			}
7211			$this->y = $y;
7212			$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
7213			$this->x = $bx;
7214			$this->y = $by;
7215		}
7216		if ($link) {
7217			$this->Link($ximg, $y, $w, $h, $link, 0);
7218		}
7219		// set pointer to align the next text/objects
7220		switch($align) {
7221			case 'T': {
7222				$this->y = $y;
7223				$this->x = $this->img_rb_x;
7224				break;
7225			}
7226			case 'M': {
7227				$this->y = $y + round($h/2);
7228				$this->x = $this->img_rb_x;
7229				break;
7230			}
7231			case 'B': {
7232				$this->y = $this->img_rb_y;
7233				$this->x = $this->img_rb_x;
7234				break;
7235			}
7236			case 'N': {
7237				$this->SetY($this->img_rb_y);
7238				break;
7239			}
7240			default:{
7241				break;
7242			}
7243		}
7244		$this->endlinex = $this->img_rb_x;
7245		if ($this->inxobj) {
7246			// we are inside an XObject template
7247			$this->xobjects[$this->xobjid]['images'][] = $info['i'];
7248		}
7249		return $info['i'];
7250	}
7251
7252	/**
7253	 * Extract info from a PNG image with alpha channel using the Imagick or GD library.
7254	 * @param $file (string) Name of the file containing the image.
7255	 * @param $x (float) Abscissa of the upper-left corner.
7256	 * @param $y (float) Ordinate of the upper-left corner.
7257	 * @param $wpx (float) Original width of the image in pixels.
7258	 * @param $hpx (float) original height of the image in pixels.
7259	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
7260	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
7261	 * @param $type (string) 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.
7262	 * @param $link (mixed) URL or identifier returned by AddLink().
7263	 * @param $align (string) 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>
7264	 * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
7265	 * @param $dpi (int) dot-per-inch resolution used on resize
7266	 * @param $palign (string) 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>
7267	 * @param $filehash (string) File hash used to build unique file names.
7268	 * @author Nicola Asuni
7269	 * @protected
7270	 * @since 4.3.007 (2008-12-04)
7271	 * @see Image()
7272	 */
7273	protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
7274		// create temp images
7275		if (empty($filehash)) {
7276			$filehash = md5($file);
7277		}
7278		// create temp image file (without alpha channel)
7279		$tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
7280		// create temp alpha file
7281		$tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
7282		$parsed = false;
7283		$parse_error = '';
7284		// ImageMagick extension
7285		if (($parsed === false) AND extension_loaded('imagick')) {
7286			try {
7287				// ImageMagick library
7288				$img = new Imagick();
7289				$img->readImage($file);
7290				// clone image object
7291				$imga = TCPDF_STATIC::objclone($img);
7292				// extract alpha channel
7293				if (method_exists($img, 'setImageAlphaChannel') AND defined('Imagick::ALPHACHANNEL_EXTRACT')) {
7294					$img->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
7295				} else {
7296					$img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
7297					$img->negateImage(true);
7298				}
7299				$img->setImageFormat('png');
7300				$img->writeImage($tempfile_alpha);
7301				// remove alpha channel
7302				if (method_exists($imga, 'setImageMatte')) {
7303					$imga->setImageMatte(false);
7304				} else {
7305					$imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
7306				}
7307				$imga->setImageFormat('png');
7308				$imga->writeImage($tempfile_plain);
7309				$parsed = true;
7310			} catch (Exception $e) {
7311				// Imagemagick fails, try with GD
7312				$parse_error = 'Imagick library error: '.$e->getMessage();
7313			}
7314		}
7315		// GD extension
7316		if (($parsed === false) AND function_exists('imagecreatefrompng')) {
7317			try {
7318				// generate images
7319				$img = imagecreatefrompng($file);
7320				$imgalpha = imagecreate($wpx, $hpx);
7321				// generate gray scale palette (0 -> 255)
7322				for ($c = 0; $c < 256; ++$c) {
7323					ImageColorAllocate($imgalpha, $c, $c, $c);
7324				}
7325				// extract alpha channel
7326				for ($xpx = 0; $xpx < $wpx; ++$xpx) {
7327					for ($ypx = 0; $ypx < $hpx; ++$ypx) {
7328						$color = imagecolorat($img, $xpx, $ypx);
7329						// get and correct gamma color
7330						$alpha = $this->getGDgamma($img, $color);
7331						imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
7332					}
7333				}
7334				imagepng($imgalpha, $tempfile_alpha);
7335				imagedestroy($imgalpha);
7336				// extract image without alpha channel
7337				$imgplain = imagecreatetruecolor($wpx, $hpx);
7338				imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
7339				imagepng($imgplain, $tempfile_plain);
7340				imagedestroy($imgplain);
7341				$parsed = true;
7342			} catch (Exception $e) {
7343				// GD fails
7344				$parse_error = 'GD library error: '.$e->getMessage();
7345			}
7346		}
7347		if ($parsed === false) {
7348			if (empty($parse_error)) {
7349				$this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
7350			} else {
7351				$this->Error($parse_error);
7352			}
7353		}
7354		// embed mask image
7355		$imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
7356		// embed image, masked with previously embedded mask
7357		$this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
7358	}
7359
7360	/**
7361	 * Get the GD-corrected PNG gamma value from alpha color
7362	 * @param $img (int) GD image Resource ID.
7363	 * @param $c (int) alpha color
7364	 * @protected
7365	 * @since 4.3.007 (2008-12-04)
7366	 */
7367	protected function getGDgamma($img, $c) {
7368		if (!isset($this->gdgammacache['#'.$c])) {
7369			$colors = imagecolorsforindex($img, $c);
7370			// GD alpha is only 7 bit (0 -> 127)
7371			$this->gdgammacache['#'.$c] = (((127 - $colors['alpha']) / 127) * 255);
7372			// correct gamma
7373			$this->gdgammacache['#'.$c] = (pow(($this->gdgammacache['#'.$c] / 255), 2.2) * 255);
7374			// store the latest values on cache to improve performances
7375			if (count($this->gdgammacache) > 8) {
7376				// remove one element from the cache array
7377				array_shift($this->gdgammacache);
7378			}
7379		}
7380		return $this->gdgammacache['#'.$c];
7381	}
7382
7383	/**
7384	 * Performs a line break.
7385	 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
7386	 * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
7387	 * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
7388	 * @public
7389	 * @since 1.0
7390	 * @see Cell()
7391	 */
7392	public function Ln($h='', $cell=false) {
7393		if (($this->num_columns > 1) AND ($this->y == $this->columns[$this->current_column]['y']) AND isset($this->columns[$this->current_column]['x']) AND ($this->x == $this->columns[$this->current_column]['x'])) {
7394			// revove vertical space from the top of the column
7395			return;
7396		}
7397		if ($cell) {
7398			if ($this->rtl) {
7399				$cellpadding = $this->cell_padding['R'];
7400			} else {
7401				$cellpadding = $this->cell_padding['L'];
7402			}
7403		} else {
7404			$cellpadding = 0;
7405		}
7406		if ($this->rtl) {
7407			$this->x = $this->w - $this->rMargin - $cellpadding;
7408		} else {
7409			$this->x = $this->lMargin + $cellpadding;
7410		}
7411		if (is_string($h)) {
7412			$h = $this->lasth;
7413		}
7414		$this->y += $h;
7415		$this->newline = true;
7416	}
7417
7418	/**
7419	 * Returns the relative X value of current position.
7420	 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
7421	 * @return float
7422	 * @public
7423	 * @since 1.2
7424	 * @see SetX(), GetY(), SetY()
7425	 */
7426	public function GetX() {
7427		//Get x position
7428		if ($this->rtl) {
7429			return ($this->w - $this->x);
7430		} else {
7431			return $this->x;
7432		}
7433	}
7434
7435	/**
7436	 * Returns the absolute X value of current position.
7437	 * @return float
7438	 * @public
7439	 * @since 1.2
7440	 * @see SetX(), GetY(), SetY()
7441	 */
7442	public function GetAbsX() {
7443		return $this->x;
7444	}
7445
7446	/**
7447	 * Returns the ordinate of the current position.
7448	 * @return float
7449	 * @public
7450	 * @since 1.0
7451	 * @see SetY(), GetX(), SetX()
7452	 */
7453	public function GetY() {
7454		return $this->y;
7455	}
7456
7457	/**
7458	 * Defines the abscissa of the current position.
7459	 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
7460	 * @param $x (float) The value of the abscissa in user units.
7461	 * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
7462	 * @public
7463	 * @since 1.2
7464	 * @see GetX(), GetY(), SetY(), SetXY()
7465	 */
7466	public function SetX($x, $rtloff=false) {
7467		$x = floatval($x);
7468		if (!$rtloff AND $this->rtl) {
7469			if ($x >= 0) {
7470				$this->x = $this->w - $x;
7471			} else {
7472				$this->x = abs($x);
7473			}
7474		} else {
7475			if ($x >= 0) {
7476				$this->x = $x;
7477			} else {
7478				$this->x = $this->w + $x;
7479			}
7480		}
7481		if ($this->x < 0) {
7482			$this->x = 0;
7483		}
7484		if ($this->x > $this->w) {
7485			$this->x = $this->w;
7486		}
7487	}
7488
7489	/**
7490	 * Moves the current abscissa back to the left margin and sets the ordinate.
7491	 * If the passed value is negative, it is relative to the bottom of the page.
7492	 * @param $y (float) The value of the ordinate in user units.
7493	 * @param $resetx (bool) if true (default) reset the X position.
7494	 * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
7495	 * @public
7496	 * @since 1.0
7497	 * @see GetX(), GetY(), SetY(), SetXY()
7498	 */
7499	public function SetY($y, $resetx=true, $rtloff=false) {
7500		$y = floatval($y);
7501		if ($resetx) {
7502			//reset x
7503			if (!$rtloff AND $this->rtl) {
7504				$this->x = $this->w - $this->rMargin;
7505			} else {
7506				$this->x = $this->lMargin;
7507			}
7508		}
7509		if ($y >= 0) {
7510			$this->y = $y;
7511		} else {
7512			$this->y = $this->h + $y;
7513		}
7514		if ($this->y < 0) {
7515			$this->y = 0;
7516		}
7517		if ($this->y > $this->h) {
7518			$this->y = $this->h;
7519		}
7520	}
7521
7522	/**
7523	 * Defines the abscissa and ordinate of the current position.
7524	 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
7525	 * @param $x (float) The value of the abscissa.
7526	 * @param $y (float) The value of the ordinate.
7527	 * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
7528	 * @public
7529	 * @since 1.2
7530	 * @see SetX(), SetY()
7531	 */
7532	public function SetXY($x, $y, $rtloff=false) {
7533		$this->SetY($y, false, $rtloff);
7534		$this->SetX($x, $rtloff);
7535	}
7536
7537	/**
7538	 * Set the absolute X coordinate of the current pointer.
7539	 * @param $x (float) The value of the abscissa in user units.
7540	 * @public
7541	 * @since 5.9.186 (2012-09-13)
7542	 * @see setAbsX(), setAbsY(), SetAbsXY()
7543	 */
7544	public function SetAbsX($x) {
7545		$this->x = floatval($x);
7546	}
7547
7548	/**
7549	 * Set the absolute Y coordinate of the current pointer.
7550	 * @param $y (float) (float) The value of the ordinate in user units.
7551	 * @public
7552	 * @since 5.9.186 (2012-09-13)
7553	 * @see setAbsX(), setAbsY(), SetAbsXY()
7554	 */
7555	public function SetAbsY($y) {
7556		$this->y = floatval($y);
7557	}
7558
7559	/**
7560	 * Set the absolute X and Y coordinates of the current pointer.
7561	 * @param $x (float) The value of the abscissa in user units.
7562	 * @param $y (float) (float) The value of the ordinate in user units.
7563	 * @public
7564	 * @since 5.9.186 (2012-09-13)
7565	 * @see setAbsX(), setAbsY(), SetAbsXY()
7566	 */
7567	public function SetAbsXY($x, $y) {
7568		$this->SetAbsX($x);
7569		$this->SetAbsY($y);
7570	}
7571
7572	/**
7573	 * Send the document to a given destination: string, local file or browser.
7574	 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
7575	 * The method first calls Close() if necessary to terminate the document.
7576	 * @param $name (string) The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
7577	 * @param $dest (string) 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 server file with the name given by name.</li><li>S: return the document as a string (name is ignored).</li><li>FI: equivalent to F + I option</li><li>FD: equivalent to F + D option</li><li>E: return the document as base64 mime multi-part email attachment (RFC 2045)</li></ul>
7578	 * @return string
7579	 * @public
7580	 * @since 1.0
7581	 * @see Close()
7582	 */
7583	public function Output($name='doc.pdf', $dest='I') {
7584		//Output PDF to some destination
7585		//Finish document if necessary
7586		if ($this->state < 3) {
7587			$this->Close();
7588		}
7589		//Normalize parameters
7590		if (is_bool($dest)) {
7591			$dest = $dest ? 'D' : 'F';
7592		}
7593		$dest = strtoupper($dest);
7594		if ($dest[0] != 'F') {
7595			$name = preg_replace('/[\s]+/', '_', $name);
7596			$name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
7597		}
7598		if ($this->sign) {
7599			// *** apply digital signature to the document ***
7600			// get the document content
7601			$pdfdoc = $this->getBuffer();
7602			// remove last newline
7603			$pdfdoc = substr($pdfdoc, 0, -1);
7604			// remove filler space
7605			$byterange_string_len = strlen(TCPDF_STATIC::$byterange_string);
7606			// define the ByteRange
7607			$byte_range = array();
7608			$byte_range[0] = 0;
7609			$byte_range[1] = strpos($pdfdoc, TCPDF_STATIC::$byterange_string) + $byterange_string_len + 10;
7610			$byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
7611			$byte_range[3] = strlen($pdfdoc) - $byte_range[2];
7612			$pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
7613			// replace the ByteRange
7614			$byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
7615			$byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
7616			$pdfdoc = str_replace(TCPDF_STATIC::$byterange_string, $byterange, $pdfdoc);
7617			// write the document to a temporary folder
7618			$tempdoc = TCPDF_STATIC::getObjFilename('doc', $this->file_id);
7619			$f = TCPDF_STATIC::fopenLocal($tempdoc, 'wb');
7620			if (!$f) {
7621				$this->Error('Unable to create temporary file: '.$tempdoc);
7622			}
7623			$pdfdoc_length = strlen($pdfdoc);
7624			fwrite($f, $pdfdoc, $pdfdoc_length);
7625			fclose($f);
7626			// get digital signature via openssl library
7627			$tempsign = TCPDF_STATIC::getObjFilename('sig', $this->file_id);
7628			if (empty($this->signature_data['extracerts'])) {
7629				openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
7630			} else {
7631				openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED, $this->signature_data['extracerts']);
7632			}
7633			// read signature
7634			$signature = file_get_contents($tempsign);
7635			// extract signature
7636			$signature = substr($signature, $pdfdoc_length);
7637			$signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
7638			$tmparr = explode("\n\n", $signature);
7639			$signature = $tmparr[1];
7640			// decode signature
7641			$signature = base64_decode(trim($signature));
7642			// add TSA timestamp to signature
7643			$signature = $this->applyTSA($signature);
7644			// convert signature to hex
7645			$signature = current(unpack('H*', $signature));
7646			$signature = str_pad($signature, $this->signature_max_length, '0');
7647			// Add signature to the document
7648			$this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
7649			$this->bufferlen = strlen($this->buffer);
7650		}
7651		switch($dest) {
7652			case 'I': {
7653				// Send PDF to the standard output
7654				if (ob_get_contents()) {
7655					$this->Error('Some data has already been output, can\'t send PDF file');
7656				}
7657				if (php_sapi_name() != 'cli') {
7658					// send output to a browser
7659					header('Content-Type: application/pdf');
7660					if (headers_sent()) {
7661						$this->Error('Some data has already been output to browser, can\'t send PDF file');
7662					}
7663					header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7664					//header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
7665					header('Pragma: public');
7666					header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7667					header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7668					header('Content-Disposition: inline; filename="'.basename($name).'"');
7669					TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
7670				} else {
7671					echo $this->getBuffer();
7672				}
7673				break;
7674			}
7675			case 'D': {
7676				// download PDF as file
7677				if (ob_get_contents()) {
7678					$this->Error('Some data has already been output, can\'t send PDF file');
7679				}
7680				header('Content-Description: File Transfer');
7681				if (headers_sent()) {
7682					$this->Error('Some data has already been output to browser, can\'t send PDF file');
7683				}
7684				header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7685				//header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
7686				header('Pragma: public');
7687				header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7688				header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7689				// force download dialog
7690				if (strpos(php_sapi_name(), 'cgi') === false) {
7691					header('Content-Type: application/force-download');
7692					header('Content-Type: application/octet-stream', false);
7693					header('Content-Type: application/download', false);
7694					header('Content-Type: application/pdf', false);
7695				} else {
7696					header('Content-Type: application/pdf');
7697				}
7698				// use the Content-Disposition header to supply a recommended filename
7699				header('Content-Disposition: attachment; filename="'.basename($name).'"');
7700				header('Content-Transfer-Encoding: binary');
7701				TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
7702				break;
7703			}
7704			case 'F':
7705			case 'FI':
7706			case 'FD': {
7707				// save PDF to a local file
7708				$f = TCPDF_STATIC::fopenLocal($name, 'wb');
7709				if (!$f) {
7710					$this->Error('Unable to create output file: '.$name);
7711				}
7712				fwrite($f, $this->getBuffer(), $this->bufferlen);
7713				fclose($f);
7714				if ($dest == 'FI') {
7715					// send headers to browser
7716					header('Content-Type: application/pdf');
7717					header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7718					//header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
7719					header('Pragma: public');
7720					header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7721					header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7722					header('Content-Disposition: inline; filename="'.basename($name).'"');
7723					TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
7724				} elseif ($dest == 'FD') {
7725					// send headers to browser
7726					if (ob_get_contents()) {
7727						$this->Error('Some data has already been output, can\'t send PDF file');
7728					}
7729					header('Content-Description: File Transfer');
7730					if (headers_sent()) {
7731						$this->Error('Some data has already been output to browser, can\'t send PDF file');
7732					}
7733					header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7734					header('Pragma: public');
7735					header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7736					header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7737					// force download dialog
7738					if (strpos(php_sapi_name(), 'cgi') === false) {
7739						header('Content-Type: application/force-download');
7740						header('Content-Type: application/octet-stream', false);
7741						header('Content-Type: application/download', false);
7742						header('Content-Type: application/pdf', false);
7743					} else {
7744						header('Content-Type: application/pdf');
7745					}
7746					// use the Content-Disposition header to supply a recommended filename
7747					header('Content-Disposition: attachment; filename="'.basename($name).'"');
7748					header('Content-Transfer-Encoding: binary');
7749					TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
7750				}
7751				break;
7752			}
7753			case 'E': {
7754				// return PDF as base64 mime multi-part email attachment (RFC 2045)
7755				$retval = 'Content-Type: application/pdf;'."\r\n";
7756				$retval .= ' name="'.$name.'"'."\r\n";
7757				$retval .= 'Content-Transfer-Encoding: base64'."\r\n";
7758				$retval .= 'Content-Disposition: attachment;'."\r\n";
7759				$retval .= ' filename="'.$name.'"'."\r\n\r\n";
7760				$retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
7761				return $retval;
7762			}
7763			case 'S': {
7764				// returns PDF as a string
7765				return $this->getBuffer();
7766			}
7767			default: {
7768				$this->Error('Incorrect output destination: '.$dest);
7769			}
7770		}
7771		return '';
7772	}
7773
7774	protected static $cleaned_ids = array();
7775	/**
7776	 * Unset all class variables except the following critical variables.
7777	 * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
7778	 * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
7779	 * @public
7780	 * @since 4.5.016 (2009-02-24)
7781	 */
7782	public function _destroy($destroyall=false, $preserve_objcopy=false) {
7783		// restore internal encoding
7784		if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
7785			mb_internal_encoding($this->internal_encoding);
7786		}
7787		if (isset(self::$cleaned_ids[$this->file_id])) {
7788			$destroyall = false;
7789		}
7790		if ($destroyall AND !$preserve_objcopy) {
7791			self::$cleaned_ids[$this->file_id] = true;
7792			// remove all temporary files
7793			if ($handle = opendir(K_PATH_CACHE)) {
7794				while ( false !== ( $file_name = readdir( $handle ) ) ) {
7795					if (strpos($file_name, '__tcpdf_'.$this->file_id.'_') === 0) {
7796						unlink(K_PATH_CACHE.$file_name);
7797					}
7798				}
7799				closedir($handle);
7800			}
7801			if (isset($this->imagekeys)) {
7802				foreach($this->imagekeys as $file) {
7803// @CHANGE DOL
7804//					unlink($file);
7805				}
7806			}
7807		}
7808		$preserve = array(
7809			'file_id',
7810			'internal_encoding',
7811			'state',
7812			'bufferlen',
7813			'buffer',
7814			'cached_files',
7815// @CHANGE DOL
7816//			'imagekeys',
7817			'sign',
7818			'signature_data',
7819			'signature_max_length',
7820			'byterange_string',
7821			'tsa_timestamp',
7822			'tsa_data'
7823		);
7824		foreach (array_keys(get_object_vars($this)) as $val) {
7825			if ($destroyall OR !in_array($val, $preserve)) {
7826				if ((!$preserve_objcopy OR ($val != 'objcopy')) AND ($val != 'file_id') AND isset($this->$val)) {
7827					unset($this->$val);
7828				}
7829			}
7830		}
7831	}
7832
7833	/**
7834	 * Check for locale-related bug
7835	 * @protected
7836	 */
7837	protected function _dochecks() {
7838		//Check for locale-related bug
7839		if (1.1 == 1) {
7840			$this->Error('Don\'t alter the locale before including class file');
7841		}
7842		//Check for decimal separator
7843		if (sprintf('%.1F', 1.0) != '1.0') {
7844			setlocale(LC_NUMERIC, 'C');
7845		}
7846	}
7847
7848	/**
7849	 * Return an array containing variations for the basic page number alias.
7850	 * @param $a (string) Base alias.
7851	 * @return array of page number aliases
7852	 * @protected
7853	 */
7854	protected function getInternalPageNumberAliases($a= '') {
7855		$alias = array();
7856		// build array of Unicode + ASCII variants (the order is important)
7857		$alias = array('u' => array(), 'a' => array());
7858		$u = '{'.$a.'}';
7859		$alias['u'][] = TCPDF_STATIC::_escape($u);
7860		if ($this->isunicode) {
7861			$alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($u, $this->isunicode, $this->CurrentFont));
7862			$alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($u, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
7863			$alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($a, $this->isunicode, $this->CurrentFont));
7864			$alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($a, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
7865		}
7866		$alias['a'][] = TCPDF_STATIC::_escape($a);
7867		return $alias;
7868	}
7869
7870	/**
7871	 * Return an array containing all internal page aliases.
7872	 * @return array of page number aliases
7873	 * @protected
7874	 */
7875	protected function getAllInternalPageNumberAliases() {
7876		$basic_alias = array(TCPDF_STATIC::$alias_tot_pages, TCPDF_STATIC::$alias_num_page, TCPDF_STATIC::$alias_group_tot_pages, TCPDF_STATIC::$alias_group_num_page, TCPDF_STATIC::$alias_right_shift);
7877		$pnalias = array();
7878		foreach($basic_alias as $k => $a) {
7879			$pnalias[$k] = $this->getInternalPageNumberAliases($a);
7880		}
7881		return $pnalias;
7882	}
7883
7884	/**
7885	 * Replace right shift page number aliases with spaces to correct right alignment.
7886	 * This works perfectly only when using monospaced fonts.
7887	 * @param $page (string) Page content.
7888	 * @param $aliases (array) Array of page aliases.
7889	 * @param $diff (int) initial difference to add.
7890	 * @return replaced page content.
7891	 * @protected
7892	 */
7893	protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
7894		foreach ($aliases as $type => $alias) {
7895			foreach ($alias as $a) {
7896				// find position of compensation factor
7897				$startnum = (strpos($a, ':') + 1);
7898				$a = substr($a, 0, $startnum);
7899				if (($pos = strpos($page, $a)) !== false) {
7900					// end of alias
7901					$endnum = strpos($page, '}', $pos);
7902					// string to be replaced
7903					$aa = substr($page, $pos, ($endnum - $pos + 1));
7904					// get compensation factor
7905					$ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
7906					$ratio = preg_replace('/[^0-9\.]/', '', $ratio);
7907					$ratio = floatval($ratio);
7908					if ($type == 'u') {
7909						$chrdiff = floor(($diff + 12) * $ratio);
7910						$shift = str_repeat(' ', $chrdiff);
7911						$shift = TCPDF_FONTS::UTF8ToUTF16BE($shift, false, $this->isunicode, $this->CurrentFont);
7912					} else {
7913						$chrdiff = floor(($diff + 11) * $ratio);
7914						$shift = str_repeat(' ', $chrdiff);
7915					}
7916					$page = str_replace($aa, $shift, $page);
7917				}
7918			}
7919		}
7920		return $page;
7921	}
7922
7923	/**
7924	 * Set page boxes to be included on page descriptions.
7925	 * @param $boxes (array) Array of page boxes to set on document: ('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox').
7926	 * @protected
7927	 */
7928	protected function setPageBoxTypes($boxes) {
7929		$this->page_boxes = array();
7930		foreach ($boxes as $box) {
7931			if (in_array($box, TCPDF_STATIC::$pageboxes)) {
7932				$this->page_boxes[] = $box;
7933			}
7934		}
7935	}
7936
7937	/**
7938	 * Output pages (and replace page number aliases).
7939	 * @protected
7940	 */
7941	protected function _putpages() {
7942		$filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
7943		// get internal aliases for page numbers
7944		$pnalias = $this->getAllInternalPageNumberAliases();
7945		$num_pages = $this->numpages;
7946		$ptpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $num_pages - 1));
7947		$ptpu = TCPDF_FONTS::UTF8ToUTF16BE($ptpa, false, $this->isunicode, $this->CurrentFont);
7948		$ptp_num_chars = $this->GetNumChars($ptpa);
7949		$pagegroupnum = 0;
7950		$groupnum = 0;
7951		$ptgu = 1;
7952		$ptga = 1;
7953		$ptg_num_chars = 1;
7954		for ($n = 1; $n <= $num_pages; ++$n) {
7955			// get current page
7956			$temppage = $this->getPageBuffer($n);
7957			$pagelen = strlen($temppage);
7958			// set replacements for total pages number
7959			$pnpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $n - 1));
7960			$pnpu = TCPDF_FONTS::UTF8ToUTF16BE($pnpa, false, $this->isunicode, $this->CurrentFont);
7961			$pnp_num_chars = $this->GetNumChars($pnpa);
7962			$pdiff = 0; // difference used for right shift alignment of page numbers
7963			$gdiff = 0; // difference used for right shift alignment of page group numbers
7964			if (!empty($this->pagegroups)) {
7965				if (isset($this->newpagegroup[$n])) {
7966					$pagegroupnum = 0;
7967					++$groupnum;
7968					$ptga = TCPDF_STATIC::formatPageNumber($this->pagegroups[$groupnum]);
7969					$ptgu = TCPDF_FONTS::UTF8ToUTF16BE($ptga, false, $this->isunicode, $this->CurrentFont);
7970					$ptg_num_chars = $this->GetNumChars($ptga);
7971				}
7972				++$pagegroupnum;
7973				$pnga = TCPDF_STATIC::formatPageNumber($pagegroupnum);
7974				$pngu = TCPDF_FONTS::UTF8ToUTF16BE($pnga, false, $this->isunicode, $this->CurrentFont);
7975				$png_num_chars = $this->GetNumChars($pnga);
7976				// replace page numbers
7977				$replace = array();
7978				$replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
7979				$replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
7980				$replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
7981				$replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
7982				list($temppage, $gdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $gdiff);
7983			}
7984			// replace page numbers
7985			$replace = array();
7986			$replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
7987			$replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
7988			$replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
7989			$replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
7990			list($temppage, $pdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $pdiff);
7991			// replace right shift alias
7992			$temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
7993			// replace EPS marker
7994			$temppage = str_replace($this->epsmarker, '', $temppage);
7995			//Page
7996			$this->page_obj_id[$n] = $this->_newobj();
7997			$out = '<<';
7998			$out .= ' /Type /Page';
7999			$out .= ' /Parent 1 0 R';
8000			if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
8001				$out .= ' /LastModified '.$this->_datestring(0, $this->doc_modification_timestamp);
8002			}
8003			$out .= ' /Resources 2 0 R';
8004			foreach ($this->page_boxes as $box) {
8005				$out .= ' /'.$box;
8006				$out .= sprintf(' [%F %F %F %F]', $this->pagedim[$n][$box]['llx'], $this->pagedim[$n][$box]['lly'], $this->pagedim[$n][$box]['urx'], $this->pagedim[$n][$box]['ury']);
8007			}
8008			if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
8009				$out .= ' /BoxColorInfo <<';
8010				foreach ($this->page_boxes as $box) {
8011					if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
8012						$out .= ' /'.$box.' <<';
8013						if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
8014							$color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
8015							$out .= ' /C [';
8016							$out .= sprintf(' %F %F %F', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
8017							$out .= ' ]';
8018						}
8019						if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
8020							$out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
8021						}
8022						if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
8023							$out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
8024						}
8025						if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
8026							$dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
8027							$out .= ' /D [';
8028							foreach ($dashes as $dash) {
8029								$out .= sprintf(' %F', ($dash * $this->k));
8030							}
8031							$out .= ' ]';
8032						}
8033						$out .= ' >>';
8034					}
8035				}
8036				$out .= ' >>';
8037			}
8038			$out .= ' /Contents '.($this->n + 1).' 0 R';
8039			$out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
8040			if (!$this->pdfa_mode) {
8041				$out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
8042			}
8043			if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
8044				// page transitions
8045				if (isset($this->pagedim[$n]['trans']['Dur'])) {
8046					$out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
8047				}
8048				$out .= ' /Trans <<';
8049				$out .= ' /Type /Trans';
8050				if (isset($this->pagedim[$n]['trans']['S'])) {
8051					$out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
8052				}
8053				if (isset($this->pagedim[$n]['trans']['D'])) {
8054					$out .= ' /D '.$this->pagedim[$n]['trans']['D'];
8055				}
8056				if (isset($this->pagedim[$n]['trans']['Dm'])) {
8057					$out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
8058				}
8059				if (isset($this->pagedim[$n]['trans']['M'])) {
8060					$out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
8061				}
8062				if (isset($this->pagedim[$n]['trans']['Di'])) {
8063					$out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
8064				}
8065				if (isset($this->pagedim[$n]['trans']['SS'])) {
8066					$out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
8067				}
8068				if (isset($this->pagedim[$n]['trans']['B'])) {
8069					$out .= ' /B '.$this->pagedim[$n]['trans']['B'];
8070				}
8071				$out .= ' >>';
8072			}
8073			$out .= $this->_getannotsrefs($n);
8074			$out .= ' /PZ '.$this->pagedim[$n]['PZ'];
8075			$out .= ' >>';
8076			$out .= "\n".'endobj';
8077			$this->_out($out);
8078			//Page content
8079			$p = ($this->compress) ? gzcompress($temppage) : $temppage;
8080			$this->_newobj();
8081			$p = $this->_getrawstream($p);
8082			$this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
8083		}
8084		//Pages root
8085		$out = $this->_getobj(1)."\n";
8086		$out .= '<< /Type /Pages /Kids [';
8087		foreach($this->page_obj_id as $page_obj) {
8088			$out .= ' '.$page_obj.' 0 R';
8089		}
8090		$out .= ' ] /Count '.$num_pages.' >>';
8091		$out .= "\n".'endobj';
8092		$this->_out($out);
8093	}
8094
8095	/**
8096	 * Get references to page annotations.
8097	 * @param $n (int) page number
8098	 * @return string
8099	 * @protected
8100	 * @author Nicola Asuni
8101	 * @since 5.0.010 (2010-05-17)
8102	 */
8103	protected function _getannotsrefs($n) {
8104		if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
8105			return '';
8106		}
8107		$out = ' /Annots [';
8108		if (isset($this->PageAnnots[$n])) {
8109			foreach ($this->PageAnnots[$n] as $key => $val) {
8110				if (!in_array($val['n'], $this->radio_groups)) {
8111					$out .= ' '.$val['n'].' 0 R';
8112				}
8113			}
8114			// add radiobutton groups
8115			if (isset($this->radiobutton_groups[$n])) {
8116				foreach ($this->radiobutton_groups[$n] as $key => $data) {
8117					if (isset($data['n'])) {
8118						$out .= ' '.$data['n'].' 0 R';
8119					}
8120				}
8121			}
8122		}
8123		if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
8124			// set reference for signature object
8125			$out .= ' '.$this->sig_obj_id.' 0 R';
8126		}
8127		if (!empty($this->empty_signature_appearance)) {
8128			foreach ($this->empty_signature_appearance as $esa) {
8129				if ($esa['page'] == $n) {
8130					// set reference for empty signature objects
8131					$out .= ' '.$esa['objid'].' 0 R';
8132				}
8133			}
8134		}
8135		$out .= ' ]';
8136		return $out;
8137	}
8138
8139	/**
8140	 * Output annotations objects for all pages.
8141	 * !!! THIS METHOD IS NOT YET COMPLETED !!!
8142	 * See section 12.5 of PDF 32000_2008 reference.
8143	 * @protected
8144	 * @author Nicola Asuni
8145	 * @since 4.0.018 (2008-08-06)
8146	 */
8147	protected function _putannotsobjs() {
8148		// reset object counter
8149		for ($n=1; $n <= $this->numpages; ++$n) {
8150			if (isset($this->PageAnnots[$n])) {
8151				// set page annotations
8152				foreach ($this->PageAnnots[$n] as $key => $pl) {
8153					$annot_obj_id = $this->PageAnnots[$n][$key]['n'];
8154					// create annotation object for grouping radiobuttons
8155					if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
8156						$radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
8157						$annots = '<<';
8158						$annots .= ' /Type /Annot';
8159						$annots .= ' /Subtype /Widget';
8160						$annots .= ' /Rect [0 0 0 0]';
8161						if ($this->radiobutton_groups[$n][$pl['txt']]['#readonly#']) {
8162							// read only
8163							$annots .= ' /F 68';
8164							$annots .= ' /Ff 49153';
8165						} else {
8166							$annots .= ' /F 4'; // default print for PDF/A
8167							$annots .= ' /Ff 49152';
8168						}
8169						$annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
8170						if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
8171							$annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $radio_button_obj_id);
8172						}
8173						$annots .= ' /FT /Btn';
8174						$annots .= ' /Kids [';
8175						$defval = '';
8176						foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
8177							if (isset($data['kid'])) {
8178								$annots .= ' '.$data['kid'].' 0 R';
8179								if ($data['def'] !== 'Off') {
8180									$defval = $data['def'];
8181								}
8182							}
8183						}
8184						$annots .= ' ]';
8185						if (!empty($defval)) {
8186							$annots .= ' /V /'.$defval;
8187						}
8188						$annots .= ' >>';
8189						$this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
8190						$this->form_obj_id[] = $radio_button_obj_id;
8191						// store object id to be used on Parent entry of Kids
8192						$this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
8193					}
8194					$formfield = false;
8195					$pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
8196					$a = $pl['x'] * $this->k;
8197					$b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
8198					$c = $pl['w'] * $this->k;
8199					$d = $pl['h'] * $this->k;
8200					$rect = sprintf('%F %F %F %F', $a, $b, $a+$c, $b+$d);
8201					// create new annotation object
8202					$annots = '<</Type /Annot';
8203					$annots .= ' /Subtype /'.$pl['opt']['subtype'];
8204					$annots .= ' /Rect ['.$rect.']';
8205					$ft = array('Btn', 'Tx', 'Ch', 'Sig');
8206					if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
8207						$annots .= ' /FT /'.$pl['opt']['ft'];
8208						$formfield = true;
8209					}
8210					if ($pl['opt']['subtype'] !== 'Link') {
8211						$annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
8212					}
8213					$annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
8214					$annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
8215					$annots .= ' /M '.$this->_datestring($annot_obj_id, $this->doc_modification_timestamp);
8216					if (isset($pl['opt']['f'])) {
8217						$fval = 0;
8218						if (is_array($pl['opt']['f'])) {
8219							foreach ($pl['opt']['f'] as $f) {
8220								switch (strtolower($f)) {
8221									case 'invisible': {
8222										$fval += 1 << 0;
8223										break;
8224									}
8225									case 'hidden': {
8226										$fval += 1 << 1;
8227										break;
8228									}
8229									case 'print': {
8230										$fval += 1 << 2;
8231										break;
8232									}
8233									case 'nozoom': {
8234										$fval += 1 << 3;
8235										break;
8236									}
8237									case 'norotate': {
8238										$fval += 1 << 4;
8239										break;
8240									}
8241									case 'noview': {
8242										$fval += 1 << 5;
8243										break;
8244									}
8245									case 'readonly': {
8246										$fval += 1 << 6;
8247										break;
8248									}
8249									case 'locked': {
8250										$fval += 1 << 8;
8251										break;
8252									}
8253									case 'togglenoview': {
8254										$fval += 1 << 9;
8255										break;
8256									}
8257									case 'lockedcontents': {
8258										$fval += 1 << 10;
8259										break;
8260									}
8261									default: {
8262										break;
8263									}
8264								}
8265							}
8266						} else {
8267							$fval = intval($pl['opt']['f']);
8268						}
8269					} else {
8270						$fval = 4;
8271					}
8272					if ($this->pdfa_mode) {
8273						// force print flag for PDF/A mode
8274						$fval |= 4;
8275					}
8276					$annots .= ' /F '.intval($fval);
8277					if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
8278						$annots .= ' /AS /'.$pl['opt']['as'];
8279					}
8280					if (isset($pl['opt']['ap'])) {
8281						// appearance stream
8282						$annots .= ' /AP <<';
8283						if (is_array($pl['opt']['ap'])) {
8284							foreach ($pl['opt']['ap'] as $apmode => $apdef) {
8285								// $apmode can be: n = normal; r = rollover; d = down;
8286								$annots .= ' /'.strtoupper($apmode);
8287								if (is_array($apdef)) {
8288									$annots .= ' <<';
8289									foreach ($apdef as $apstate => $stream) {
8290										// reference to XObject that define the appearance for this mode-state
8291										$apsobjid = $this->_putAPXObject($c, $d, $stream);
8292										$annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
8293									}
8294									$annots .= ' >>';
8295								} else {
8296									// reference to XObject that define the appearance for this mode
8297									$apsobjid = $this->_putAPXObject($c, $d, $apdef);
8298									$annots .= ' '.$apsobjid.' 0 R';
8299								}
8300							}
8301						} else {
8302							$annots .= $pl['opt']['ap'];
8303						}
8304						$annots .= ' >>';
8305					}
8306					if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
8307						$annots .= ' /BS <<';
8308						$annots .= ' /Type /Border';
8309						if (isset($pl['opt']['bs']['w'])) {
8310							$annots .= ' /W '.intval($pl['opt']['bs']['w']);
8311						}
8312						$bstyles = array('S', 'D', 'B', 'I', 'U');
8313						if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
8314							$annots .= ' /S /'.$pl['opt']['bs']['s'];
8315						}
8316						if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
8317							$annots .= ' /D [';
8318							foreach ($pl['opt']['bs']['d'] as $cord) {
8319								$annots .= ' '.intval($cord);
8320							}
8321							$annots .= ']';
8322						}
8323						$annots .= ' >>';
8324					} else {
8325						$annots .= ' /Border [';
8326						if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
8327							$annots .= intval($pl['opt']['border'][0]).' ';
8328							$annots .= intval($pl['opt']['border'][1]).' ';
8329							$annots .= intval($pl['opt']['border'][2]);
8330							if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
8331								$annots .= ' [';
8332								foreach ($pl['opt']['border'][3] as $dash) {
8333									$annots .= intval($dash).' ';
8334								}
8335								$annots .= ']';
8336							}
8337						} else {
8338							$annots .= '0 0 0';
8339						}
8340						$annots .= ']';
8341					}
8342					if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
8343						$annots .= ' /BE <<';
8344						$bstyles = array('S', 'C');
8345						if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $bstyles)) {
8346							$annots .= ' /S /'.$pl['opt']['bs']['s'];
8347						} else {
8348							$annots .= ' /S /S';
8349						}
8350						if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
8351							$annots .= ' /I '.sprintf(' %F', $pl['opt']['be']['i']);
8352						}
8353						$annots .= '>>';
8354					}
8355					if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
8356						$annots .= ' /C '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['c']);
8357					}
8358					//$annots .= ' /StructParent ';
8359					//$annots .= ' /OC ';
8360					$markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
8361					if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
8362						// this is a markup type
8363						if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
8364							$annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
8365						}
8366						//$annots .= ' /Popup ';
8367						if (isset($pl['opt']['ca'])) {
8368							$annots .= ' /CA '.sprintf('%F', floatval($pl['opt']['ca']));
8369						}
8370						if (isset($pl['opt']['rc'])) {
8371							$annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
8372						}
8373						$annots .= ' /CreationDate '.$this->_datestring($annot_obj_id, $this->doc_creation_timestamp);
8374						//$annots .= ' /IRT ';
8375						if (isset($pl['opt']['subj'])) {
8376							$annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
8377						}
8378						//$annots .= ' /RT ';
8379						//$annots .= ' /IT ';
8380						//$annots .= ' /ExData ';
8381					}
8382					$lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
8383					// Annotation types
8384					switch (strtolower($pl['opt']['subtype'])) {
8385						case 'text': {
8386							if (isset($pl['opt']['open'])) {
8387								$annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
8388							}
8389							$iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
8390							if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
8391								$annots .= ' /Name /'.$pl['opt']['name'];
8392							} else {
8393								$annots .= ' /Name /Note';
8394							}
8395							$statemodels = array('Marked', 'Review');
8396							if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
8397								$annots .= ' /StateModel /'.$pl['opt']['statemodel'];
8398							} else {
8399								$pl['opt']['statemodel'] = 'Marked';
8400								$annots .= ' /StateModel /'.$pl['opt']['statemodel'];
8401							}
8402							if ($pl['opt']['statemodel'] == 'Marked') {
8403								$states = array('Accepted', 'Unmarked');
8404							} else {
8405								$states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
8406							}
8407							if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
8408								$annots .= ' /State /'.$pl['opt']['state'];
8409							} else {
8410								if ($pl['opt']['statemodel'] == 'Marked') {
8411									$annots .= ' /State /Unmarked';
8412								} else {
8413									$annots .= ' /State /None';
8414								}
8415							}
8416							break;
8417						}
8418						case 'link': {
8419							if (is_string($pl['txt']) && !empty($pl['txt'])) {
8420								if ($pl['txt'][0] == '#') {
8421									// internal destination
8422									$annots .= ' /A <</S /GoTo /D '.TCPDF_STATIC::encodeNameObject(substr($pl['txt'], 1)).'>>';
8423								} elseif ($pl['txt'][0] == '%') {
8424									// embedded PDF file
8425									$filename = basename(substr($pl['txt'], 1));
8426									$annots .= ' /A << /S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($n - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
8427								} elseif ($pl['txt'][0] == '*') {
8428									// embedded generic file
8429									$filename = basename(substr($pl['txt'], 1));
8430									$jsa = 'var D=event.target.doc;var MyData=D.dataObjects;for (var i in MyData) if (MyData[i].path=="'.$filename.'") D.exportDataObject( { cName : MyData[i].name, nLaunch : 2});';
8431									$annots .= ' /A << /S /JavaScript /JS '.$this->_textstring($jsa, $annot_obj_id).'>>';
8432								} else {
8433									$parsedUrl = parse_url($pl['txt']);
8434									if (empty($parsedUrl['scheme']) AND (!empty($parsedUrl['path']) && strtolower(substr($parsedUrl['path'], -4)) == '.pdf')) {
8435										// relative link to a PDF file
8436										$dest = '[0 /Fit]'; // default page 0
8437										if (!empty($parsedUrl['fragment'])) {
8438											// check for named destination
8439											$tmp = explode('=', $parsedUrl['fragment']);
8440											$dest = '('.((count($tmp) == 2) ? $tmp[1] : $tmp[0]).')';
8441										}
8442										$annots .= ' /A <</S /GoToR /D '.$dest.' /F '.$this->_datastring($this->unhtmlentities($parsedUrl['path']), $annot_obj_id).' /NewWindow true>>';
8443									} else {
8444										// external URI link
8445										$annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
8446									}
8447								}
8448							} elseif (isset($this->links[$pl['txt']])) {
8449								// internal link ID
8450								$l = $this->links[$pl['txt']];
8451								if (isset($this->page_obj_id[($l['p'])])) {
8452									$annots .= sprintf(' /Dest [%u 0 R /XYZ 0 %F null]', $this->page_obj_id[($l['p'])], ($this->pagedim[$l['p']]['h'] - ($l['y'] * $this->k)));
8453								}
8454							}
8455							$hmodes = array('N', 'I', 'O', 'P');
8456							if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
8457								$annots .= ' /H /'.$pl['opt']['h'];
8458							} else {
8459								$annots .= ' /H /I';
8460							}
8461							//$annots .= ' /PA ';
8462							//$annots .= ' /Quadpoints ';
8463							break;
8464						}
8465						case 'freetext': {
8466							if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
8467								$annots .= ' /DA ('.$pl['opt']['da'].')';
8468							}
8469							if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
8470								$annots .= ' /Q '.intval($pl['opt']['q']);
8471							}
8472							if (isset($pl['opt']['rc'])) {
8473								$annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
8474							}
8475							if (isset($pl['opt']['ds'])) {
8476								$annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
8477							}
8478							if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
8479								$annots .= ' /CL [';
8480								foreach ($pl['opt']['cl'] as $cl) {
8481									$annots .= sprintf('%F ', $cl * $this->k);
8482								}
8483								$annots .= ']';
8484							}
8485							$tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
8486							if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
8487								$annots .= ' /IT /'.$pl['opt']['it'];
8488							}
8489							if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
8490								$l = $pl['opt']['rd'][0] * $this->k;
8491								$r = $pl['opt']['rd'][1] * $this->k;
8492								$t = $pl['opt']['rd'][2] * $this->k;
8493								$b = $pl['opt']['rd'][3] * $this->k;
8494								$annots .= ' /RD ['.sprintf('%F %F %F %F', $l, $r, $t, $b).']';
8495							}
8496							if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
8497								$annots .= ' /LE /'.$pl['opt']['le'];
8498							}
8499							break;
8500						}
8501						case 'line': {
8502							break;
8503						}
8504						case 'square': {
8505							break;
8506						}
8507						case 'circle': {
8508							break;
8509						}
8510						case 'polygon': {
8511							break;
8512						}
8513						case 'polyline': {
8514							break;
8515						}
8516						case 'highlight': {
8517							break;
8518						}
8519						case 'underline': {
8520							break;
8521						}
8522						case 'squiggly': {
8523							break;
8524						}
8525						case 'strikeout': {
8526							break;
8527						}
8528						case 'stamp': {
8529							break;
8530						}
8531						case 'caret': {
8532							break;
8533						}
8534						case 'ink': {
8535							break;
8536						}
8537						case 'popup': {
8538							break;
8539						}
8540						case 'fileattachment': {
8541							if ($this->pdfa_mode && $this->pdfa_version != 3) {
8542								// embedded files are not allowed in PDF/A mode version 1 and 2
8543								break;
8544							}
8545							if (!isset($pl['opt']['fs'])) {
8546								break;
8547							}
8548							$filename = basename($pl['opt']['fs']);
8549							if (isset($this->embeddedfiles[$filename]['f'])) {
8550								$annots .= ' /FS '.$this->embeddedfiles[$filename]['f'].' 0 R';
8551								$iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
8552								if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
8553									$annots .= ' /Name /'.$pl['opt']['name'];
8554								} else {
8555									$annots .= ' /Name /PushPin';
8556								}
8557								// index (zero-based) of the annotation in the Annots array of this page
8558								$this->embeddedfiles[$filename]['a'] = $key;
8559							}
8560							break;
8561						}
8562						case 'sound': {
8563							if (!isset($pl['opt']['fs'])) {
8564								break;
8565							}
8566							$filename = basename($pl['opt']['fs']);
8567							if (isset($this->embeddedfiles[$filename]['f'])) {
8568								// ... TO BE COMPLETED ...
8569								// /R /C /B /E /CO /CP
8570								$annots .= ' /Sound '.$this->embeddedfiles[$filename]['f'].' 0 R';
8571								$iconsapp = array('Speaker', 'Mic');
8572								if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
8573									$annots .= ' /Name /'.$pl['opt']['name'];
8574								} else {
8575									$annots .= ' /Name /Speaker';
8576								}
8577							}
8578							break;
8579						}
8580						case 'movie': {
8581							break;
8582						}
8583						case 'widget': {
8584							$hmode = array('N', 'I', 'O', 'P', 'T');
8585							if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
8586								$annots .= ' /H /'.$pl['opt']['h'];
8587							}
8588							if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
8589								$annots .= ' /MK <<';
8590								if (isset($pl['opt']['mk']['r'])) {
8591									$annots .= ' /R '.$pl['opt']['mk']['r'];
8592								}
8593								if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
8594									$annots .= ' /BC '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bc']);
8595								}
8596								if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
8597									$annots .= ' /BG '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bg']);
8598								}
8599								if (isset($pl['opt']['mk']['ca'])) {
8600									$annots .= ' /CA '.$pl['opt']['mk']['ca'];
8601								}
8602								if (isset($pl['opt']['mk']['rc'])) {
8603									$annots .= ' /RC '.$pl['opt']['mk']['rc'];
8604								}
8605								if (isset($pl['opt']['mk']['ac'])) {
8606									$annots .= ' /AC '.$pl['opt']['mk']['ac'];
8607								}
8608								if (isset($pl['opt']['mk']['i'])) {
8609									$info = $this->getImageBuffer($pl['opt']['mk']['i']);
8610									if ($info !== false) {
8611										$annots .= ' /I '.$info['n'].' 0 R';
8612									}
8613								}
8614								if (isset($pl['opt']['mk']['ri'])) {
8615									$info = $this->getImageBuffer($pl['opt']['mk']['ri']);
8616									if ($info !== false) {
8617										$annots .= ' /RI '.$info['n'].' 0 R';
8618									}
8619								}
8620								if (isset($pl['opt']['mk']['ix'])) {
8621									$info = $this->getImageBuffer($pl['opt']['mk']['ix']);
8622									if ($info !== false) {
8623										$annots .= ' /IX '.$info['n'].' 0 R';
8624									}
8625								}
8626								if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
8627									$annots .= ' /IF <<';
8628									$if_sw = array('A', 'B', 'S', 'N');
8629									if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
8630										$annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
8631									}
8632									$if_s = array('A', 'P');
8633									if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
8634										$annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
8635									}
8636									if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
8637										$annots .= sprintf(' /A [%F %F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
8638									}
8639									if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
8640										$annots .= ' /FB true';
8641									}
8642									$annots .= '>>';
8643								}
8644								if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
8645									$annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
8646								}
8647								$annots .= '>>';
8648							} // end MK
8649							// --- Entries for field dictionaries ---
8650							if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
8651								// set parent
8652								$annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
8653							}
8654							if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
8655								$annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
8656							}
8657							if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
8658								$annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
8659							}
8660							if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
8661								$annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
8662							}
8663							if (isset($pl['opt']['ff'])) {
8664								if (is_array($pl['opt']['ff'])) {
8665									// array of bit settings
8666									$flag = 0;
8667									foreach($pl['opt']['ff'] as $val) {
8668										$flag += 1 << ($val - 1);
8669									}
8670								} else {
8671									$flag = intval($pl['opt']['ff']);
8672								}
8673								$annots .= ' /Ff '.$flag;
8674							}
8675							if (isset($pl['opt']['maxlen'])) {
8676								$annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
8677							}
8678							if (isset($pl['opt']['v'])) {
8679								$annots .= ' /V';
8680								if (is_array($pl['opt']['v'])) {
8681									foreach ($pl['opt']['v'] AS $optval) {
8682										if (is_float($optval)) {
8683											$optval = sprintf('%F', $optval);
8684										}
8685										$annots .= ' '.$optval;
8686									}
8687								} else {
8688									$annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
8689								}
8690							}
8691							if (isset($pl['opt']['dv'])) {
8692								$annots .= ' /DV';
8693								if (is_array($pl['opt']['dv'])) {
8694									foreach ($pl['opt']['dv'] AS $optval) {
8695										if (is_float($optval)) {
8696											$optval = sprintf('%F', $optval);
8697										}
8698										$annots .= ' '.$optval;
8699									}
8700								} else {
8701									$annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
8702								}
8703							}
8704							if (isset($pl['opt']['rv'])) {
8705								$annots .= ' /RV';
8706								if (is_array($pl['opt']['rv'])) {
8707									foreach ($pl['opt']['rv'] AS $optval) {
8708										if (is_float($optval)) {
8709											$optval = sprintf('%F', $optval);
8710										}
8711										$annots .= ' '.$optval;
8712									}
8713								} else {
8714									$annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
8715								}
8716							}
8717							if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
8718								$annots .= ' /A << '.$pl['opt']['a'].' >>';
8719							}
8720							if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
8721								$annots .= ' /AA << '.$pl['opt']['aa'].' >>';
8722							}
8723							if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
8724								$annots .= ' /DA ('.$pl['opt']['da'].')';
8725							}
8726							if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
8727								$annots .= ' /Q '.intval($pl['opt']['q']);
8728							}
8729							if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
8730								$annots .= ' /Opt [';
8731								foreach($pl['opt']['opt'] AS $copt) {
8732									if (is_array($copt)) {
8733										$annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
8734									} else {
8735										$annots .= ' '.$this->_textstring($copt, $annot_obj_id);
8736									}
8737								}
8738								$annots .= ']';
8739							}
8740							if (isset($pl['opt']['ti'])) {
8741								$annots .= ' /TI '.intval($pl['opt']['ti']);
8742							}
8743							if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
8744								$annots .= ' /I [';
8745								foreach($pl['opt']['i'] AS $copt) {
8746									$annots .= intval($copt).' ';
8747								}
8748								$annots .= ']';
8749							}
8750							break;
8751						}
8752						case 'screen': {
8753							break;
8754						}
8755						case 'printermark': {
8756							break;
8757						}
8758						case 'trapnet': {
8759							break;
8760						}
8761						case 'watermark': {
8762							break;
8763						}
8764						case '3d': {
8765							break;
8766						}
8767						default: {
8768							break;
8769						}
8770					}
8771					$annots .= '>>';
8772					// create new annotation object
8773					$this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
8774					if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
8775						// store reference of form object
8776						$this->form_obj_id[] = $annot_obj_id;
8777					}
8778				}
8779			}
8780		} // end for each page
8781	}
8782
8783	/**
8784	 * Put appearance streams XObject used to define annotation's appearance states.
8785	 * @param $w (int) annotation width
8786	 * @param $h (int) annotation height
8787	 * @param $stream (string) appearance stream
8788	 * @return int object ID
8789	 * @protected
8790	 * @since 4.8.001 (2009-09-09)
8791	 */
8792	protected function _putAPXObject($w=0, $h=0, $stream='') {
8793		$stream = trim($stream);
8794		$out = $this->_getobj()."\n";
8795		$this->xobjects['AX'.$this->n] = array('n' => $this->n);
8796		$out .= '<<';
8797		$out .= ' /Type /XObject';
8798		$out .= ' /Subtype /Form';
8799		$out .= ' /FormType 1';
8800		if ($this->compress) {
8801			$stream = gzcompress($stream);
8802			$out .= ' /Filter /FlateDecode';
8803		}
8804		$rect = sprintf('%F %F', $w, $h);
8805		$out .= ' /BBox [0 0 '.$rect.']';
8806		$out .= ' /Matrix [1 0 0 1 0 0]';
8807		$out .= ' /Resources 2 0 R';
8808		$stream = $this->_getrawstream($stream);
8809		$out .= ' /Length '.strlen($stream);
8810		$out .= ' >>';
8811		$out .= ' stream'."\n".$stream."\n".'endstream';
8812		$out .= "\n".'endobj';
8813		$this->_out($out);
8814		return $this->n;
8815	}
8816
8817	/**
8818	 * Output fonts.
8819	 * @author Nicola Asuni
8820	 * @protected
8821	 */
8822	protected function _putfonts() {
8823		$nf = $this->n;
8824		foreach ($this->diffs as $diff) {
8825			//Encodings
8826			$this->_newobj();
8827			$this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
8828		}
8829		$mqr = TCPDF_STATIC::get_mqr();
8830		TCPDF_STATIC::set_mqr(false);
8831		foreach ($this->FontFiles as $file => $info) {
8832			// search and get font file to embedd
8833			$fontfile = TCPDF_FONTS::getFontFullPath($file, $info['fontdir']);
8834			if (!TCPDF_STATIC::empty_string($fontfile)) {
8835				$font = file_get_contents($fontfile);
8836				$compressed = (substr($file, -2) == '.z');
8837				if ((!$compressed) AND (isset($info['length2']))) {
8838					$header = (ord($font[0]) == 128);
8839					if ($header) {
8840						// strip first binary header
8841						$font = substr($font, 6);
8842					}
8843					if ($header AND (ord($font[$info['length1']]) == 128)) {
8844						// strip second binary header
8845						$font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
8846					}
8847				} elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
8848					if ($compressed) {
8849						// uncompress font
8850						$font = gzuncompress($font);
8851					}
8852					// merge subset characters
8853					$subsetchars = array(); // used chars
8854					foreach ($info['fontkeys'] as $fontkey) {
8855						$fontinfo = $this->getFontBuffer($fontkey);
8856						$subsetchars += $fontinfo['subsetchars'];
8857					}
8858					// rebuild a font subset
8859					$font = TCPDF_FONTS::_getTrueTypeFontSubset($font, $subsetchars);
8860					// calculate new font length
8861					$info['length1'] = strlen($font);
8862					if ($compressed) {
8863						// recompress font
8864						$font = gzcompress($font);
8865					}
8866				}
8867				$this->_newobj();
8868				$this->FontFiles[$file]['n'] = $this->n;
8869				$stream = $this->_getrawstream($font);
8870				$out = '<< /Length '.strlen($stream);
8871				if ($compressed) {
8872					$out .= ' /Filter /FlateDecode';
8873				}
8874				$out .= ' /Length1 '.$info['length1'];
8875				if (isset($info['length2'])) {
8876					$out .= ' /Length2 '.$info['length2'].' /Length3 0';
8877				}
8878				$out .= ' >>';
8879				$out .= ' stream'."\n".$stream."\n".'endstream';
8880				$out .= "\n".'endobj';
8881				$this->_out($out);
8882			}
8883		}
8884		TCPDF_STATIC::set_mqr($mqr);
8885		foreach ($this->fontkeys as $k) {
8886			//Font objects
8887			$font = $this->getFontBuffer($k);
8888			$type = $font['type'];
8889			$name = $font['name'];
8890			if ($type == 'core') {
8891				// standard core font
8892				$out = $this->_getobj($this->font_obj_ids[$k])."\n";
8893				$out .= '<</Type /Font';
8894				$out .= ' /Subtype /Type1';
8895				$out .= ' /BaseFont /'.$name;
8896				$out .= ' /Name /F'.$font['i'];
8897				if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
8898					$out .= ' /Encoding /WinAnsiEncoding';
8899				}
8900				if ($k == 'helvetica') {
8901					// add default font for annotations
8902					$this->annotation_fonts[$k] = $font['i'];
8903				}
8904				$out .= ' >>';
8905				$out .= "\n".'endobj';
8906				$this->_out($out);
8907			} elseif (($type == 'Type1') OR ($type == 'TrueType')) {
8908				// additional Type1 or TrueType font
8909				$out = $this->_getobj($this->font_obj_ids[$k])."\n";
8910				$out .= '<</Type /Font';
8911				$out .= ' /Subtype /'.$type;
8912				$out .= ' /BaseFont /'.$name;
8913				$out .= ' /Name /F'.$font['i'];
8914				$out .= ' /FirstChar 32 /LastChar 255';
8915				$out .= ' /Widths '.($this->n + 1).' 0 R';
8916				$out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
8917				if ($font['enc']) {
8918					if (isset($font['diff'])) {
8919						$out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
8920					} else {
8921						$out .= ' /Encoding /WinAnsiEncoding';
8922					}
8923				}
8924				$out .= ' >>';
8925				$out .= "\n".'endobj';
8926				$this->_out($out);
8927				// Widths
8928				$this->_newobj();
8929				$s = '[';
8930				for ($i = 32; $i < 256; ++$i) {
8931					if (isset($font['cw'][$i])) {
8932						$s .= $font['cw'][$i].' ';
8933					} else {
8934						$s .= $font['dw'].' ';
8935					}
8936				}
8937				$s .= ']';
8938				$s .= "\n".'endobj';
8939				$this->_out($s);
8940				//Descriptor
8941				$this->_newobj();
8942				$s = '<</Type /FontDescriptor /FontName /'.$name;
8943				foreach ($font['desc'] as $fdk => $fdv) {
8944					if (is_float($fdv)) {
8945						$fdv = sprintf('%F', $fdv);
8946					}
8947					$s .= ' /'.$fdk.' '.$fdv.'';
8948				}
8949				if (!TCPDF_STATIC::empty_string($font['file'])) {
8950					$s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
8951				}
8952				$s .= '>>';
8953				$s .= "\n".'endobj';
8954				$this->_out($s);
8955			} else {
8956				// additional types
8957				$mtd = '_put'.strtolower($type);
8958				if (!method_exists($this, $mtd)) {
8959					$this->Error('Unsupported font type: '.$type);
8960				}
8961				$this->$mtd($font);
8962			}
8963		}
8964	}
8965
8966	/**
8967	 * Adds unicode fonts.<br>
8968	 * Based on PDF Reference 1.3 (section 5)
8969	 * @param $font (array) font data
8970	 * @protected
8971	 * @author Nicola Asuni
8972	 * @since 1.52.0.TC005 (2005-01-05)
8973	 */
8974	protected function _puttruetypeunicode($font) {
8975		$fontname = '';
8976		if ($font['subset']) {
8977			// change name for font subsetting
8978			$subtag = sprintf('%06u', $font['i']);
8979			$subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
8980			$fontname .= $subtag.'+';
8981		}
8982		$fontname .= $font['name'];
8983		// Type0 Font
8984		// A composite font composed of other fonts, organized hierarchically
8985		$out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
8986		$out .= '<< /Type /Font';
8987		$out .= ' /Subtype /Type0';
8988		$out .= ' /BaseFont /'.$fontname;
8989		$out .= ' /Name /F'.$font['i'];
8990		$out .= ' /Encoding /'.$font['enc'];
8991		$out .= ' /ToUnicode '.($this->n + 1).' 0 R';
8992		$out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
8993		$out .= ' >>';
8994		$out .= "\n".'endobj';
8995		$this->_out($out);
8996		// ToUnicode map for Identity-H
8997		$stream = TCPDF_FONT_DATA::$uni_identity_h;
8998		// ToUnicode Object
8999		$this->_newobj();
9000		$stream = ($this->compress) ? gzcompress($stream) : $stream;
9001		$filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
9002		$stream = $this->_getrawstream($stream);
9003		$this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
9004		// CIDFontType2
9005		// A CIDFont whose glyph descriptions are based on TrueType font technology
9006		$oid = $this->_newobj();
9007		$out = '<< /Type /Font';
9008		$out .= ' /Subtype /CIDFontType2';
9009		$out .= ' /BaseFont /'.$fontname;
9010		// A dictionary containing entries that define the character collection of the CIDFont.
9011		$cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
9012		$cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
9013		$cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
9014		$out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
9015		$out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
9016		$out .= ' /DW '.$font['dw']; // default width
9017		$out .= "\n".TCPDF_FONTS::_putfontwidths($font, 0);
9018		if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
9019			$out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
9020		}
9021		$out .= ' >>';
9022		$out .= "\n".'endobj';
9023		$this->_out($out);
9024		// Font descriptor
9025		// A font descriptor describing the CIDFont default metrics other than its glyph widths
9026		$this->_newobj();
9027		$out = '<< /Type /FontDescriptor';
9028		$out .= ' /FontName /'.$fontname;
9029		foreach ($font['desc'] as $key => $value) {
9030			if (is_float($value)) {
9031				$value = sprintf('%F', $value);
9032			}
9033			$out .= ' /'.$key.' '.$value;
9034		}
9035		$fontdir = false;
9036		if (!TCPDF_STATIC::empty_string($font['file'])) {
9037			// A stream containing a TrueType font
9038			$out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
9039			$fontdir = $this->FontFiles[$font['file']]['fontdir'];
9040		}
9041		$out .= ' >>';
9042		$out .= "\n".'endobj';
9043		$this->_out($out);
9044		if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
9045			$this->_newobj();
9046			// Embed CIDToGIDMap
9047			// A specification of the mapping from CIDs to glyph indices
9048			// search and get CTG font file to embedd
9049			$ctgfile = strtolower($font['ctg']);
9050			// search and get ctg font file to embedd
9051			$fontfile = TCPDF_FONTS::getFontFullPath($ctgfile, $fontdir);
9052			if (TCPDF_STATIC::empty_string($fontfile)) {
9053				$this->Error('Font file not found: '.$ctgfile);
9054			}
9055			$stream = $this->_getrawstream(file_get_contents($fontfile));
9056			$out = '<< /Length '.strlen($stream).'';
9057			if (substr($fontfile, -2) == '.z') { // check file extension
9058				// Decompresses data encoded using the public-domain
9059				// zlib/deflate compression method, reproducing the
9060				// original text or binary data
9061				$out .= ' /Filter /FlateDecode';
9062			}
9063			$out .= ' >>';
9064			$out .= ' stream'."\n".$stream."\n".'endstream';
9065			$out .= "\n".'endobj';
9066			$this->_out($out);
9067		}
9068	}
9069
9070	/**
9071	 * Output CID-0 fonts.
9072	 * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
9073	 * @param $font (array) font data
9074	 * @protected
9075	 * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
9076	 * @since 3.2.000 (2008-06-23)
9077	 */
9078	protected function _putcidfont0($font) {
9079		$cidoffset = 0;
9080		if (!isset($font['cw'][1])) {
9081			$cidoffset = 31;
9082		}
9083		if (isset($font['cidinfo']['uni2cid'])) {
9084			// convert unicode to cid.
9085			$uni2cid = $font['cidinfo']['uni2cid'];
9086			$cw = array();
9087			foreach ($font['cw'] as $uni => $width) {
9088				if (isset($uni2cid[$uni])) {
9089					$cw[($uni2cid[$uni] + $cidoffset)] = $width;
9090				} elseif ($uni < 256) {
9091					$cw[$uni] = $width;
9092				} // else unknown character
9093			}
9094			$font = array_merge($font, array('cw' => $cw));
9095		}
9096		$name = $font['name'];
9097		$enc = $font['enc'];
9098		if ($enc) {
9099			$longname = $name.'-'.$enc;
9100		} else {
9101			$longname = $name;
9102		}
9103		$out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
9104		$out .= '<</Type /Font';
9105		$out .= ' /Subtype /Type0';
9106		$out .= ' /BaseFont /'.$longname;
9107		$out .= ' /Name /F'.$font['i'];
9108		if ($enc) {
9109			$out .= ' /Encoding /'.$enc;
9110		}
9111		$out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
9112		$out .= ' >>';
9113		$out .= "\n".'endobj';
9114		$this->_out($out);
9115		$oid = $this->_newobj();
9116		$out = '<</Type /Font';
9117		$out .= ' /Subtype /CIDFontType0';
9118		$out .= ' /BaseFont /'.$name;
9119		$cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
9120		$cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
9121		$cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
9122		$out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
9123		$out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
9124		$out .= ' /DW '.$font['dw'];
9125		$out .= "\n".TCPDF_FONTS::_putfontwidths($font, $cidoffset);
9126		$out .= ' >>';
9127		$out .= "\n".'endobj';
9128		$this->_out($out);
9129		$this->_newobj();
9130		$s = '<</Type /FontDescriptor /FontName /'.$name;
9131		foreach ($font['desc'] as $k => $v) {
9132			if ($k != 'Style') {
9133				if (is_float($v)) {
9134					$v = sprintf('%F', $v);
9135				}
9136				$s .= ' /'.$k.' '.$v.'';
9137			}
9138		}
9139		$s .= '>>';
9140		$s .= "\n".'endobj';
9141		$this->_out($s);
9142	}
9143
9144	/**
9145	 * Output images.
9146	 * @protected
9147	 */
9148	protected function _putimages() {
9149		$filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
9150		foreach ($this->imagekeys as $file) {
9151			$info = $this->getImageBuffer($file);
9152			// set object for alternate images array
9153			if ((!$this->pdfa_mode) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
9154				$altoid = $this->_newobj();
9155				$out = '[';
9156				foreach ($info['altimgs'] as $altimage) {
9157					if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
9158						$out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
9159						$out .= ' /DefaultForPrinting';
9160						if ($altimage[1] === true) {
9161							$out .= ' true';
9162						} else {
9163							$out .= ' false';
9164						}
9165						$out .= ' >>';
9166					}
9167				}
9168				$out .= ' ]';
9169				$out .= "\n".'endobj';
9170				$this->_out($out);
9171			}
9172			// set image object
9173			$oid = $this->_newobj();
9174			$this->xobjects['I'.$info['i']] = array('n' => $oid);
9175			$this->setImageSubBuffer($file, 'n', $this->n);
9176			$out = '<</Type /XObject';
9177			$out .= ' /Subtype /Image';
9178			$out .= ' /Width '.$info['w'];
9179			$out .= ' /Height '.$info['h'];
9180			if (array_key_exists('masked', $info)) {
9181				$out .= ' /SMask '.($this->n - 1).' 0 R';
9182			}
9183			// set color space
9184			$icc = false;
9185			if (isset($info['icc']) AND ($info['icc'] !== false)) {
9186				// ICC Colour Space
9187				$icc = true;
9188				$out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
9189			} elseif ($info['cs'] == 'Indexed') {
9190				// Indexed Colour Space
9191				$out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
9192			} else {
9193				// Device Colour Space
9194				$out .= ' /ColorSpace /'.$info['cs'];
9195			}
9196			if ($info['cs'] == 'DeviceCMYK') {
9197				$out .= ' /Decode [1 0 1 0 1 0 1 0]';
9198			}
9199			$out .= ' /BitsPerComponent '.$info['bpc'];
9200			if (isset($altoid) AND ($altoid > 0)) {
9201				// reference to alternate images dictionary
9202				$out .= ' /Alternates '.$altoid.' 0 R';
9203			}
9204			if (isset($info['exurl']) AND !empty($info['exurl'])) {
9205				// external stream
9206				$out .= ' /Length 0';
9207				$out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
9208				if (isset($info['f'])) {
9209					$out .= ' /FFilter /'.$info['f'];
9210				}
9211				$out .= ' >>';
9212				$out .= ' stream'."\n".'endstream';
9213			} else {
9214				if (isset($info['f'])) {
9215					$out .= ' /Filter /'.$info['f'];
9216				}
9217				if (isset($info['parms'])) {
9218					$out .= ' '.$info['parms'];
9219				}
9220				if (isset($info['trns']) AND is_array($info['trns'])) {
9221					$trns = '';
9222					$count_info = count($info['trns']);
9223					if ($info['cs'] == 'Indexed') {
9224						$maxval =(pow(2, $info['bpc']) - 1);
9225						for ($i = 0; $i < $count_info; ++$i) {
9226							if (($info['trns'][$i] != 0) AND ($info['trns'][$i] != $maxval)) {
9227								// this is not a binary type mask @TODO: create a SMask
9228								$trns = '';
9229								break;
9230							} elseif (empty($trns) AND ($info['trns'][$i] == 0)) {
9231								// store the first fully transparent value
9232								$trns .= $i.' '.$i.' ';
9233							}
9234						}
9235					} else {
9236						// grayscale or RGB
9237						for ($i = 0; $i < $count_info; ++$i) {
9238							if ($info['trns'][$i] == 0) {
9239								$trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
9240							}
9241						}
9242					}
9243					// Colour Key Masking
9244					if (!empty($trns)) {
9245						$out .= ' /Mask ['.$trns.']';
9246					}
9247				}
9248				$stream = $this->_getrawstream($info['data']);
9249				$out .= ' /Length '.strlen($stream).' >>';
9250				$out .= ' stream'."\n".$stream."\n".'endstream';
9251			}
9252			$out .= "\n".'endobj';
9253			$this->_out($out);
9254			if ($icc) {
9255				// ICC colour profile
9256				$this->_newobj();
9257				$icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
9258				$icc = $this->_getrawstream($icc);
9259				$this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
9260			} elseif ($info['cs'] == 'Indexed') {
9261				// colour palette
9262				$this->_newobj();
9263				$pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
9264				$pal = $this->_getrawstream($pal);
9265				$this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
9266			}
9267		}
9268	}
9269
9270	/**
9271	 * Output Form XObjects Templates.
9272	 * @author Nicola Asuni
9273	 * @since 5.8.017 (2010-08-24)
9274	 * @protected
9275	 * @see startTemplate(), endTemplate(), printTemplate()
9276	 */
9277	protected function _putxobjects() {
9278		foreach ($this->xobjects as $key => $data) {
9279			if (isset($data['outdata'])) {
9280				$stream = str_replace($this->epsmarker, '', trim($data['outdata']));
9281				$out = $this->_getobj($data['n'])."\n";
9282				$out .= '<<';
9283				$out .= ' /Type /XObject';
9284				$out .= ' /Subtype /Form';
9285				$out .= ' /FormType 1';
9286				if ($this->compress) {
9287					$stream = gzcompress($stream);
9288					$out .= ' /Filter /FlateDecode';
9289				}
9290				$out .= sprintf(' /BBox [%F %F %F %F]', ($data['x'] * $this->k), (-$data['y'] * $this->k), (($data['w'] + $data['x']) * $this->k), (($data['h'] - $data['y']) * $this->k));
9291				$out .= ' /Matrix [1 0 0 1 0 0]';
9292				$out .= ' /Resources <<';
9293				$out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
9294				if (!$this->pdfa_mode) {
9295					// transparency
9296					if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
9297						$out .= ' /ExtGState <<';
9298						foreach ($data['extgstates'] as $k => $extgstate) {
9299							if (isset($this->extgstates[$k]['name'])) {
9300								$out .= ' /'.$this->extgstates[$k]['name'];
9301							} else {
9302								$out .= ' /GS'.$k;
9303							}
9304							$out .= ' '.$this->extgstates[$k]['n'].' 0 R';
9305						}
9306						$out .= ' >>';
9307					}
9308					if (isset($data['gradients']) AND !empty($data['gradients'])) {
9309						$gp = '';
9310						$gs = '';
9311						foreach ($data['gradients'] as $id => $grad) {
9312							// gradient patterns
9313							$gp .= ' /p'.$id.' '.$this->gradients[$id]['pattern'].' 0 R';
9314							// gradient shadings
9315							$gs .= ' /Sh'.$id.' '.$this->gradients[$id]['id'].' 0 R';
9316						}
9317						$out .= ' /Pattern <<'.$gp.' >>';
9318						$out .= ' /Shading <<'.$gs.' >>';
9319					}
9320				}
9321				// spot colors
9322				if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
9323					$out .= ' /ColorSpace <<';
9324					foreach ($data['spot_colors'] as $name => $color) {
9325						$out .= ' /CS'.$color['i'].' '.$this->spot_colors[$name]['n'].' 0 R';
9326					}
9327					$out .= ' >>';
9328				}
9329				// fonts
9330				if (!empty($data['fonts'])) {
9331					$out .= ' /Font <<';
9332					foreach ($data['fonts'] as $fontkey => $fontid) {
9333						$out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
9334					}
9335					$out .= ' >>';
9336				}
9337				// images or nested xobjects
9338				if (!empty($data['images']) OR !empty($data['xobjects'])) {
9339					$out .= ' /XObject <<';
9340					foreach ($data['images'] as $imgid) {
9341						$out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
9342					}
9343					foreach ($data['xobjects'] as $sub_id => $sub_objid) {
9344						$out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
9345					}
9346					$out .= ' >>';
9347				}
9348				$out .= ' >>'; //end resources
9349				if (isset($data['group']) AND ($data['group'] !== false)) {
9350					// set transparency group
9351					$out .= ' /Group << /Type /Group /S /Transparency';
9352					if (is_array($data['group'])) {
9353						if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
9354							$out .= ' /CS /'.$data['group']['CS'];
9355						}
9356						if (isset($data['group']['I'])) {
9357							$out .= ' /I /'.($data['group']['I']===true?'true':'false');
9358						}
9359						if (isset($data['group']['K'])) {
9360							$out .= ' /K /'.($data['group']['K']===true?'true':'false');
9361						}
9362					}
9363					$out .= ' >>';
9364				}
9365				$stream = $this->_getrawstream($stream, $data['n']);
9366				$out .= ' /Length '.strlen($stream);
9367				$out .= ' >>';
9368				$out .= ' stream'."\n".$stream."\n".'endstream';
9369				$out .= "\n".'endobj';
9370				$this->_out($out);
9371			}
9372		}
9373	}
9374
9375	/**
9376	 * Output Spot Colors Resources.
9377	 * @protected
9378	 * @since 4.0.024 (2008-09-12)
9379	 */
9380	protected function _putspotcolors() {
9381		foreach ($this->spot_colors as $name => $color) {
9382			$this->_newobj();
9383			$this->spot_colors[$name]['n'] = $this->n;
9384			$out = '[/Separation /'.str_replace(' ', '#20', $name);
9385			$out .= ' /DeviceCMYK <<';
9386			$out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
9387			$out .= ' '.sprintf('/C1 [%F %F %F %F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
9388			$out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
9389			$out .= "\n".'endobj';
9390			$this->_out($out);
9391		}
9392	}
9393
9394	/**
9395	 * Return XObjects Dictionary.
9396	 * @return string XObjects dictionary
9397	 * @protected
9398	 * @since 5.8.014 (2010-08-23)
9399	 */
9400	protected function _getxobjectdict() {
9401		$out = '';
9402		foreach ($this->xobjects as $id => $objid) {
9403			$out .= ' /'.$id.' '.$objid['n'].' 0 R';
9404		}
9405		return $out;
9406	}
9407
9408	/**
9409	 * Output Resources Dictionary.
9410	 * @protected
9411	 */
9412	protected function _putresourcedict() {
9413		$out = $this->_getobj(2)."\n";
9414		$out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
9415		$out .= ' /Font <<';
9416		foreach ($this->fontkeys as $fontkey) {
9417			$font = $this->getFontBuffer($fontkey);
9418			$out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
9419		}
9420		$out .= ' >>';
9421		$out .= ' /XObject <<';
9422		$out .= $this->_getxobjectdict();
9423		$out .= ' >>';
9424		// layers
9425		if (!empty($this->pdflayers)) {
9426			$out .= ' /Properties <<';
9427			foreach ($this->pdflayers as $layer) {
9428				$out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
9429			}
9430			$out .= ' >>';
9431		}
9432		if (!$this->pdfa_mode) {
9433			// transparency
9434			if (isset($this->extgstates) AND !empty($this->extgstates)) {
9435				$out .= ' /ExtGState <<';
9436				foreach ($this->extgstates as $k => $extgstate) {
9437					if (isset($extgstate['name'])) {
9438						$out .= ' /'.$extgstate['name'];
9439					} else {
9440						$out .= ' /GS'.$k;
9441					}
9442					$out .= ' '.$extgstate['n'].' 0 R';
9443				}
9444				$out .= ' >>';
9445			}
9446			if (isset($this->gradients) AND !empty($this->gradients)) {
9447				$gp = '';
9448				$gs = '';
9449				foreach ($this->gradients as $id => $grad) {
9450					// gradient patterns
9451					$gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
9452					// gradient shadings
9453					$gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
9454				}
9455				$out .= ' /Pattern <<'.$gp.' >>';
9456				$out .= ' /Shading <<'.$gs.' >>';
9457			}
9458		}
9459		// spot colors
9460		if (isset($this->spot_colors) AND !empty($this->spot_colors)) {
9461			$out .= ' /ColorSpace <<';
9462			foreach ($this->spot_colors as $color) {
9463				$out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
9464			}
9465			$out .= ' >>';
9466		}
9467		$out .= ' >>';
9468		$out .= "\n".'endobj';
9469		$this->_out($out);
9470	}
9471
9472	/**
9473	 * Output Resources.
9474	 * @protected
9475	 */
9476	protected function _putresources() {
9477		$this->_putextgstates();
9478		$this->_putocg();
9479		$this->_putfonts();
9480		$this->_putimages();
9481		$this->_putspotcolors();
9482		$this->_putshaders();
9483		$this->_putxobjects();
9484		$this->_putresourcedict();
9485		$this->_putdests();
9486		$this->_putEmbeddedFiles();
9487		$this->_putannotsobjs();
9488		$this->_putjavascript();
9489		$this->_putbookmarks();
9490		$this->_putencryption();
9491	}
9492
9493	/**
9494	 * Adds some Metadata information (Document Information Dictionary)
9495	 * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
9496	 * @return int object id
9497	 * @protected
9498	 */
9499	protected function _putinfo() {
9500		$oid = $this->_newobj();
9501		$out = '<<';
9502		// store current isunicode value
9503		$prev_isunicode = $this->isunicode;
9504		if ($this->docinfounicode) {
9505			$this->isunicode = true;
9506		}
9507		if (!TCPDF_STATIC::empty_string($this->title)) {
9508			// The document's title.
9509			$out .= ' /Title '.$this->_textstring($this->title, $oid);
9510		}
9511		if (!TCPDF_STATIC::empty_string($this->author)) {
9512			// The name of the person who created the document.
9513			$out .= ' /Author '.$this->_textstring($this->author, $oid);
9514		}
9515		if (!TCPDF_STATIC::empty_string($this->subject)) {
9516			// The subject of the document.
9517			$out .= ' /Subject '.$this->_textstring($this->subject, $oid);
9518		}
9519		if (!TCPDF_STATIC::empty_string($this->keywords)) {
9520			// Keywords associated with the document.
9521			$out .= ' /Keywords '.$this->_textstring($this->keywords, $oid);
9522		}
9523		if (!TCPDF_STATIC::empty_string($this->creator)) {
9524			// If the document was converted to PDF from another format, the name of the conforming product that created the original document from which it was converted.
9525			$out .= ' /Creator '.$this->_textstring($this->creator, $oid);
9526		}
9527		// restore previous isunicode value
9528		$this->isunicode = $prev_isunicode;
9529		// default producer
9530		$out .= ' /Producer '.$this->_textstring(TCPDF_STATIC::getTCPDFProducer(), $oid);
9531		// The date and time the document was created, in human-readable form
9532		$out .= ' /CreationDate '.$this->_datestring(0, $this->doc_creation_timestamp);
9533		// The date and time the document was most recently modified, in human-readable form
9534		$out .= ' /ModDate '.$this->_datestring(0, $this->doc_modification_timestamp);
9535		// A name object indicating whether the document has been modified to include trapping information
9536		$out .= ' /Trapped /False';
9537		$out .= ' >>';
9538		$out .= "\n".'endobj';
9539		$this->_out($out);
9540		return $oid;
9541	}
9542
9543	/**
9544	 * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
9545	 * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
9546	 * @param $xmp (string) Custom XMP data.
9547	 * @since 5.9.128 (2011-10-06)
9548	 * @public
9549	 */
9550	public function setExtraXMP($xmp) {
9551		$this->custom_xmp = $xmp;
9552	}
9553
9554	/**
9555	 * Set additional XMP data to be added on the default XMP data just before the end of "rdf:RDF" tag.
9556	 * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
9557	 * @param $xmp (string) Custom XMP RDF data.
9558	 * @since 6.3.0 (2019-09-19)
9559	 * @public
9560	 */
9561	public function setExtraXMPRDF($xmp) {
9562		$this->custom_xmp_rdf = $xmp;
9563	}
9564
9565	/**
9566	 * Put XMP data object and return ID.
9567	 * @return (int) The object ID.
9568	 * @since 5.9.121 (2011-09-28)
9569	 * @protected
9570	 */
9571	protected function _putXMP() {
9572		$oid = $this->_newobj();
9573		// store current isunicode value
9574		$prev_isunicode = $this->isunicode;
9575		$this->isunicode = true;
9576		$prev_encrypted = $this->encrypted;
9577		$this->encrypted = false;
9578		// set XMP data
9579		$xmp = '<?xpacket begin="'.TCPDF_FONTS::unichr(0xfeff, $this->isunicode).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
9580		$xmp .= '<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 4.2.1-c043 52.372728, 2009/01/18-15:08:04">'."\n";
9581		$xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
9582		$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
9583		$xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
9584		$xmp .= "\t\t\t".'<dc:title>'."\n";
9585		$xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
9586		$xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->title).'</rdf:li>'."\n";
9587		$xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
9588		$xmp .= "\t\t\t".'</dc:title>'."\n";
9589		$xmp .= "\t\t\t".'<dc:creator>'."\n";
9590		$xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
9591		$xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->author).'</rdf:li>'."\n";
9592		$xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
9593		$xmp .= "\t\t\t".'</dc:creator>'."\n";
9594		$xmp .= "\t\t\t".'<dc:description>'."\n";
9595		$xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
9596		$xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->subject).'</rdf:li>'."\n";
9597		$xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
9598		$xmp .= "\t\t\t".'</dc:description>'."\n";
9599		$xmp .= "\t\t\t".'<dc:subject>'."\n";
9600		$xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
9601		$xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->keywords).'</rdf:li>'."\n";
9602		$xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
9603		$xmp .= "\t\t\t".'</dc:subject>'."\n";
9604		$xmp .= "\t\t".'</rdf:Description>'."\n";
9605		// convert doc creation date format
9606		$dcdate = TCPDF_STATIC::getFormattedDate($this->doc_creation_timestamp);
9607		$doccreationdate = substr($dcdate, 0, 4).'-'.substr($dcdate, 4, 2).'-'.substr($dcdate, 6, 2);
9608		$doccreationdate .= 'T'.substr($dcdate, 8, 2).':'.substr($dcdate, 10, 2).':'.substr($dcdate, 12, 2);
9609		$doccreationdate .= substr($dcdate, 14, 3).':'.substr($dcdate, 18, 2);
9610		$doccreationdate = TCPDF_STATIC::_escapeXML($doccreationdate);
9611		// convert doc modification date format
9612		$dmdate = TCPDF_STATIC::getFormattedDate($this->doc_modification_timestamp);
9613		$docmoddate = substr($dmdate, 0, 4).'-'.substr($dmdate, 4, 2).'-'.substr($dmdate, 6, 2);
9614		$docmoddate .= 'T'.substr($dmdate, 8, 2).':'.substr($dmdate, 10, 2).':'.substr($dmdate, 12, 2);
9615		$docmoddate .= substr($dmdate, 14, 3).':'.substr($dmdate, 18, 2);
9616		$docmoddate = TCPDF_STATIC::_escapeXML($docmoddate);
9617		$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
9618		$xmp .= "\t\t\t".'<xmp:CreateDate>'.$doccreationdate.'</xmp:CreateDate>'."\n";
9619		$xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator.'</xmp:CreatorTool>'."\n";
9620		$xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docmoddate.'</xmp:ModifyDate>'."\n";
9621		$xmp .= "\t\t\t".'<xmp:MetadataDate>'.$doccreationdate.'</xmp:MetadataDate>'."\n";
9622		$xmp .= "\t\t".'</rdf:Description>'."\n";
9623		$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
9624		$xmp .= "\t\t\t".'<pdf:Keywords>'.TCPDF_STATIC::_escapeXML($this->keywords).'</pdf:Keywords>'."\n";
9625		$xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC::_escapeXML(TCPDF_STATIC::getTCPDFProducer()).'</pdf:Producer>'."\n";
9626		$xmp .= "\t\t".'</rdf:Description>'."\n";
9627		$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
9628		$uuid = 'uuid:'.substr($this->file_id, 0, 8).'-'.substr($this->file_id, 8, 4).'-'.substr($this->file_id, 12, 4).'-'.substr($this->file_id, 16, 4).'-'.substr($this->file_id, 20, 12);
9629		$xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
9630		$xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
9631		$xmp .= "\t\t".'</rdf:Description>'."\n";
9632		if ($this->pdfa_mode) {
9633			$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
9634			$xmp .= "\t\t\t".'<pdfaid:part>'.$this->pdfa_version.'</pdfaid:part>'."\n";
9635			$xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
9636			$xmp .= "\t\t".'</rdf:Description>'."\n";
9637		}
9638		// XMP extension schemas
9639		$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/" xmlns:pdfaSchema="http://www.aiim.org/pdfa/ns/schema#" xmlns:pdfaProperty="http://www.aiim.org/pdfa/ns/property#">'."\n";
9640		$xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
9641		$xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
9642		$xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9643		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
9644		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
9645		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
9646		$xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
9647		$xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9648		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
9649		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
9650		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
9651		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
9652		$xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
9653		$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9654		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9655		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
9656		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
9657		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
9658		$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9659		$xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
9660		$xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
9661		$xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
9662		$xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9663		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
9664		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
9665		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
9666		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
9667		$xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
9668		$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9669		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9670		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
9671		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
9672		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
9673		$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9674		$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9675		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9676		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
9677		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
9678		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
9679		$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9680		$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9681		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9682		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
9683		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
9684		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
9685		$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9686		$xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
9687		$xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
9688		$xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
9689		$xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
9690		$xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
9691		$xmp .= "\t\t".'</rdf:Description>'."\n";
9692		$xmp .= $this->custom_xmp_rdf;
9693		$xmp .= "\t".'</rdf:RDF>'."\n";
9694		$xmp .= $this->custom_xmp;
9695		$xmp .= '</x:xmpmeta>'."\n";
9696		$xmp .= '<?xpacket end="w"?>';
9697		$out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
9698		// restore previous isunicode value
9699		$this->isunicode = $prev_isunicode;
9700		$this->encrypted = $prev_encrypted;
9701		$this->_out($out);
9702		return $oid;
9703	}
9704
9705	/**
9706	 * Output Catalog.
9707	 * @return int object id
9708	 * @protected
9709	 */
9710	protected function _putcatalog() {
9711		// put XMP
9712		$xmpobj = $this->_putXMP();
9713		// if required, add standard sRGB ICC colour profile
9714		if ($this->pdfa_mode OR $this->force_srgb) {
9715			$iccobj = $this->_newobj();
9716			$icc = file_get_contents(dirname(__FILE__).'/include/sRGB.icc');
9717			$filter = '';
9718			if ($this->compress) {
9719				$filter = ' /Filter /FlateDecode';
9720				$icc = gzcompress($icc);
9721			}
9722			$icc = $this->_getrawstream($icc);
9723			$this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
9724		}
9725		// start catalog
9726		$oid = $this->_newobj();
9727		$out = '<< /Type /Catalog';
9728		$out .= ' /Version /'.$this->PDFVersion;
9729		//$out .= ' /Extensions <<>>';
9730		$out .= ' /Pages 1 0 R';
9731		//$out .= ' /PageLabels ' //...;
9732		$out .= ' /Names <<';
9733		if ((!$this->pdfa_mode) AND !empty($this->n_js)) {
9734			$out .= ' /JavaScript '.$this->n_js;
9735		}
9736		if (!empty($this->efnames)) {
9737			$out .= ' /EmbeddedFiles <</Names [';
9738			foreach ($this->efnames AS $fn => $fref) {
9739				$out .= ' '.$this->_datastring($fn).' '.$fref;
9740			}
9741			$out .= ' ]>>';
9742		}
9743		$out .= ' >>';
9744		if (!empty($this->dests)) {
9745			$out .= ' /Dests '.($this->n_dests).' 0 R';
9746		}
9747		$out .= $this->_putviewerpreferences();
9748		if (isset($this->LayoutMode) AND (!TCPDF_STATIC::empty_string($this->LayoutMode))) {
9749			$out .= ' /PageLayout /'.$this->LayoutMode;
9750		}
9751		if (isset($this->PageMode) AND (!TCPDF_STATIC::empty_string($this->PageMode))) {
9752			$out .= ' /PageMode /'.$this->PageMode;
9753		}
9754		if (count($this->outlines) > 0) {
9755			$out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
9756			$out .= ' /PageMode /UseOutlines';
9757		}
9758		//$out .= ' /Threads []';
9759		if ($this->ZoomMode == 'fullpage') {
9760			$out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
9761		} elseif ($this->ZoomMode == 'fullwidth') {
9762			$out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
9763		} elseif ($this->ZoomMode == 'real') {
9764			$out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
9765		} elseif (!is_string($this->ZoomMode)) {
9766			$out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %F]', ($this->ZoomMode / 100));
9767		}
9768		//$out .= ' /AA <<>>';
9769		//$out .= ' /URI <<>>';
9770		$out .= ' /Metadata '.$xmpobj.' 0 R';
9771		//$out .= ' /StructTreeRoot <<>>';
9772		//$out .= ' /MarkInfo <<>>';
9773		if (isset($this->l['a_meta_language'])) {
9774			$out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
9775		}
9776		//$out .= ' /SpiderInfo <<>>';
9777		// set OutputIntent to sRGB IEC61966-2.1 if required
9778		if ($this->pdfa_mode OR $this->force_srgb) {
9779			$out .= ' /OutputIntents [<<';
9780			$out .= ' /Type /OutputIntent';
9781			$out .= ' /S /GTS_PDFA1';
9782			$out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
9783			$out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
9784			$out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
9785			$out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
9786			$out .= ' /DestOutputProfile '.$iccobj.' 0 R';
9787			$out .= ' >>]';
9788		}
9789		//$out .= ' /PieceInfo <<>>';
9790		if (!empty($this->pdflayers)) {
9791			$lyrobjs = '';
9792			$lyrobjs_off = '';
9793			$lyrobjs_lock = '';
9794			foreach ($this->pdflayers as $layer) {
9795				$layer_obj_ref = ' '.$layer['objid'].' 0 R';
9796				$lyrobjs .= $layer_obj_ref;
9797				if ($layer['view'] === false) {
9798					$lyrobjs_off .= $layer_obj_ref;
9799				}
9800				if ($layer['lock']) {
9801					$lyrobjs_lock .= $layer_obj_ref;
9802				}
9803			}
9804			$out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
9805			$out .= ' /D <<';
9806			$out .= ' /Name '.$this->_textstring('Layers', $oid);
9807			$out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
9808			$out .= ' /BaseState /ON';
9809			$out .= ' /OFF ['.$lyrobjs_off.']';
9810			$out .= ' /Locked ['.$lyrobjs_lock.']';
9811			$out .= ' /Intent /View';
9812			$out .= ' /AS [';
9813			$out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
9814			$out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
9815			$out .= ' ]';
9816			$out .= ' /Order ['.$lyrobjs.']';
9817			$out .= ' /ListMode /AllPages';
9818			//$out .= ' /RBGroups ['..']';
9819			//$out .= ' /Locked ['..']';
9820			$out .= ' >>';
9821			$out .= ' >>';
9822		}
9823		// AcroForm
9824		if (!empty($this->form_obj_id)
9825			OR ($this->sign AND isset($this->signature_data['cert_type']))
9826			OR !empty($this->empty_signature_appearance)) {
9827			$out .= ' /AcroForm <<';
9828			$objrefs = '';
9829			if ($this->sign AND isset($this->signature_data['cert_type'])) {
9830				// set reference for signature object
9831				$objrefs .= $this->sig_obj_id.' 0 R';
9832			}
9833			if (!empty($this->empty_signature_appearance)) {
9834				foreach ($this->empty_signature_appearance as $esa) {
9835					// set reference for empty signature objects
9836					$objrefs .= ' '.$esa['objid'].' 0 R';
9837				}
9838			}
9839			if (!empty($this->form_obj_id)) {
9840				foreach($this->form_obj_id as $objid) {
9841					$objrefs .= ' '.$objid.' 0 R';
9842				}
9843			}
9844			$out .= ' /Fields ['.$objrefs.']';
9845			// It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
9846			if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
9847				$out .= ' /NeedAppearances false';
9848			}
9849			if ($this->sign AND isset($this->signature_data['cert_type'])) {
9850				if ($this->signature_data['cert_type'] > 0) {
9851					$out .= ' /SigFlags 3';
9852				} else {
9853					$out .= ' /SigFlags 1';
9854				}
9855			}
9856			//$out .= ' /CO ';
9857			if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
9858				$out .= ' /DR <<';
9859				$out .= ' /Font <<';
9860				foreach ($this->annotation_fonts as $fontkey => $fontid) {
9861					$out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
9862				}
9863				$out .= ' >> >>';
9864			}
9865			$font = $this->getFontBuffer('helvetica');
9866			$out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
9867			$out .= ' /Q '.(($this->rtl)?'2':'0');
9868			//$out .= ' /XFA ';
9869			$out .= ' >>';
9870			// signatures
9871			if ($this->sign AND isset($this->signature_data['cert_type'])
9872				AND (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A'))) {
9873				if ($this->signature_data['cert_type'] > 0) {
9874					$out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
9875				} else {
9876					$out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
9877				}
9878			}
9879		}
9880		//$out .= ' /Legal <<>>';
9881		//$out .= ' /Requirements []';
9882		//$out .= ' /Collection <<>>';
9883		//$out .= ' /NeedsRendering true';
9884		$out .= ' >>';
9885		$out .= "\n".'endobj';
9886		$this->_out($out);
9887		return $oid;
9888	}
9889
9890	/**
9891	 * Output viewer preferences.
9892	 * @return string for viewer preferences
9893	 * @author Nicola asuni
9894	 * @since 3.1.000 (2008-06-09)
9895	 * @protected
9896	 */
9897	protected function _putviewerpreferences() {
9898		$vp = $this->viewer_preferences;
9899		$out = ' /ViewerPreferences <<';
9900		if ($this->rtl) {
9901			$out .= ' /Direction /R2L';
9902		} else {
9903			$out .= ' /Direction /L2R';
9904		}
9905		if (isset($vp['HideToolbar']) AND ($vp['HideToolbar'])) {
9906			$out .= ' /HideToolbar true';
9907		}
9908		if (isset($vp['HideMenubar']) AND ($vp['HideMenubar'])) {
9909			$out .= ' /HideMenubar true';
9910		}
9911		if (isset($vp['HideWindowUI']) AND ($vp['HideWindowUI'])) {
9912			$out .= ' /HideWindowUI true';
9913		}
9914		if (isset($vp['FitWindow']) AND ($vp['FitWindow'])) {
9915			$out .= ' /FitWindow true';
9916		}
9917		if (isset($vp['CenterWindow']) AND ($vp['CenterWindow'])) {
9918			$out .= ' /CenterWindow true';
9919		}
9920		if (isset($vp['DisplayDocTitle']) AND ($vp['DisplayDocTitle'])) {
9921			$out .= ' /DisplayDocTitle true';
9922		}
9923		if (isset($vp['NonFullScreenPageMode'])) {
9924			$out .= ' /NonFullScreenPageMode /'.$vp['NonFullScreenPageMode'];
9925		}
9926		if (isset($vp['ViewArea'])) {
9927			$out .= ' /ViewArea /'.$vp['ViewArea'];
9928		}
9929		if (isset($vp['ViewClip'])) {
9930			$out .= ' /ViewClip /'.$vp['ViewClip'];
9931		}
9932		if (isset($vp['PrintArea'])) {
9933			$out .= ' /PrintArea /'.$vp['PrintArea'];
9934		}
9935		if (isset($vp['PrintClip'])) {
9936			$out .= ' /PrintClip /'.$vp['PrintClip'];
9937		}
9938		if (isset($vp['PrintScaling'])) {
9939			$out .= ' /PrintScaling /'.$vp['PrintScaling'];
9940		}
9941		if (isset($vp['Duplex']) AND (!TCPDF_STATIC::empty_string($vp['Duplex']))) {
9942			$out .= ' /Duplex /'.$vp['Duplex'];
9943		}
9944		if (isset($vp['PickTrayByPDFSize'])) {
9945			if ($vp['PickTrayByPDFSize']) {
9946				$out .= ' /PickTrayByPDFSize true';
9947			} else {
9948				$out .= ' /PickTrayByPDFSize false';
9949			}
9950		}
9951		if (isset($vp['PrintPageRange'])) {
9952			$PrintPageRangeNum = '';
9953			foreach ($vp['PrintPageRange'] as $k => $v) {
9954				$PrintPageRangeNum .= ' '.($v - 1).'';
9955			}
9956			$out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
9957		}
9958		if (isset($vp['NumCopies'])) {
9959			$out .= ' /NumCopies '.intval($vp['NumCopies']);
9960		}
9961		$out .= ' >>';
9962		return $out;
9963	}
9964
9965	/**
9966	 * Output PDF File Header (7.5.2).
9967	 * @protected
9968	 */
9969	protected function _putheader() {
9970		$this->_out('%PDF-'.$this->PDFVersion);
9971		$this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
9972	}
9973
9974	/**
9975	 * Output end of document (EOF).
9976	 * @protected
9977	 */
9978	protected function _enddoc() {
9979		if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
9980			// save subset chars of the previous font
9981			$this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
9982		}
9983		$this->state = 1;
9984		$this->_putheader();
9985		$this->_putpages();
9986		$this->_putresources();
9987		// empty signature fields
9988		if (!empty($this->empty_signature_appearance)) {
9989			foreach ($this->empty_signature_appearance as $key => $esa) {
9990				// widget annotation for empty signature
9991				$out = $this->_getobj($esa['objid'])."\n";
9992				$out .= '<< /Type /Annot';
9993				$out .= ' /Subtype /Widget';
9994				$out .= ' /Rect ['.$esa['rect'].']';
9995				$out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
9996				$out .= ' /F 4';
9997				$out .= ' /FT /Sig';
9998				$signame = $esa['name'].sprintf(' [%03d]', ($key + 1));
9999				$out .= ' /T '.$this->_textstring($signame, $esa['objid']);
10000				$out .= ' /Ff 0';
10001				$out .= ' >>';
10002				$out .= "\n".'endobj';
10003				$this->_out($out);
10004			}
10005		}
10006		// Signature
10007		if ($this->sign AND isset($this->signature_data['cert_type'])) {
10008			// widget annotation for signature
10009			$out = $this->_getobj($this->sig_obj_id)."\n";
10010			$out .= '<< /Type /Annot';
10011			$out .= ' /Subtype /Widget';
10012			$out .= ' /Rect ['.$this->signature_appearance['rect'].']';
10013			$out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
10014			$out .= ' /F 4';
10015			$out .= ' /FT /Sig';
10016			$out .= ' /T '.$this->_textstring($this->signature_appearance['name'], $this->sig_obj_id);
10017			$out .= ' /Ff 0';
10018			$out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
10019			$out .= ' >>';
10020			$out .= "\n".'endobj';
10021			$this->_out($out);
10022			// signature
10023			$this->_putsignature();
10024		}
10025		// Info
10026		$objid_info = $this->_putinfo();
10027		// Catalog
10028		$objid_catalog = $this->_putcatalog();
10029		// Cross-ref
10030		$o = $this->bufferlen;
10031		// XREF section
10032		$this->_out('xref');
10033		$this->_out('0 '.($this->n + 1));
10034		$this->_out('0000000000 65535 f ');
10035		$freegen = ($this->n + 2);
10036		for ($i=1; $i <= $this->n; ++$i) {
10037			if (!isset($this->offsets[$i]) AND ($i > 1)) {
10038				$this->_out(sprintf('0000000000 %05d f ', $freegen));
10039				++$freegen;
10040			} else {
10041				$this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
10042			}
10043		}
10044		// TRAILER
10045		$out = 'trailer'."\n";
10046		$out .= '<<';
10047		$out .= ' /Size '.($this->n + 1);
10048		$out .= ' /Root '.$objid_catalog.' 0 R';
10049		$out .= ' /Info '.$objid_info.' 0 R';
10050		if ($this->encrypted) {
10051			$out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
10052		}
10053		$out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
10054		$out .= ' >>';
10055		$this->_out($out);
10056		$this->_out('startxref');
10057		$this->_out($o);
10058		$this->_out('%%EOF');
10059		$this->state = 3; // end-of-doc
10060	}
10061
10062	/**
10063	 * Initialize a new page.
10064	 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
10065	 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
10066	 * @protected
10067	 * @see getPageSizeFromFormat(), setPageFormat()
10068	 */
10069	protected function _beginpage($orientation='', $format='') {
10070		++$this->page;
10071		$this->pageobjects[$this->page] = array();
10072		$this->setPageBuffer($this->page, '');
10073		// initialize array for graphics tranformation positions inside a page buffer
10074		$this->transfmrk[$this->page] = array();
10075		$this->state = 2;
10076		if (TCPDF_STATIC::empty_string($orientation)) {
10077			if (isset($this->CurOrientation)) {
10078				$orientation = $this->CurOrientation;
10079			} elseif ($this->fwPt > $this->fhPt) {
10080				// landscape
10081				$orientation = 'L';
10082			} else {
10083				// portrait
10084				$orientation = 'P';
10085			}
10086		}
10087		if (TCPDF_STATIC::empty_string($format)) {
10088			$this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
10089			$this->setPageOrientation($orientation);
10090		} else {
10091			$this->setPageFormat($format, $orientation);
10092		}
10093		if ($this->rtl) {
10094			$this->x = $this->w - $this->rMargin;
10095		} else {
10096			$this->x = $this->lMargin;
10097		}
10098		$this->y = $this->tMargin;
10099		if (isset($this->newpagegroup[$this->page])) {
10100			// start a new group
10101			$this->currpagegroup = $this->newpagegroup[$this->page];
10102			$this->pagegroups[$this->currpagegroup] = 1;
10103		} elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
10104			++$this->pagegroups[$this->currpagegroup];
10105		}
10106	}
10107
10108	/**
10109	 * Mark end of page.
10110	 * @protected
10111	 */
10112	protected function _endpage() {
10113		$this->setVisibility('all');
10114		$this->state = 1;
10115	}
10116
10117	/**
10118	 * Begin a new object and return the object number.
10119	 * @return int object number
10120	 * @protected
10121	 */
10122	protected function _newobj() {
10123		$this->_out($this->_getobj());
10124		return $this->n;
10125	}
10126
10127	/**
10128	 * Return the starting object string for the selected object ID.
10129	 * @param $objid (int) Object ID (leave empty to get a new ID).
10130	 * @return string the starting object string
10131	 * @protected
10132	 * @since 5.8.009 (2010-08-20)
10133	 */
10134	protected function _getobj($objid='') {
10135		if ($objid === '') {
10136			++$this->n;
10137			$objid = $this->n;
10138		}
10139		$this->offsets[$objid] = $this->bufferlen;
10140		$this->pageobjects[$this->page][] = $objid;
10141		return $objid.' 0 obj';
10142	}
10143
10144	/**
10145	 * Underline text.
10146	 * @param $x (int) X coordinate
10147	 * @param $y (int) Y coordinate
10148	 * @param $txt (string) text to underline
10149	 * @protected
10150	 */
10151	protected function _dounderline($x, $y, $txt) {
10152		$w = $this->GetStringWidth($txt);
10153		return $this->_dounderlinew($x, $y, $w);
10154	}
10155
10156	/**
10157	 * Underline for rectangular text area.
10158	 * @param $x (int) X coordinate
10159	 * @param $y (int) Y coordinate
10160	 * @param $w (int) width to underline
10161	 * @protected
10162	 * @since 4.8.008 (2009-09-29)
10163	 */
10164	protected function _dounderlinew($x, $y, $w) {
10165		$linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
10166		return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
10167	}
10168
10169	/**
10170	 * Line through text.
10171	 * @param $x (int) X coordinate
10172	 * @param $y (int) Y coordinate
10173	 * @param $txt (string) text to linethrough
10174	 * @protected
10175	 */
10176	protected function _dolinethrough($x, $y, $txt) {
10177		$w = $this->GetStringWidth($txt);
10178		return $this->_dolinethroughw($x, $y, $w);
10179	}
10180
10181	/**
10182	 * Line through for rectangular text area.
10183	 * @param $x (int) X coordinate
10184	 * @param $y (int) Y coordinate
10185	 * @param $w (int) line length (width)
10186	 * @protected
10187	 * @since 4.9.008 (2009-09-29)
10188	 */
10189	protected function _dolinethroughw($x, $y, $w) {
10190		$linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
10191		return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
10192	}
10193
10194	/**
10195	 * Overline text.
10196	 * @param $x (int) X coordinate
10197	 * @param $y (int) Y coordinate
10198	 * @param $txt (string) text to overline
10199	 * @protected
10200	 * @since 4.9.015 (2010-04-19)
10201	 */
10202	protected function _dooverline($x, $y, $txt) {
10203		$w = $this->GetStringWidth($txt);
10204		return $this->_dooverlinew($x, $y, $w);
10205	}
10206
10207	/**
10208	 * Overline for rectangular text area.
10209	 * @param $x (int) X coordinate
10210	 * @param $y (int) Y coordinate
10211	 * @param $w (int) width to overline
10212	 * @protected
10213	 * @since 4.9.015 (2010-04-19)
10214	 */
10215	protected function _dooverlinew($x, $y, $w) {
10216		$linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
10217		return sprintf('%F %F %F %F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
10218
10219	}
10220
10221	/**
10222	 * Format a data string for meta information
10223	 * @param $s (string) data string to escape.
10224	 * @param $n (int) object ID
10225	 * @return string escaped string.
10226	 * @protected
10227	 */
10228	protected function _datastring($s, $n=0) {
10229		if ($n == 0) {
10230			$n = $this->n;
10231		}
10232		$s = $this->_encrypt_data($n, $s);
10233		return '('. TCPDF_STATIC::_escape($s).')';
10234	}
10235
10236	/**
10237	 * Set the document creation timestamp
10238	 * @param $time (mixed) Document creation timestamp in seconds or date-time string.
10239	 * @public
10240	 * @since 5.9.152 (2012-03-23)
10241	 */
10242	public function setDocCreationTimestamp($time) {
10243		if (is_string($time)) {
10244			$time = TCPDF_STATIC::getTimestamp($time);
10245		}
10246		$this->doc_creation_timestamp = intval($time);
10247	}
10248
10249	/**
10250	 * Set the document modification timestamp
10251	 * @param $time (mixed) Document modification timestamp in seconds or date-time string.
10252	 * @public
10253	 * @since 5.9.152 (2012-03-23)
10254	 */
10255	public function setDocModificationTimestamp($time) {
10256		if (is_string($time)) {
10257			$time = TCPDF_STATIC::getTimestamp($time);
10258		}
10259		$this->doc_modification_timestamp = intval($time);
10260	}
10261
10262	/**
10263	 * Returns document creation timestamp in seconds.
10264	 * @return (int) Creation timestamp in seconds.
10265	 * @public
10266	 * @since 5.9.152 (2012-03-23)
10267	 */
10268	public function getDocCreationTimestamp() {
10269		return $this->doc_creation_timestamp;
10270	}
10271
10272	/**
10273	 * Returns document modification timestamp in seconds.
10274	 * @return (int) Modfication timestamp in seconds.
10275	 * @public
10276	 * @since 5.9.152 (2012-03-23)
10277	 */
10278	public function getDocModificationTimestamp() {
10279		return $this->doc_modification_timestamp;
10280	}
10281
10282	/**
10283	 * Returns a formatted date for meta information
10284	 * @param $n (int) Object ID.
10285	 * @param $timestamp (int) Timestamp to convert.
10286	 * @return string escaped date string.
10287	 * @protected
10288	 * @since 4.6.028 (2009-08-25)
10289	 */
10290	protected function _datestring($n=0, $timestamp=0) {
10291		if ((empty($timestamp)) OR ($timestamp < 0)) {
10292			$timestamp = $this->doc_creation_timestamp;
10293		}
10294		return $this->_datastring('D:'.TCPDF_STATIC::getFormattedDate($timestamp), $n);
10295	}
10296
10297	/**
10298	 * Format a text string for meta information
10299	 * @param $s (string) string to escape.
10300	 * @param $n (int) object ID
10301	 * @return string escaped string.
10302	 * @protected
10303	 */
10304	protected function _textstring($s, $n=0) {
10305		if ($this->isunicode) {
10306			//Convert string to UTF-16BE
10307			$s = TCPDF_FONTS::UTF8ToUTF16BE($s, true, $this->isunicode, $this->CurrentFont);
10308		}
10309		return $this->_datastring($s, $n);
10310	}
10311
10312	/**
10313	 * get raw output stream.
10314	 * @param $s (string) string to output.
10315	 * @param $n (int) object reference for encryption mode
10316	 * @protected
10317	 * @author Nicola Asuni
10318	 * @since 5.5.000 (2010-06-22)
10319	 */
10320	protected function _getrawstream($s, $n=0) {
10321		if ($n <= 0) {
10322			// default to current object
10323			$n = $this->n;
10324		}
10325		return $this->_encrypt_data($n, $s);
10326	}
10327
10328	/**
10329	 * Output a string to the document.
10330	 * @param $s (string) string to output.
10331	 * @protected
10332	 */
10333	protected function _out($s) {
10334		if ($this->state == 2) {
10335			if ($this->inxobj) {
10336				// we are inside an XObject template
10337				$this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
10338			} elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
10339				// puts data before page footer
10340				$pagebuff = $this->getPageBuffer($this->page);
10341				$page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
10342				$footer = substr($pagebuff, -$this->footerlen[$this->page]);
10343				$this->setPageBuffer($this->page, $page.$s."\n".$footer);
10344				// update footer position
10345				$this->footerpos[$this->page] += strlen($s."\n");
10346			} else {
10347				// set page data
10348				$this->setPageBuffer($this->page, $s."\n", true);
10349			}
10350		} elseif ($this->state > 0) {
10351			// set general data
10352			$this->setBuffer($s."\n");
10353		}
10354	}
10355
10356	/**
10357	 * Set header font.
10358	 * @param $font (array) Array describing the basic font parameters: (family, style, size).
10359	 * @public
10360	 * @since 1.1
10361	 */
10362	public function setHeaderFont($font) {
10363		$this->header_font = $font;
10364	}
10365
10366	/**
10367	 * Get header font.
10368	 * @return array() Array describing the basic font parameters: (family, style, size).
10369	 * @public
10370	 * @since 4.0.012 (2008-07-24)
10371	 */
10372	public function getHeaderFont() {
10373		return $this->header_font;
10374	}
10375
10376	/**
10377	 * Set footer font.
10378	 * @param $font (array) Array describing the basic font parameters: (family, style, size).
10379	 * @public
10380	 * @since 1.1
10381	 */
10382	public function setFooterFont($font) {
10383		$this->footer_font = $font;
10384	}
10385
10386	/**
10387	 * Get Footer font.
10388	 * @return array() Array describing the basic font parameters: (family, style, size).
10389	 * @public
10390	 * @since 4.0.012 (2008-07-24)
10391	 */
10392	public function getFooterFont() {
10393		return $this->footer_font;
10394	}
10395
10396	/**
10397	 * Set language array.
10398	 * @param $language (array)
10399	 * @public
10400	 * @since 1.1
10401	 */
10402	public function setLanguageArray($language) {
10403		$this->l = $language;
10404		if (isset($this->l['a_meta_dir'])) {
10405			$this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
10406		} else {
10407			$this->rtl = false;
10408		}
10409	}
10410
10411	/**
10412	 * Returns the PDF data.
10413	 * @public
10414	 */
10415	public function getPDFData() {
10416		if ($this->state < 3) {
10417			$this->Close();
10418		}
10419		return $this->buffer;
10420	}
10421
10422	/**
10423	 * Output anchor link.
10424	 * @param $url (string) link URL or internal link (i.e.: &lt;a href="#23,4.5"&gt;link to page 23 at 4.5 Y position&lt;/a&gt;)
10425	 * @param $name (string) link name
10426	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
10427	 * @param $firstline (boolean) if true prints only the first line and return the remaining string.
10428	 * @param $color (array) array of RGB text color
10429	 * @param $style (string) font style (U, D, B, I)
10430	 * @param $firstblock (boolean) if true the string is the starting of a line.
10431	 * @return the number of cells used or the remaining text if $firstline = true;
10432	 * @public
10433	 */
10434	public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
10435		if (isset($url[1]) AND ($url[0] == '#') AND is_numeric($url[1])) {
10436			// convert url to internal link
10437			$lnkdata = explode(',', $url);
10438			if (isset($lnkdata[0]) ) {
10439				$page = substr($lnkdata[0], 1);
10440				if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
10441					$lnky = floatval($lnkdata[1]);
10442				} else {
10443					$lnky = 0;
10444				}
10445				$url = $this->AddLink();
10446				$this->SetLink($url, $lnky, $page);
10447			}
10448		}
10449		// store current settings
10450		$prevcolor = $this->fgcolor;
10451		$prevstyle = $this->FontStyle;
10452		if (empty($color)) {
10453			$this->SetTextColorArray($this->htmlLinkColorArray);
10454		} else {
10455			$this->SetTextColorArray($color);
10456		}
10457		if ($style == -1) {
10458			$this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
10459		} else {
10460			$this->SetFont('', $this->FontStyle.$style);
10461		}
10462		$ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
10463		// restore settings
10464		$this->SetFont('', $prevstyle);
10465		$this->SetTextColorArray($prevcolor);
10466		return $ret;
10467	}
10468
10469	/**
10470	 * Converts pixels to User's Units.
10471	 * @param $px (int) pixels
10472	 * @return float value in user's unit
10473	 * @public
10474	 * @see setImageScale(), getImageScale()
10475	 */
10476	public function pixelsToUnits($px) {
10477		return ($px / ($this->imgscale * $this->k));
10478	}
10479
10480	/**
10481	 * Reverse function for htmlentities.
10482	 * Convert entities in UTF-8.
10483	 * @param $text_to_convert (string) Text to convert.
10484	 * @return string converted text string
10485	 * @public
10486	 */
10487	public function unhtmlentities($text_to_convert) {
10488		return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
10489	}
10490
10491	// ENCRYPTION METHODS ----------------------------------
10492
10493	/**
10494	 * Compute encryption key depending on object number where the encrypted data is stored.
10495	 * This is used for all strings and streams without crypt filter specifier.
10496	 * @param $n (int) object number
10497	 * @return int object key
10498	 * @protected
10499	 * @author Nicola Asuni
10500	 * @since 2.0.000 (2008-01-02)
10501	 */
10502	protected function _objectkey($n) {
10503		$objkey = $this->encryptdata['key'].pack('VXxx', $n);
10504		if ($this->encryptdata['mode'] == 2) { // AES-128
10505			// AES padding
10506			$objkey .= "\x73\x41\x6C\x54"; // sAlT
10507		}
10508		$objkey = substr(TCPDF_STATIC::_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
10509		$objkey = substr($objkey, 0, 16);
10510		return $objkey;
10511	}
10512
10513	/**
10514	 * Encrypt the input string.
10515	 * @param $n (int) object number
10516	 * @param $s (string) data string to encrypt
10517	 * @return encrypted string
10518	 * @protected
10519	 * @author Nicola Asuni
10520	 * @since 5.0.005 (2010-05-11)
10521	 */
10522	protected function _encrypt_data($n, $s) {
10523		if (!$this->encrypted) {
10524			return $s;
10525		}
10526		switch ($this->encryptdata['mode']) {
10527			case 0:   // RC4-40
10528			case 1: { // RC4-128
10529				$s = TCPDF_STATIC::_RC4($this->_objectkey($n), $s, $this->last_enc_key, $this->last_enc_key_c);
10530				break;
10531			}
10532			case 2: { // AES-128
10533				$s = TCPDF_STATIC::_AES($this->_objectkey($n), $s);
10534				break;
10535			}
10536			case 3: { // AES-256
10537				$s = TCPDF_STATIC::_AES($this->encryptdata['key'], $s);
10538				break;
10539			}
10540		}
10541		return $s;
10542	}
10543
10544	/**
10545	 * Put encryption on PDF document.
10546	 * @protected
10547	 * @author Nicola Asuni
10548	 * @since 2.0.000 (2008-01-02)
10549	 */
10550	protected function _putencryption() {
10551		if (!$this->encrypted) {
10552			return;
10553		}
10554		$this->encryptdata['objid'] = $this->_newobj();
10555		$out = '<<';
10556		if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
10557			$this->encryptdata['Filter'] = 'Standard';
10558		}
10559		$out .= ' /Filter /'.$this->encryptdata['Filter'];
10560		if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
10561			$out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
10562		}
10563		if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
10564			$this->encryptdata['V'] = 1;
10565		}
10566		// V is a code specifying the algorithm to be used in encrypting and decrypting the document
10567		$out .= ' /V '.$this->encryptdata['V'];
10568		if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
10569			// The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
10570			$out .= ' /Length '.$this->encryptdata['Length'];
10571		} else {
10572			$out .= ' /Length 40';
10573		}
10574		if ($this->encryptdata['V'] >= 4) {
10575			if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
10576				$this->encryptdata['StmF'] = 'Identity';
10577			}
10578			if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
10579				// The name of the crypt filter that shall be used when decrypting all strings in the document.
10580				$this->encryptdata['StrF'] = 'Identity';
10581			}
10582			// A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
10583			if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
10584				$out .= ' /CF <<';
10585				$out .= ' /'.$this->encryptdata['StmF'].' <<';
10586				$out .= ' /Type /CryptFilter';
10587				if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
10588					// The method used
10589					$out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
10590					if ($this->encryptdata['pubkey']) {
10591						$out .= ' /Recipients [';
10592						foreach ($this->encryptdata['Recipients'] as $rec) {
10593							$out .= ' <'.$rec.'>';
10594						}
10595						$out .= ' ]';
10596						if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
10597							$out .= ' /EncryptMetadata false';
10598						} else {
10599							$out .= ' /EncryptMetadata true';
10600						}
10601					}
10602				} else {
10603					$out .= ' /CFM /None';
10604				}
10605				if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
10606					// The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
10607					$out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
10608				} else {
10609					$out .= ' /AuthEvent /DocOpen';
10610				}
10611				if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
10612					// The bit length of the encryption key.
10613					$out .= ' /Length '.$this->encryptdata['CF']['Length'];
10614				}
10615				$out .= ' >> >>';
10616			}
10617			// The name of the crypt filter that shall be used by default when decrypting streams.
10618			$out .= ' /StmF /'.$this->encryptdata['StmF'];
10619			// The name of the crypt filter that shall be used when decrypting all strings in the document.
10620			$out .= ' /StrF /'.$this->encryptdata['StrF'];
10621			if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
10622				// The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
10623				$out .= ' /EFF /'.$this->encryptdata[''];
10624			}
10625		}
10626		// Additional encryption dictionary entries for the standard security handler
10627		if ($this->encryptdata['pubkey']) {
10628			if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
10629				$out .= ' /Recipients [';
10630				foreach ($this->encryptdata['Recipients'] as $rec) {
10631					$out .= ' <'.$rec.'>';
10632				}
10633				$out .= ' ]';
10634			}
10635		} else {
10636			$out .= ' /R';
10637			if ($this->encryptdata['V'] == 5) { // AES-256
10638				$out .= ' 5';
10639				$out .= ' /OE ('.TCPDF_STATIC::_escape($this->encryptdata['OE']).')';
10640				$out .= ' /UE ('.TCPDF_STATIC::_escape($this->encryptdata['UE']).')';
10641				$out .= ' /Perms ('.TCPDF_STATIC::_escape($this->encryptdata['perms']).')';
10642			} elseif ($this->encryptdata['V'] == 4) { // AES-128
10643				$out .= ' 4';
10644			} elseif ($this->encryptdata['V'] < 2) { // RC-40
10645				$out .= ' 2';
10646			} else { // RC-128
10647				$out .= ' 3';
10648			}
10649			$out .= ' /O ('.TCPDF_STATIC::_escape($this->encryptdata['O']).')';
10650			$out .= ' /U ('.TCPDF_STATIC::_escape($this->encryptdata['U']).')';
10651			$out .= ' /P '.$this->encryptdata['P'];
10652			if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
10653				$out .= ' /EncryptMetadata false';
10654			} else {
10655				$out .= ' /EncryptMetadata true';
10656			}
10657		}
10658		$out .= ' >>';
10659		$out .= "\n".'endobj';
10660		$this->_out($out);
10661	}
10662
10663	/**
10664	 * Compute U value (used for encryption)
10665	 * @return string U value
10666	 * @protected
10667	 * @since 2.0.000 (2008-01-02)
10668	 * @author Nicola Asuni
10669	 */
10670	protected function _Uvalue() {
10671		if ($this->encryptdata['mode'] == 0) { // RC4-40
10672			return TCPDF_STATIC::_RC4($this->encryptdata['key'], TCPDF_STATIC::$enc_padding, $this->last_enc_key, $this->last_enc_key_c);
10673		} elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
10674			$tmp = TCPDF_STATIC::_md5_16(TCPDF_STATIC::$enc_padding.$this->encryptdata['fileid']);
10675			$enc = TCPDF_STATIC::_RC4($this->encryptdata['key'], $tmp, $this->last_enc_key, $this->last_enc_key_c);
10676			$len = strlen($tmp);
10677			for ($i = 1; $i <= 19; ++$i) {
10678				$ek = '';
10679				for ($j = 0; $j < $len; ++$j) {
10680					$ek .= chr(ord($this->encryptdata['key'][$j]) ^ $i);
10681				}
10682				$enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
10683			}
10684			$enc .= str_repeat("\x00", 16);
10685			return substr($enc, 0, 32);
10686		} elseif ($this->encryptdata['mode'] == 3) { // AES-256
10687			$seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
10688			// User Validation Salt
10689			$this->encryptdata['UVS'] = substr($seed, 0, 8);
10690			// User Key Salt
10691			$this->encryptdata['UKS'] = substr($seed, 8, 16);
10692			return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
10693		}
10694	}
10695
10696	/**
10697	 * Compute UE value (used for encryption)
10698	 * @return string UE value
10699	 * @protected
10700	 * @since 5.9.006 (2010-10-19)
10701	 * @author Nicola Asuni
10702	 */
10703	protected function _UEvalue() {
10704		$hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
10705		return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
10706	}
10707
10708	/**
10709	 * Compute O value (used for encryption)
10710	 * @return string O value
10711	 * @protected
10712	 * @since 2.0.000 (2008-01-02)
10713	 * @author Nicola Asuni
10714	 */
10715	protected function _Ovalue() {
10716		if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
10717			$tmp = TCPDF_STATIC::_md5_16($this->encryptdata['owner_password']);
10718			if ($this->encryptdata['mode'] > 0) {
10719				for ($i = 0; $i < 50; ++$i) {
10720					$tmp = TCPDF_STATIC::_md5_16($tmp);
10721				}
10722			}
10723			$owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
10724			$enc = TCPDF_STATIC::_RC4($owner_key, $this->encryptdata['user_password'], $this->last_enc_key, $this->last_enc_key_c);
10725			if ($this->encryptdata['mode'] > 0) {
10726				$len = strlen($owner_key);
10727				for ($i = 1; $i <= 19; ++$i) {
10728					$ek = '';
10729					for ($j = 0; $j < $len; ++$j) {
10730						$ek .= chr(ord($owner_key[$j]) ^ $i);
10731					}
10732					$enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
10733				}
10734			}
10735			return $enc;
10736		} elseif ($this->encryptdata['mode'] == 3) { // AES-256
10737			$seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
10738			// Owner Validation Salt
10739			$this->encryptdata['OVS'] = substr($seed, 0, 8);
10740			// Owner Key Salt
10741			$this->encryptdata['OKS'] = substr($seed, 8, 16);
10742			return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
10743		}
10744	}
10745
10746	/**
10747	 * Compute OE value (used for encryption)
10748	 * @return string OE value
10749	 * @protected
10750	 * @since 5.9.006 (2010-10-19)
10751	 * @author Nicola Asuni
10752	 */
10753	protected function _OEvalue() {
10754		$hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
10755		return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
10756	}
10757
10758	/**
10759	 * Convert password for AES-256 encryption mode
10760	 * @param $password (string) password
10761	 * @return string password
10762	 * @protected
10763	 * @since 5.9.006 (2010-10-19)
10764	 * @author Nicola Asuni
10765	 */
10766	protected function _fixAES256Password($password) {
10767		$psw = ''; // password to be returned
10768		$psw_array = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($password, $this->isunicode, $this->CurrentFont), $password, $this->rtl, $this->isunicode, $this->CurrentFont);
10769		foreach ($psw_array as $c) {
10770			$psw .= TCPDF_FONTS::unichr($c, $this->isunicode);
10771		}
10772		return substr($psw, 0, 127);
10773	}
10774
10775	/**
10776	 * Compute encryption key
10777	 * @protected
10778	 * @since 2.0.000 (2008-01-02)
10779	 * @author Nicola Asuni
10780	 */
10781	protected function _generateencryptionkey() {
10782		$keybytelen = ($this->encryptdata['Length'] / 8);
10783		if (!$this->encryptdata['pubkey']) { // standard mode
10784			if ($this->encryptdata['mode'] == 3) { // AES-256
10785				// generate 256 bit random key
10786				$this->encryptdata['key'] = substr(hash('sha256', TCPDF_STATIC::getRandomSeed(), true), 0, $keybytelen);
10787				// truncate passwords
10788				$this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
10789				$this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
10790				// Compute U value
10791				$this->encryptdata['U'] = $this->_Uvalue();
10792				// Compute UE value
10793				$this->encryptdata['UE'] = $this->_UEvalue();
10794				// Compute O value
10795				$this->encryptdata['O'] = $this->_Ovalue();
10796				// Compute OE value
10797				$this->encryptdata['OE'] = $this->_OEvalue();
10798				// Compute P value
10799				$this->encryptdata['P'] = $this->encryptdata['protection'];
10800				// Computing the encryption dictionary's Perms (permissions) value
10801				$perms = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
10802				$perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
10803				if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
10804					$perms .= 'F';
10805				} else {
10806					$perms .= 'T';
10807				}
10808				$perms .= 'adb'; // bytes 9-11
10809				$perms .= 'nick'; // bytes 12-15
10810				$this->encryptdata['perms'] = TCPDF_STATIC::_AESnopad($this->encryptdata['key'], $perms);
10811			} else { // RC4-40, RC4-128, AES-128
10812				// Pad passwords
10813				$this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].TCPDF_STATIC::$enc_padding, 0, 32);
10814				$this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].TCPDF_STATIC::$enc_padding, 0, 32);
10815				// Compute O value
10816				$this->encryptdata['O'] = $this->_Ovalue();
10817				// get default permissions (reverse byte order)
10818				$permissions = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']);
10819				// Compute encryption key
10820				$tmp = TCPDF_STATIC::_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
10821				if ($this->encryptdata['mode'] > 0) {
10822					for ($i = 0; $i < 50; ++$i) {
10823						$tmp = TCPDF_STATIC::_md5_16(substr($tmp, 0, $keybytelen));
10824					}
10825				}
10826				$this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
10827				// Compute U value
10828				$this->encryptdata['U'] = $this->_Uvalue();
10829				// Compute P value
10830				$this->encryptdata['P'] = $this->encryptdata['protection'];
10831			}
10832		} else { // Public-Key mode
10833			// random 20-byte seed
10834			$seed = sha1(TCPDF_STATIC::getRandomSeed(), true);
10835			$recipient_bytes = '';
10836			foreach ($this->encryptdata['pubkeys'] as $pubkey) {
10837				// for each public certificate
10838				if (isset($pubkey['p'])) {
10839					$pkprotection = TCPDF_STATIC::getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
10840				} else {
10841					$pkprotection = $this->encryptdata['protection'];
10842				}
10843				// get default permissions (reverse byte order)
10844				$pkpermissions = TCPDF_STATIC::getEncPermissionsString($pkprotection);
10845				// envelope data
10846				$envelope = $seed.$pkpermissions;
10847				// write the envelope data to a temporary file
10848				$tempkeyfile = TCPDF_STATIC::getObjFilename('key', $this->file_id);
10849				$f = TCPDF_STATIC::fopenLocal($tempkeyfile, 'wb');
10850				if (!$f) {
10851					$this->Error('Unable to create temporary key file: '.$tempkeyfile);
10852				}
10853				$envelope_length = strlen($envelope);
10854				fwrite($f, $envelope, $envelope_length);
10855				fclose($f);
10856				$tempencfile = TCPDF_STATIC::getObjFilename('enc', $this->file_id);
10857				if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) {
10858					$this->Error('Unable to encrypt the file: '.$tempkeyfile);
10859				}
10860				// read encryption signature
10861				$signature = file_get_contents($tempencfile, false, null, $envelope_length);
10862				// extract signature
10863				$signature = substr($signature, strpos($signature, 'Content-Disposition'));
10864				$tmparr = explode("\n\n", $signature);
10865				$signature = trim($tmparr[1]);
10866				unset($tmparr);
10867				// decode signature
10868				$signature = base64_decode($signature);
10869				// convert signature to hex
10870				$hexsignature = current(unpack('H*', $signature));
10871				// store signature on recipients array
10872				$this->encryptdata['Recipients'][] = $hexsignature;
10873				// The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
10874				$recipient_bytes .= $signature;
10875			}
10876			// calculate encryption key
10877			if ($this->encryptdata['mode'] == 3) { // AES-256
10878				$this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
10879			} else { // RC4-40, RC4-128, AES-128
10880				$this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
10881			}
10882		}
10883	}
10884
10885	/**
10886	 * Set document protection
10887	 * Remark: the protection against modification is for people who have the full Acrobat product.
10888	 * 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.
10889	 * 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.
10890	 * @param $permissions (Array) the set of permissions (specify the ones you want to block):<ul><li>print : Print the document;</li><li>modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';</li><li>copy : Copy or otherwise extract text and graphics from the document;</li><li>annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);</li><li>fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;</li><li>extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);</li><li>assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;</li><li>print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.</li><li>owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.</li></ul>
10891	 * @param $user_pass (String) user password. Empty by default.
10892	 * @param $owner_pass (String) owner password. If not specified, a random value is used.
10893	 * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
10894	 * @param $pubkeys (String) array of recipients containing public-key certificates ('c') and permissions ('p'). For example: array(array('c' => 'file://../examples/data/cert/tcpdf.crt', 'p' => array('print')))
10895	 * @public
10896	 * @since 2.0.000 (2008-01-02)
10897	 * @author Nicola Asuni
10898	 */
10899	public function SetProtection($permissions=array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-high'), $user_pass='', $owner_pass=null, $mode=0, $pubkeys=null) {
10900		if ($this->pdfa_mode) {
10901			// encryption is not allowed in PDF/A mode
10902			return;
10903		}
10904		$this->encryptdata['protection'] = TCPDF_STATIC::getUserPermissionCode($permissions, $mode);
10905		if (($pubkeys !== null) AND (is_array($pubkeys))) {
10906			// public-key mode
10907			$this->encryptdata['pubkeys'] = $pubkeys;
10908			if ($mode == 0) {
10909				// public-Key Security requires at least 128 bit
10910				$mode = 1;
10911			}
10912			if (!function_exists('openssl_pkcs7_encrypt')) {
10913				$this->Error('Public-Key Security requires openssl library.');
10914			}
10915			// Set Public-Key filter (available are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
10916			$this->encryptdata['pubkey'] = true;
10917			$this->encryptdata['Filter'] = 'Adobe.PubSec';
10918			$this->encryptdata['StmF'] = 'DefaultCryptFilter';
10919			$this->encryptdata['StrF'] = 'DefaultCryptFilter';
10920		} else {
10921			// standard mode (password mode)
10922			$this->encryptdata['pubkey'] = false;
10923			$this->encryptdata['Filter'] = 'Standard';
10924			$this->encryptdata['StmF'] = 'StdCF';
10925			$this->encryptdata['StrF'] = 'StdCF';
10926		}
10927		if ($mode > 1) { // AES
10928			if (!extension_loaded('openssl') && !extension_loaded('mcrypt')) {
10929				$this->Error('AES encryption requires openssl or mcrypt extension (http://www.php.net/manual/en/mcrypt.requirements.php).');
10930			}
10931			if (extension_loaded('openssl') && !in_array('aes-256-cbc', openssl_get_cipher_methods())) {
10932				$this->Error('AES encryption requires openssl/aes-256-cbc cypher.');
10933			}
10934			if (extension_loaded('mcrypt') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
10935				$this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
10936			}
10937			if (($mode == 3) AND !function_exists('hash')) {
10938				// the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
10939				$this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
10940			}
10941		}
10942		if ($owner_pass === null) {
10943			$owner_pass = md5(TCPDF_STATIC::getRandomSeed());
10944		}
10945		$this->encryptdata['user_password'] = $user_pass;
10946		$this->encryptdata['owner_password'] = $owner_pass;
10947		$this->encryptdata['mode'] = $mode;
10948		switch ($mode) {
10949			case 0: { // RC4 40 bit
10950				$this->encryptdata['V'] = 1;
10951				$this->encryptdata['Length'] = 40;
10952				$this->encryptdata['CF']['CFM'] = 'V2';
10953				break;
10954			}
10955			case 1: { // RC4 128 bit
10956				$this->encryptdata['V'] = 2;
10957				$this->encryptdata['Length'] = 128;
10958				$this->encryptdata['CF']['CFM'] = 'V2';
10959				if ($this->encryptdata['pubkey']) {
10960					$this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
10961					$this->encryptdata['Recipients'] = array();
10962				}
10963				break;
10964			}
10965			case 2: { // AES 128 bit
10966				$this->encryptdata['V'] = 4;
10967				$this->encryptdata['Length'] = 128;
10968				$this->encryptdata['CF']['CFM'] = 'AESV2';
10969				$this->encryptdata['CF']['Length'] = 128;
10970				if ($this->encryptdata['pubkey']) {
10971					$this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
10972					$this->encryptdata['Recipients'] = array();
10973				}
10974				break;
10975			}
10976			case 3: { // AES 256 bit
10977				$this->encryptdata['V'] = 5;
10978				$this->encryptdata['Length'] = 256;
10979				$this->encryptdata['CF']['CFM'] = 'AESV3';
10980				$this->encryptdata['CF']['Length'] = 256;
10981				if ($this->encryptdata['pubkey']) {
10982					$this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
10983					$this->encryptdata['Recipients'] = array();
10984				}
10985				break;
10986			}
10987		}
10988		$this->encrypted = true;
10989		$this->encryptdata['fileid'] = TCPDF_STATIC::convertHexStringToString($this->file_id);
10990		$this->_generateencryptionkey();
10991	}
10992
10993	// END OF ENCRYPTION FUNCTIONS -------------------------
10994
10995	// START TRANSFORMATIONS SECTION -----------------------
10996
10997	/**
10998	 * Starts a 2D tranformation saving current graphic state.
10999	 * This function must be called before scaling, mirroring, translation, rotation and skewing.
11000	 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
11001	 * @public
11002	 * @since 2.1.000 (2008-01-07)
11003	 * @see StartTransform(), StopTransform()
11004	 */
11005	public function StartTransform() {
11006		if ($this->state != 2) {
11007			return;
11008		}
11009		$this->_outSaveGraphicsState();
11010		if ($this->inxobj) {
11011			// we are inside an XObject template
11012			$this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
11013		} else {
11014			$this->transfmrk[$this->page][] = $this->pagelen[$this->page];
11015		}
11016		++$this->transfmatrix_key;
11017		$this->transfmatrix[$this->transfmatrix_key] = array();
11018	}
11019
11020	/**
11021	 * Stops a 2D tranformation restoring previous graphic state.
11022	 * This function must be called after scaling, mirroring, translation, rotation and skewing.
11023	 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
11024	 * @public
11025	 * @since 2.1.000 (2008-01-07)
11026	 * @see StartTransform(), StopTransform()
11027	 */
11028	public function StopTransform() {
11029		if ($this->state != 2) {
11030			return;
11031		}
11032		$this->_outRestoreGraphicsState();
11033		if (isset($this->transfmatrix[$this->transfmatrix_key])) {
11034			array_pop($this->transfmatrix[$this->transfmatrix_key]);
11035			--$this->transfmatrix_key;
11036		}
11037		if ($this->inxobj) {
11038			// we are inside an XObject template
11039			array_pop($this->xobjects[$this->xobjid]['transfmrk']);
11040		} else {
11041			array_pop($this->transfmrk[$this->page]);
11042		}
11043	}
11044	/**
11045	 * Horizontal Scaling.
11046	 * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
11047	 * @param $x (int) abscissa of the scaling center. Default is current x position
11048	 * @param $y (int) ordinate of the scaling center. Default is current y position
11049	 * @public
11050	 * @since 2.1.000 (2008-01-07)
11051	 * @see StartTransform(), StopTransform()
11052	 */
11053	public function ScaleX($s_x, $x='', $y='') {
11054		$this->Scale($s_x, 100, $x, $y);
11055	}
11056
11057	/**
11058	 * Vertical Scaling.
11059	 * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
11060	 * @param $x (int) abscissa of the scaling center. Default is current x position
11061	 * @param $y (int) ordinate of the scaling center. Default is current y position
11062	 * @public
11063	 * @since 2.1.000 (2008-01-07)
11064	 * @see StartTransform(), StopTransform()
11065	 */
11066	public function ScaleY($s_y, $x='', $y='') {
11067		$this->Scale(100, $s_y, $x, $y);
11068	}
11069
11070	/**
11071	 * Vertical and horizontal proportional Scaling.
11072	 * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
11073	 * @param $x (int) abscissa of the scaling center. Default is current x position
11074	 * @param $y (int) ordinate of the scaling center. Default is current y position
11075	 * @public
11076	 * @since 2.1.000 (2008-01-07)
11077	 * @see StartTransform(), StopTransform()
11078	 */
11079	public function ScaleXY($s, $x='', $y='') {
11080		$this->Scale($s, $s, $x, $y);
11081	}
11082
11083	/**
11084	 * Vertical and horizontal non-proportional Scaling.
11085	 * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
11086	 * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
11087	 * @param $x (int) abscissa of the scaling center. Default is current x position
11088	 * @param $y (int) ordinate of the scaling center. Default is current y position
11089	 * @public
11090	 * @since 2.1.000 (2008-01-07)
11091	 * @see StartTransform(), StopTransform()
11092	 */
11093	public function Scale($s_x, $s_y, $x='', $y='') {
11094		if ($x === '') {
11095			$x = $this->x;
11096		}
11097		if ($y === '') {
11098			$y = $this->y;
11099		}
11100		if (($s_x == 0) OR ($s_y == 0)) {
11101			$this->Error('Please do not use values equal to zero for scaling');
11102		}
11103		$y = ($this->h - $y) * $this->k;
11104		$x *= $this->k;
11105		//calculate elements of transformation matrix
11106		$s_x /= 100;
11107		$s_y /= 100;
11108		$tm = array();
11109		$tm[0] = $s_x;
11110		$tm[1] = 0;
11111		$tm[2] = 0;
11112		$tm[3] = $s_y;
11113		$tm[4] = $x * (1 - $s_x);
11114		$tm[5] = $y * (1 - $s_y);
11115		//scale the coordinate system
11116		$this->Transform($tm);
11117	}
11118
11119	/**
11120	 * Horizontal Mirroring.
11121	 * @param $x (int) abscissa of the point. Default is current x position
11122	 * @public
11123	 * @since 2.1.000 (2008-01-07)
11124	 * @see StartTransform(), StopTransform()
11125	 */
11126	public function MirrorH($x='') {
11127		$this->Scale(-100, 100, $x);
11128	}
11129
11130	/**
11131	 * Verical Mirroring.
11132	 * @param $y (int) ordinate of the point. Default is current y position
11133	 * @public
11134	 * @since 2.1.000 (2008-01-07)
11135	 * @see StartTransform(), StopTransform()
11136	 */
11137	public function MirrorV($y='') {
11138		$this->Scale(100, -100, '', $y);
11139	}
11140
11141	/**
11142	 * Point reflection mirroring.
11143	 * @param $x (int) abscissa of the point. Default is current x position
11144	 * @param $y (int) ordinate of the point. Default is current y position
11145	 * @public
11146	 * @since 2.1.000 (2008-01-07)
11147	 * @see StartTransform(), StopTransform()
11148	 */
11149	public function MirrorP($x='',$y='') {
11150		$this->Scale(-100, -100, $x, $y);
11151	}
11152
11153	/**
11154	 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
11155	 * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
11156	 * @param $x (int) abscissa of the point. Default is current x position
11157	 * @param $y (int) ordinate of the point. Default is current y position
11158	 * @public
11159	 * @since 2.1.000 (2008-01-07)
11160	 * @see StartTransform(), StopTransform()
11161	 */
11162	public function MirrorL($angle=0, $x='',$y='') {
11163		$this->Scale(-100, 100, $x, $y);
11164		$this->Rotate(-2*($angle-90), $x, $y);
11165	}
11166
11167	/**
11168	 * Translate graphic object horizontally.
11169	 * @param $t_x (int) movement to the right (or left for RTL)
11170	 * @public
11171	 * @since 2.1.000 (2008-01-07)
11172	 * @see StartTransform(), StopTransform()
11173	 */
11174	public function TranslateX($t_x) {
11175		$this->Translate($t_x, 0);
11176	}
11177
11178	/**
11179	 * Translate graphic object vertically.
11180	 * @param $t_y (int) movement to the bottom
11181	 * @public
11182	 * @since 2.1.000 (2008-01-07)
11183	 * @see StartTransform(), StopTransform()
11184	 */
11185	public function TranslateY($t_y) {
11186		$this->Translate(0, $t_y);
11187	}
11188
11189	/**
11190	 * Translate graphic object horizontally and vertically.
11191	 * @param $t_x (int) movement to the right
11192	 * @param $t_y (int) movement to the bottom
11193	 * @public
11194	 * @since 2.1.000 (2008-01-07)
11195	 * @see StartTransform(), StopTransform()
11196	 */
11197	public function Translate($t_x, $t_y) {
11198		//calculate elements of transformation matrix
11199		$tm = array();
11200		$tm[0] = 1;
11201		$tm[1] = 0;
11202		$tm[2] = 0;
11203		$tm[3] = 1;
11204		$tm[4] = $t_x * $this->k;
11205		$tm[5] = -$t_y * $this->k;
11206		//translate the coordinate system
11207		$this->Transform($tm);
11208	}
11209
11210	/**
11211	 * Rotate object.
11212	 * @param $angle (float) angle in degrees for counter-clockwise rotation
11213	 * @param $x (int) abscissa of the rotation center. Default is current x position
11214	 * @param $y (int) ordinate of the rotation center. Default is current y position
11215	 * @public
11216	 * @since 2.1.000 (2008-01-07)
11217	 * @see StartTransform(), StopTransform()
11218	 */
11219	public function Rotate($angle, $x='', $y='') {
11220		if ($x === '') {
11221			$x = $this->x;
11222		}
11223		if ($y === '') {
11224			$y = $this->y;
11225		}
11226		$y = ($this->h - $y) * $this->k;
11227		$x *= $this->k;
11228		//calculate elements of transformation matrix
11229		$tm = array();
11230		$tm[0] = cos(deg2rad($angle));
11231		$tm[1] = sin(deg2rad($angle));
11232		$tm[2] = -$tm[1];
11233		$tm[3] = $tm[0];
11234		$tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
11235		$tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
11236		//rotate the coordinate system around ($x,$y)
11237		$this->Transform($tm);
11238	}
11239
11240	/**
11241	 * Skew horizontally.
11242	 * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
11243	 * @param $x (int) abscissa of the skewing center. default is current x position
11244	 * @param $y (int) ordinate of the skewing center. default is current y position
11245	 * @public
11246	 * @since 2.1.000 (2008-01-07)
11247	 * @see StartTransform(), StopTransform()
11248	 */
11249	public function SkewX($angle_x, $x='', $y='') {
11250		$this->Skew($angle_x, 0, $x, $y);
11251	}
11252
11253	/**
11254	 * Skew vertically.
11255	 * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
11256	 * @param $x (int) abscissa of the skewing center. default is current x position
11257	 * @param $y (int) ordinate of the skewing center. default is current y position
11258	 * @public
11259	 * @since 2.1.000 (2008-01-07)
11260	 * @see StartTransform(), StopTransform()
11261	 */
11262	public function SkewY($angle_y, $x='', $y='') {
11263		$this->Skew(0, $angle_y, $x, $y);
11264	}
11265
11266	/**
11267	 * Skew.
11268	 * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
11269	 * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
11270	 * @param $x (int) abscissa of the skewing center. default is current x position
11271	 * @param $y (int) ordinate of the skewing center. default is current y position
11272	 * @public
11273	 * @since 2.1.000 (2008-01-07)
11274	 * @see StartTransform(), StopTransform()
11275	 */
11276	public function Skew($angle_x, $angle_y, $x='', $y='') {
11277		if ($x === '') {
11278			$x = $this->x;
11279		}
11280		if ($y === '') {
11281			$y = $this->y;
11282		}
11283		if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
11284			$this->Error('Please use values between -90 and +90 degrees for Skewing.');
11285		}
11286		$x *= $this->k;
11287		$y = ($this->h - $y) * $this->k;
11288		//calculate elements of transformation matrix
11289		$tm = array();
11290		$tm[0] = 1;
11291		$tm[1] = tan(deg2rad($angle_y));
11292		$tm[2] = tan(deg2rad($angle_x));
11293		$tm[3] = 1;
11294		$tm[4] = -$tm[2] * $y;
11295		$tm[5] = -$tm[1] * $x;
11296		//skew the coordinate system
11297		$this->Transform($tm);
11298	}
11299
11300	/**
11301	 * Apply graphic transformations.
11302	 * @param $tm (array) transformation matrix
11303	 * @protected
11304	 * @since 2.1.000 (2008-01-07)
11305	 * @see StartTransform(), StopTransform()
11306	 */
11307	protected function Transform($tm) {
11308		if ($this->state != 2) {
11309			return;
11310		}
11311		$this->_out(sprintf('%F %F %F %F %F %F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
11312		// add tranformation matrix
11313		$this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
11314		// update transformation mark
11315		if ($this->inxobj) {
11316			// we are inside an XObject template
11317			if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
11318				$key = key($this->xobjects[$this->xobjid]['transfmrk']);
11319				$this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
11320			}
11321		} elseif (end($this->transfmrk[$this->page]) !== false) {
11322			$key = key($this->transfmrk[$this->page]);
11323			$this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
11324		}
11325	}
11326
11327	// END TRANSFORMATIONS SECTION -------------------------
11328
11329	// START GRAPHIC FUNCTIONS SECTION ---------------------
11330	// The following section is based on the code provided by David Hernandez Sanz
11331
11332	/**
11333	 * 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.
11334	 * @param $width (float) The width.
11335	 * @public
11336	 * @since 1.0
11337	 * @see Line(), Rect(), Cell(), MultiCell()
11338	 */
11339	public function SetLineWidth($width) {
11340		//Set line width
11341		$this->LineWidth = $width;
11342		$this->linestyleWidth = sprintf('%F w', ($width * $this->k));
11343		if ($this->state == 2) {
11344			$this->_out($this->linestyleWidth);
11345		}
11346	}
11347
11348	/**
11349	 * Returns the current the line width.
11350	 * @return int Line width
11351	 * @public
11352	 * @since 2.1.000 (2008-01-07)
11353	 * @see Line(), SetLineWidth()
11354	 */
11355	public function GetLineWidth() {
11356		return $this->LineWidth;
11357	}
11358
11359	/**
11360	 * Set line style.
11361	 * @param $style (array) Line style. Array with keys among the following:
11362	 * <ul>
11363	 *	 <li>width (float): Width of the line in user units.</li>
11364	 *	 <li>cap (string): Type of cap to put on the line. Possible values are:
11365	 * butt, round, square. The difference between "square" and "butt" is that
11366	 * "square" projects a flat end past the end of the line.</li>
11367	 *	 <li>join (string): Type of join. Possible values are: miter, round,
11368	 * bevel.</li>
11369	 *	 <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
11370	 * series of length values, which are the lengths of the on and off dashes.
11371	 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
11372	 * 1 off, 2 on, 1 off, ...</li>
11373	 *	 <li>phase (integer): Modifier on the dash pattern which is used to shift
11374	 * the point at which the pattern starts.</li>
11375	 *	 <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName).</li>
11376	 * </ul>
11377	 * @param $ret (boolean) if true do not send the command.
11378	 * @return string the PDF command
11379	 * @public
11380	 * @since 2.1.000 (2008-01-08)
11381	 */
11382	public function SetLineStyle($style, $ret=false) {
11383		$s = ''; // string to be returned
11384		if (!is_array($style)) {
11385			return;
11386		}
11387		if (isset($style['width'])) {
11388			$this->LineWidth = $style['width'];
11389			$this->linestyleWidth = sprintf('%F w', ($style['width'] * $this->k));
11390			$s .= $this->linestyleWidth.' ';
11391		}
11392		if (isset($style['cap'])) {
11393			$ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
11394			if (isset($ca[$style['cap']])) {
11395				$this->linestyleCap = $ca[$style['cap']].' J';
11396				$s .= $this->linestyleCap.' ';
11397			}
11398		}
11399		if (isset($style['join'])) {
11400			$ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
11401			if (isset($ja[$style['join']])) {
11402				$this->linestyleJoin = $ja[$style['join']].' j';
11403				$s .= $this->linestyleJoin.' ';
11404			}
11405		}
11406		if (isset($style['dash'])) {
11407			$dash_string = '';
11408			if ($style['dash']) {
11409				if (preg_match('/^.+,/', $style['dash']) > 0) {
11410					$tab = explode(',', $style['dash']);
11411				} else {
11412					$tab = array($style['dash']);
11413				}
11414				$dash_string = '';
11415				foreach ($tab as $i => $v) {
11416					if ($i) {
11417						$dash_string .= ' ';
11418					}
11419					$dash_string .= sprintf('%F', $v);
11420				}
11421			}
11422			if (!isset($style['phase']) OR !$style['dash']) {
11423				$style['phase'] = 0;
11424			}
11425			$this->linestyleDash = sprintf('[%s] %F d', $dash_string, $style['phase']);
11426			$s .= $this->linestyleDash.' ';
11427		}
11428		if (isset($style['color'])) {
11429			$s .= $this->SetDrawColorArray($style['color'], true).' ';
11430		}
11431		if (!$ret AND ($this->state == 2)) {
11432			$this->_out($s);
11433		}
11434		return $s;
11435	}
11436
11437	/**
11438	 * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
11439	 * @param $x (float) Abscissa of point.
11440	 * @param $y (float) Ordinate of point.
11441	 * @protected
11442	 * @since 2.1.000 (2008-01-08)
11443	 */
11444	protected function _outPoint($x, $y) {
11445		if ($this->state == 2) {
11446			$this->_out(sprintf('%F %F m', ($x * $this->k), (($this->h - $y) * $this->k)));
11447		}
11448	}
11449
11450	/**
11451	 * Append a straight line segment from the current point to the point (x, y).
11452	 * The new current point shall be (x, y).
11453	 * @param $x (float) Abscissa of end point.
11454	 * @param $y (float) Ordinate of end point.
11455	 * @protected
11456	 * @since 2.1.000 (2008-01-08)
11457	 */
11458	protected function _outLine($x, $y) {
11459		if ($this->state == 2) {
11460			$this->_out(sprintf('%F %F l', ($x * $this->k), (($this->h - $y) * $this->k)));
11461		}
11462	}
11463
11464	/**
11465	 * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
11466	 * @param $x (float) Abscissa of upper-left corner.
11467	 * @param $y (float) Ordinate of upper-left corner.
11468	 * @param $w (float) Width.
11469	 * @param $h (float) Height.
11470	 * @param $op (string) options
11471	 * @protected
11472	 * @since 2.1.000 (2008-01-08)
11473	 */
11474	protected function _outRect($x, $y, $w, $h, $op) {
11475		if ($this->state == 2) {
11476			$this->_out(sprintf('%F %F %F %F re %s', ($x * $this->k), (($this->h - $y) * $this->k), ($w * $this->k), (-$h * $this->k), $op));
11477		}
11478	}
11479
11480	/**
11481	 * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x2, y2) as the Bezier control points.
11482	 * The new current point shall be (x3, y3).
11483	 * @param $x1 (float) Abscissa of control point 1.
11484	 * @param $y1 (float) Ordinate of control point 1.
11485	 * @param $x2 (float) Abscissa of control point 2.
11486	 * @param $y2 (float) Ordinate of control point 2.
11487	 * @param $x3 (float) Abscissa of end point.
11488	 * @param $y3 (float) Ordinate of end point.
11489	 * @protected
11490	 * @since 2.1.000 (2008-01-08)
11491	 */
11492	protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
11493		if ($this->state == 2) {
11494			$this->_out(sprintf('%F %F %F %F %F %F 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)));
11495		}
11496	}
11497
11498	/**
11499	 * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using the current point and (x2, y2) as the Bezier control points.
11500	 * The new current point shall be (x3, y3).
11501	 * @param $x2 (float) Abscissa of control point 2.
11502	 * @param $y2 (float) Ordinate of control point 2.
11503	 * @param $x3 (float) Abscissa of end point.
11504	 * @param $y3 (float) Ordinate of end point.
11505	 * @protected
11506	 * @since 4.9.019 (2010-04-26)
11507	 */
11508	protected function _outCurveV($x2, $y2, $x3, $y3) {
11509		if ($this->state == 2) {
11510			$this->_out(sprintf('%F %F %F %F v', ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
11511		}
11512	}
11513
11514	/**
11515	 * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x3, y3) as the Bezier control points.
11516	 * The new current point shall be (x3, y3).
11517	 * @param $x1 (float) Abscissa of control point 1.
11518	 * @param $y1 (float) Ordinate of control point 1.
11519	 * @param $x3 (float) Abscissa of end point.
11520	 * @param $y3 (float) Ordinate of end point.
11521	 * @protected
11522	 * @since 2.1.000 (2008-01-08)
11523	 */
11524	protected function _outCurveY($x1, $y1, $x3, $y3) {
11525		if ($this->state == 2) {
11526			$this->_out(sprintf('%F %F %F %F y', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
11527		}
11528	}
11529
11530	/**
11531	 * Draws a line between two points.
11532	 * @param $x1 (float) Abscissa of first point.
11533	 * @param $y1 (float) Ordinate of first point.
11534	 * @param $x2 (float) Abscissa of second point.
11535	 * @param $y2 (float) Ordinate of second point.
11536	 * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
11537	 * @public
11538	 * @since 1.0
11539	 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
11540	 */
11541	public function Line($x1, $y1, $x2, $y2, $style=array()) {
11542		if ($this->state != 2) {
11543			return;
11544		}
11545		if (is_array($style)) {
11546			$this->SetLineStyle($style);
11547		}
11548		$this->_outPoint($x1, $y1);
11549		$this->_outLine($x2, $y2);
11550		$this->_out('S');
11551	}
11552
11553	/**
11554	 * Draws a rectangle.
11555	 * @param $x (float) Abscissa of upper-left corner.
11556	 * @param $y (float) Ordinate of upper-left corner.
11557	 * @param $w (float) Width.
11558	 * @param $h (float) Height.
11559	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11560	 * @param $border_style (array) Border style of rectangle. Array with keys among the following:
11561	 * <ul>
11562	 *	 <li>all: Line style of all borders. Array like for SetLineStyle().</li>
11563	 *	 <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
11564	 * </ul>
11565	 * If a key is not present or is null, the correspondent border is not drawn. Default value: default line style (empty array).
11566	 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
11567	 * @public
11568	 * @since 1.0
11569	 * @see SetLineStyle()
11570	 */
11571	public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
11572		if ($this->state != 2) {
11573			return;
11574		}
11575		if (empty($style)) {
11576			$style = 'S';
11577		}
11578		if (!(strpos($style, 'F') === false) AND !empty($fill_color)) {
11579			// set background color
11580			$this->SetFillColorArray($fill_color);
11581		}
11582		if (!empty($border_style)) {
11583			if (isset($border_style['all']) AND !empty($border_style['all'])) {
11584				//set global style for border
11585				$this->SetLineStyle($border_style['all']);
11586				$border_style = array();
11587			} else {
11588				// remove stroke operator from style
11589				$opnostroke = array('S' => '', 'D' => '', 's' => '', 'd' => '', 'B' => 'F', 'FD' => 'F', 'DF' => 'F', 'B*' => 'F*', 'F*D' => 'F*', 'DF*' => 'F*', 'b' => 'f', 'fd' => 'f', 'df' => 'f', 'b*' => 'f*', 'f*d' => 'f*', 'df*' => 'f*' );
11590				if (isset($opnostroke[$style])) {
11591					$style = $opnostroke[$style];
11592				}
11593			}
11594		}
11595		if (!empty($style)) {
11596			$op = TCPDF_STATIC::getPathPaintOperator($style);
11597			$this->_outRect($x, $y, $w, $h, $op);
11598		}
11599		if (!empty($border_style)) {
11600			$border_style2 = array();
11601			foreach ($border_style as $line => $value) {
11602				$length = strlen($line);
11603				for ($i = 0; $i < $length; ++$i) {
11604					$border_style2[$line[$i]] = $value;
11605				}
11606			}
11607			$border_style = $border_style2;
11608			if (isset($border_style['L']) AND $border_style['L']) {
11609				$this->Line($x, $y, $x, $y + $h, $border_style['L']);
11610			}
11611			if (isset($border_style['T']) AND $border_style['T']) {
11612				$this->Line($x, $y, $x + $w, $y, $border_style['T']);
11613			}
11614			if (isset($border_style['R']) AND $border_style['R']) {
11615				$this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
11616			}
11617			if (isset($border_style['B']) AND $border_style['B']) {
11618				$this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
11619			}
11620		}
11621	}
11622
11623	/**
11624	 * Draws a Bezier curve.
11625	 * The Bezier curve is a tangent to the line between the control points at
11626	 * either end of the curve.
11627	 * @param $x0 (float) Abscissa of start point.
11628	 * @param $y0 (float) Ordinate of start point.
11629	 * @param $x1 (float) Abscissa of control point 1.
11630	 * @param $y1 (float) Ordinate of control point 1.
11631	 * @param $x2 (float) Abscissa of control point 2.
11632	 * @param $y2 (float) Ordinate of control point 2.
11633	 * @param $x3 (float) Abscissa of end point.
11634	 * @param $y3 (float) Ordinate of end point.
11635	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11636	 * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
11637	 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
11638	 * @public
11639	 * @see SetLineStyle()
11640	 * @since 2.1.000 (2008-01-08)
11641	 */
11642	public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
11643		if ($this->state != 2) {
11644			return;
11645		}
11646		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
11647			$this->SetFillColorArray($fill_color);
11648		}
11649		$op = TCPDF_STATIC::getPathPaintOperator($style);
11650		if ($line_style) {
11651			$this->SetLineStyle($line_style);
11652		}
11653		$this->_outPoint($x0, $y0);
11654		$this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
11655		$this->_out($op);
11656	}
11657
11658	/**
11659	 * Draws a poly-Bezier curve.
11660	 * Each Bezier curve segment is a tangent to the line between the control points at
11661	 * either end of the curve.
11662	 * @param $x0 (float) Abscissa of start point.
11663	 * @param $y0 (float) Ordinate of start point.
11664	 * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
11665	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11666	 * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
11667	 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
11668	 * @public
11669	 * @see SetLineStyle()
11670	 * @since 3.0008 (2008-05-12)
11671	 */
11672	public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
11673		if ($this->state != 2) {
11674			return;
11675		}
11676		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
11677			$this->SetFillColorArray($fill_color);
11678		}
11679		$op = TCPDF_STATIC::getPathPaintOperator($style);
11680		if ($op == 'f') {
11681			$line_style = array();
11682		}
11683		if ($line_style) {
11684			$this->SetLineStyle($line_style);
11685		}
11686		$this->_outPoint($x0, $y0);
11687		foreach ($segments as $segment) {
11688			list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
11689			$this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
11690		}
11691		$this->_out($op);
11692	}
11693
11694	/**
11695	 * Draws an ellipse.
11696	 * An ellipse is formed from n Bezier curves.
11697	 * @param $x0 (float) Abscissa of center point.
11698	 * @param $y0 (float) Ordinate of center point.
11699	 * @param $rx (float) Horizontal radius.
11700	 * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
11701	 * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
11702	 * @param $astart: (float) Angle start of draw line. Default value: 0.
11703	 * @param $afinish: (float) Angle finish of draw line. Default value: 360.
11704	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11705	 * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
11706	 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
11707	 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
11708	 * @author Nicola Asuni
11709	 * @public
11710	 * @since 2.1.000 (2008-01-08)
11711	 */
11712	public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
11713		if ($this->state != 2) {
11714			return;
11715		}
11716		if (TCPDF_STATIC::empty_string($ry) OR ($ry == 0)) {
11717			$ry = $rx;
11718		}
11719		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
11720			$this->SetFillColorArray($fill_color);
11721		}
11722		$op = TCPDF_STATIC::getPathPaintOperator($style);
11723		if ($op == 'f') {
11724			$line_style = array();
11725		}
11726		if ($line_style) {
11727			$this->SetLineStyle($line_style);
11728		}
11729		$this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
11730		$this->_out($op);
11731	}
11732
11733	/**
11734	 * Append an elliptical arc to the current path.
11735	 * An ellipse is formed from n Bezier curves.
11736	 * @param $xc (float) Abscissa of center point.
11737	 * @param $yc (float) Ordinate of center point.
11738	 * @param $rx (float) Horizontal radius.
11739	 * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
11740	 * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
11741	 * @param $angs: (float) Angle start of draw line. Default value: 0.
11742	 * @param $angf: (float) Angle finish of draw line. Default value: 360.
11743	 * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
11744	 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
11745	 * @param $startpoint (boolean) if true output a starting point.
11746	 * @param $ccw (boolean) if true draws in counter-clockwise.
11747	 * @param $svg (boolean) if true the angles are in svg mode (already calculated).
11748	 * @return array bounding box coordinates (x min, y min, x max, y max)
11749	 * @author Nicola Asuni
11750	 * @protected
11751	 * @since 4.9.019 (2010-04-26)
11752	 */
11753	protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
11754		if (($rx <= 0) OR ($ry < 0)) {
11755			return;
11756		}
11757		$k = $this->k;
11758		if ($nc < 2) {
11759			$nc = 2;
11760		}
11761		$xmin = 2147483647;
11762		$ymin = 2147483647;
11763		$xmax = 0;
11764		$ymax = 0;
11765		if ($pie) {
11766			// center of the arc
11767			$this->_outPoint($xc, $yc);
11768		}
11769		$xang = deg2rad((float) $xang);
11770		$angs = deg2rad((float) $angs);
11771		$angf = deg2rad((float) $angf);
11772		if ($svg) {
11773			$as = $angs;
11774			$af = $angf;
11775		} else {
11776			$as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
11777			$af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
11778		}
11779		if ($as < 0) {
11780			$as += (2 * M_PI);
11781		}
11782		if ($af < 0) {
11783			$af += (2 * M_PI);
11784		}
11785		if ($ccw AND ($as > $af)) {
11786			// reverse rotation
11787			$as -= (2 * M_PI);
11788		} elseif (!$ccw AND ($as < $af)) {
11789			// reverse rotation
11790			$af -= (2 * M_PI);
11791		}
11792		$total_angle = ($af - $as);
11793		if ($nc < 2) {
11794			$nc = 2;
11795		}
11796		// total arcs to draw
11797		$nc *= (2 * abs($total_angle) / M_PI);
11798		$nc = round($nc) + 1;
11799		// angle of each arc
11800		$arcang = ($total_angle / $nc);
11801		// center point in PDF coordinates
11802		$x0 = $xc;
11803		$y0 = ($this->h - $yc);
11804		// starting angle
11805		$ang = $as;
11806		$alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
11807		$cos_xang = cos($xang);
11808		$sin_xang = sin($xang);
11809		$cos_ang = cos($ang);
11810		$sin_ang = sin($ang);
11811		// first arc point
11812		$px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
11813		$py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
11814		// first Bezier control point
11815		$qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
11816		$qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
11817		if ($pie) {
11818			// line from center to arc starting point
11819			$this->_outLine($px1, $this->h - $py1);
11820		} elseif ($startpoint) {
11821			// arc starting point
11822			$this->_outPoint($px1, $this->h - $py1);
11823		}
11824		// draw arcs
11825		for ($i = 1; $i <= $nc; ++$i) {
11826			// starting angle
11827			$ang = $as + ($i * $arcang);
11828			if ($i == $nc) {
11829				$ang = $af;
11830			}
11831			$cos_ang = cos($ang);
11832			$sin_ang = sin($ang);
11833			// second arc point
11834			$px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
11835			$py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
11836			// second Bezier control point
11837			$qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
11838			$qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
11839			// draw arc
11840			$cx1 = ($px1 + $qx1);
11841			$cy1 = ($this->h - ($py1 + $qy1));
11842			$cx2 = ($px2 - $qx2);
11843			$cy2 = ($this->h - ($py2 - $qy2));
11844			$cx3 = $px2;
11845			$cy3 = ($this->h - $py2);
11846			$this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
11847			// get bounding box coordinates
11848			$xmin = min($xmin, $cx1, $cx2, $cx3);
11849			$ymin = min($ymin, $cy1, $cy2, $cy3);
11850			$xmax = max($xmax, $cx1, $cx2, $cx3);
11851			$ymax = max($ymax, $cy1, $cy2, $cy3);
11852			// move to next point
11853			$px1 = $px2;
11854			$py1 = $py2;
11855			$qx1 = $qx2;
11856			$qy1 = $qy2;
11857		}
11858		if ($pie) {
11859			$this->_outLine($xc, $yc);
11860			// get bounding box coordinates
11861			$xmin = min($xmin, $xc);
11862			$ymin = min($ymin, $yc);
11863			$xmax = max($xmax, $xc);
11864			$ymax = max($ymax, $yc);
11865		}
11866		return array($xmin, $ymin, $xmax, $ymax);
11867	}
11868
11869	/**
11870	 * Draws a circle.
11871	 * A circle is formed from n Bezier curves.
11872	 * @param $x0 (float) Abscissa of center point.
11873	 * @param $y0 (float) Ordinate of center point.
11874	 * @param $r (float) Radius.
11875	 * @param $angstr: (float) Angle start of draw line. Default value: 0.
11876	 * @param $angend: (float) Angle finish of draw line. Default value: 360.
11877	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11878	 * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
11879	 * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
11880	 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
11881	 * @public
11882	 * @since 2.1.000 (2008-01-08)
11883	 */
11884	public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
11885		$this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
11886	}
11887
11888	/**
11889	 * Draws a polygonal line
11890	 * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
11891	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11892	 * @param $line_style (array) Line style of polygon. Array with keys among the following:
11893	 * <ul>
11894	 *	 <li>all: Line style of all lines. Array like for SetLineStyle().</li>
11895	 *	 <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
11896	 * </ul>
11897	 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
11898	 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
11899	 * @since 4.8.003 (2009-09-15)
11900	 * @public
11901	 */
11902	public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
11903		$this->Polygon($p, $style, $line_style, $fill_color, false);
11904	}
11905
11906	/**
11907	 * Draws a polygon.
11908	 * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
11909	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11910	 * @param $line_style (array) Line style of polygon. Array with keys among the following:
11911	 * <ul>
11912	 *	 <li>all: Line style of all lines. Array like for SetLineStyle().</li>
11913	 *	 <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
11914	 * </ul>
11915	 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
11916	 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
11917	 * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
11918	 * @public
11919	 * @since 2.1.000 (2008-01-08)
11920	 */
11921	public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
11922		if ($this->state != 2) {
11923			return;
11924		}
11925		$nc = count($p); // number of coordinates
11926		$np = $nc / 2; // number of points
11927		if ($closed) {
11928			// close polygon by adding the first 2 points at the end (one line)
11929			for ($i = 0; $i < 4; ++$i) {
11930				$p[$nc + $i] = $p[$i];
11931			}
11932			// copy style for the last added line
11933			if (isset($line_style[0])) {
11934				$line_style[$np] = $line_style[0];
11935			}
11936			$nc += 4;
11937		}
11938		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
11939			$this->SetFillColorArray($fill_color);
11940		}
11941		$op = TCPDF_STATIC::getPathPaintOperator($style);
11942		if ($op == 'f') {
11943			$line_style = array();
11944		}
11945		$draw = true;
11946		if ($line_style) {
11947			if (isset($line_style['all'])) {
11948				$this->SetLineStyle($line_style['all']);
11949			} else {
11950				$draw = false;
11951				if ($op == 'B') {
11952					// draw fill
11953					$op = 'f';
11954					$this->_outPoint($p[0], $p[1]);
11955					for ($i = 2; $i < $nc; $i = $i + 2) {
11956						$this->_outLine($p[$i], $p[$i + 1]);
11957					}
11958					$this->_out($op);
11959				}
11960				// draw outline
11961				$this->_outPoint($p[0], $p[1]);
11962				for ($i = 2; $i < $nc; $i = $i + 2) {
11963					$line_num = ($i / 2) - 1;
11964					if (isset($line_style[$line_num])) {
11965						if ($line_style[$line_num] != 0) {
11966							if (is_array($line_style[$line_num])) {
11967								$this->_out('S');
11968								$this->SetLineStyle($line_style[$line_num]);
11969								$this->_outPoint($p[$i - 2], $p[$i - 1]);
11970								$this->_outLine($p[$i], $p[$i + 1]);
11971								$this->_out('S');
11972								$this->_outPoint($p[$i], $p[$i + 1]);
11973							} else {
11974								$this->_outLine($p[$i], $p[$i + 1]);
11975							}
11976						}
11977					} else {
11978						$this->_outLine($p[$i], $p[$i + 1]);
11979					}
11980				}
11981				$this->_out($op);
11982			}
11983		}
11984		if ($draw) {
11985			$this->_outPoint($p[0], $p[1]);
11986			for ($i = 2; $i < $nc; $i = $i + 2) {
11987				$this->_outLine($p[$i], $p[$i + 1]);
11988			}
11989			$this->_out($op);
11990		}
11991	}
11992
11993	/**
11994	 * Draws a regular polygon.
11995	 * @param $x0 (float) Abscissa of center point.
11996	 * @param $y0 (float) Ordinate of center point.
11997	 * @param $r: (float) Radius of inscribed circle.
11998	 * @param $ns (integer) Number of sides.
11999	 * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
12000	 * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
12001	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
12002	 * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
12003	 * <ul>
12004	 *	 <li>all: Line style of all sides. Array like for SetLineStyle().</li>
12005	 *	 <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
12006	 * </ul>
12007	 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
12008	 * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
12009	 * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
12010	 * <ul>
12011	 *	 <li>D or empty string: Draw (default).</li>
12012	 *	 <li>F: Fill.</li>
12013	 *	 <li>DF or FD: Draw and fill.</li>
12014	 *	 <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
12015	 *	 <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
12016	 * </ul>
12017	 * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
12018	 * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
12019	 * @public
12020	 * @since 2.1.000 (2008-01-08)
12021	 */
12022	public function RegularPolygon($x0, $y0, $r, $ns, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {
12023		if (3 > $ns) {
12024			$ns = 3;
12025		}
12026		if ($draw_circle) {
12027			$this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
12028		}
12029		$p = array();
12030		for ($i = 0; $i < $ns; ++$i) {
12031			$a = $angle + ($i * 360 / $ns);
12032			$a_rad = deg2rad((float) $a);
12033			$p[] = $x0 + ($r * sin($a_rad));
12034			$p[] = $y0 + ($r * cos($a_rad));
12035		}
12036		$this->Polygon($p, $style, $line_style, $fill_color);
12037	}
12038
12039	/**
12040	 * Draws a star polygon
12041	 * @param $x0 (float) Abscissa of center point.
12042	 * @param $y0 (float) Ordinate of center point.
12043	 * @param $r (float) Radius of inscribed circle.
12044	 * @param $nv (integer) Number of vertices.
12045	 * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
12046	 * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
12047	 * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
12048	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
12049	 * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
12050	 * <ul>
12051	 *	 <li>all: Line style of all sides. Array like for
12052	 * SetLineStyle().</li>
12053	 *	 <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
12054	 * </ul>
12055	 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
12056	 * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
12057	 * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
12058	 * <ul>
12059	 *	 <li>D or empty string: Draw (default).</li>
12060	 *	 <li>F: Fill.</li>
12061	 *	 <li>DF or FD: Draw and fill.</li>
12062	 *	 <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
12063	 *	 <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
12064	 * </ul>
12065	 * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
12066	 * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
12067	 * @public
12068	 * @since 2.1.000 (2008-01-08)
12069	 */
12070	public function StarPolygon($x0, $y0, $r, $nv, $ng, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {
12071		if ($nv < 2) {
12072			$nv = 2;
12073		}
12074		if ($draw_circle) {
12075			$this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
12076		}
12077		$p2 = array();
12078		$visited = array();
12079		for ($i = 0; $i < $nv; ++$i) {
12080			$a = $angle + ($i * 360 / $nv);
12081			$a_rad = deg2rad((float) $a);
12082			$p2[] = $x0 + ($r * sin($a_rad));
12083			$p2[] = $y0 + ($r * cos($a_rad));
12084			$visited[] = false;
12085		}
12086		$p = array();
12087		$i = 0;
12088		do {
12089			$p[] = $p2[$i * 2];
12090			$p[] = $p2[($i * 2) + 1];
12091			$visited[$i] = true;
12092			$i += $ng;
12093			$i %= $nv;
12094		} while (!$visited[$i]);
12095		$this->Polygon($p, $style, $line_style, $fill_color);
12096	}
12097
12098	/**
12099	 * Draws a rounded rectangle.
12100	 * @param $x (float) Abscissa of upper-left corner.
12101	 * @param $y (float) Ordinate of upper-left corner.
12102	 * @param $w (float) Width.
12103	 * @param $h (float) Height.
12104	 * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
12105	 * @param $round_corner (string) 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 right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
12106	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
12107	 * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
12108	 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
12109	 * @public
12110	 * @since 2.1.000 (2008-01-08)
12111	 */
12112	public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
12113		$this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
12114	}
12115
12116	/**
12117	 * Draws a rounded rectangle.
12118	 * @param $x (float) Abscissa of upper-left corner.
12119	 * @param $y (float) Ordinate of upper-left corner.
12120	 * @param $w (float) Width.
12121	 * @param $h (float) Height.
12122	 * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
12123	 * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
12124	 * @param $round_corner (string) 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 right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
12125	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
12126	 * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
12127	 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
12128	 * @public
12129	 * @since 4.9.019 (2010-04-22)
12130	 */
12131	public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
12132		if ($this->state != 2) {
12133			return;
12134		}
12135		if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
12136			// Not rounded
12137			$this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
12138			return;
12139		}
12140		// Rounded
12141		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
12142			$this->SetFillColorArray($fill_color);
12143		}
12144		$op = TCPDF_STATIC::getPathPaintOperator($style);
12145		if ($op == 'f') {
12146			$border_style = array();
12147		}
12148		if ($border_style) {
12149			$this->SetLineStyle($border_style);
12150		}
12151		$MyArc = 4 / 3 * (sqrt(2) - 1);
12152		$this->_outPoint($x + $rx, $y);
12153		$xc = $x + $w - $rx;
12154		$yc = $y + $ry;
12155		$this->_outLine($xc, $y);
12156		if ($round_corner[0]) {
12157			$this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
12158		} else {
12159			$this->_outLine($x + $w, $y);
12160		}
12161		$xc = $x + $w - $rx;
12162		$yc = $y + $h - $ry;
12163		$this->_outLine($x + $w, $yc);
12164		if ($round_corner[1]) {
12165			$this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
12166		} else {
12167			$this->_outLine($x + $w, $y + $h);
12168		}
12169		$xc = $x + $rx;
12170		$yc = $y + $h - $ry;
12171		$this->_outLine($xc, $y + $h);
12172		if ($round_corner[2]) {
12173			$this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
12174		} else {
12175			$this->_outLine($x, $y + $h);
12176		}
12177		$xc = $x + $rx;
12178		$yc = $y + $ry;
12179		$this->_outLine($x, $yc);
12180		if ($round_corner[3]) {
12181			$this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
12182		} else {
12183			$this->_outLine($x, $y);
12184			$this->_outLine($x + $rx, $y);
12185		}
12186		$this->_out($op);
12187	}
12188
12189	/**
12190	 * Draws a grahic arrow.
12191	 * @param $x0 (float) Abscissa of first point.
12192	 * @param $y0 (float) Ordinate of first point.
12193	 * @param $x1 (float) Abscissa of second point.
12194	 * @param $y1 (float) Ordinate of second point.
12195	 * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
12196	 * @param $arm_size (float) length of arrowhead arms
12197	 * @param $arm_angle (int) angle between an arm and the shaft
12198	 * @author Piotr Galecki, Nicola Asuni, Andy Meier
12199	 * @since 4.6.018 (2009-07-10)
12200	 */
12201	public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
12202		// getting arrow direction angle
12203		// 0 deg angle is when both arms go along X axis. angle grows clockwise.
12204		$dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
12205		if ($dir_angle < 0) {
12206			$dir_angle += (2 * M_PI);
12207		}
12208		$arm_angle = deg2rad($arm_angle);
12209		$sx1 = $x1;
12210		$sy1 = $y1;
12211		if ($head_style > 0) {
12212			// calculate the stopping point for the arrow shaft
12213			$sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
12214			$sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
12215		}
12216		// main arrow line / shaft
12217		$this->Line($x0, $y0, $sx1, $sy1);
12218		// left arrowhead arm tip
12219		$x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
12220		$y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
12221		// right arrowhead arm tip
12222		$x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
12223		$y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
12224		$mode = 'D';
12225		$style = array();
12226		switch ($head_style) {
12227			case 0: {
12228				// draw only arrowhead arms
12229				$mode = 'D';
12230				$style = array(1, 1, 0);
12231				break;
12232			}
12233			case 1: {
12234				// draw closed arrowhead, but no fill
12235				$mode = 'D';
12236				break;
12237			}
12238			case 2: {
12239				// closed and filled arrowhead
12240				$mode = 'DF';
12241				break;
12242			}
12243			case 3: {
12244				// filled arrowhead
12245				$mode = 'F';
12246				break;
12247			}
12248		}
12249		$this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
12250	}
12251
12252	// END GRAPHIC FUNCTIONS SECTION -----------------------
12253
12254	/**
12255	 * Add a Named Destination.
12256	 * NOTE: destination names are unique, so only last entry will be saved.
12257	 * @param $name (string) Destination name.
12258	 * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
12259	 * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
12260	 * @param $x (float) X position in user units of the destiantion on the selected page (default = -1 = current position;).
12261	 * @return (string) Stripped named destination identifier or false in case of error.
12262	 * @public
12263	 * @author Christian Deligant, Nicola Asuni
12264	 * @since 5.9.097 (2011-06-23)
12265	 */
12266	public function setDestination($name, $y=-1, $page='', $x=-1) {
12267		// remove unsupported characters
12268		$name = TCPDF_STATIC::encodeNameObject($name);
12269		if (TCPDF_STATIC::empty_string($name)) {
12270			return false;
12271		}
12272		if ($y == -1) {
12273			$y = $this->GetY();
12274		} elseif ($y < 0) {
12275			$y = 0;
12276		} elseif ($y > $this->h) {
12277			$y = $this->h;
12278		}
12279		if ($x == -1) {
12280			$x = $this->GetX();
12281		} elseif ($x < 0) {
12282			$x = 0;
12283		} elseif ($x > $this->w) {
12284			$x = $this->w;
12285		}
12286		$fixed = false;
12287		if (!empty($page) AND ($page[0] == '*')) {
12288			$page = intval(substr($page, 1));
12289			// this page number will not be changed when moving/add/deleting pages
12290			$fixed = true;
12291		}
12292		if (empty($page)) {
12293			$page = $this->PageNo();
12294			if (empty($page)) {
12295				return;
12296			}
12297		}
12298		$this->dests[$name] = array('x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed);
12299		return $name;
12300	}
12301
12302	/**
12303	 * Return the Named Destination array.
12304	 * @return (array) Named Destination array.
12305	 * @public
12306	 * @author Nicola Asuni
12307	 * @since 5.9.097 (2011-06-23)
12308	 */
12309	public function getDestination() {
12310		return $this->dests;
12311	}
12312
12313	/**
12314	 * Insert Named Destinations.
12315	 * @protected
12316	 * @author Johannes G\FCntert, Nicola Asuni
12317	 * @since 5.9.098 (2011-06-23)
12318	 */
12319	protected function _putdests() {
12320		if (empty($this->dests)) {
12321			return;
12322		}
12323		$this->n_dests = $this->_newobj();
12324		$out = ' <<';
12325		foreach($this->dests as $name => $o) {
12326			$out .= ' /'.$name.' '.sprintf('[%u 0 R /XYZ %F %F null]', $this->page_obj_id[($o['p'])], ($o['x'] * $this->k), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
12327		}
12328		$out .= ' >>';
12329		$out .= "\n".'endobj';
12330		$this->_out($out);
12331	}
12332
12333	/**
12334	 * Adds a bookmark - alias for Bookmark().
12335	 * @param $txt (string) Bookmark description.
12336	 * @param $level (int) Bookmark level (minimum value is 0).
12337	 * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
12338	 * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
12339	 * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
12340	 * @param $color (array) RGB color array (values from 0 to 255).
12341	 * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
12342	 * @param $link (mixed) URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
12343	 * @public
12344	 */
12345	public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
12346		$this->Bookmark($txt, $level, $y, $page, $style, $color, $x, $link);
12347	}
12348
12349	/**
12350	 * Adds a bookmark.
12351	 * @param $txt (string) Bookmark description.
12352	 * @param $level (int) Bookmark level (minimum value is 0).
12353	 * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
12354	 * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
12355	 * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
12356	 * @param $color (array) RGB color array (values from 0 to 255).
12357	 * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
12358	 * @param $link (mixed) URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
12359	 * @public
12360	 * @since 2.1.002 (2008-02-12)
12361	 */
12362	public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
12363		if ($level < 0) {
12364			$level = 0;
12365		}
12366		if (isset($this->outlines[0])) {
12367			$lastoutline = end($this->outlines);
12368			$maxlevel = $lastoutline['l'] + 1;
12369		} else {
12370			$maxlevel = 0;
12371		}
12372		if ($level > $maxlevel) {
12373			$level = $maxlevel;
12374		}
12375		if ($y == -1) {
12376			$y = $this->GetY();
12377		} elseif ($y < 0) {
12378			$y = 0;
12379		} elseif ($y > $this->h) {
12380			$y = $this->h;
12381		}
12382		if ($x == -1) {
12383			$x = $this->GetX();
12384		} elseif ($x < 0) {
12385			$x = 0;
12386		} elseif ($x > $this->w) {
12387			$x = $this->w;
12388		}
12389		$fixed = false;
12390		if (!empty($page) AND ($page[0] == '*')) {
12391			$page = intval(substr($page, 1));
12392			// this page number will not be changed when moving/add/deleting pages
12393			$fixed = true;
12394		}
12395		if (empty($page)) {
12396			$page = $this->PageNo();
12397			if (empty($page)) {
12398				return;
12399			}
12400		}
12401		$this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);
12402	}
12403
12404	/**
12405	 * Sort bookmarks for page and key.
12406	 * @protected
12407	 * @since 5.9.119 (2011-09-19)
12408	 */
12409	protected function sortBookmarks() {
12410		// get sorting columns
12411		$outline_p = array();
12412		$outline_y = array();
12413		foreach ($this->outlines as $key => $row) {
12414			$outline_p[$key] = $row['p'];
12415			$outline_k[$key] = $key;
12416		}
12417		// sort outlines by page and original position
12418		array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
12419	}
12420
12421	/**
12422	 * Create a bookmark PDF string.
12423	 * @protected
12424	 * @author Olivier Plathey, Nicola Asuni
12425	 * @since 2.1.002 (2008-02-12)
12426	 */
12427	protected function _putbookmarks() {
12428		$nb = count($this->outlines);
12429		if ($nb == 0) {
12430			return;
12431		}
12432		// sort bookmarks
12433		$this->sortBookmarks();
12434		$lru = array();
12435		$level = 0;
12436		foreach ($this->outlines as $i => $o) {
12437			if ($o['l'] > 0) {
12438				$parent = $lru[($o['l'] - 1)];
12439				//Set parent and last pointers
12440				$this->outlines[$i]['parent'] = $parent;
12441				$this->outlines[$parent]['last'] = $i;
12442				if ($o['l'] > $level) {
12443					//Level increasing: set first pointer
12444					$this->outlines[$parent]['first'] = $i;
12445				}
12446			} else {
12447				$this->outlines[$i]['parent'] = $nb;
12448			}
12449			if (($o['l'] <= $level) AND ($i > 0)) {
12450				//Set prev and next pointers
12451				$prev = $lru[$o['l']];
12452				$this->outlines[$prev]['next'] = $i;
12453				$this->outlines[$i]['prev'] = $prev;
12454			}
12455			$lru[$o['l']] = $i;
12456			$level = $o['l'];
12457		}
12458		//Outline items
12459		$n = $this->n + 1;
12460		$nltags = '/<br[\s]?\/>|<\/(blockquote|dd|dl|div|dt|h1|h2|h3|h4|h5|h6|hr|li|ol|p|pre|ul|tcpdf|table|tr|td)>/si';
12461		foreach ($this->outlines as $i => $o) {
12462			$oid = $this->_newobj();
12463			// covert HTML title to string
12464			$title = preg_replace($nltags, "\n", $o['t']);
12465			$title = preg_replace("/[\r]+/si", '', $title);
12466			$title = preg_replace("/[\n]+/si", "\n", $title);
12467			$title = strip_tags($title);
12468			$title = $this->stringTrim($title);
12469			$out = '<</Title '.$this->_textstring($title, $oid);
12470			$out .= ' /Parent '.($n + $o['parent']).' 0 R';
12471			if (isset($o['prev'])) {
12472				$out .= ' /Prev '.($n + $o['prev']).' 0 R';
12473			}
12474			if (isset($o['next'])) {
12475				$out .= ' /Next '.($n + $o['next']).' 0 R';
12476			}
12477			if (isset($o['first'])) {
12478				$out .= ' /First '.($n + $o['first']).' 0 R';
12479			}
12480			if (isset($o['last'])) {
12481				$out .= ' /Last '.($n + $o['last']).' 0 R';
12482			}
12483			if (isset($o['u']) AND !empty($o['u'])) {
12484				// link
12485				if (is_string($o['u'])) {
12486					if ($o['u'][0] == '#') {
12487						// internal destination
12488						$out .= ' /Dest /'.TCPDF_STATIC::encodeNameObject(substr($o['u'], 1));
12489					} elseif ($o['u'][0] == '%') {
12490						// embedded PDF file
12491						$filename = basename(substr($o['u'], 1));
12492						$out .= ' /A <</S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($o['p'] - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
12493					} elseif ($o['u'][0] == '*') {
12494						// embedded generic file
12495						$filename = basename(substr($o['u'], 1));
12496						$jsa = 'var D=event.target.doc;var MyData=D.dataObjects;for (var i in MyData) if (MyData[i].path=="'.$filename.'") D.exportDataObject( { cName : MyData[i].name, nLaunch : 2});';
12497						$out .= ' /A <</S /JavaScript /JS '.$this->_textstring($jsa, $oid).'>>';
12498					} else {
12499						// external URI link
12500						$out .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($o['u']), $oid).'>>';
12501					}
12502				} elseif (isset($this->links[$o['u']])) {
12503					// internal link ID
12504					$l = $this->links[$o['u']];
12505					if (isset($this->page_obj_id[($l['p'])])) {
12506						$out .= sprintf(' /Dest [%u 0 R /XYZ 0 %F null]', $this->page_obj_id[($l['p'])], ($this->pagedim[$l['p']]['h'] - ($l['y'] * $this->k)));
12507					}
12508				}
12509			} elseif (isset($this->page_obj_id[($o['p'])])) {
12510				// link to a page
12511				$out .= ' '.sprintf('/Dest [%u 0 R /XYZ %F %F null]', $this->page_obj_id[($o['p'])], ($o['x'] * $this->k), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
12512			}
12513			// set font style
12514			$style = 0;
12515			if (!empty($o['s'])) {
12516				// bold
12517				if (strpos($o['s'], 'B') !== false) {
12518					$style |= 2;
12519				}
12520				// oblique
12521				if (strpos($o['s'], 'I') !== false) {
12522					$style |= 1;
12523				}
12524			}
12525			$out .= sprintf(' /F %d', $style);
12526			// set bookmark color
12527			if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
12528				$color = array_values($o['c']);
12529				$out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
12530			} else {
12531				// black
12532				$out .= ' /C [0.0 0.0 0.0]';
12533			}
12534			$out .= ' /Count 0'; // normally closed item
12535			$out .= ' >>';
12536			$out .= "\n".'endobj';
12537			$this->_out($out);
12538		}
12539		//Outline root
12540		$this->OutlineRoot = $this->_newobj();
12541		$this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
12542	}
12543
12544	// --- JAVASCRIPT ------------------------------------------------------
12545
12546	/**
12547	 * Adds a javascript
12548	 * @param $script (string) Javascript code
12549	 * @public
12550	 * @author Johannes G\FCntert, Nicola Asuni
12551	 * @since 2.1.002 (2008-02-12)
12552	 */
12553	public function IncludeJS($script) {
12554		$this->javascript .= $script;
12555	}
12556
12557	/**
12558	 * Adds a javascript object and return object ID
12559	 * @param $script (string) Javascript code
12560	 * @param $onload (boolean) if true executes this object when opening the document
12561	 * @return int internal object ID
12562	 * @public
12563	 * @author Nicola Asuni
12564	 * @since 4.8.000 (2009-09-07)
12565	 */
12566	public function addJavascriptObject($script, $onload=false) {
12567		if ($this->pdfa_mode) {
12568			// javascript is not allowed in PDF/A mode
12569			return false;
12570		}
12571		++$this->n;
12572		$this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
12573		return $this->n;
12574	}
12575
12576	/**
12577	 * Create a javascript PDF string.
12578	 * @protected
12579	 * @author Johannes G\FCntert, Nicola Asuni
12580	 * @since 2.1.002 (2008-02-12)
12581	 */
12582	protected function _putjavascript() {
12583		if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
12584			return;
12585		}
12586		if (strpos($this->javascript, 'this.addField') > 0) {
12587			if (!$this->ur['enabled']) {
12588				//$this->setUserRights();
12589			}
12590			// the following two lines are used to avoid form fields duplication after saving
12591			// The addField method only works when releasing user rights (UR3)
12592			$jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
12593			$jsb = "getField('tcpdfdocsaved').value='saved';";
12594			$this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
12595		}
12596		// name tree for javascript
12597		$this->n_js = '<< /Names [';
12598		if (!empty($this->javascript)) {
12599			$this->n_js .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
12600		}
12601		if (!empty($this->js_objects)) {
12602			foreach ($this->js_objects as $key => $val) {
12603				if ($val['onload']) {
12604					$this->n_js .= ' (JS'.$key.') '.$key.' 0 R';
12605				}
12606			}
12607		}
12608		$this->n_js .= ' ] >>';
12609		// default Javascript object
12610		if (!empty($this->javascript)) {
12611			$obj_id = $this->_newobj();
12612			$out = '<< /S /JavaScript';
12613			$out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
12614			$out .= ' >>';
12615			$out .= "\n".'endobj';
12616			$this->_out($out);
12617		}
12618		// additional Javascript objects
12619		if (!empty($this->js_objects)) {
12620			foreach ($this->js_objects as $key => $val) {
12621				$out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
12622				$this->_out($out);
12623			}
12624		}
12625	}
12626
12627	/**
12628	 * Adds a javascript form field.
12629	 * @param $type (string) field type
12630	 * @param $name (string) field name
12631	 * @param $x (int) horizontal position
12632	 * @param $y (int) vertical position
12633	 * @param $w (int) width
12634	 * @param $h (int) height
12635	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12636	 * @protected
12637	 * @author Denis Van Nuffelen, Nicola Asuni
12638	 * @since 2.1.002 (2008-02-12)
12639	 */
12640	protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
12641		if ($this->rtl) {
12642			$x = $x - $w;
12643		}
12644		// the followind avoid fields duplication after saving the document
12645		$this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
12646		$k = $this->k;
12647		$this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%u,[%F,%F,%F,%F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
12648		$this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
12649		foreach($prop as $key => $val) {
12650			if (strcmp(substr($key, -5), 'Color') == 0) {
12651				$val = TCPDF_COLORS::_JScolor($val);
12652			} else {
12653				$val = "'".$val."'";
12654			}
12655			$this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
12656		}
12657		if ($this->rtl) {
12658			$this->x -= $w;
12659		} else {
12660			$this->x += $w;
12661		}
12662		$this->javascript .= '}';
12663	}
12664
12665	// --- FORM FIELDS -----------------------------------------------------
12666
12667
12668
12669	/**
12670	 * Set default properties for form fields.
12671	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12672	 * @public
12673	 * @author Nicola Asuni
12674	 * @since 4.8.000 (2009-09-06)
12675	 */
12676	public function setFormDefaultProp($prop=array()) {
12677		$this->default_form_prop = $prop;
12678	}
12679
12680	/**
12681	 * Return the default properties for form fields.
12682	 * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12683	 * @public
12684	 * @author Nicola Asuni
12685	 * @since 4.8.000 (2009-09-06)
12686	 */
12687	public function getFormDefaultProp() {
12688		return $this->default_form_prop;
12689	}
12690
12691	/**
12692	 * Creates a text field
12693	 * @param $name (string) field name
12694	 * @param $w (float) Width of the rectangle
12695	 * @param $h (float) Height of the rectangle
12696	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12697	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
12698	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
12699	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
12700	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
12701	 * @public
12702	 * @author Nicola Asuni
12703	 * @since 4.8.000 (2009-09-07)
12704	 */
12705	public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
12706		if ($x === '') {
12707			$x = $this->x;
12708		}
12709		if ($y === '') {
12710			$y = $this->y;
12711		}
12712		// check page for no-write regions and adapt page margins if necessary
12713		list($x, $y) = $this->checkPageRegions($h, $x, $y);
12714		if ($js) {
12715			$this->_addfield('text', $name, $x, $y, $w, $h, $prop);
12716			return;
12717		}
12718		// get default style
12719		$prop = array_merge($this->getFormDefaultProp(), $prop);
12720		// get annotation data
12721		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
12722		// set default appearance stream
12723		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
12724		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
12725		$popt['da'] = $fontstyle;
12726		// build appearance stream
12727		$popt['ap'] = array();
12728		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
12729		$text = '';
12730		if (isset($prop['value']) AND !empty($prop['value'])) {
12731			$text = $prop['value'];
12732		} elseif (isset($opt['v']) AND !empty($opt['v'])) {
12733			$text = $opt['v'];
12734		}
12735		$tmpid = $this->startTemplate($w, $h, false);
12736		$align = '';
12737		if (isset($popt['q'])) {
12738			switch ($popt['q']) {
12739				case 0: {
12740					$align = 'L';
12741					break;
12742				}
12743				case 1: {
12744					$align = 'C';
12745					break;
12746				}
12747				case 2: {
12748					$align = 'R';
12749					break;
12750				}
12751				default: {
12752					$align = '';
12753					break;
12754				}
12755			}
12756		}
12757		$this->MultiCell($w, $h, $text, 0, $align, false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
12758		$this->endTemplate();
12759		--$this->n;
12760		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
12761		unset($this->xobjects[$tmpid]);
12762		$popt['ap']['n'] .= 'Q EMC';
12763		// merge options
12764		$opt = array_merge($popt, $opt);
12765		// remove some conflicting options
12766		unset($opt['bs']);
12767		// set remaining annotation data
12768		$opt['Subtype'] = 'Widget';
12769		$opt['ft'] = 'Tx';
12770		$opt['t'] = $name;
12771		// Additional annotation's parameters (check _putannotsobj() method):
12772		//$opt['f']
12773		//$opt['as']
12774		//$opt['bs']
12775		//$opt['be']
12776		//$opt['c']
12777		//$opt['border']
12778		//$opt['h']
12779		//$opt['mk'];
12780		//$opt['mk']['r']
12781		//$opt['mk']['bc'];
12782		//$opt['mk']['bg'];
12783		unset($opt['mk']['ca']);
12784		unset($opt['mk']['rc']);
12785		unset($opt['mk']['ac']);
12786		unset($opt['mk']['i']);
12787		unset($opt['mk']['ri']);
12788		unset($opt['mk']['ix']);
12789		unset($opt['mk']['if']);
12790		//$opt['mk']['if']['sw'];
12791		//$opt['mk']['if']['s'];
12792		//$opt['mk']['if']['a'];
12793		//$opt['mk']['if']['fb'];
12794		unset($opt['mk']['tp']);
12795		//$opt['tu']
12796		//$opt['tm']
12797		//$opt['ff']
12798		//$opt['v']
12799		//$opt['dv']
12800		//$opt['a']
12801		//$opt['aa']
12802		//$opt['q']
12803		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
12804		if ($this->rtl) {
12805			$this->x -= $w;
12806		} else {
12807			$this->x += $w;
12808		}
12809	}
12810
12811	/**
12812	 * Creates a RadioButton field.
12813	 * @param $name (string) Field name.
12814	 * @param $w (int) Width of the radio button.
12815	 * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12816	 * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
12817	 * @param $onvalue (string) Value to be returned if selected.
12818	 * @param $checked (boolean) Define the initial state.
12819	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
12820	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
12821	 * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
12822	 * @public
12823	 * @author Nicola Asuni
12824	 * @since 4.8.000 (2009-09-07)
12825	 */
12826	public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
12827		if ($x === '') {
12828			$x = $this->x;
12829		}
12830		if ($y === '') {
12831			$y = $this->y;
12832		}
12833		// check page for no-write regions and adapt page margins if necessary
12834		list($x, $y) = $this->checkPageRegions($w, $x, $y);
12835		if ($js) {
12836			$this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
12837			return;
12838		}
12839		if (TCPDF_STATIC::empty_string($onvalue)) {
12840			$onvalue = 'On';
12841		}
12842		if ($checked) {
12843			$defval = $onvalue;
12844		} else {
12845			$defval = 'Off';
12846		}
12847		// set font
12848		$font = 'zapfdingbats';
12849		if ($this->pdfa_mode) {
12850			// all fonts must be embedded
12851			$font = 'pdfa'.$font;
12852		}
12853		$this->AddFont($font);
12854		$tmpfont = $this->getFontBuffer($font);
12855		// set data for parent group
12856		if (!isset($this->radiobutton_groups[$this->page])) {
12857			$this->radiobutton_groups[$this->page] = array();
12858		}
12859		if (!isset($this->radiobutton_groups[$this->page][$name])) {
12860			$this->radiobutton_groups[$this->page][$name] = array();
12861			++$this->n;
12862			$this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
12863			$this->radio_groups[] = $this->n;
12864		}
12865		$kid = ($this->n + 1);
12866		// save object ID to be added on Kids entry on parent object
12867		$this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
12868		// get default style
12869		$prop = array_merge($this->getFormDefaultProp(), $prop);
12870		$prop['NoToggleToOff'] = 'true';
12871		$prop['Radio'] = 'true';
12872		$prop['borderStyle'] = 'inset';
12873		// get annotation data
12874		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
12875		// set additional default options
12876		$this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
12877		$fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
12878		$popt['da'] = $fontstyle;
12879		// build appearance stream
12880		$popt['ap'] = array();
12881		$popt['ap']['n'] = array();
12882		$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][108])) / 2) * $this->k);
12883		$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
12884		$popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(108).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
12885		$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(109).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
12886		if (!isset($popt['mk'])) {
12887			$popt['mk'] = array();
12888		}
12889		$popt['mk']['ca'] = '(l)';
12890		// merge options
12891		$opt = array_merge($popt, $opt);
12892		// set remaining annotation data
12893		$opt['Subtype'] = 'Widget';
12894		$opt['ft'] = 'Btn';
12895		if ($checked) {
12896			$opt['v'] = array('/'.$onvalue);
12897			$opt['as'] = $onvalue;
12898		} else {
12899			$opt['as'] = 'Off';
12900		}
12901		// store readonly flag
12902		if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
12903			$this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
12904		}
12905		$this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
12906		$this->Annotation($x, $y, $w, $w, $name, $opt, 0);
12907		if ($this->rtl) {
12908			$this->x -= $w;
12909		} else {
12910			$this->x += $w;
12911		}
12912	}
12913
12914	/**
12915	 * Creates a List-box field
12916	 * @param $name (string) field name
12917	 * @param $w (int) width
12918	 * @param $h (int) height
12919	 * @param $values (array) array containing the list of values.
12920	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12921	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
12922	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
12923	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
12924	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
12925	 * @public
12926	 * @author Nicola Asuni
12927	 * @since 4.8.000 (2009-09-07)
12928	 */
12929	public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
12930		if ($x === '') {
12931			$x = $this->x;
12932		}
12933		if ($y === '') {
12934			$y = $this->y;
12935		}
12936		// check page for no-write regions and adapt page margins if necessary
12937		list($x, $y) = $this->checkPageRegions($h, $x, $y);
12938		if ($js) {
12939			$this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
12940			$s = '';
12941			foreach ($values as $value) {
12942				if (is_array($value)) {
12943					$s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
12944				} else {
12945					$s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
12946				}
12947			}
12948			$this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
12949			return;
12950		}
12951		// get default style
12952		$prop = array_merge($this->getFormDefaultProp(), $prop);
12953		// get annotation data
12954		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
12955		// set additional default values
12956		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
12957		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
12958		$popt['da'] = $fontstyle;
12959		// build appearance stream
12960		$popt['ap'] = array();
12961		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
12962		$text = '';
12963		foreach($values as $item) {
12964			if (is_array($item)) {
12965				$text .= $item[1]."\n";
12966			} else {
12967				$text .= $item."\n";
12968			}
12969		}
12970		$tmpid = $this->startTemplate($w, $h, false);
12971		$this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
12972		$this->endTemplate();
12973		--$this->n;
12974		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
12975		unset($this->xobjects[$tmpid]);
12976		$popt['ap']['n'] .= 'Q EMC';
12977		// merge options
12978		$opt = array_merge($popt, $opt);
12979		// set remaining annotation data
12980		$opt['Subtype'] = 'Widget';
12981		$opt['ft'] = 'Ch';
12982		$opt['t'] = $name;
12983		$opt['opt'] = $values;
12984		unset($opt['mk']['ca']);
12985		unset($opt['mk']['rc']);
12986		unset($opt['mk']['ac']);
12987		unset($opt['mk']['i']);
12988		unset($opt['mk']['ri']);
12989		unset($opt['mk']['ix']);
12990		unset($opt['mk']['if']);
12991		unset($opt['mk']['tp']);
12992		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
12993		if ($this->rtl) {
12994			$this->x -= $w;
12995		} else {
12996			$this->x += $w;
12997		}
12998	}
12999
13000	/**
13001	 * Creates a Combo-box field
13002	 * @param $name (string) field name
13003	 * @param $w (int) width
13004	 * @param $h (int) height
13005	 * @param $values (array) array containing the list of values.
13006	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13007	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
13008	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
13009	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
13010	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13011	 * @public
13012	 * @author Nicola Asuni
13013	 * @since 4.8.000 (2009-09-07)
13014	 */
13015	public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
13016		if ($x === '') {
13017			$x = $this->x;
13018		}
13019		if ($y === '') {
13020			$y = $this->y;
13021		}
13022		// check page for no-write regions and adapt page margins if necessary
13023		list($x, $y) = $this->checkPageRegions($h, $x, $y);
13024		if ($js) {
13025			$this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
13026			$s = '';
13027			foreach ($values as $value) {
13028				if (is_array($value)) {
13029					$s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
13030				} else {
13031					$s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
13032				}
13033			}
13034			$this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
13035			return;
13036		}
13037		// get default style
13038		$prop = array_merge($this->getFormDefaultProp(), $prop);
13039		$prop['Combo'] = true;
13040		// get annotation data
13041		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
13042		// set additional default options
13043		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
13044		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
13045		$popt['da'] = $fontstyle;
13046		// build appearance stream
13047		$popt['ap'] = array();
13048		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
13049		$text = '';
13050		foreach($values as $item) {
13051			if (is_array($item)) {
13052				$text .= $item[1]."\n";
13053			} else {
13054				$text .= $item."\n";
13055			}
13056		}
13057		$tmpid = $this->startTemplate($w, $h, false);
13058		$this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
13059		$this->endTemplate();
13060		--$this->n;
13061		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
13062		unset($this->xobjects[$tmpid]);
13063		$popt['ap']['n'] .= 'Q EMC';
13064		// merge options
13065		$opt = array_merge($popt, $opt);
13066		// set remaining annotation data
13067		$opt['Subtype'] = 'Widget';
13068		$opt['ft'] = 'Ch';
13069		$opt['t'] = $name;
13070		$opt['opt'] = $values;
13071		unset($opt['mk']['ca']);
13072		unset($opt['mk']['rc']);
13073		unset($opt['mk']['ac']);
13074		unset($opt['mk']['i']);
13075		unset($opt['mk']['ri']);
13076		unset($opt['mk']['ix']);
13077		unset($opt['mk']['if']);
13078		unset($opt['mk']['tp']);
13079		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
13080		if ($this->rtl) {
13081			$this->x -= $w;
13082		} else {
13083			$this->x += $w;
13084		}
13085	}
13086
13087	/**
13088	 * Creates a CheckBox field
13089	 * @param $name (string) field name
13090	 * @param $w (int) width
13091	 * @param $checked (boolean) define the initial state.
13092	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13093	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
13094	 * @param $onvalue (string) value to be returned if selected.
13095	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
13096	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
13097	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13098	 * @public
13099	 * @author Nicola Asuni
13100	 * @since 4.8.000 (2009-09-07)
13101	 */
13102	public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
13103		if ($x === '') {
13104			$x = $this->x;
13105		}
13106		if ($y === '') {
13107			$y = $this->y;
13108		}
13109		// check page for no-write regions and adapt page margins if necessary
13110		list($x, $y) = $this->checkPageRegions($w, $x, $y);
13111		if ($js) {
13112			$this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
13113			return;
13114		}
13115		if (!isset($prop['value'])) {
13116			$prop['value'] = array('Yes');
13117		}
13118		// get default style
13119		$prop = array_merge($this->getFormDefaultProp(), $prop);
13120		$prop['borderStyle'] = 'inset';
13121		// get annotation data
13122		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
13123		// set additional default options
13124		$font = 'zapfdingbats';
13125		if ($this->pdfa_mode) {
13126			// all fonts must be embedded
13127			$font = 'pdfa'.$font;
13128		}
13129		$this->AddFont($font);
13130		$tmpfont = $this->getFontBuffer($font);
13131		$this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
13132		$fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
13133		$popt['da'] = $fontstyle;
13134		// build appearance stream
13135		$popt['ap'] = array();
13136		$popt['ap']['n'] = array();
13137		$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][110])) / 2) * $this->k);
13138		$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
13139		$popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(110).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
13140		$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(111).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
13141		// merge options
13142		$opt = array_merge($popt, $opt);
13143		// set remaining annotation data
13144		$opt['Subtype'] = 'Widget';
13145		$opt['ft'] = 'Btn';
13146		$opt['t'] = $name;
13147		if (TCPDF_STATIC::empty_string($onvalue)) {
13148			$onvalue = 'Yes';
13149		}
13150		$opt['opt'] = array($onvalue);
13151		if ($checked) {
13152			$opt['v'] = array('/Yes');
13153			$opt['as'] = 'Yes';
13154		} else {
13155			$opt['v'] = array('/Off');
13156			$opt['as'] = 'Off';
13157		}
13158		$this->Annotation($x, $y, $w, $w, $name, $opt, 0);
13159		if ($this->rtl) {
13160			$this->x -= $w;
13161		} else {
13162			$this->x += $w;
13163		}
13164	}
13165
13166	/**
13167	 * Creates a button field
13168	 * @param $name (string) field name
13169	 * @param $w (int) width
13170	 * @param $h (int) height
13171	 * @param $caption (string) caption.
13172	 * @param $action (mixed) action triggered by pressing the button. Use a string to specify a javascript action. Use an array to specify a form action options as on section 12.7.5 of PDF32000_2008.
13173	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13174	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
13175	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
13176	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
13177	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13178	 * @public
13179	 * @author Nicola Asuni
13180	 * @since 4.8.000 (2009-09-07)
13181	 */
13182	public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
13183		if ($x === '') {
13184			$x = $this->x;
13185		}
13186		if ($y === '') {
13187			$y = $this->y;
13188		}
13189		// check page for no-write regions and adapt page margins if necessary
13190		list($x, $y) = $this->checkPageRegions($h, $x, $y);
13191		if ($js) {
13192			$this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
13193			$this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
13194			$this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
13195			$this->javascript .= 'f'.$name.".highlight='push';\n";
13196			$this->javascript .= 'f'.$name.".print=false;\n";
13197			return;
13198		}
13199		// get default style
13200		$prop = array_merge($this->getFormDefaultProp(), $prop);
13201		$prop['Pushbutton'] = 'true';
13202		$prop['highlight'] = 'push';
13203		$prop['display'] = 'display.noPrint';
13204		// get annotation data
13205		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
13206		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
13207		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
13208		$popt['da'] = $fontstyle;
13209		// build appearance stream
13210		$popt['ap'] = array();
13211		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
13212		$tmpid = $this->startTemplate($w, $h, false);
13213		$bw = (2 / $this->k); // border width
13214		$border = array(
13215			'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
13216			'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
13217			'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
13218			'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
13219		$this->SetFillColor(204);
13220		$this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
13221		$this->endTemplate();
13222		--$this->n;
13223		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
13224		unset($this->xobjects[$tmpid]);
13225		$popt['ap']['n'] .= 'Q EMC';
13226		// set additional default options
13227		if (!isset($popt['mk'])) {
13228			$popt['mk'] = array();
13229		}
13230		$ann_obj_id = ($this->n + 1);
13231		if (!empty($action) AND !is_array($action)) {
13232			$ann_obj_id = ($this->n + 2);
13233		}
13234		$popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
13235		$popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
13236		$popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
13237		// merge options
13238		$opt = array_merge($popt, $opt);
13239		// set remaining annotation data
13240		$opt['Subtype'] = 'Widget';
13241		$opt['ft'] = 'Btn';
13242		$opt['t'] = $caption;
13243		$opt['v'] = $name;
13244		if (!empty($action)) {
13245			if (is_array($action)) {
13246				// form action options as on section 12.7.5 of PDF32000_2008.
13247				$opt['aa'] = '/D <<';
13248				$bmode = array('SubmitForm', 'ResetForm', 'ImportData');
13249				foreach ($action AS $key => $val) {
13250					if (($key == 'S') AND in_array($val, $bmode)) {
13251						$opt['aa'] .= ' /S /'.$val;
13252					} elseif (($key == 'F') AND (!empty($val))) {
13253						$opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
13254					} elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
13255						$opt['aa'] .= ' /Fields [';
13256						foreach ($val AS $field) {
13257							$opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
13258						}
13259						$opt['aa'] .= ']';
13260					} elseif (($key == 'Flags')) {
13261						$ff = 0;
13262						if (is_array($val)) {
13263							foreach ($val AS $flag) {
13264								switch ($flag) {
13265									case 'Include/Exclude': {
13266										$ff += 1 << 0;
13267										break;
13268									}
13269									case 'IncludeNoValueFields': {
13270										$ff += 1 << 1;
13271										break;
13272									}
13273									case 'ExportFormat': {
13274										$ff += 1 << 2;
13275										break;
13276									}
13277									case 'GetMethod': {
13278										$ff += 1 << 3;
13279										break;
13280									}
13281									case 'SubmitCoordinates': {
13282										$ff += 1 << 4;
13283										break;
13284									}
13285									case 'XFDF': {
13286										$ff += 1 << 5;
13287										break;
13288									}
13289									case 'IncludeAppendSaves': {
13290										$ff += 1 << 6;
13291										break;
13292									}
13293									case 'IncludeAnnotations': {
13294										$ff += 1 << 7;
13295										break;
13296									}
13297									case 'SubmitPDF': {
13298										$ff += 1 << 8;
13299										break;
13300									}
13301									case 'CanonicalFormat': {
13302										$ff += 1 << 9;
13303										break;
13304									}
13305									case 'ExclNonUserAnnots': {
13306										$ff += 1 << 10;
13307										break;
13308									}
13309									case 'ExclFKey': {
13310										$ff += 1 << 11;
13311										break;
13312									}
13313									case 'EmbedForm': {
13314										$ff += 1 << 13;
13315										break;
13316									}
13317								}
13318							}
13319						} else {
13320							$ff = intval($val);
13321						}
13322						$opt['aa'] .= ' /Flags '.$ff;
13323					}
13324				}
13325				$opt['aa'] .= ' >>';
13326			} else {
13327				// Javascript action or raw action command
13328				$js_obj_id = $this->addJavascriptObject($action);
13329				$opt['aa'] = '/D '.$js_obj_id.' 0 R';
13330			}
13331		}
13332		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
13333		if ($this->rtl) {
13334			$this->x -= $w;
13335		} else {
13336			$this->x += $w;
13337		}
13338	}
13339
13340	// --- END FORMS FIELDS ------------------------------------------------
13341
13342	/**
13343	 * Add certification signature (DocMDP or UR3)
13344	 * You can set only one signature type
13345	 * @protected
13346	 * @author Nicola Asuni
13347	 * @since 4.6.008 (2009-05-07)
13348	 */
13349	protected function _putsignature() {
13350		if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
13351			return;
13352		}
13353		$sigobjid = ($this->sig_obj_id + 1);
13354		$out = $this->_getobj($sigobjid)."\n";
13355		$out .= '<< /Type /Sig';
13356		$out .= ' /Filter /Adobe.PPKLite';
13357		$out .= ' /SubFilter /adbe.pkcs7.detached';
13358		$out .= ' '.TCPDF_STATIC::$byterange_string;
13359		$out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
13360		if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
13361			$out .= ' /Reference ['; // array of signature reference dictionaries
13362			$out .= ' << /Type /SigRef';
13363			if ($this->signature_data['cert_type'] > 0) {
13364				$out .= ' /TransformMethod /DocMDP';
13365				$out .= ' /TransformParams <<';
13366				$out .= ' /Type /TransformParams';
13367				$out .= ' /P '.$this->signature_data['cert_type'];
13368				$out .= ' /V /1.2';
13369			} else {
13370				$out .= ' /TransformMethod /UR3';
13371				$out .= ' /TransformParams <<';
13372				$out .= ' /Type /TransformParams';
13373				$out .= ' /V /2.2';
13374				if (!TCPDF_STATIC::empty_string($this->ur['document'])) {
13375					$out .= ' /Document['.$this->ur['document'].']';
13376				}
13377				if (!TCPDF_STATIC::empty_string($this->ur['form'])) {
13378					$out .= ' /Form['.$this->ur['form'].']';
13379				}
13380				if (!TCPDF_STATIC::empty_string($this->ur['signature'])) {
13381					$out .= ' /Signature['.$this->ur['signature'].']';
13382				}
13383				if (!TCPDF_STATIC::empty_string($this->ur['annots'])) {
13384					$out .= ' /Annots['.$this->ur['annots'].']';
13385				}
13386				if (!TCPDF_STATIC::empty_string($this->ur['ef'])) {
13387					$out .= ' /EF['.$this->ur['ef'].']';
13388				}
13389				if (!TCPDF_STATIC::empty_string($this->ur['formex'])) {
13390					$out .= ' /FormEX['.$this->ur['formex'].']';
13391				}
13392			}
13393			$out .= ' >>'; // close TransformParams
13394			// optional digest data (values must be calculated and replaced later)
13395			//$out .= ' /Data ********** 0 R';
13396			//$out .= ' /DigestMethod/MD5';
13397			//$out .= ' /DigestLocation[********** 34]';
13398			//$out .= ' /DigestValue<********************************>';
13399			$out .= ' >>';
13400			$out .= ' ]'; // end of reference
13401		}
13402		if (isset($this->signature_data['info']['Name']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Name'])) {
13403			$out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
13404		}
13405		if (isset($this->signature_data['info']['Location']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Location'])) {
13406			$out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
13407		}
13408		if (isset($this->signature_data['info']['Reason']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Reason'])) {
13409			$out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
13410		}
13411		if (isset($this->signature_data['info']['ContactInfo']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['ContactInfo'])) {
13412			$out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
13413		}
13414		$out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp);
13415		$out .= ' >>';
13416		$out .= "\n".'endobj';
13417		$this->_out($out);
13418	}
13419
13420	/**
13421	 * Set User's Rights for PDF Reader
13422	 * WARNING: This is experimental and currently do not work.
13423	 * Check the PDF Reference 8.7.1 Transform Methods,
13424	 * Table 8.105 Entries in the UR transform parameters dictionary
13425	 * @param $enable (boolean) if true enable user's rights on PDF reader
13426	 * @param $document (string) 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.
13427	 * @param $annots (string) 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.
13428	 * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
13429	 * @param $signature (string) 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.
13430	 * @param $ef (string) Names specifying additional usage rights for named embedded files in the document. Valid names are /Create/Delete/Modify/Import, which permit the user to perform the named operation on named embedded files
13431	 Names specifying additional embedded-files-related usage rights for the document.
13432	 * @param $formex (string) Names specifying additional form-field-related usage rights. The only valid name is BarcodePlaintext, which permits text form field data to be encoded as a plaintext two-dimensional barcode.
13433	 * @public
13434	 * @author Nicola Asuni
13435	 * @since 2.9.000 (2008-03-26)
13436	 */
13437	public function setUserRights(
13438			$enable=true,
13439			$document='/FullSave',
13440			$annots='/Create/Delete/Modify/Copy/Import/Export',
13441			$form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
13442			$signature='/Modify',
13443			$ef='/Create/Delete/Modify/Import',
13444			$formex='') {
13445		$this->ur['enabled'] = $enable;
13446		$this->ur['document'] = $document;
13447		$this->ur['annots'] = $annots;
13448		$this->ur['form'] = $form;
13449		$this->ur['signature'] = $signature;
13450		$this->ur['ef'] = $ef;
13451		$this->ur['formex'] = $formex;
13452		if (!$this->sign) {
13453			$this->setSignature('', '', '', '', 0, array());
13454		}
13455	}
13456
13457	/**
13458	 * Enable document signature (requires the OpenSSL Library).
13459	 * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
13460	 * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
13461	 * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
13462	 * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
13463	 * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
13464	 * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
13465	 * @param $private_key_password (string) password
13466	 * @param $extracerts (string) specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.
13467	 * @param $cert_type (int) The access permissions granted for this document. Valid values shall be: 1 = No changes to the document shall be permitted; any change to the document shall invalidate the signature; 2 = Permitted changes shall be filling in forms, instantiating page templates, and signing; other changes shall invalidate the signature; 3 = Permitted changes shall be the same as for 2, as well as annotation creation, deletion, and modification; other changes shall invalidate the signature.
13468	 * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
13469	 * @param $approval (string) Enable approval signature eg. for PDF incremental update
13470	 * @public
13471	 * @author Nicola Asuni
13472	 * @since 4.6.005 (2009-04-24)
13473	 */
13474	public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array(), $approval='') {
13475		// to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
13476		// to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
13477		// to convert pfx certificate to pem: openssl
13478		//     OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
13479		$this->sign = true;
13480		++$this->n;
13481		$this->sig_obj_id = $this->n; // signature widget
13482		++$this->n; // signature object ($this->sig_obj_id + 1)
13483		$this->signature_data = array();
13484		if (strlen($signing_cert) == 0) {
13485			$this->Error('Please provide a certificate file and password!');
13486		}
13487		if (strlen($private_key) == 0) {
13488			$private_key = $signing_cert;
13489		}
13490		$this->signature_data['signcert'] = $signing_cert;
13491		$this->signature_data['privkey'] = $private_key;
13492		$this->signature_data['password'] = $private_key_password;
13493		$this->signature_data['extracerts'] = $extracerts;
13494		$this->signature_data['cert_type'] = $cert_type;
13495		$this->signature_data['info'] = $info;
13496		$this->signature_data['approval'] = $approval;
13497	}
13498
13499	/**
13500	 * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
13501	 * @param $x (float) Abscissa of the upper-left corner.
13502	 * @param $y (float) Ordinate of the upper-left corner.
13503	 * @param $w (float) Width of the signature area.
13504	 * @param $h (float) Height of the signature area.
13505	 * @param $page (int) option page number (if < 0 the current page is used).
13506	 * @param $name (string) Name of the signature.
13507	 * @public
13508	 * @author Nicola Asuni
13509	 * @since 5.3.011 (2010-06-17)
13510	 */
13511	public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13512		$this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
13513	}
13514
13515	/**
13516	 * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
13517	 * @param $x (float) Abscissa of the upper-left corner.
13518	 * @param $y (float) Ordinate of the upper-left corner.
13519	 * @param $w (float) Width of the signature area.
13520	 * @param $h (float) Height of the signature area.
13521	 * @param $page (int) option page number (if < 0 the current page is used).
13522	 * @param $name (string) Name of the signature.
13523	 * @public
13524	 * @author Nicola Asuni
13525	 * @since 5.9.101 (2011-07-06)
13526	 */
13527	public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13528		++$this->n;
13529		$this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
13530	}
13531
13532	/**
13533	 * Get the array that defines the signature appearance (page and rectangle coordinates).
13534	 * @param $x (float) Abscissa of the upper-left corner.
13535	 * @param $y (float) Ordinate of the upper-left corner.
13536	 * @param $w (float) Width of the signature area.
13537	 * @param $h (float) Height of the signature area.
13538	 * @param $page (int) option page number (if < 0 the current page is used).
13539	 * @param $name (string) Name of the signature.
13540	 * @return (array) Array defining page and rectangle coordinates of signature appearance.
13541	 * @protected
13542	 * @author Nicola Asuni
13543	 * @since 5.9.101 (2011-07-06)
13544	 */
13545	protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13546		$sigapp = array();
13547		if (($page < 1) OR ($page > $this->numpages)) {
13548			$sigapp['page'] = $this->page;
13549		} else {
13550			$sigapp['page'] = intval($page);
13551		}
13552		if (empty($name)) {
13553			$sigapp['name'] = 'Signature';
13554		} else {
13555			$sigapp['name'] = $name;
13556		}
13557		$a = $x * $this->k;
13558		$b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
13559		$c = $w * $this->k;
13560		$d = $h * $this->k;
13561		$sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a + $c), ($b + $d));
13562		return $sigapp;
13563	}
13564
13565	/**
13566	 * Enable document timestamping (requires the OpenSSL Library).
13567	 * The trusted timestamping improve document security that means that no one should be able to change the document once it has been recorded.
13568	 * Use with digital signature only!
13569	 * @param $tsa_host (string) Time Stamping Authority (TSA) server (prefixed with 'https://')
13570	 * @param $tsa_username (string) Specifies the username for TSA authorization (optional) OR specifies the TSA authorization PEM file (see: example_66.php, optional)
13571	 * @param $tsa_password (string) Specifies the password for TSA authorization (optional)
13572	 * @param $tsa_cert (string) Specifies the location of TSA certificate for authorization (optional for cURL)
13573	 * @public
13574	 * @author Richard Stockinger
13575	 * @since 6.0.090 (2014-06-16)
13576	 */
13577	public function setTimeStamp($tsa_host='', $tsa_username='', $tsa_password='', $tsa_cert='') {
13578		$this->tsa_data = array();
13579		if (!function_exists('curl_init')) {
13580			$this->Error('Please enable cURL PHP extension!');
13581		}
13582		if (strlen($tsa_host) == 0) {
13583			$this->Error('Please specify the host of Time Stamping Authority (TSA)!');
13584		}
13585		$this->tsa_data['tsa_host'] = $tsa_host;
13586		if (is_file($tsa_username)) {
13587			$this->tsa_data['tsa_auth'] = $tsa_username;
13588		} else {
13589			$this->tsa_data['tsa_username'] = $tsa_username;
13590		}
13591		$this->tsa_data['tsa_password'] = $tsa_password;
13592		$this->tsa_data['tsa_cert'] = $tsa_cert;
13593		$this->tsa_timestamp = true;
13594	}
13595
13596	/**
13597	 * NOT YET IMPLEMENTED
13598	 * Request TSA for a timestamp
13599	 * @param $signature (string) Digital signature as binary string
13600	 * @return (string) Timestamped digital signature
13601	 * @protected
13602	 * @author Richard Stockinger
13603	 * @since 6.0.090 (2014-06-16)
13604	 */
13605	protected function applyTSA($signature) {
13606		if (!$this->tsa_timestamp) {
13607			return $signature;
13608		}
13609		//@TODO: implement this feature
13610		return $signature;
13611	}
13612
13613	/**
13614	 * Create a new page group.
13615	 * NOTE: call this function before calling AddPage()
13616	 * @param $page (int) starting group page (leave empty for next page).
13617	 * @public
13618	 * @since 3.0.000 (2008-03-27)
13619	 */
13620	public function startPageGroup($page='') {
13621		if (empty($page)) {
13622			$page = $this->page + 1;
13623		}
13624		$this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
13625	}
13626
13627	/**
13628	 * Set the starting page number.
13629	 * @param $num (int) Starting page number.
13630	 * @since 5.9.093 (2011-06-16)
13631	 * @public
13632	 */
13633	public function setStartingPageNumber($num=1) {
13634		$this->starting_page_number = max(0, intval($num));
13635	}
13636
13637	/**
13638	 * Returns the string alias used right align page numbers.
13639	 * If the current font is unicode type, the returned string wil contain an additional open curly brace.
13640	 * @return string
13641	 * @since 5.9.099 (2011-06-27)
13642	 * @public
13643	 */
13644	public function getAliasRightShift() {
13645		// calculate aproximatively the ratio between widths of aliases and replacements.
13646		$ref = '{'.TCPDF_STATIC::$alias_right_shift.'}{'.TCPDF_STATIC::$alias_tot_pages.'}{'.TCPDF_STATIC::$alias_num_page.'}';
13647		$rep = str_repeat(' ', $this->GetNumChars($ref));
13648		$wrep = $this->GetStringWidth($rep);
13649		if ($wrep > 0) {
13650			$wdiff = max(1, ($this->GetStringWidth($ref) / $wrep));
13651		} else {
13652			$wdiff = 1;
13653		}
13654		$sdiff = sprintf('%F', $wdiff);
13655		$alias = TCPDF_STATIC::$alias_right_shift.$sdiff.'}';
13656		if ($this->isUnicodeFont()) {
13657			$alias = '{'.$alias;
13658		}
13659		return $alias;
13660	}
13661
13662	/**
13663	 * Returns the string alias used for the total number of pages.
13664	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13665	 * This alias will be replaced by the total number of pages in the document.
13666	 * @return string
13667	 * @since 4.0.018 (2008-08-08)
13668	 * @public
13669	 */
13670	public function getAliasNbPages() {
13671		if ($this->isUnicodeFont()) {
13672			return '{'.TCPDF_STATIC::$alias_tot_pages.'}';
13673		}
13674		return TCPDF_STATIC::$alias_tot_pages;
13675	}
13676
13677	/**
13678	 * Returns the string alias used for the page number.
13679	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13680	 * This alias will be replaced by the page number.
13681	 * @return string
13682	 * @since 4.5.000 (2009-01-02)
13683	 * @public
13684	 */
13685	public function getAliasNumPage() {
13686		if ($this->isUnicodeFont()) {
13687			return '{'.TCPDF_STATIC::$alias_num_page.'}';
13688		}
13689		return TCPDF_STATIC::$alias_num_page;
13690	}
13691
13692	/**
13693	 * Return the alias for the total number of pages in the current page group.
13694	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13695	 * This alias will be replaced by the total number of pages in this group.
13696	 * @return alias of the current page group
13697	 * @public
13698	 * @since 3.0.000 (2008-03-27)
13699	 */
13700	public function getPageGroupAlias() {
13701		if ($this->isUnicodeFont()) {
13702			return '{'.TCPDF_STATIC::$alias_group_tot_pages.'}';
13703		}
13704		return TCPDF_STATIC::$alias_group_tot_pages;
13705	}
13706
13707	/**
13708	 * Return the alias for the page number on the current page group.
13709	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13710	 * This alias will be replaced by the page number (relative to the belonging group).
13711	 * @return alias of the current page group
13712	 * @public
13713	 * @since 4.5.000 (2009-01-02)
13714	 */
13715	public function getPageNumGroupAlias() {
13716		if ($this->isUnicodeFont()) {
13717			return '{'.TCPDF_STATIC::$alias_group_num_page.'}';
13718		}
13719		return TCPDF_STATIC::$alias_group_num_page;
13720	}
13721
13722	/**
13723	 * Return the current page in the group.
13724	 * @return current page in the group
13725	 * @public
13726	 * @since 3.0.000 (2008-03-27)
13727	 */
13728	public function getGroupPageNo() {
13729		return $this->pagegroups[$this->currpagegroup];
13730	}
13731
13732	/**
13733	 * Returns the current group page number formatted as a string.
13734	 * @public
13735	 * @since 4.3.003 (2008-11-18)
13736	 * @see PaneNo(), formatPageNumber()
13737	 */
13738	public function getGroupPageNoFormatted() {
13739		return TCPDF_STATIC::formatPageNumber($this->getGroupPageNo());
13740	}
13741
13742	/**
13743	 * Returns the current page number formatted as a string.
13744	 * @public
13745	 * @since 4.2.005 (2008-11-06)
13746	 * @see PaneNo(), formatPageNumber()
13747	 */
13748	public function PageNoFormatted() {
13749		return TCPDF_STATIC::formatPageNumber($this->PageNo());
13750	}
13751
13752	/**
13753	 * Put pdf layers.
13754	 * @protected
13755	 * @since 3.0.000 (2008-03-27)
13756	 */
13757	protected function _putocg() {
13758		if (empty($this->pdflayers)) {
13759			return;
13760		}
13761		foreach ($this->pdflayers as $key => $layer) {
13762			 $this->pdflayers[$key]['objid'] = $this->_newobj();
13763			 $out = '<< /Type /OCG';
13764			 $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
13765			 $out .= ' /Usage <<';
13766			 if (isset($layer['print']) AND ($layer['print'] !== NULL)) {
13767				$out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
13768			 }
13769			 $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
13770			 $out .= ' >> >>';
13771			 $out .= "\n".'endobj';
13772			 $this->_out($out);
13773		}
13774	}
13775
13776	/**
13777	 * Start a new pdf layer.
13778	 * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
13779	 * @param $print (boolean|null) Set to TRUE to print this layer, FALSE to not print and NULL to not set this option
13780	 * @param $view (boolean) Set to true to view this layer.
13781	 * @param $lock (boolean) If true lock the layer
13782	 * @public
13783	 * @since 5.9.102 (2011-07-13)
13784	 */
13785	public function startLayer($name='', $print=true, $view=true, $lock=true) {
13786		if ($this->state != 2) {
13787			return;
13788		}
13789		$layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
13790		if (empty($name)) {
13791			$name = $layer;
13792		} else {
13793			$name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
13794		}
13795		$this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view, 'lock' => $lock);
13796		$this->openMarkedContent = true;
13797		$this->_out('/OC /'.$layer.' BDC');
13798	}
13799
13800	/**
13801	 * End the current PDF layer.
13802	 * @public
13803	 * @since 5.9.102 (2011-07-13)
13804	 */
13805	public function endLayer() {
13806		if ($this->state != 2) {
13807			return;
13808		}
13809		if ($this->openMarkedContent) {
13810			// close existing open marked-content layer
13811			$this->_out('EMC');
13812			$this->openMarkedContent = false;
13813		}
13814	}
13815
13816	/**
13817	 * Set the visibility of the successive elements.
13818	 * This can be useful, for instance, to put a background
13819	 * image or color that will show on screen but won't print.
13820	 * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
13821	 * @public
13822	 * @since 3.0.000 (2008-03-27)
13823	 */
13824	public function setVisibility($v) {
13825		if ($this->state != 2) {
13826			return;
13827		}
13828		$this->endLayer();
13829		switch($v) {
13830			case 'print': {
13831				$this->startLayer('Print', true, false);
13832				break;
13833			}
13834			case 'view':
13835			case 'screen': {
13836				$this->startLayer('View', false, true);
13837				break;
13838			}
13839			case 'all': {
13840				$this->_out('');
13841				break;
13842			}
13843			default: {
13844				$this->Error('Incorrect visibility: '.$v);
13845				break;
13846			}
13847		}
13848	}
13849
13850	/**
13851	 * Add transparency parameters to the current extgstate
13852	 * @param $parms (array) parameters
13853	 * @return the number of extgstates
13854	 * @protected
13855	 * @since 3.0.000 (2008-03-27)
13856	 */
13857	protected function addExtGState($parms) {
13858		if ($this->pdfa_mode) {
13859			// transparencies are not allowed in PDF/A mode
13860			return;
13861		}
13862		// check if this ExtGState already exist
13863		foreach ($this->extgstates as $i => $ext) {
13864			if ($ext['parms'] == $parms) {
13865				if ($this->inxobj) {
13866					// we are inside an XObject template
13867					$this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
13868				}
13869				// return reference to existing ExtGState
13870				return $i;
13871			}
13872		}
13873		$n = (count($this->extgstates) + 1);
13874		$this->extgstates[$n] = array('parms' => $parms);
13875		if ($this->inxobj) {
13876			// we are inside an XObject template
13877			$this->xobjects[$this->xobjid]['extgstates'][$n] = $this->extgstates[$n];
13878		}
13879		return $n;
13880	}
13881
13882	/**
13883	 * Add an extgstate
13884	 * @param $gs (array) extgstate
13885	 * @protected
13886	 * @since 3.0.000 (2008-03-27)
13887	 */
13888	protected function setExtGState($gs) {
13889		if ($this->pdfa_mode OR ($this->state != 2)) {
13890			// transparency is not allowed in PDF/A mode
13891			return;
13892		}
13893		$this->_out(sprintf('/GS%d gs', $gs));
13894	}
13895
13896	/**
13897	 * Put extgstates for object transparency
13898	 * @protected
13899	 * @since 3.0.000 (2008-03-27)
13900	 */
13901	protected function _putextgstates() {
13902		foreach ($this->extgstates as $i => $ext) {
13903			$this->extgstates[$i]['n'] = $this->_newobj();
13904			$out = '<< /Type /ExtGState';
13905			foreach ($ext['parms'] as $k => $v) {
13906				if (is_float($v)) {
13907					$v = sprintf('%F', $v);
13908				} elseif ($v === true) {
13909					$v = 'true';
13910				} elseif ($v === false) {
13911					$v = 'false';
13912				}
13913				$out .= ' /'.$k.' '.$v;
13914			}
13915			$out .= ' >>';
13916			$out .= "\n".'endobj';
13917			$this->_out($out);
13918		}
13919	}
13920
13921	/**
13922	 * Set overprint mode for stroking (OP) and non-stroking (op) painting operations.
13923	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13924	 * @param $stroking (boolean) If true apply overprint for stroking operations.
13925	 * @param $nonstroking (boolean) If true apply overprint for painting operations other than stroking.
13926	 * @param $mode (integer) Overprint mode: (0 = each source colour component value replaces the value previously painted for the corresponding device colorant; 1 = a tint value of 0.0 for a source colour component shall leave the corresponding component of the previously painted colour unchanged).
13927	 * @public
13928	 * @since 5.9.152 (2012-03-23)
13929	 */
13930	public function setOverprint($stroking=true, $nonstroking='', $mode=0) {
13931		if ($this->state != 2) {
13932			return;
13933		}
13934		$stroking = $stroking ? true : false;
13935		if (TCPDF_STATIC::empty_string($nonstroking)) {
13936			// default value if not set
13937			$nonstroking = $stroking;
13938		} else {
13939			$nonstroking = $nonstroking ? true : false;
13940		}
13941		if (($mode != 0) AND ($mode != 1)) {
13942			$mode = 0;
13943		}
13944		$this->overprint = array('OP' => $stroking, 'op' => $nonstroking, 'OPM' => $mode);
13945		$gs = $this->addExtGState($this->overprint);
13946		$this->setExtGState($gs);
13947	}
13948
13949	/**
13950	 * Get the overprint mode array (OP, op, OPM).
13951	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13952	 * @return array.
13953	 * @public
13954	 * @since 5.9.152 (2012-03-23)
13955	 */
13956	public function getOverprint() {
13957		return $this->overprint;
13958	}
13959
13960	/**
13961	 * Set alpha for stroking (CA) and non-stroking (ca) operations.
13962	 * @param $stroking (float) Alpha value for stroking operations: real value from 0 (transparent) to 1 (opaque).
13963	 * @param $bm (string) blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
13964	 * @param $nonstroking (float) Alpha value for non-stroking operations: real value from 0 (transparent) to 1 (opaque).
13965	 * @param $ais (boolean)
13966	 * @public
13967	 * @since 3.0.000 (2008-03-27)
13968	 */
13969	public function setAlpha($stroking=1, $bm='Normal', $nonstroking='', $ais=false) {
13970		if ($this->pdfa_mode) {
13971			// transparency is not allowed in PDF/A mode
13972			return;
13973		}
13974		$stroking = floatval($stroking);
13975		if (TCPDF_STATIC::empty_string($nonstroking)) {
13976			// default value if not set
13977			$nonstroking = $stroking;
13978		} else {
13979			$nonstroking = floatval($nonstroking);
13980		}
13981		if ($bm[0] == '/') {
13982			// remove trailing slash
13983			$bm = substr($bm, 1);
13984		}
13985		if (!in_array($bm, array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
13986			$bm = 'Normal';
13987		}
13988		$ais = $ais ? true : false;
13989		$this->alpha = array('CA' => $stroking, 'ca' => $nonstroking, 'BM' => '/'.$bm, 'AIS' => $ais);
13990		$gs = $this->addExtGState($this->alpha);
13991		$this->setExtGState($gs);
13992	}
13993
13994	/**
13995	 * Get the alpha mode array (CA, ca, BM, AIS).
13996	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13997	 * @return array.
13998	 * @public
13999	 * @since 5.9.152 (2012-03-23)
14000	 */
14001	public function getAlpha() {
14002		return $this->alpha;
14003	}
14004
14005	/**
14006	 * Set the default JPEG compression quality (1-100)
14007	 * @param $quality (int) JPEG quality, integer between 1 and 100
14008	 * @public
14009	 * @since 3.0.000 (2008-03-27)
14010	 */
14011	public function setJPEGQuality($quality) {
14012		if (($quality < 1) OR ($quality > 100)) {
14013			$quality = 75;
14014		}
14015		$this->jpeg_quality = intval($quality);
14016	}
14017
14018	/**
14019	 * Set the default number of columns in a row for HTML tables.
14020	 * @param $cols (int) number of columns
14021	 * @public
14022	 * @since 3.0.014 (2008-06-04)
14023	 */
14024	public function setDefaultTableColumns($cols=4) {
14025		$this->default_table_columns = intval($cols);
14026	}
14027
14028	/**
14029	 * Set the height of the cell (line height) respect the font height.
14030	 * @param $h (int) cell proportion respect font height (typical value = 1.25).
14031	 * @public
14032	 * @since 3.0.014 (2008-06-04)
14033	 */
14034	public function setCellHeightRatio($h) {
14035		$this->cell_height_ratio = $h;
14036	}
14037
14038	/**
14039	 * return the height of cell repect font height.
14040	 * @public
14041	 * @since 4.0.012 (2008-07-24)
14042	 */
14043	public function getCellHeightRatio() {
14044		return $this->cell_height_ratio;
14045	}
14046
14047	/**
14048	 * Set the PDF version (check PDF reference for valid values).
14049	 * @param $version (string) PDF document version.
14050	 * @public
14051	 * @since 3.1.000 (2008-06-09)
14052	 */
14053	public function setPDFVersion($version='1.7') {
14054		if ($this->pdfa_mode && $this->pdfa_version == 1 ) {
14055			// PDF/A mode
14056			$this->PDFVersion = '1.4';
14057		} else {
14058			$this->PDFVersion = $version;
14059		}
14060	}
14061
14062	/**
14063	 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
14064	 * (see Section 8.1 of PDF reference, "Viewer Preferences").
14065	 * <ul><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><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><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><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><li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li><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><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><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><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><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><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><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><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><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><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><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></ul>
14066	 * @param $preferences (array) array of options.
14067	 * @author Nicola Asuni
14068	 * @public
14069	 * @since 3.1.000 (2008-06-09)
14070	 */
14071	public function setViewerPreferences($preferences) {
14072		$this->viewer_preferences = $preferences;
14073	}
14074
14075	/**
14076	 * Paints color transition registration bars
14077	 * @param $x (float) abscissa of the top left corner of the rectangle.
14078	 * @param $y (float) ordinate of the top left corner of the rectangle.
14079	 * @param $w (float) width of the rectangle.
14080	 * @param $h (float) height of the rectangle.
14081	 * @param $transition (boolean) if true prints tcolor transitions to white.
14082	 * @param $vertical (boolean) if true prints bar vertically.
14083	 * @param $colors (string) colors to print separated by comma. Valid values are: A,W,R,G,B,C,M,Y,K,RGB,CMYK,ALL,ALLSPOT,<SPOT_COLOR_NAME>. Where: A = grayscale black, W = grayscale white, R = RGB red, G RGB green, B RGB blue, C = CMYK cyan, M = CMYK magenta, Y = CMYK yellow, K = CMYK key/black, RGB = RGB registration color, CMYK = CMYK registration color, ALL = Spot registration color, ALLSPOT = print all defined spot colors, <SPOT_COLOR_NAME> = name of the spot color to print.
14084	 * @author Nicola Asuni
14085	 * @since 4.9.000 (2010-03-26)
14086	 * @public
14087	 */
14088	public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
14089		if (strpos($colors, 'ALLSPOT') !== false) {
14090			// expand spot colors
14091			$spot_colors = '';
14092			foreach ($this->spot_colors as $spot_color_name => $v) {
14093				$spot_colors .= ','.$spot_color_name;
14094			}
14095			if (!empty($spot_colors)) {
14096				$spot_colors = substr($spot_colors, 1);
14097				$colors = str_replace('ALLSPOT', $spot_colors, $colors);
14098			} else {
14099				$colors = str_replace('ALLSPOT', 'NONE', $colors);
14100			}
14101		}
14102		$bars = explode(',', $colors);
14103		$numbars = count($bars); // number of bars to print
14104		if ($numbars <= 0) {
14105			return;
14106		}
14107		// set bar measures
14108		if ($vertical) {
14109			$coords = array(0, 0, 0, 1);
14110			$wb = $w / $numbars; // bar width
14111			$hb = $h; // bar height
14112			$xd = $wb; // delta x
14113			$yd = 0; // delta y
14114		} else {
14115			$coords = array(1, 0, 0, 0);
14116			$wb = $w; // bar width
14117			$hb = $h / $numbars; // bar height
14118			$xd = 0; // delta x
14119			$yd = $hb; // delta y
14120		}
14121		$xb = $x;
14122		$yb = $y;
14123		foreach ($bars as $col) {
14124			switch ($col) {
14125				// set transition colors
14126				case 'A': { // BLACK (GRAYSCALE)
14127					$col_a = array(255);
14128					$col_b = array(0);
14129					break;
14130				}
14131				case 'W': { // WHITE (GRAYSCALE)
14132					$col_a = array(0);
14133					$col_b = array(255);
14134					break;
14135				}
14136				case 'R': { // RED (RGB)
14137					$col_a = array(255,255,255);
14138					$col_b = array(255,0,0);
14139					break;
14140				}
14141				case 'G': { // GREEN (RGB)
14142					$col_a = array(255,255,255);
14143					$col_b = array(0,255,0);
14144					break;
14145				}
14146				case 'B': { // BLUE (RGB)
14147					$col_a = array(255,255,255);
14148					$col_b = array(0,0,255);
14149					break;
14150				}
14151				case 'C': { // CYAN (CMYK)
14152					$col_a = array(0,0,0,0);
14153					$col_b = array(100,0,0,0);
14154					break;
14155				}
14156				case 'M': { // MAGENTA (CMYK)
14157					$col_a = array(0,0,0,0);
14158					$col_b = array(0,100,0,0);
14159					break;
14160				}
14161				case 'Y': { // YELLOW (CMYK)
14162					$col_a = array(0,0,0,0);
14163					$col_b = array(0,0,100,0);
14164					break;
14165				}
14166				case 'K': { // KEY - BLACK (CMYK)
14167					$col_a = array(0,0,0,0);
14168					$col_b = array(0,0,0,100);
14169					break;
14170				}
14171				case 'RGB': { // BLACK REGISTRATION (RGB)
14172					$col_a = array(255,255,255);
14173					$col_b = array(0,0,0);
14174					break;
14175				}
14176				case 'CMYK': { // BLACK REGISTRATION (CMYK)
14177					$col_a = array(0,0,0,0);
14178					$col_b = array(100,100,100,100);
14179					break;
14180				}
14181				case 'ALL': { // SPOT COLOR REGISTRATION
14182					$col_a = array(0,0,0,0,'None');
14183					$col_b = array(100,100,100,100,'All');
14184					break;
14185				}
14186				case 'NONE': { // SKIP THIS COLOR
14187					$col_a = array(0,0,0,0,'None');
14188					$col_b = array(0,0,0,0,'None');
14189					break;
14190				}
14191				default: { // SPECIFIC SPOT COLOR NAME
14192					$col_a = array(0,0,0,0,'None');
14193					$col_b = TCPDF_COLORS::getSpotColor($col, $this->spot_colors);
14194					if ($col_b === false) {
14195						// in case of error defaults to the registration color
14196						$col_b = array(100,100,100,100,'All');
14197					}
14198					break;
14199				}
14200			}
14201			if ($col != 'NONE') {
14202				if ($transition) {
14203					// color gradient
14204					$this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
14205				} else {
14206					$this->SetFillColorArray($col_b);
14207					// colored rectangle
14208					$this->Rect($xb, $yb, $wb, $hb, 'F', array());
14209				}
14210				$xb += $xd;
14211				$yb += $yd;
14212			}
14213		}
14214	}
14215
14216	/**
14217	 * Paints crop marks.
14218	 * @param $x (float) abscissa of the crop mark center.
14219	 * @param $y (float) ordinate of the crop mark center.
14220	 * @param $w (float) width of the crop mark.
14221	 * @param $h (float) height of the crop mark.
14222	 * @param $type (string) type of crop mark, one symbol per type separated by comma: T = TOP, F = BOTTOM, L = LEFT, R = RIGHT, TL = A = TOP-LEFT, TR = B = TOP-RIGHT, BL = C = BOTTOM-LEFT, BR = D = BOTTOM-RIGHT.
14223	 * @param $color (array) crop mark color (default spot registration color).
14224	 * @author Nicola Asuni
14225	 * @since 4.9.000 (2010-03-26)
14226	 * @public
14227	 */
14228	public function cropMark($x, $y, $w, $h, $type='T,R,B,L', $color=array(100,100,100,100,'All')) {
14229		$this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
14230		$type = strtoupper($type);
14231		$type = preg_replace('/[^A-Z\-\,]*/', '', $type);
14232		// split type in single components
14233		$type = str_replace('-', ',', $type);
14234		$type = str_replace('TL', 'T,L', $type);
14235		$type = str_replace('TR', 'T,R', $type);
14236		$type = str_replace('BL', 'F,L', $type);
14237		$type = str_replace('BR', 'F,R', $type);
14238		$type = str_replace('A', 'T,L', $type);
14239		$type = str_replace('B', 'T,R', $type);
14240		$type = str_replace('T,RO', 'BO', $type);
14241		$type = str_replace('C', 'F,L', $type);
14242		$type = str_replace('D', 'F,R', $type);
14243		$crops = explode(',', strtoupper($type));
14244		// remove duplicates
14245		$crops = array_unique($crops);
14246		$dw = ($w / 4); // horizontal space to leave before the intersection point
14247		$dh = ($h / 4); // vertical space to leave before the intersection point
14248		foreach ($crops as $crop) {
14249			switch ($crop) {
14250				case 'T':
14251				case 'TOP': {
14252					$x1 = $x;
14253					$y1 = ($y - $h);
14254					$x2 = $x;
14255					$y2 = ($y - $dh);
14256					break;
14257				}
14258				case 'F':
14259				case 'BOTTOM': {
14260					$x1 = $x;
14261					$y1 = ($y + $dh);
14262					$x2 = $x;
14263					$y2 = ($y + $h);
14264					break;
14265				}
14266				case 'L':
14267				case 'LEFT': {
14268					$x1 = ($x - $w);
14269					$y1 = $y;
14270					$x2 = ($x - $dw);
14271					$y2 = $y;
14272					break;
14273				}
14274				case 'R':
14275				case 'RIGHT': {
14276					$x1 = ($x + $dw);
14277					$y1 = $y;
14278					$x2 = ($x + $w);
14279					$y2 = $y;
14280					break;
14281				}
14282			}
14283			$this->Line($x1, $y1, $x2, $y2);
14284		}
14285	}
14286
14287	/**
14288	 * Paints a registration mark
14289	 * @param $x (float) abscissa of the registration mark center.
14290	 * @param $y (float) ordinate of the registration mark center.
14291	 * @param $r (float) radius of the crop mark.
14292	 * @param $double (boolean) if true print two concentric crop marks.
14293	 * @param $cola (array) crop mark color (default spot registration color 'All').
14294	 * @param $colb (array) second crop mark color (default spot registration color 'None').
14295	 * @author Nicola Asuni
14296	 * @since 4.9.000 (2010-03-26)
14297	 * @public
14298	 */
14299	public function registrationMark($x, $y, $r, $double=false, $cola=array(100,100,100,100,'All'), $colb=array(0,0,0,0,'None')) {
14300		$line_style = array('width' => max((0.5 / $this->k),($r / 30)), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
14301		$this->SetFillColorArray($cola);
14302		$this->PieSector($x, $y, $r, 90, 180, 'F');
14303		$this->PieSector($x, $y, $r, 270, 360, 'F');
14304		$this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
14305		if ($double) {
14306			$ri = $r * 0.5;
14307			$this->SetFillColorArray($colb);
14308			$this->PieSector($x, $y, $ri, 90, 180, 'F');
14309			$this->PieSector($x, $y, $ri, 270, 360, 'F');
14310			$this->SetFillColorArray($cola);
14311			$this->PieSector($x, $y, $ri, 0, 90, 'F');
14312			$this->PieSector($x, $y, $ri, 180, 270, 'F');
14313			$this->Circle($x, $y, $ri, 0, 360, 'C', $line_style, array(), 8);
14314		}
14315	}
14316
14317	/**
14318	 * Paints a CMYK registration mark
14319	 * @param $x (float) abscissa of the registration mark center.
14320	 * @param $y (float) ordinate of the registration mark center.
14321	 * @param $r (float) radius of the crop mark.
14322	 * @author Nicola Asuni
14323	 * @since 6.0.038 (2013-09-30)
14324	 * @public
14325	 */
14326	public function registrationMarkCMYK($x, $y, $r) {
14327		// line width
14328		$lw = max((0.5 / $this->k),($r / 8));
14329		// internal radius
14330		$ri = ($r * 0.6);
14331		// external radius
14332		$re = ($r * 1.3);
14333		// Cyan
14334		$this->SetFillColorArray(array(100,0,0,0));
14335		$this->PieSector($x, $y, $ri, 270, 360, 'F');
14336		// Magenta
14337		$this->SetFillColorArray(array(0,100,0,0));
14338		$this->PieSector($x, $y, $ri, 0, 90, 'F');
14339		// Yellow
14340		$this->SetFillColorArray(array(0,0,100,0));
14341		$this->PieSector($x, $y, $ri, 90, 180, 'F');
14342		// Key - black
14343		$this->SetFillColorArray(array(0,0,0,100));
14344		$this->PieSector($x, $y, $ri, 180, 270, 'F');
14345		// registration color
14346		$line_style = array('width' => $lw, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(100,100,100,100,'All'));
14347		$this->SetFillColorArray(array(100,100,100,100,'All'));
14348		// external circle
14349		$this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
14350		// cross lines
14351		$this->Line($x, ($y - $re), $x, ($y - $ri));
14352		$this->Line($x, ($y + $ri), $x, ($y + $re));
14353		$this->Line(($x - $re), $y, ($x - $ri), $y);
14354		$this->Line(($x + $ri), $y, ($x + $re), $y);
14355	}
14356
14357	/**
14358	 * Paints a linear colour gradient.
14359	 * @param $x (float) abscissa of the top left corner of the rectangle.
14360	 * @param $y (float) ordinate of the top left corner of the rectangle.
14361	 * @param $w (float) width of the rectangle.
14362	 * @param $h (float) height of the rectangle.
14363	 * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
14364	 * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
14365	 * @param $coords (array) 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).
14366	 * @author Andreas W\FCrmser, Nicola Asuni
14367	 * @since 3.1.000 (2008-06-09)
14368	 * @public
14369	 */
14370	public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
14371		$this->Clip($x, $y, $w, $h);
14372		$this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
14373	}
14374
14375	/**
14376	 * Paints a radial colour gradient.
14377	 * @param $x (float) abscissa of the top left corner of the rectangle.
14378	 * @param $y (float) ordinate of the top left corner of the rectangle.
14379	 * @param $w (float) width of the rectangle.
14380	 * @param $h (float) height of the rectangle.
14381	 * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
14382	 * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
14383	 * @param $coords (array) 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.
14384	 * @author Andreas W\FCrmser, Nicola Asuni
14385	 * @since 3.1.000 (2008-06-09)
14386	 * @public
14387	 */
14388	public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
14389		$this->Clip($x, $y, $w, $h);
14390		$this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
14391	}
14392
14393	/**
14394	 * Paints a coons patch mesh.
14395	 * @param $x (float) abscissa of the top left corner of the rectangle.
14396	 * @param $y (float) ordinate of the top left corner of the rectangle.
14397	 * @param $w (float) width of the rectangle.
14398	 * @param $h (float) height of the rectangle.
14399	 * @param $col1 (array) first color (lower left corner) (RGB components).
14400	 * @param $col2 (array) second color (lower right corner) (RGB components).
14401	 * @param $col3 (array) third color (upper right corner) (RGB components).
14402	 * @param $col4 (array) fourth color (upper left corner) (RGB components).
14403	 * @param $coords (array) <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>
14404	 * @param $coords_min (array) minimum value used by the coordinates. If a coordinate's value is smaller than this it will be cut to coords_min. default: 0
14405	 * @param $coords_max (array) maximum value used by the coordinates. If a coordinate's value is greater than this it will be cut to coords_max. default: 1
14406	 * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
14407	 * @author Andreas W\FCrmser, Nicola Asuni
14408	 * @since 3.1.000 (2008-06-09)
14409	 * @public
14410	 */
14411	public function CoonsPatchMesh($x, $y, $w, $h, $col1=array(), $col2=array(), $col3=array(), $col4=array(), $coords=array(0.00,0.0,0.33,0.00,0.67,0.00,1.00,0.00,1.00,0.33,1.00,0.67,1.00,1.00,0.67,1.00,0.33,1.00,0.00,1.00,0.00,0.67,0.00,0.33), $coords_min=0, $coords_max=1, $antialias=false) {
14412		if ($this->pdfa_mode OR ($this->state != 2)) {
14413			return;
14414		}
14415		$this->Clip($x, $y, $w, $h);
14416		$n = count($this->gradients) + 1;
14417		$this->gradients[$n] = array();
14418		$this->gradients[$n]['type'] = 6; //coons patch mesh
14419		$this->gradients[$n]['coords'] = array();
14420		$this->gradients[$n]['antialias'] = $antialias;
14421		$this->gradients[$n]['colors'] = array();
14422		$this->gradients[$n]['transparency'] = false;
14423		//check the coords array if it is the simple array or the multi patch array
14424		if (!isset($coords[0]['f'])) {
14425			//simple array -> convert to multi patch array
14426			if (!isset($col1[1])) {
14427				$col1[1] = $col1[2] = $col1[0];
14428			}
14429			if (!isset($col2[1])) {
14430				$col2[1] = $col2[2] = $col2[0];
14431			}
14432			if (!isset($col3[1])) {
14433				$col3[1] = $col3[2] = $col3[0];
14434			}
14435			if (!isset($col4[1])) {
14436				$col4[1] = $col4[2] = $col4[0];
14437			}
14438			$patch_array[0]['f'] = 0;
14439			$patch_array[0]['points'] = $coords;
14440			$patch_array[0]['colors'][0]['r'] = $col1[0];
14441			$patch_array[0]['colors'][0]['g'] = $col1[1];
14442			$patch_array[0]['colors'][0]['b'] = $col1[2];
14443			$patch_array[0]['colors'][1]['r'] = $col2[0];
14444			$patch_array[0]['colors'][1]['g'] = $col2[1];
14445			$patch_array[0]['colors'][1]['b'] = $col2[2];
14446			$patch_array[0]['colors'][2]['r'] = $col3[0];
14447			$patch_array[0]['colors'][2]['g'] = $col3[1];
14448			$patch_array[0]['colors'][2]['b'] = $col3[2];
14449			$patch_array[0]['colors'][3]['r'] = $col4[0];
14450			$patch_array[0]['colors'][3]['g'] = $col4[1];
14451			$patch_array[0]['colors'][3]['b'] = $col4[2];
14452		} else {
14453			//multi patch array
14454			$patch_array = $coords;
14455		}
14456		$bpcd = 65535; //16 bits per coordinate
14457		//build the data stream
14458		$this->gradients[$n]['stream'] = '';
14459		$count_patch = count($patch_array);
14460		for ($i=0; $i < $count_patch; ++$i) {
14461			$this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
14462			$count_points = count($patch_array[$i]['points']);
14463			for ($j=0; $j < $count_points; ++$j) {
14464				//each point as 16 bit
14465				$patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
14466				if ($patch_array[$i]['points'][$j] < 0) {
14467					$patch_array[$i]['points'][$j] = 0;
14468				}
14469				if ($patch_array[$i]['points'][$j] > $bpcd) {
14470					$patch_array[$i]['points'][$j] = $bpcd;
14471				}
14472				$this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
14473				$this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
14474			}
14475			$count_cols = count($patch_array[$i]['colors']);
14476			for ($j=0; $j < $count_cols; ++$j) {
14477				//each color component as 8 bit
14478				$this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
14479				$this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
14480				$this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
14481			}
14482		}
14483		//paint the gradient
14484		$this->_out('/Sh'.$n.' sh');
14485		//restore previous Graphic State
14486		$this->_outRestoreGraphicsState();
14487		if ($this->inxobj) {
14488			// we are inside an XObject template
14489			$this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
14490		}
14491	}
14492
14493	/**
14494	 * Set a rectangular clipping area.
14495	 * @param $x (float) abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
14496	 * @param $y (float) ordinate of the top left corner of the rectangle.
14497	 * @param $w (float) width of the rectangle.
14498	 * @param $h (float) height of the rectangle.
14499	 * @author Andreas W\FCrmser, Nicola Asuni
14500	 * @since 3.1.000 (2008-06-09)
14501	 * @protected
14502	 */
14503	protected function Clip($x, $y, $w, $h) {
14504		if ($this->state != 2) {
14505			 return;
14506		}
14507		if ($this->rtl) {
14508			$x = $this->w - $x - $w;
14509		}
14510		//save current Graphic State
14511		$s = 'q';
14512		//set clipping area
14513		$s .= sprintf(' %F %F %F %F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
14514		//set up transformation matrix for gradient
14515		$s .= sprintf(' %F 0 0 %F %F %F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
14516		$this->_out($s);
14517	}
14518
14519	/**
14520	 * Output gradient.
14521	 * @param $type (int) type of gradient (1 Function-based shading; 2 Axial shading; 3 Radial shading; 4 Free-form Gouraud-shaded triangle mesh; 5 Lattice-form Gouraud-shaded triangle mesh; 6 Coons patch mesh; 7 Tensor-product patch mesh). (Not all types are currently supported)
14522	 * @param $coords (array) array of coordinates.
14523	 * @param $stops (array) array gradient color components: color = array of GRAY, RGB or CMYK color components; offset = (0 to 1) represents a location along the gradient vector; exponent = exponent of the exponential interpolation function (default = 1).
14524	 * @param $background (array) An array of colour components appropriate to the colour space, specifying a single background colour value.
14525	 * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
14526	 * @author Nicola Asuni
14527	 * @since 3.1.000 (2008-06-09)
14528	 * @public
14529	 */
14530	public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
14531		if ($this->pdfa_mode OR ($this->state != 2)) {
14532			return;
14533		}
14534		$n = count($this->gradients) + 1;
14535		$this->gradients[$n] = array();
14536		$this->gradients[$n]['type'] = $type;
14537		$this->gradients[$n]['coords'] = $coords;
14538		$this->gradients[$n]['antialias'] = $antialias;
14539		$this->gradients[$n]['colors'] = array();
14540		$this->gradients[$n]['transparency'] = false;
14541		// color space
14542		$numcolspace = count($stops[0]['color']);
14543		$bcolor = array_values($background);
14544		switch($numcolspace) {
14545			case 5:   // SPOT
14546			case 4: { // CMYK
14547				$this->gradients[$n]['colspace'] = 'DeviceCMYK';
14548				if (!empty($background)) {
14549					$this->gradients[$n]['background'] = sprintf('%F %F %F %F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
14550				}
14551				break;
14552			}
14553			case 3: { // RGB
14554				$this->gradients[$n]['colspace'] = 'DeviceRGB';
14555				if (!empty($background)) {
14556					$this->gradients[$n]['background'] = sprintf('%F %F %F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
14557				}
14558				break;
14559			}
14560			case 1: { // GRAY SCALE
14561				$this->gradients[$n]['colspace'] = 'DeviceGray';
14562				if (!empty($background)) {
14563					$this->gradients[$n]['background'] = sprintf('%F', $bcolor[0]/255);
14564				}
14565				break;
14566			}
14567		}
14568		$num_stops = count($stops);
14569		$last_stop_id = $num_stops - 1;
14570		foreach ($stops as $key => $stop) {
14571			$this->gradients[$n]['colors'][$key] = array();
14572			// offset represents a location along the gradient vector
14573			if (isset($stop['offset'])) {
14574				$this->gradients[$n]['colors'][$key]['offset'] = $stop['offset'];
14575			} else {
14576				if ($key == 0) {
14577					$this->gradients[$n]['colors'][$key]['offset'] = 0;
14578				} elseif ($key == $last_stop_id) {
14579					$this->gradients[$n]['colors'][$key]['offset'] = 1;
14580				} else {
14581					$offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
14582					$this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep;
14583				}
14584			}
14585			if (isset($stop['opacity'])) {
14586				$this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity'];
14587				if ((!$this->pdfa_mode) AND ($stop['opacity'] < 1)) {
14588					$this->gradients[$n]['transparency'] = true;
14589				}
14590			} else {
14591				$this->gradients[$n]['colors'][$key]['opacity'] = 1;
14592			}
14593			// exponent for the exponential interpolation function
14594			if (isset($stop['exponent'])) {
14595				$this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent'];
14596			} else {
14597				$this->gradients[$n]['colors'][$key]['exponent'] = 1;
14598			}
14599			// set colors
14600			$color = array_values($stop['color']);
14601			switch($numcolspace) {
14602				case 5:   // SPOT
14603				case 4: { // CMYK
14604					$this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F %F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
14605					break;
14606				}
14607				case 3: { // RGB
14608					$this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F', $color[0]/255, $color[1]/255, $color[2]/255);
14609					break;
14610				}
14611				case 1: { // GRAY SCALE
14612					$this->gradients[$n]['colors'][$key]['color'] = sprintf('%F', $color[0]/255);
14613					break;
14614				}
14615			}
14616		}
14617		if ($this->gradients[$n]['transparency']) {
14618			// paint luminosity gradient
14619			$this->_out('/TGS'.$n.' gs');
14620		}
14621		//paint the gradient
14622		$this->_out('/Sh'.$n.' sh');
14623		//restore previous Graphic State
14624		$this->_outRestoreGraphicsState();
14625		if ($this->inxobj) {
14626			// we are inside an XObject template
14627			$this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
14628		}
14629	}
14630
14631	/**
14632	 * Output gradient shaders.
14633	 * @author Nicola Asuni
14634	 * @since 3.1.000 (2008-06-09)
14635	 * @protected
14636	 */
14637	function _putshaders() {
14638		if ($this->pdfa_mode) {
14639			return;
14640		}
14641		$idt = count($this->gradients); //index for transparency gradients
14642		foreach ($this->gradients as $id => $grad) {
14643			if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
14644				$fc = $this->_newobj();
14645				$out = '<<';
14646				$out .= ' /FunctionType 3';
14647				$out .= ' /Domain [0 1]';
14648				$functions = '';
14649				$bounds = '';
14650				$encode = '';
14651				$i = 1;
14652				$num_cols = count($grad['colors']);
14653				$lastcols = $num_cols - 1;
14654				for ($i = 1; $i < $num_cols; ++$i) {
14655					$functions .= ($fc + $i).' 0 R ';
14656					if ($i < $lastcols) {
14657						$bounds .= sprintf('%F ', $grad['colors'][$i]['offset']);
14658					}
14659					$encode .= '0 1 ';
14660				}
14661				$out .= ' /Functions ['.trim($functions).']';
14662				$out .= ' /Bounds ['.trim($bounds).']';
14663				$out .= ' /Encode ['.trim($encode).']';
14664				$out .= ' >>';
14665				$out .= "\n".'endobj';
14666				$this->_out($out);
14667				for ($i = 1; $i < $num_cols; ++$i) {
14668					$this->_newobj();
14669					$out = '<<';
14670					$out .= ' /FunctionType 2';
14671					$out .= ' /Domain [0 1]';
14672					$out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
14673					$out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
14674					$out .= ' /N '.$grad['colors'][$i]['exponent'];
14675					$out .= ' >>';
14676					$out .= "\n".'endobj';
14677					$this->_out($out);
14678				}
14679				// set transparency functions
14680				if ($grad['transparency']) {
14681					$ft = $this->_newobj();
14682					$out = '<<';
14683					$out .= ' /FunctionType 3';
14684					$out .= ' /Domain [0 1]';
14685					$functions = '';
14686					$i = 1;
14687					$num_cols = count($grad['colors']);
14688					for ($i = 1; $i < $num_cols; ++$i) {
14689						$functions .= ($ft + $i).' 0 R ';
14690					}
14691					$out .= ' /Functions ['.trim($functions).']';
14692					$out .= ' /Bounds ['.trim($bounds).']';
14693					$out .= ' /Encode ['.trim($encode).']';
14694					$out .= ' >>';
14695					$out .= "\n".'endobj';
14696					$this->_out($out);
14697					for ($i = 1; $i < $num_cols; ++$i) {
14698						$this->_newobj();
14699						$out = '<<';
14700						$out .= ' /FunctionType 2';
14701						$out .= ' /Domain [0 1]';
14702						$out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
14703						$out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
14704						$out .= ' /N '.$grad['colors'][$i]['exponent'];
14705						$out .= ' >>';
14706						$out .= "\n".'endobj';
14707						$this->_out($out);
14708					}
14709				}
14710			}
14711			// set shading object
14712			$this->_newobj();
14713			$out = '<< /ShadingType '.$grad['type'];
14714			if (isset($grad['colspace'])) {
14715				$out .= ' /ColorSpace /'.$grad['colspace'];
14716			} else {
14717				$out .= ' /ColorSpace /DeviceRGB';
14718			}
14719			if (isset($grad['background']) AND !empty($grad['background'])) {
14720				$out .= ' /Background ['.$grad['background'].']';
14721			}
14722			if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
14723				$out .= ' /AntiAlias true';
14724			}
14725			if ($grad['type'] == 2) {
14726				$out .= ' '.sprintf('/Coords [%F %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
14727				$out .= ' /Domain [0 1]';
14728				$out .= ' /Function '.$fc.' 0 R';
14729				$out .= ' /Extend [true true]';
14730				$out .= ' >>';
14731			} elseif ($grad['type'] == 3) {
14732				//x0, y0, r0, x1, y1, r1
14733				//at this this time radius of inner circle is 0
14734				$out .= ' '.sprintf('/Coords [%F %F 0 %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
14735				$out .= ' /Domain [0 1]';
14736				$out .= ' /Function '.$fc.' 0 R';
14737				$out .= ' /Extend [true true]';
14738				$out .= ' >>';
14739			} elseif ($grad['type'] == 6) {
14740				$out .= ' /BitsPerCoordinate 16';
14741				$out .= ' /BitsPerComponent 8';
14742				$out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
14743				$out .= ' /BitsPerFlag 8';
14744				$stream = $this->_getrawstream($grad['stream']);
14745				$out .= ' /Length '.strlen($stream);
14746				$out .= ' >>';
14747				$out .= ' stream'."\n".$stream."\n".'endstream';
14748			}
14749			$out .= "\n".'endobj';
14750			$this->_out($out);
14751			if ($grad['transparency']) {
14752				$shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
14753				$shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
14754			}
14755			$this->gradients[$id]['id'] = $this->n;
14756			// set pattern object
14757			$this->_newobj();
14758			$out = '<< /Type /Pattern /PatternType 2';
14759			$out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R';
14760			$out .= ' >>';
14761			$out .= "\n".'endobj';
14762			$this->_out($out);
14763			$this->gradients[$id]['pattern'] = $this->n;
14764			// set shading and pattern for transparency mask
14765			if ($grad['transparency']) {
14766				// luminosity pattern
14767				$idgs = $id + $idt;
14768				$this->_newobj();
14769				$this->_out($shading_transparency);
14770				$this->gradients[$idgs]['id'] = $this->n;
14771				$this->_newobj();
14772				$out = '<< /Type /Pattern /PatternType 2';
14773				$out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R';
14774				$out .= ' >>';
14775				$out .= "\n".'endobj';
14776				$this->_out($out);
14777				$this->gradients[$idgs]['pattern'] = $this->n;
14778				// luminosity XObject
14779				$oid = $this->_newobj();
14780				$this->xobjects['LX'.$oid] = array('n' => $oid);
14781				$filter = '';
14782				$stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q';
14783				if ($this->compress) {
14784					$filter = ' /Filter /FlateDecode';
14785					$stream = gzcompress($stream);
14786				}
14787				$stream = $this->_getrawstream($stream);
14788				$out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
14789				$out .= ' /Length '.strlen($stream);
14790				$rect = sprintf('%F %F', $this->wPt, $this->hPt);
14791				$out .= ' /BBox [0 0 '.$rect.']';
14792				$out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
14793				$out .= ' /Resources <<';
14794				$out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
14795				$out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>';
14796				$out .= ' >>';
14797				$out .= ' >> ';
14798				$out .= ' stream'."\n".$stream."\n".'endstream';
14799				$out .= "\n".'endobj';
14800				$this->_out($out);
14801				// SMask
14802				$this->_newobj();
14803				$out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj';
14804				$this->_out($out);
14805				// ExtGState
14806				$this->_newobj();
14807				$out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj';
14808				$this->_out($out);
14809				$this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id);
14810			}
14811		}
14812	}
14813
14814	/**
14815	 * Draw the sector of a circle.
14816	 * It can be used for instance to render pie charts.
14817	 * @param $xc (float) abscissa of the center.
14818	 * @param $yc (float) ordinate of the center.
14819	 * @param $r (float) radius.
14820	 * @param $a (float) start angle (in degrees).
14821	 * @param $b (float) end angle (in degrees).
14822	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
14823	 * @param $cw: (float) indicates whether to go clockwise (default: true).
14824	 * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). Default: 90.
14825	 * @author Maxime Delorme, Nicola Asuni
14826	 * @since 3.1.000 (2008-06-09)
14827	 * @public
14828	 */
14829	public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
14830		$this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
14831	}
14832
14833	/**
14834	 * Draw the sector of an ellipse.
14835	 * It can be used for instance to render pie charts.
14836	 * @param $xc (float) abscissa of the center.
14837	 * @param $yc (float) ordinate of the center.
14838	 * @param $rx (float) the x-axis radius.
14839	 * @param $ry (float) the y-axis radius.
14840	 * @param $a (float) start angle (in degrees).
14841	 * @param $b (float) end angle (in degrees).
14842	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
14843	 * @param $cw: (float) indicates whether to go clockwise.
14844	 * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
14845	 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of arc.
14846	 * @author Maxime Delorme, Nicola Asuni
14847	 * @since 3.1.000 (2008-06-09)
14848	 * @public
14849	 */
14850	public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
14851		if ($this->state != 2) {
14852			 return;
14853		}
14854		if ($this->rtl) {
14855			$xc = ($this->w - $xc);
14856		}
14857		$op = TCPDF_STATIC::getPathPaintOperator($style);
14858		if ($op == 'f') {
14859			$line_style = array();
14860		}
14861		if ($cw) {
14862			$d = $b;
14863			$b = (360 - $a + $o);
14864			$a = (360 - $d + $o);
14865		} else {
14866			$b += $o;
14867			$a += $o;
14868		}
14869		$this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
14870		$this->_out($op);
14871	}
14872
14873	/**
14874	 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
14875	 * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
14876	 * Only vector drawing is supported, not text or bitmap.
14877	 * 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).
14878	 * @param $file (string) Name of the file containing the image or a '@' character followed by the EPS/AI data string.
14879	 * @param $x (float) Abscissa of the upper-left corner.
14880	 * @param $y (float) Ordinate of the upper-left corner.
14881	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
14882	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
14883	 * @param $link (mixed) URL or identifier returned by AddLink().
14884	 * @param $useBoundingBox (boolean) specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
14885	 * @param $align (string) 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>
14886	 * @param $palign (string) 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>
14887	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
14888	 * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
14889	 * @param $fixoutvals (boolean) if true remove values outside the bounding box.
14890	 * @author Valentin Schmidt, Nicola Asuni
14891	 * @since 3.1.000 (2008-06-09)
14892	 * @public
14893	 */
14894	public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
14895		if ($this->state != 2) {
14896			 return;
14897		}
14898		if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
14899			// convert EPS to raster image using GD or ImageMagick libraries
14900			return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
14901		}
14902		if ($x === '') {
14903			$x = $this->x;
14904		}
14905		if ($y === '') {
14906			$y = $this->y;
14907		}
14908		// check page for no-write regions and adapt page margins if necessary
14909		list($x, $y) = $this->checkPageRegions($h, $x, $y);
14910		$k = $this->k;
14911		if ($file[0] === '@') { // image from string
14912			$data = substr($file, 1);
14913		} else { // EPS/AI file
14914			$data = TCPDF_STATIC::fileGetContents($file);
14915		}
14916		if ($data === FALSE) {
14917			$this->Error('EPS file not found: '.$file);
14918		}
14919		$regs = array();
14920		// EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
14921		preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
14922		if (count($regs) > 1) {
14923			$version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
14924			if (strpos($version_str, 'Adobe Illustrator') !== false) {
14925				$versexp = explode(' ', $version_str);
14926				$version = (float)array_pop($versexp);
14927				if ($version >= 9) {
14928					$this->Error('This version of Adobe Illustrator file is not supported: '.$file);
14929				}
14930			}
14931		}
14932		// strip binary bytes in front of PS-header
14933		$start = strpos($data, '%!PS-Adobe');
14934		if ($start > 0) {
14935			$data = substr($data, $start);
14936		}
14937		// find BoundingBox params
14938		preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
14939		if (count($regs) > 1) {
14940			list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
14941		} else {
14942			$this->Error('No BoundingBox found in EPS/AI file: '.$file);
14943		}
14944		$start = strpos($data, '%%EndSetup');
14945		if ($start === false) {
14946			$start = strpos($data, '%%EndProlog');
14947		}
14948		if ($start === false) {
14949			$start = strpos($data, '%%BoundingBox');
14950		}
14951		$data = substr($data, $start);
14952		$end = strpos($data, '%%PageTrailer');
14953		if ($end===false) {
14954			$end = strpos($data, 'showpage');
14955		}
14956		if ($end) {
14957			$data = substr($data, 0, $end);
14958		}
14959		// calculate image width and height on document
14960		if (($w <= 0) AND ($h <= 0)) {
14961			$w = ($x2 - $x1) / $k;
14962			$h = ($y2 - $y1) / $k;
14963		} elseif ($w <= 0) {
14964			$w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
14965		} elseif ($h <= 0) {
14966			$h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
14967		}
14968		// fit the image on available space
14969		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
14970		if ($this->rasterize_vector_images) {
14971			// convert EPS to raster image using GD or ImageMagick libraries
14972			return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
14973		}
14974		// set scaling factors
14975		$scale_x = $w / (($x2 - $x1) / $k);
14976		$scale_y = $h / (($y2 - $y1) / $k);
14977		// set alignment
14978		$this->img_rb_y = $y + $h;
14979		// set alignment
14980		if ($this->rtl) {
14981			if ($palign == 'L') {
14982				$ximg = $this->lMargin;
14983			} elseif ($palign == 'C') {
14984				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
14985			} elseif ($palign == 'R') {
14986				$ximg = $this->w - $this->rMargin - $w;
14987			} else {
14988				$ximg = $x - $w;
14989			}
14990			$this->img_rb_x = $ximg;
14991		} else {
14992			if ($palign == 'L') {
14993				$ximg = $this->lMargin;
14994			} elseif ($palign == 'C') {
14995				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
14996			} elseif ($palign == 'R') {
14997				$ximg = $this->w - $this->rMargin - $w;
14998			} else {
14999				$ximg = $x;
15000			}
15001			$this->img_rb_x = $ximg + $w;
15002		}
15003		if ($useBoundingBox) {
15004			$dx = $ximg * $k - $x1;
15005			$dy = $y * $k - $y1;
15006		} else {
15007			$dx = $ximg * $k;
15008			$dy = $y * $k;
15009		}
15010		// save the current graphic state
15011		$this->_out('q'.$this->epsmarker);
15012		// translate
15013		$this->_out(sprintf('%F %F %F %F %F %F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
15014		// scale
15015		if (isset($scale_x)) {
15016			$this->_out(sprintf('%F %F %F %F %F %F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
15017		}
15018		// handle pc/unix/mac line endings
15019		$lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY);
15020		$u=0;
15021		$cnt = count($lines);
15022		for ($i=0; $i < $cnt; ++$i) {
15023			$line = $lines[$i];
15024			if (($line == '') OR ($line[0] == '%')) {
15025				continue;
15026			}
15027			$len = strlen($line);
15028			// check for spot color names
15029			$color_name = '';
15030			if (strcasecmp('x', substr(trim($line), -1)) == 0) {
15031				if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
15032					// extract spot color name
15033					$color_name = $matches[0];
15034					// remove color name from string
15035					$line = str_replace(' '.$color_name, '', $line);
15036					// remove pharentesis from color name
15037					$color_name = substr($color_name, 1, -1);
15038				}
15039			}
15040			$chunks = explode(' ', $line);
15041			$cmd = trim(array_pop($chunks));
15042			// RGB
15043			if (($cmd == 'Xa') OR ($cmd == 'XA')) {
15044				$b = array_pop($chunks);
15045				$g = array_pop($chunks);
15046				$r = array_pop($chunks);
15047				$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!
15048				continue;
15049			}
15050			$skip = false;
15051			if ($fixoutvals) {
15052				// check for values outside the bounding box
15053				switch ($cmd) {
15054					case 'm':
15055					case 'l':
15056					case 'L': {
15057						// skip values outside bounding box
15058						foreach ($chunks as $key => $val) {
15059							if ((($key % 2) == 0) AND (($val < $x1) OR ($val > $x2))) {
15060								$skip = true;
15061							} elseif ((($key % 2) != 0) AND (($val < $y1) OR ($val > $y2))) {
15062								$skip = true;
15063							}
15064						}
15065					}
15066				}
15067			}
15068			switch ($cmd) {
15069				case 'm':
15070				case 'l':
15071				case 'v':
15072				case 'y':
15073				case 'c':
15074				case 'k':
15075				case 'K':
15076				case 'g':
15077				case 'G':
15078				case 's':
15079				case 'S':
15080				case 'J':
15081				case 'j':
15082				case 'w':
15083				case 'M':
15084				case 'd':
15085				case 'n': {
15086					if ($skip) {
15087						break;
15088					}
15089					$this->_out($line);
15090					break;
15091				}
15092				case 'x': {// custom fill color
15093					if (empty($color_name)) {
15094						// CMYK color
15095						list($col_c, $col_m, $col_y, $col_k) = $chunks;
15096						$this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
15097					} else {
15098						// Spot Color (CMYK + tint)
15099						list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
15100						$this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
15101						$color_cmd = sprintf('/CS%d cs %F scn', $this->spot_colors[$color_name]['i'], (1 - $col_t));
15102						$this->_out($color_cmd);
15103					}
15104					break;
15105				}
15106				case 'X': { // custom stroke color
15107					if (empty($color_name)) {
15108						// CMYK color
15109						list($col_c, $col_m, $col_y, $col_k) = $chunks;
15110						$this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
15111					} else {
15112						// Spot Color (CMYK + tint)
15113						list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
15114						$this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
15115						$color_cmd = sprintf('/CS%d CS %F SCN', $this->spot_colors[$color_name]['i'], (1 - $col_t));
15116						$this->_out($color_cmd);
15117					}
15118					break;
15119				}
15120				case 'Y':
15121				case 'N':
15122				case 'V':
15123				case 'L':
15124				case 'C': {
15125					if ($skip) {
15126						break;
15127					}
15128					$line[($len - 1)] = strtolower($cmd);
15129					$this->_out($line);
15130					break;
15131				}
15132				case 'b':
15133				case 'B': {
15134					$this->_out($cmd . '*');
15135					break;
15136				}
15137				case 'f':
15138				case 'F': {
15139					if ($u > 0) {
15140						$isU = false;
15141						$max = min(($i + 5), $cnt);
15142						for ($j = ($i + 1); $j < $max; ++$j) {
15143							$isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
15144						}
15145						if ($isU) {
15146							$this->_out('f*');
15147						}
15148					} else {
15149						$this->_out('f*');
15150					}
15151					break;
15152				}
15153				case '*u': {
15154					++$u;
15155					break;
15156				}
15157				case '*U': {
15158					--$u;
15159					break;
15160				}
15161			}
15162		}
15163		// restore previous graphic state
15164		$this->_out($this->epsmarker.'Q');
15165		if (!empty($border)) {
15166			$bx = $this->x;
15167			$by = $this->y;
15168			$this->x = $ximg;
15169			if ($this->rtl) {
15170				$this->x += $w;
15171			}
15172			$this->y = $y;
15173			$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
15174			$this->x = $bx;
15175			$this->y = $by;
15176		}
15177		if ($link) {
15178			$this->Link($ximg, $y, $w, $h, $link, 0);
15179		}
15180		// set pointer to align the next text/objects
15181		switch($align) {
15182			case 'T':{
15183				$this->y = $y;
15184				$this->x = $this->img_rb_x;
15185				break;
15186			}
15187			case 'M':{
15188				$this->y = $y + round($h/2);
15189				$this->x = $this->img_rb_x;
15190				break;
15191			}
15192			case 'B':{
15193				$this->y = $this->img_rb_y;
15194				$this->x = $this->img_rb_x;
15195				break;
15196			}
15197			case 'N':{
15198				$this->SetY($this->img_rb_y);
15199				break;
15200			}
15201			default:{
15202				break;
15203			}
15204		}
15205		$this->endlinex = $this->img_rb_x;
15206	}
15207
15208	/**
15209	 * Set document barcode.
15210	 * @param $bc (string) barcode
15211	 * @public
15212	 */
15213	public function setBarcode($bc='') {
15214		$this->barcode = $bc;
15215	}
15216
15217	/**
15218	 * Get current barcode.
15219	 * @return string
15220	 * @public
15221	 * @since 4.0.012 (2008-07-24)
15222	 */
15223	public function getBarcode() {
15224		return $this->barcode;
15225	}
15226
15227	/**
15228	 * Print a Linear Barcode.
15229	 * @param $code (string) code to print
15230	 * @param $type (string) type of barcode (see tcpdf_barcodes_1d.php for supported formats).
15231	 * @param $x (int) x position in user units (empty string = current x position)
15232	 * @param $y (int) y position in user units (empty string = current y position)
15233	 * @param $w (int) width in user units (empty string = remaining page width)
15234	 * @param $h (int) height in user units (empty string = remaining page height)
15235	 * @param $xres (float) width of the smallest bar in user units (empty string = default value = 0.4mm)
15236	 * @param $style (array) array of options:<ul>
15237	 * <li>boolean $style['border'] if true prints a border</li>
15238	 * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
15239	 * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
15240	 * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
15241	 * <li>array $style['fgcolor'] color array for bars and text</li>
15242	 * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
15243	 * <li>boolean $style['text'] if true prints text below the barcode</li>
15244	 * <li>string $style['label'] override default label</li>
15245	 * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
15246	 * <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>
15247	 * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
15248	 * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
15249	 * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
15250	 * <li>string $style['fitwidth'] if true reduce the width to fit the barcode width + padding. When this option is enabled the 'stretch' option is automatically disabled.</li>
15251	 * <li>string $style['cellfitalign'] this option works only when 'fitwidth' is true and 'position' is unset or empty. Set the horizontal position of the containing barcode cell inside the specified rectangle: L = left; C = center; R = right.</li></ul>
15252	 * @param $align (string) Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
15253	 * @author Nicola Asuni
15254	 * @since 3.1.000 (2008-06-09)
15255	 * @public
15256	 */
15257	public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style=array(), $align='') {
15258		if (TCPDF_STATIC::empty_string(trim($code))) {
15259			return;
15260		}
15261		require_once(dirname(__FILE__).'/tcpdf_barcodes_1d.php');
15262		// save current graphic settings
15263		$gvars = $this->getGraphicVars();
15264		// create new barcode object
15265		$barcodeobj = new TCPDFBarcode($code, $type);
15266		$arrcode = $barcodeobj->getBarcodeArray();
15267		if (($arrcode === false) OR empty($arrcode) OR ($arrcode['maxw'] <= 0)) {
15268			$this->Error('Error in 1D barcode string');
15269		}
15270		if ($arrcode['maxh'] <= 0) {
15271			$arrcode['maxh'] = 1;
15272		}
15273		// set default values
15274		if (!isset($style['position'])) {
15275			$style['position'] = '';
15276		} elseif ($style['position'] == 'S') {
15277			// keep this for backward compatibility
15278			$style['position'] = '';
15279			$style['stretch'] = true;
15280		}
15281		if (!isset($style['fitwidth'])) {
15282			if (!isset($style['stretch'])) {
15283				$style['fitwidth'] = true;
15284			} else {
15285				$style['fitwidth'] = false;
15286			}
15287		}
15288		if ($style['fitwidth']) {
15289			// disable stretch
15290			$style['stretch'] = false;
15291		}
15292		if (!isset($style['stretch'])) {
15293			if (($w === '') OR ($w <= 0)) {
15294				$style['stretch'] = false;
15295			} else {
15296				$style['stretch'] = true;
15297			}
15298		}
15299		if (!isset($style['fgcolor'])) {
15300			$style['fgcolor'] = array(0,0,0); // default black
15301		}
15302		if (!isset($style['bgcolor'])) {
15303			$style['bgcolor'] = false; // default transparent
15304		}
15305		if (!isset($style['border'])) {
15306			$style['border'] = false;
15307		}
15308		$fontsize = 0;
15309		if (!isset($style['text'])) {
15310			$style['text'] = false;
15311		}
15312		if ($style['text'] AND isset($style['font'])) {
15313			if (isset($style['fontsize'])) {
15314				$fontsize = $style['fontsize'];
15315			}
15316			$this->SetFont($style['font'], '', $fontsize);
15317		}
15318		if (!isset($style['stretchtext'])) {
15319			$style['stretchtext'] = 4;
15320		}
15321		if ($x === '') {
15322			$x = $this->x;
15323		}
15324		if ($y === '') {
15325			$y = $this->y;
15326		}
15327		// check page for no-write regions and adapt page margins if necessary
15328		list($x, $y) = $this->checkPageRegions($h, $x, $y);
15329		if (($w === '') OR ($w <= 0)) {
15330			if ($this->rtl) {
15331				$w = $x - $this->lMargin;
15332			} else {
15333				$w = $this->w - $this->rMargin - $x;
15334			}
15335		}
15336		// padding
15337		if (!isset($style['padding'])) {
15338			$padding = 0;
15339		} elseif ($style['padding'] === 'auto') {
15340			$padding = 10 * ($w / ($arrcode['maxw'] + 20));
15341		} else {
15342			$padding = floatval($style['padding']);
15343		}
15344		// horizontal padding
15345		if (!isset($style['hpadding'])) {
15346			$hpadding = $padding;
15347		} elseif ($style['hpadding'] === 'auto') {
15348			$hpadding = 10 * ($w / ($arrcode['maxw'] + 20));
15349		} else {
15350			$hpadding = floatval($style['hpadding']);
15351		}
15352		// vertical padding
15353		if (!isset($style['vpadding'])) {
15354			$vpadding = $padding;
15355		} elseif ($style['vpadding'] === 'auto') {
15356			$vpadding = ($hpadding / 2);
15357		} else {
15358			$vpadding = floatval($style['vpadding']);
15359		}
15360		// calculate xres (single bar width)
15361		$max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
15362		if ($style['stretch']) {
15363			$xres = $max_xres;
15364		} else {
15365			if (TCPDF_STATIC::empty_string($xres)) {
15366				$xres = (0.141 * $this->k); // default bar width = 0.4 mm
15367			}
15368			if ($xres > $max_xres) {
15369				// correct xres to fit on $w
15370				$xres = $max_xres;
15371			}
15372			if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
15373				OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
15374				$hpadding = 10 * $xres;
15375				if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
15376					$vpadding = ($hpadding / 2);
15377				}
15378			}
15379		}
15380		if ($style['fitwidth']) {
15381			$wold = $w;
15382			$w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));
15383			if (isset($style['cellfitalign'])) {
15384				switch ($style['cellfitalign']) {
15385					case 'L': {
15386						if ($this->rtl) {
15387							$x -= ($wold - $w);
15388						}
15389						break;
15390					}
15391					case 'R': {
15392						if (!$this->rtl) {
15393							$x += ($wold - $w);
15394						}
15395						break;
15396					}
15397					case 'C': {
15398						if ($this->rtl) {
15399							$x -= (($wold - $w) / 2);
15400						} else {
15401							$x += (($wold - $w) / 2);
15402						}
15403						break;
15404					}
15405					default : {
15406						break;
15407					}
15408				}
15409			}
15410		}
15411		$text_height = $this->getCellHeight($fontsize / $this->k);
15412		// height
15413		if (($h === '') OR ($h <= 0)) {
15414			// set default height
15415			$h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;
15416		}
15417		$barh = $h - $text_height - (2 * $vpadding);
15418		if ($barh <=0) {
15419			// try to reduce font or padding to fit barcode on available height
15420			if ($text_height > $h) {
15421				$fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));
15422				$text_height = $this->getCellHeight($fontsize / $this->k);
15423				$this->SetFont($style['font'], '', $fontsize);
15424			}
15425			if ($vpadding > 0) {
15426				$vpadding = (($h - $text_height) / 4);
15427			}
15428			$barh = $h - $text_height - (2 * $vpadding);
15429		}
15430		// fit the barcode on available space
15431		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
15432		// set alignment
15433		$this->img_rb_y = $y + $h;
15434		// set alignment
15435		if ($this->rtl) {
15436			if ($style['position'] == 'L') {
15437				$xpos = $this->lMargin;
15438			} elseif ($style['position'] == 'C') {
15439				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15440			} elseif ($style['position'] == 'R') {
15441				$xpos = $this->w - $this->rMargin - $w;
15442			} else {
15443				$xpos = $x - $w;
15444			}
15445			$this->img_rb_x = $xpos;
15446		} else {
15447			if ($style['position'] == 'L') {
15448				$xpos = $this->lMargin;
15449			} elseif ($style['position'] == 'C') {
15450				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15451			} elseif ($style['position'] == 'R') {
15452				$xpos = $this->w - $this->rMargin - $w;
15453			} else {
15454				$xpos = $x;
15455			}
15456			$this->img_rb_x = $xpos + $w;
15457		}
15458		$xpos_rect = $xpos;
15459		if (!isset($style['align'])) {
15460			$style['align'] = 'C';
15461		}
15462		switch ($style['align']) {
15463			case 'L': {
15464				$xpos = $xpos_rect + $hpadding;
15465				break;
15466			}
15467			case 'R': {
15468				$xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;
15469				break;
15470			}
15471			case 'C':
15472			default : {
15473				$xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);
15474				break;
15475			}
15476		}
15477		$xpos_text = $xpos;
15478		// barcode is always printed in LTR direction
15479		$tempRTL = $this->rtl;
15480		$this->rtl = false;
15481		// print background color
15482		if ($style['bgcolor']) {
15483			$this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
15484		} elseif ($style['border']) {
15485			$this->Rect($xpos_rect, $y, $w, $h, 'D');
15486		}
15487		// set foreground color
15488		$this->SetDrawColorArray($style['fgcolor']);
15489		$this->SetTextColorArray($style['fgcolor']);
15490		// print bars
15491		foreach ($arrcode['bcode'] as $k => $v) {
15492			$bw = ($v['w'] * $xres);
15493			if ($v['t']) {
15494				// draw a vertical bar
15495				$ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);
15496				$this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
15497			}
15498			$xpos += $bw;
15499		}
15500		// print text
15501		if ($style['text']) {
15502			if (isset($style['label']) AND !TCPDF_STATIC::empty_string($style['label'])) {
15503				$label = $style['label'];
15504			} else {
15505				$label = $code;
15506			}
15507			$txtwidth = ($arrcode['maxw'] * $xres);
15508			if ($this->GetStringWidth($label) > $txtwidth) {
15509				$style['stretchtext'] = 2;
15510			}
15511			// print text
15512			$this->x = $xpos_text;
15513			$this->y = $y + $vpadding + $barh;
15514			$cellpadding = $this->cell_padding;
15515			$this->SetCellPadding(0);
15516			$this->Cell($txtwidth, '', $label, 0, 0, 'C', false, '', $style['stretchtext'], false, 'T', 'T');
15517			$this->cell_padding = $cellpadding;
15518		}
15519		// restore original direction
15520		$this->rtl = $tempRTL;
15521		// restore previous settings
15522		$this->setGraphicVars($gvars);
15523		// set pointer to align the next text/objects
15524		switch($align) {
15525			case 'T':{
15526				$this->y = $y;
15527				$this->x = $this->img_rb_x;
15528				break;
15529			}
15530			case 'M':{
15531				$this->y = $y + round($h / 2);
15532				$this->x = $this->img_rb_x;
15533				break;
15534			}
15535			case 'B':{
15536				$this->y = $this->img_rb_y;
15537				$this->x = $this->img_rb_x;
15538				break;
15539			}
15540			case 'N':{
15541				$this->SetY($this->img_rb_y);
15542				break;
15543			}
15544			default:{
15545				break;
15546			}
15547		}
15548		$this->endlinex = $this->img_rb_x;
15549	}
15550
15551	/**
15552	 * Print 2D Barcode.
15553	 * @param $code (string) code to print
15554	 * @param $type (string) type of barcode (see tcpdf_barcodes_2d.php for supported formats).
15555	 * @param $x (int) x position in user units
15556	 * @param $y (int) y position in user units
15557	 * @param $w (int) width in user units
15558	 * @param $h (int) height in user units
15559	 * @param $style (array) array of options:<ul>
15560	 * <li>boolean $style['border'] if true prints a border around the barcode</li>
15561	 * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
15562	 * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
15563	 * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
15564	 * <li>int $style['module_width'] width of a single module in points</li>
15565	 * <li>int $style['module_height'] height of a single module in points</li>
15566	 * <li>array $style['fgcolor'] color array for bars and text</li>
15567	 * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
15568	 * <li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li>
15569	 * @param $align (string) Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
15570	 * @param $distort (boolean) if true distort the barcode to fit width and height, otherwise preserve aspect ratio
15571	 * @author Nicola Asuni
15572	 * @since 4.5.037 (2009-04-07)
15573	 * @public
15574	 */
15575	public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style=array(), $align='', $distort=false) {
15576		if (TCPDF_STATIC::empty_string(trim($code))) {
15577			return;
15578		}
15579		require_once(dirname(__FILE__).'/tcpdf_barcodes_2d.php');
15580		// save current graphic settings
15581		$gvars = $this->getGraphicVars();
15582		// create new barcode object
15583		$barcodeobj = new TCPDF2DBarcode($code, $type);
15584		$arrcode = $barcodeobj->getBarcodeArray();
15585		if (($arrcode === false) OR empty($arrcode) OR !isset($arrcode['num_rows']) OR ($arrcode['num_rows'] == 0) OR !isset($arrcode['num_cols']) OR ($arrcode['num_cols'] == 0)) {
15586			$this->Error('Error in 2D barcode string');
15587		}
15588		// set default values
15589		if (!isset($style['position'])) {
15590			$style['position'] = '';
15591		}
15592		if (!isset($style['fgcolor'])) {
15593			$style['fgcolor'] = array(0,0,0); // default black
15594		}
15595		if (!isset($style['bgcolor'])) {
15596			$style['bgcolor'] = false; // default transparent
15597		}
15598		if (!isset($style['border'])) {
15599			$style['border'] = false;
15600		}
15601		// padding
15602		if (!isset($style['padding'])) {
15603			$style['padding'] = 0;
15604		} elseif ($style['padding'] === 'auto') {
15605			$style['padding'] = 4;
15606		}
15607		if (!isset($style['hpadding'])) {
15608			$style['hpadding'] = $style['padding'];
15609		} elseif ($style['hpadding'] === 'auto') {
15610			$style['hpadding'] = 4;
15611		}
15612		if (!isset($style['vpadding'])) {
15613			$style['vpadding'] = $style['padding'];
15614		} elseif ($style['vpadding'] === 'auto') {
15615			$style['vpadding'] = 4;
15616		}
15617		$hpad = (2 * $style['hpadding']);
15618		$vpad = (2 * $style['vpadding']);
15619		// cell (module) dimension
15620		if (!isset($style['module_width'])) {
15621			$style['module_width'] = 1; // width of a single module in points
15622		}
15623		if (!isset($style['module_height'])) {
15624			$style['module_height'] = 1; // height of a single module in points
15625		}
15626		if ($x === '') {
15627			$x = $this->x;
15628		}
15629		if ($y === '') {
15630			$y = $this->y;
15631		}
15632		// check page for no-write regions and adapt page margins if necessary
15633		list($x, $y) = $this->checkPageRegions($h, $x, $y);
15634		// number of barcode columns and rows
15635		$rows = $arrcode['num_rows'];
15636		$cols = $arrcode['num_cols'];
15637		if (($rows <= 0) || ($cols <= 0)){
15638			$this->Error('Error in 2D barcode string');
15639		}
15640		// module width and height
15641		$mw = $style['module_width'];
15642		$mh = $style['module_height'];
15643		if (($mw <= 0) OR ($mh <= 0)) {
15644			$this->Error('Error in 2D barcode string');
15645		}
15646		// get max dimensions
15647		if ($this->rtl) {
15648			$maxw = $x - $this->lMargin;
15649		} else {
15650			$maxw = $this->w - $this->rMargin - $x;
15651		}
15652		$maxh = ($this->h - $this->tMargin - $this->bMargin);
15653		$ratioHW = ((($rows * $mh) + $hpad) / (($cols * $mw) + $vpad));
15654		$ratioWH = ((($cols * $mw) + $vpad) / (($rows * $mh) + $hpad));
15655		if (!$distort) {
15656			if (($maxw * $ratioHW) > $maxh) {
15657				$maxw = $maxh * $ratioWH;
15658			}
15659			if (($maxh * $ratioWH) > $maxw) {
15660				$maxh = $maxw * $ratioHW;
15661			}
15662		}
15663		// set maximum dimensions
15664		if ($w > $maxw) {
15665			$w = $maxw;
15666		}
15667		if ($h > $maxh) {
15668			$h = $maxh;
15669		}
15670		// set dimensions
15671		if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {
15672			$w = ($cols + $hpad) * ($mw / $this->k);
15673			$h = ($rows + $vpad) * ($mh / $this->k);
15674		} elseif (($w === '') OR ($w <= 0)) {
15675			$w = $h * $ratioWH;
15676		} elseif (($h === '') OR ($h <= 0)) {
15677			$h = $w * $ratioHW;
15678		}
15679		// barcode size (excluding padding)
15680		$bw = ($w * $cols) / ($cols + $hpad);
15681		$bh = ($h * $rows) / ($rows + $vpad);
15682		// dimension of single barcode cell unit
15683		$cw = $bw / $cols;
15684		$ch = $bh / $rows;
15685		if (!$distort) {
15686			if (($cw / $ch) > ($mw / $mh)) {
15687				// correct horizontal distortion
15688				$cw = $ch * $mw / $mh;
15689				$bw = $cw * $cols;
15690				$style['hpadding'] = ($w - $bw) / (2 * $cw);
15691			} else {
15692				// correct vertical distortion
15693				$ch = $cw * $mh / $mw;
15694				$bh = $ch * $rows;
15695				$style['vpadding'] = ($h - $bh) / (2 * $ch);
15696			}
15697		}
15698		// fit the barcode on available space
15699		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
15700		// set alignment
15701		$this->img_rb_y = $y + $h;
15702		// set alignment
15703		if ($this->rtl) {
15704			if ($style['position'] == 'L') {
15705				$xpos = $this->lMargin;
15706			} elseif ($style['position'] == 'C') {
15707				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15708			} elseif ($style['position'] == 'R') {
15709				$xpos = $this->w - $this->rMargin - $w;
15710			} else {
15711				$xpos = $x - $w;
15712			}
15713			$this->img_rb_x = $xpos;
15714		} else {
15715			if ($style['position'] == 'L') {
15716				$xpos = $this->lMargin;
15717			} elseif ($style['position'] == 'C') {
15718				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15719			} elseif ($style['position'] == 'R') {
15720				$xpos = $this->w - $this->rMargin - $w;
15721			} else {
15722				$xpos = $x;
15723			}
15724			$this->img_rb_x = $xpos + $w;
15725		}
15726		$xstart = $xpos + ($style['hpadding'] * $cw);
15727		$ystart = $y + ($style['vpadding'] * $ch);
15728		// barcode is always printed in LTR direction
15729		$tempRTL = $this->rtl;
15730		$this->rtl = false;
15731		// print background color
15732		if ($style['bgcolor']) {
15733			$this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
15734		} elseif ($style['border']) {
15735			$this->Rect($xpos, $y, $w, $h, 'D');
15736		}
15737		// set foreground color
15738		$this->SetDrawColorArray($style['fgcolor']);
15739		// print barcode cells
15740		// for each row
15741		for ($r = 0; $r < $rows; ++$r) {
15742			$xr = $xstart;
15743			// for each column
15744			for ($c = 0; $c < $cols; ++$c) {
15745				if ($arrcode['bcode'][$r][$c] == 1) {
15746					// draw a single barcode cell
15747					$this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
15748				}
15749				$xr += $cw;
15750			}
15751			$ystart += $ch;
15752		}
15753		// restore original direction
15754		$this->rtl = $tempRTL;
15755		// restore previous settings
15756		$this->setGraphicVars($gvars);
15757		// set pointer to align the next text/objects
15758		switch($align) {
15759			case 'T':{
15760				$this->y = $y;
15761				$this->x = $this->img_rb_x;
15762				break;
15763			}
15764			case 'M':{
15765				$this->y = $y + round($h/2);
15766				$this->x = $this->img_rb_x;
15767				break;
15768			}
15769			case 'B':{
15770				$this->y = $this->img_rb_y;
15771				$this->x = $this->img_rb_x;
15772				break;
15773			}
15774			case 'N':{
15775				$this->SetY($this->img_rb_y);
15776				break;
15777			}
15778			default:{
15779				break;
15780			}
15781		}
15782		$this->endlinex = $this->img_rb_x;
15783	}
15784
15785	/**
15786	 * Returns an array containing current margins:
15787	 * <ul>
15788			<li>$ret['left'] = left margin</li>
15789			<li>$ret['right'] = right margin</li>
15790			<li>$ret['top'] = top margin</li>
15791			<li>$ret['bottom'] = bottom margin</li>
15792			<li>$ret['header'] = header margin</li>
15793			<li>$ret['footer'] = footer margin</li>
15794			<li>$ret['cell'] = cell padding array</li>
15795			<li>$ret['padding_left'] = cell left padding</li>
15796			<li>$ret['padding_top'] = cell top padding</li>
15797			<li>$ret['padding_right'] = cell right padding</li>
15798			<li>$ret['padding_bottom'] = cell bottom padding</li>
15799	 * </ul>
15800	 * @return array containing all margins measures
15801	 * @public
15802	 * @since 3.2.000 (2008-06-23)
15803	 */
15804	public function getMargins() {
15805		$ret = array(
15806			'left' => $this->lMargin,
15807			'right' => $this->rMargin,
15808			'top' => $this->tMargin,
15809			'bottom' => $this->bMargin,
15810			'header' => $this->header_margin,
15811			'footer' => $this->footer_margin,
15812			'cell' => $this->cell_padding,
15813			'padding_left' => $this->cell_padding['L'],
15814			'padding_top' => $this->cell_padding['T'],
15815			'padding_right' => $this->cell_padding['R'],
15816			'padding_bottom' => $this->cell_padding['B']
15817		);
15818		return $ret;
15819	}
15820
15821	/**
15822	 * Returns an array containing original margins:
15823	 * <ul>
15824			<li>$ret['left'] = left margin</li>
15825			<li>$ret['right'] = right margin</li>
15826	 * </ul>
15827	 * @return array containing all margins measures
15828	 * @public
15829	 * @since 4.0.012 (2008-07-24)
15830	 */
15831	public function getOriginalMargins() {
15832		$ret = array(
15833			'left' => $this->original_lMargin,
15834			'right' => $this->original_rMargin
15835		);
15836		return $ret;
15837	}
15838
15839	/**
15840	 * Returns the current font size.
15841	 * @return current font size
15842	 * @public
15843	 * @since 3.2.000 (2008-06-23)
15844	 */
15845	public function getFontSize() {
15846		return $this->FontSize;
15847	}
15848
15849	/**
15850	 * Returns the current font size in points unit.
15851	 * @return current font size in points unit
15852	 * @public
15853	 * @since 3.2.000 (2008-06-23)
15854	 */
15855	public function getFontSizePt() {
15856		return $this->FontSizePt;
15857	}
15858
15859	/**
15860	 * Returns the current font family name.
15861	 * @return string current font family name
15862	 * @public
15863	 * @since 4.3.008 (2008-12-05)
15864	 */
15865	public function getFontFamily() {
15866		return $this->FontFamily;
15867	}
15868
15869	/**
15870	 * Returns the current font style.
15871	 * @return string current font style
15872	 * @public
15873	 * @since 4.3.008 (2008-12-05)
15874	 */
15875	public function getFontStyle() {
15876		return $this->FontStyle;
15877	}
15878
15879	/**
15880	 * Cleanup HTML code (requires HTML Tidy library).
15881	 * @param $html (string) htmlcode to fix
15882	 * @param $default_css (string) CSS commands to add
15883	 * @param $tagvs (array) parameters for setHtmlVSpace method
15884	 * @param $tidy_options (array) options for tidy_parse_string function
15885	 * @return string XHTML code cleaned up
15886	 * @author Nicola Asuni
15887	 * @public
15888	 * @since 5.9.017 (2010-11-16)
15889	 * @see setHtmlVSpace()
15890	 */
15891	public function fixHTMLCode($html, $default_css='', $tagvs='', $tidy_options='') {
15892		return TCPDF_STATIC::fixHTMLCode($html, $default_css, $tagvs, $tidy_options, $this->tagvspaces);
15893	}
15894
15895	/**
15896	 * Returns the border width from CSS property
15897	 * @param $width (string) border width
15898	 * @return int with in user units
15899	 * @protected
15900	 * @since 5.7.000 (2010-08-02)
15901	 */
15902	protected function getCSSBorderWidth($width) {
15903		if ($width == 'thin') {
15904			$width = (2 / $this->k);
15905		} elseif ($width == 'medium') {
15906			$width = (4 / $this->k);
15907		} elseif ($width == 'thick') {
15908			$width = (6 / $this->k);
15909		} else {
15910			$width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
15911		}
15912		return $width;
15913	}
15914
15915	/**
15916	 * Returns the border dash style from CSS property
15917	 * @param $style (string) border style to convert
15918	 * @return int sash style (return -1 in case of none or hidden border)
15919	 * @protected
15920	 * @since 5.7.000 (2010-08-02)
15921	 */
15922	protected function getCSSBorderDashStyle($style) {
15923		switch (strtolower($style)) {
15924			case 'none':
15925			case 'hidden': {
15926				$dash = -1;
15927				break;
15928			}
15929			case 'dotted': {
15930				$dash = 1;
15931				break;
15932			}
15933			case 'dashed': {
15934				$dash = 3;
15935				break;
15936			}
15937			case 'double':
15938			case 'groove':
15939			case 'ridge':
15940			case 'inset':
15941			case 'outset':
15942			case 'solid':
15943			default: {
15944				$dash = 0;
15945				break;
15946			}
15947		}
15948		return $dash;
15949	}
15950
15951	/**
15952	 * Returns the border style array from CSS border properties
15953	 * @param $cssborder (string) border properties
15954	 * @return array containing border properties
15955	 * @protected
15956	 * @since 5.7.000 (2010-08-02)
15957	 */
15958	protected function getCSSBorderStyle($cssborder) {
15959		$bprop = preg_split('/[\s]+/', trim($cssborder));
15960		$border = array(); // value to be returned
15961		switch (count($bprop)) {
15962			case 3: {
15963				$width = $bprop[0];
15964				$style = $bprop[1];
15965				$color = $bprop[2];
15966				break;
15967			}
15968			case 2: {
15969				$width = 'medium';
15970				$style = $bprop[0];
15971				$color = $bprop[1];
15972				break;
15973			}
15974			case 1: {
15975				$width = 'medium';
15976				$style = $bprop[0];
15977				$color = 'black';
15978				break;
15979			}
15980			default: {
15981				$width = 'medium';
15982				$style = 'solid';
15983				$color = 'black';
15984				break;
15985			}
15986		}
15987		if ($style == 'none') {
15988			return array();
15989		}
15990		$border['cap'] = 'square';
15991		$border['join'] = 'miter';
15992		$border['dash'] = $this->getCSSBorderDashStyle($style);
15993		if ($border['dash'] < 0) {
15994			return array();
15995		}
15996		$border['width'] = $this->getCSSBorderWidth($width);
15997		$border['color'] = TCPDF_COLORS::convertHTMLColorToDec($color, $this->spot_colors);
15998		return $border;
15999	}
16000
16001	/**
16002	 * Get the internal Cell padding from CSS attribute.
16003	 * @param $csspadding (string) padding properties
16004	 * @param $width (float) width of the containing element
16005	 * @return array of cell paddings
16006	 * @public
16007	 * @since 5.9.000 (2010-10-04)
16008	 */
16009	public function getCSSPadding($csspadding, $width=0) {
16010		$padding = preg_split('/[\s]+/', trim($csspadding));
16011		$cell_padding = array(); // value to be returned
16012		switch (count($padding)) {
16013			case 4: {
16014				$cell_padding['T'] = $padding[0];
16015				$cell_padding['R'] = $padding[1];
16016				$cell_padding['B'] = $padding[2];
16017				$cell_padding['L'] = $padding[3];
16018				break;
16019			}
16020			case 3: {
16021				$cell_padding['T'] = $padding[0];
16022				$cell_padding['R'] = $padding[1];
16023				$cell_padding['B'] = $padding[2];
16024				$cell_padding['L'] = $padding[1];
16025				break;
16026			}
16027			case 2: {
16028				$cell_padding['T'] = $padding[0];
16029				$cell_padding['R'] = $padding[1];
16030				$cell_padding['B'] = $padding[0];
16031				$cell_padding['L'] = $padding[1];
16032				break;
16033			}
16034			case 1: {
16035				$cell_padding['T'] = $padding[0];
16036				$cell_padding['R'] = $padding[0];
16037				$cell_padding['B'] = $padding[0];
16038				$cell_padding['L'] = $padding[0];
16039				break;
16040			}
16041			default: {
16042				return $this->cell_padding;
16043			}
16044		}
16045		if ($width == 0) {
16046			$width = $this->w - $this->lMargin - $this->rMargin;
16047		}
16048		$cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
16049		$cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
16050		$cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
16051		$cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
16052		return $cell_padding;
16053	}
16054
16055	/**
16056	 * Get the internal Cell margin from CSS attribute.
16057	 * @param $cssmargin (string) margin properties
16058	 * @param $width (float) width of the containing element
16059	 * @return array of cell margins
16060	 * @public
16061	 * @since 5.9.000 (2010-10-04)
16062	 */
16063	public function getCSSMargin($cssmargin, $width=0) {
16064		$margin = preg_split('/[\s]+/', trim($cssmargin));
16065		$cell_margin = array(); // value to be returned
16066		switch (count($margin)) {
16067			case 4: {
16068				$cell_margin['T'] = $margin[0];
16069				$cell_margin['R'] = $margin[1];
16070				$cell_margin['B'] = $margin[2];
16071				$cell_margin['L'] = $margin[3];
16072				break;
16073			}
16074			case 3: {
16075				$cell_margin['T'] = $margin[0];
16076				$cell_margin['R'] = $margin[1];
16077				$cell_margin['B'] = $margin[2];
16078				$cell_margin['L'] = $margin[1];
16079				break;
16080			}
16081			case 2: {
16082				$cell_margin['T'] = $margin[0];
16083				$cell_margin['R'] = $margin[1];
16084				$cell_margin['B'] = $margin[0];
16085				$cell_margin['L'] = $margin[1];
16086				break;
16087			}
16088			case 1: {
16089				$cell_margin['T'] = $margin[0];
16090				$cell_margin['R'] = $margin[0];
16091				$cell_margin['B'] = $margin[0];
16092				$cell_margin['L'] = $margin[0];
16093				break;
16094			}
16095			default: {
16096				return $this->cell_margin;
16097			}
16098		}
16099		if ($width == 0) {
16100			$width = $this->w - $this->lMargin - $this->rMargin;
16101		}
16102		$cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
16103		$cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
16104		$cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
16105		$cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
16106		return $cell_margin;
16107	}
16108
16109	/**
16110	 * Get the border-spacing from CSS attribute.
16111	 * @param $cssbspace (string) border-spacing CSS properties
16112	 * @param $width (float) width of the containing element
16113	 * @return array of border spacings
16114	 * @public
16115	 * @since 5.9.010 (2010-10-27)
16116	 */
16117	public function getCSSBorderMargin($cssbspace, $width=0) {
16118		$space = preg_split('/[\s]+/', trim($cssbspace));
16119		$border_spacing = array(); // value to be returned
16120		switch (count($space)) {
16121			case 2: {
16122				$border_spacing['H'] = $space[0];
16123				$border_spacing['V'] = $space[1];
16124				break;
16125			}
16126			case 1: {
16127				$border_spacing['H'] = $space[0];
16128				$border_spacing['V'] = $space[0];
16129				break;
16130			}
16131			default: {
16132				return array('H' => 0, 'V' => 0);
16133			}
16134		}
16135		if ($width == 0) {
16136			$width = $this->w - $this->lMargin - $this->rMargin;
16137		}
16138		$border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
16139		$border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
16140		return $border_spacing;
16141	}
16142
16143	/**
16144	 * Returns the letter-spacing value from CSS value
16145	 * @param $spacing (string) letter-spacing value
16146	 * @param $parent (float) font spacing (tracking) value of the parent element
16147	 * @return float quantity to increases or decreases the space between characters in a text.
16148	 * @protected
16149	 * @since 5.9.000 (2010-10-02)
16150	 */
16151	protected function getCSSFontSpacing($spacing, $parent=0) {
16152		$val = 0; // value to be returned
16153		$spacing = trim($spacing);
16154		switch ($spacing) {
16155			case 'normal': {
16156				$val = 0;
16157				break;
16158			}
16159			case 'inherit': {
16160				if ($parent == 'normal') {
16161					$val = 0;
16162				} else {
16163					$val = $parent;
16164				}
16165				break;
16166			}
16167			default: {
16168				$val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
16169			}
16170		}
16171		return $val;
16172	}
16173
16174	/**
16175	 * Returns the percentage of font stretching from CSS value
16176	 * @param $stretch (string) stretch mode
16177	 * @param $parent (float) stretch value of the parent element
16178	 * @return float font stretching percentage
16179	 * @protected
16180	 * @since 5.9.000 (2010-10-02)
16181	 */
16182	protected function getCSSFontStretching($stretch, $parent=100) {
16183		$val = 100; // value to be returned
16184		$stretch = trim($stretch);
16185		switch ($stretch) {
16186			case 'ultra-condensed': {
16187				$val = 40;
16188				break;
16189			}
16190			case 'extra-condensed': {
16191				$val = 55;
16192				break;
16193			}
16194			case 'condensed': {
16195				$val = 70;
16196				break;
16197			}
16198			case 'semi-condensed': {
16199				$val = 85;
16200				break;
16201			}
16202			case 'normal': {
16203				$val = 100;
16204				break;
16205			}
16206			case 'semi-expanded': {
16207				$val = 115;
16208				break;
16209			}
16210			case 'expanded': {
16211				$val = 130;
16212				break;
16213			}
16214			case 'extra-expanded': {
16215				$val = 145;
16216				break;
16217			}
16218			case 'ultra-expanded': {
16219				$val = 160;
16220				break;
16221			}
16222			case 'wider': {
16223				$val = ($parent + 10);
16224				break;
16225			}
16226			case 'narrower': {
16227				$val = ($parent - 10);
16228				break;
16229			}
16230			case 'inherit': {
16231				if ($parent == 'normal') {
16232					$val = 100;
16233				} else {
16234					$val = $parent;
16235				}
16236				break;
16237			}
16238			default: {
16239				$val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
16240			}
16241		}
16242		return $val;
16243	}
16244
16245	/**
16246	 * Convert HTML string containing font size value to points
16247	 * @param $val (string) String containing font size value and unit.
16248	 * @param $refsize (float) Reference font size in points.
16249	 * @param $parent_size (float) Parent font size in points.
16250	 * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
16251	 * @return float value in points
16252	 * @public
16253	 */
16254	public function getHTMLFontUnits($val, $refsize=12, $parent_size=12, $defaultunit='pt') {
16255		$refsize = TCPDF_FONTS::getFontRefSize($refsize);
16256		$parent_size = TCPDF_FONTS::getFontRefSize($parent_size, $refsize);
16257		switch ($val) {
16258			case 'xx-small': {
16259				$size = ($refsize - 4);
16260				break;
16261			}
16262			case 'x-small': {
16263				$size = ($refsize - 3);
16264				break;
16265			}
16266			case 'small': {
16267				$size = ($refsize - 2);
16268				break;
16269			}
16270			case 'medium': {
16271				$size = $refsize;
16272				break;
16273			}
16274			case 'large': {
16275				$size = ($refsize + 2);
16276				break;
16277			}
16278			case 'x-large': {
16279				$size = ($refsize + 4);
16280				break;
16281			}
16282			case 'xx-large': {
16283				$size = ($refsize + 6);
16284				break;
16285			}
16286			case 'smaller': {
16287				$size = ($parent_size - 3);
16288				break;
16289			}
16290			case 'larger': {
16291				$size = ($parent_size + 3);
16292				break;
16293			}
16294			default: {
16295				$size = $this->getHTMLUnitToUnits($val, $parent_size, $defaultunit, true);
16296			}
16297		}
16298		return $size;
16299	}
16300
16301	/**
16302	 * Returns the HTML DOM array.
16303	 * @param $html (string) html code
16304	 * @return array
16305	 * @protected
16306	 * @since 3.2.000 (2008-06-20)
16307	 */
16308	protected function getHtmlDomArray($html) {
16309		// array of CSS styles ( selector => properties).
16310		$css = array();
16311		// get CSS array defined at previous call
16312		$matches = array();
16313		if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) {
16314			if (isset($matches[1][0])) {
16315				$css = array_merge($css, json_decode($this->unhtmlentities($matches[1][0]), true));
16316			}
16317			$html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html);
16318		}
16319		// extract external CSS files
16320		$matches = array();
16321		if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) {
16322			foreach ($matches[1] as $key => $link) {
16323				$type = array();
16324				if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
16325					$type = array();
16326					preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
16327					// get 'all' and 'print' media, other media types are discarded
16328					// (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
16329					if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
16330						$type = array();
16331						if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
16332							// read CSS data file
16333							$cssdata = TCPDF_STATIC::fileGetContents(trim($type[1]));
16334							if (($cssdata !== FALSE) AND (strlen($cssdata) > 0)) {
16335								$css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
16336							}
16337						}
16338					}
16339				}
16340			}
16341		}
16342		// extract style tags
16343		$matches = array();
16344		if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) {
16345			foreach ($matches[1] as $key => $media) {
16346				$type = array();
16347				preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
16348				// get 'all' and 'print' media, other media types are discarded
16349				// (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
16350				if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
16351					$cssdata = $matches[2][$key];
16352					$css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
16353				}
16354			}
16355		}
16356		// create a special tag to contain the CSS array (used for table content)
16357		$csstagarray = '<cssarray>'.htmlentities(json_encode($css)).'</cssarray>';
16358		// remove head and style blocks
16359		$html = preg_replace('/<head([^\>]*)>(.*?)<\/head>/siU', '', $html);
16360		$html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html);
16361		// define block tags
16362		$blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
16363		// define self-closing tags
16364		$selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
16365		// remove all unsupported tags (the line below lists all supported tags)
16366		$html = strip_tags($html, '<marker/><a><b><blockquote><body><br><br/><dd><del><div><dl><dt><em><font><form><h1><h2><h3><h4><h5><h6><hr><hr/><i><img><input><label><li><ol><option><p><pre><s><select><small><span><strike><strong><sub><sup><table><tablehead><tcpdf><td><textarea><th><thead><tr><tt><u><ul>');
16367		//replace some blank characters
16368		$html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
16369		$html = preg_replace('/<(table|tr|td|th|tcpdf|blockquote|dd|div|dl|dt|form|h1|h2|h3|h4|h5|h6|br|hr|li|ol|ul|p)([^\>]*)>[\n\r\t]+/', '<\\1\\2>', $html);
16370		$html = preg_replace('@(\r\n|\r)@', "\n", $html);
16371		$repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
16372		$html = strtr($html, $repTable);
16373		$offset = 0;
16374		while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
16375			$html_a = substr($html, 0, $offset);
16376			$html_b = substr($html, $offset, ($pos - $offset + 6));
16377			while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
16378				// preserve newlines on <pre> tag
16379				$html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
16380			}
16381			while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) {
16382				// preserve spaces on <pre> tag
16383				$html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b);
16384			}
16385			$html = $html_a.$html_b.substr($html, $pos + 6);
16386			$offset = strlen($html_a.$html_b);
16387		}
16388		$offset = 0;
16389		while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
16390			$html_a = substr($html, 0, $offset);
16391			$html_b = substr($html, $offset, ($pos - $offset + 11));
16392			while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
16393				// preserve newlines on <textarea> tag
16394				$html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
16395				$html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
16396			}
16397			$html = $html_a.$html_b.substr($html, $pos + 11);
16398			$offset = strlen($html_a.$html_b);
16399		}
16400		$html = preg_replace('/([\s]*)<option/si', '<option', $html);
16401		$html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
16402		$offset = 0;
16403		while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
16404			$html_a = substr($html, 0, $offset);
16405			$html_b = substr($html, $offset, ($pos - $offset + 9));
16406			while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
16407				$html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
16408				$html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
16409			}
16410			$html = $html_a.$html_b.substr($html, $pos + 9);
16411			$offset = strlen($html_a.$html_b);
16412		}
16413		if (preg_match("'</select'si", $html)) {
16414			$html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
16415			$html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
16416		}
16417		$html = str_replace("\n", ' ', $html);
16418		// restore textarea newlines
16419		$html = str_replace('<TBR>', "\n", $html);
16420		// remove extra spaces from code
16421		$html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
16422		$html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html);
16423		$html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
16424		$html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html);
16425		$html = preg_replace('/<\/(table|tr|td|th|blockquote|dd|dt|dl|div|dt|h1|h2|h3|h4|h5|h6|hr|li|ol|ul|p)>[\s]+</', '</\\1><', $html);
16426		$html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
16427		$html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
16428		$html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html);
16429		$html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1>&nbsp;\\2', $html);
16430		$html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
16431		$html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
16432		$html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
16433		$html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html);
16434		$html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html);
16435		$html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces
16436		$html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces
16437		$html = preg_replace('/<su([bp])/', '<zws/><su\\1', $html); // fix sub/sup alignment
16438		$html = preg_replace('/<\/su([bp])>/', '</su\\1><zws/>', $html); // fix sub/sup alignment
16439		$html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space
16440		// trim string
16441		$html = $this->stringTrim($html);
16442		// fix br tag after li
16443		$html = preg_replace('/<li><br([^\>]*)>/', '<li> <br\\1>', $html);
16444		// fix first image tag alignment
16445		$html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
16446		// pattern for generic tag
16447		$tagpattern = '/(<[^>]+>)/';
16448		// explodes the string
16449		$a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
16450		// count elements
16451		$maxel = count($a);
16452		$elkey = 0;
16453		$key = 0;
16454		// create an array of elements
16455		$dom = array();
16456		$dom[$key] = array();
16457		// set inheritable properties fot the first void element
16458		// possible inheritable properties are: azimuth, border-collapse, border-spacing, caption-side, color, cursor, direction, empty-cells, font, font-family, font-stretch, font-size, font-size-adjust, font-style, font-variant, font-weight, letter-spacing, line-height, list-style, list-style-image, list-style-position, list-style-type, orphans, page, page-break-inside, quotes, speak, speak-header, text-align, text-indent, text-transform, volume, white-space, widows, word-spacing
16459		$dom[$key]['tag'] = false;
16460		$dom[$key]['block'] = false;
16461		$dom[$key]['value'] = '';
16462		$dom[$key]['parent'] = 0;
16463		$dom[$key]['hide'] = false;
16464		$dom[$key]['fontname'] = $this->FontFamily;
16465		$dom[$key]['fontstyle'] = $this->FontStyle;
16466		$dom[$key]['fontsize'] = $this->FontSizePt;
16467		$dom[$key]['font-stretch'] = $this->font_stretching;
16468		$dom[$key]['letter-spacing'] = $this->font_spacing;
16469		$dom[$key]['stroke'] = $this->textstrokewidth;
16470		$dom[$key]['fill'] = (($this->textrendermode % 2) == 0);
16471		$dom[$key]['clip'] = ($this->textrendermode > 3);
16472		$dom[$key]['line-height'] = $this->cell_height_ratio;
16473		$dom[$key]['bgcolor'] = false;
16474		$dom[$key]['fgcolor'] = $this->fgcolor; // color
16475		$dom[$key]['strokecolor'] = $this->strokecolor;
16476		$dom[$key]['align'] = '';
16477		$dom[$key]['listtype'] = '';
16478		$dom[$key]['text-indent'] = 0;
16479		$dom[$key]['text-transform'] = '';
16480		$dom[$key]['border'] = array();
16481		$dom[$key]['dir'] = $this->rtl?'rtl':'ltr';
16482		$thead = false; // true when we are inside the THEAD tag
16483		++$key;
16484		$level = array();
16485		array_push($level, 0); // root
16486		while ($elkey < $maxel) {
16487			$dom[$key] = array();
16488			$element = $a[$elkey];
16489			$dom[$key]['elkey'] = $elkey;
16490			if (preg_match($tagpattern, $element)) {
16491				// html tag
16492				$element = substr($element, 1, -1);
16493				// get tag name
16494				preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
16495				$tagname = strtolower($tag[1]);
16496				// check if we are inside a table header
16497				if ($tagname == 'thead') {
16498					if ($element[0] == '/') {
16499						$thead = false;
16500					} else {
16501						$thead = true;
16502					}
16503					++$elkey;
16504					continue;
16505				}
16506				$dom[$key]['tag'] = true;
16507				$dom[$key]['value'] = $tagname;
16508				if (in_array($dom[$key]['value'], $blocktags)) {
16509					$dom[$key]['block'] = true;
16510				} else {
16511					$dom[$key]['block'] = false;
16512				}
16513				if ($element[0] == '/') {
16514					// *** closing html tag
16515					$dom[$key]['opening'] = false;
16516					$dom[$key]['parent'] = end($level);
16517					array_pop($level);
16518					$dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
16519					$dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
16520					$dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
16521					$dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
16522					$dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
16523					$dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
16524					$dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
16525					$dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
16526					$dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
16527					$dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
16528					$dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
16529					$dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
16530					$dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
16531					$dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
16532					$dom[$key]['text-transform'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['text-transform'];
16533					$dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
16534					if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
16535						$dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
16536					}
16537					// set the number of columns in table tag
16538					if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
16539						$dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
16540					}
16541					if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
16542						$dom[($dom[$key]['parent'])]['content'] = $csstagarray;
16543						for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
16544							$dom[($dom[$key]['parent'])]['content'] .= stripslashes($a[$dom[$i]['elkey']]);
16545						}
16546						$key = $i;
16547						// mark nested tables
16548						$dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
16549						// remove thead sections from nested tables
16550						$dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
16551						$dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
16552					}
16553					// store header rows on a new table
16554					if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] === true)) {
16555						if (TCPDF_STATIC::empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
16556							$dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
16557						}
16558						for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
16559							$dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
16560						}
16561						if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
16562							$dom[($dom[$key]['parent'])]['attribute'] = array();
16563						}
16564						// header elements must be always contained in a single page
16565						$dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
16566					}
16567					if (($dom[$key]['value'] == 'table') AND (!TCPDF_STATIC::empty_string($dom[($dom[$key]['parent'])]['thead']))) {
16568						// remove the nobr attributes from the table header
16569						$dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
16570						$dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
16571					}
16572				} else {
16573					// *** opening or self-closing html tag
16574					$dom[$key]['opening'] = true;
16575					$dom[$key]['parent'] = end($level);
16576					if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
16577						// self-closing tag
16578						$dom[$key]['self'] = true;
16579					} else {
16580						// opening tag
16581						array_push($level, $key);
16582						$dom[$key]['self'] = false;
16583					}
16584					// copy some values from parent
16585					$parentkey = 0;
16586					if ($key > 0) {
16587						$parentkey = $dom[$key]['parent'];
16588						$dom[$key]['hide'] = $dom[$parentkey]['hide'];
16589						$dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
16590						$dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
16591						$dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
16592						$dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
16593						$dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
16594						$dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
16595						$dom[$key]['fill'] = $dom[$parentkey]['fill'];
16596						$dom[$key]['clip'] = $dom[$parentkey]['clip'];
16597						$dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
16598						$dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
16599						$dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
16600						$dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
16601						$dom[$key]['align'] = $dom[$parentkey]['align'];
16602						$dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
16603						$dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
16604						$dom[$key]['text-transform'] = $dom[$parentkey]['text-transform'];
16605						$dom[$key]['border'] = array();
16606						$dom[$key]['dir'] = $dom[$parentkey]['dir'];
16607					}
16608					// get attributes
16609					preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER);
16610					$dom[$key]['attribute'] = array(); // reset attribute array
16611                    foreach($attr_array[1] as $id => $name) {
16612                        $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
16613                    }
16614					if (!empty($css)) {
16615						// merge CSS style to current style
16616						list($dom[$key]['csssel'], $dom[$key]['cssdata']) = TCPDF_STATIC::getCSSdataArray($dom, $key, $css);
16617						$dom[$key]['attribute']['style'] = TCPDF_STATIC::getTagStyleFromCSSarray($dom[$key]['cssdata']);
16618					}
16619					// split style attributes
16620					if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
16621						// get style attributes
16622						preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
16623						$dom[$key]['style'] = array(); // reset style attribute array
16624                        foreach($style_array[1] as $id => $name) {
16625                            // in case of duplicate attribute the last replace the previous
16626                            $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
16627                        }
16628						// --- get some style attributes ---
16629						// text direction
16630						if (isset($dom[$key]['style']['direction'])) {
16631							$dom[$key]['dir'] = $dom[$key]['style']['direction'];
16632						}
16633						// display
16634						if (isset($dom[$key]['style']['display'])) {
16635							$dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
16636						}
16637						// font family
16638						if (isset($dom[$key]['style']['font-family'])) {
16639							$dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
16640						}
16641						// list-style-type
16642						if (isset($dom[$key]['style']['list-style-type'])) {
16643							$dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
16644							if ($dom[$key]['listtype'] == 'inherit') {
16645								$dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
16646							}
16647						}
16648						// text-indent
16649						if (isset($dom[$key]['style']['text-indent'])) {
16650							$dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
16651							if ($dom[$key]['text-indent'] == 'inherit') {
16652								$dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
16653							}
16654						}
16655						// text-transform
16656						if (isset($dom[$key]['style']['text-transform'])) {
16657							$dom[$key]['text-transform'] = $dom[$key]['style']['text-transform'];
16658						}
16659						// font size
16660						if (isset($dom[$key]['style']['font-size'])) {
16661							$fsize = trim($dom[$key]['style']['font-size']);
16662							$dom[$key]['fontsize'] = $this->getHTMLFontUnits($fsize, $dom[0]['fontsize'], $dom[$parentkey]['fontsize'], 'pt');
16663						}
16664						// font-stretch
16665						if (isset($dom[$key]['style']['font-stretch'])) {
16666							$dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
16667						}
16668						// letter-spacing
16669						if (isset($dom[$key]['style']['letter-spacing'])) {
16670							$dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
16671						}
16672						// line-height (internally is the cell height ratio)
16673						if (isset($dom[$key]['style']['line-height'])) {
16674							$lineheight = trim($dom[$key]['style']['line-height']);
16675							switch ($lineheight) {
16676								// A normal line height. This is default
16677								case 'normal': {
16678									$dom[$key]['line-height'] = $dom[0]['line-height'];
16679									break;
16680								}
16681								case 'inherit': {
16682									$dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
16683								}
16684								default: {
16685									if (is_numeric($lineheight)) {
16686										// convert to percentage of font height
16687										$lineheight = ($lineheight * 100).'%';
16688									}
16689									$dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
16690									if (substr($lineheight, -1) !== '%') {
16691										if ($dom[$key]['fontsize'] <= 0) {
16692											$dom[$key]['line-height'] = 1;
16693										} else {
16694											$dom[$key]['line-height'] = (($dom[$key]['line-height'] - $this->cell_padding['T'] - $this->cell_padding['B']) / $dom[$key]['fontsize']);
16695										}
16696									}
16697								}
16698							}
16699						}
16700						// font style
16701						if (isset($dom[$key]['style']['font-weight'])) {
16702							if (strtolower($dom[$key]['style']['font-weight'][0]) == 'n') {
16703								if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
16704									$dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
16705								}
16706							} elseif (strtolower($dom[$key]['style']['font-weight'][0]) == 'b') {
16707								$dom[$key]['fontstyle'] .= 'B';
16708							}
16709						}
16710						if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style'][0]) == 'i')) {
16711							$dom[$key]['fontstyle'] .= 'I';
16712						}
16713						// font color
16714						if (isset($dom[$key]['style']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['color']))) {
16715							$dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['color'], $this->spot_colors);
16716						} elseif ($dom[$key]['value'] == 'a') {
16717							$dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
16718						}
16719						// background color
16720						if (isset($dom[$key]['style']['background-color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['background-color']))) {
16721							$dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['background-color'], $this->spot_colors);
16722						}
16723						// text-decoration
16724						if (isset($dom[$key]['style']['text-decoration'])) {
16725							$decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
16726							foreach ($decors as $dec) {
16727								$dec = trim($dec);
16728								if (!TCPDF_STATIC::empty_string($dec)) {
16729									if ($dec[0] == 'u') {
16730										// underline
16731										$dom[$key]['fontstyle'] .= 'U';
16732									} elseif ($dec[0] == 'l') {
16733										// line-through
16734										$dom[$key]['fontstyle'] .= 'D';
16735									} elseif ($dec[0] == 'o') {
16736										// overline
16737										$dom[$key]['fontstyle'] .= 'O';
16738									}
16739								}
16740							}
16741						} elseif ($dom[$key]['value'] == 'a') {
16742							$dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
16743						}
16744						// check for width attribute
16745						if (isset($dom[$key]['style']['width'])) {
16746							$dom[$key]['width'] = $dom[$key]['style']['width'];
16747						}
16748						// check for height attribute
16749						if (isset($dom[$key]['style']['height'])) {
16750							$dom[$key]['height'] = $dom[$key]['style']['height'];
16751						}
16752						// check for text alignment
16753						if (isset($dom[$key]['style']['text-align'])) {
16754							$dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align'][0]);
16755						}
16756						// check for CSS border properties
16757						if (isset($dom[$key]['style']['border'])) {
16758							$borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
16759							if (!empty($borderstyle)) {
16760								$dom[$key]['border']['LTRB'] = $borderstyle;
16761							}
16762						}
16763						if (isset($dom[$key]['style']['border-color'])) {
16764							$brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
16765							if (isset($brd_colors[3])) {
16766								$dom[$key]['border']['L']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[3], $this->spot_colors);
16767							}
16768							if (isset($brd_colors[1])) {
16769								$dom[$key]['border']['R']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[1], $this->spot_colors);
16770							}
16771							if (isset($brd_colors[0])) {
16772								$dom[$key]['border']['T']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[0], $this->spot_colors);
16773							}
16774							if (isset($brd_colors[2])) {
16775								$dom[$key]['border']['B']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[2], $this->spot_colors);
16776							}
16777						}
16778						if (isset($dom[$key]['style']['border-width'])) {
16779							$brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
16780							if (isset($brd_widths[3])) {
16781								$dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
16782							}
16783							if (isset($brd_widths[1])) {
16784								$dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
16785							}
16786							if (isset($brd_widths[0])) {
16787								$dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
16788							}
16789							if (isset($brd_widths[2])) {
16790								$dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
16791							}
16792						}
16793						if (isset($dom[$key]['style']['border-style'])) {
16794							$brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
16795							if (isset($brd_styles[3]) AND ($brd_styles[3]!='none')) {
16796								$dom[$key]['border']['L']['cap'] = 'square';
16797								$dom[$key]['border']['L']['join'] = 'miter';
16798								$dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
16799								if ($dom[$key]['border']['L']['dash'] < 0) {
16800									$dom[$key]['border']['L'] = array();
16801								}
16802							}
16803							if (isset($brd_styles[1])) {
16804								$dom[$key]['border']['R']['cap'] = 'square';
16805								$dom[$key]['border']['R']['join'] = 'miter';
16806								$dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
16807								if ($dom[$key]['border']['R']['dash'] < 0) {
16808									$dom[$key]['border']['R'] = array();
16809								}
16810							}
16811							if (isset($brd_styles[0])) {
16812								$dom[$key]['border']['T']['cap'] = 'square';
16813								$dom[$key]['border']['T']['join'] = 'miter';
16814								$dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
16815								if ($dom[$key]['border']['T']['dash'] < 0) {
16816									$dom[$key]['border']['T'] = array();
16817								}
16818							}
16819							if (isset($brd_styles[2])) {
16820								$dom[$key]['border']['B']['cap'] = 'square';
16821								$dom[$key]['border']['B']['join'] = 'miter';
16822								$dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
16823								if ($dom[$key]['border']['B']['dash'] < 0) {
16824									$dom[$key]['border']['B'] = array();
16825								}
16826							}
16827						}
16828						$cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
16829						foreach ($cellside as $bsk => $bsv) {
16830							if (isset($dom[$key]['style']['border-'.$bsv])) {
16831								$borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
16832								if (!empty($borderstyle)) {
16833									$dom[$key]['border'][$bsk] = $borderstyle;
16834								}
16835							}
16836							if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
16837								$dom[$key]['border'][$bsk]['color'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color'], $this->spot_colors);
16838							}
16839							if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
16840								$dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
16841							}
16842							if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
16843								$dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
16844								if ($dom[$key]['border'][$bsk]['dash'] < 0) {
16845									$dom[$key]['border'][$bsk] = array();
16846								}
16847							}
16848						}
16849						// check for CSS padding properties
16850						if (isset($dom[$key]['style']['padding'])) {
16851							$dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
16852						} else {
16853							$dom[$key]['padding'] = $this->cell_padding;
16854						}
16855						foreach ($cellside as $psk => $psv) {
16856							if (isset($dom[$key]['style']['padding-'.$psv])) {
16857								$dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
16858							}
16859						}
16860						// check for CSS margin properties
16861						if (isset($dom[$key]['style']['margin'])) {
16862							$dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
16863						} else {
16864							$dom[$key]['margin'] = $this->cell_margin;
16865						}
16866						foreach ($cellside as $psk => $psv) {
16867							if (isset($dom[$key]['style']['margin-'.$psv])) {
16868								$dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
16869							}
16870						}
16871						// check for CSS border-spacing properties
16872						if (isset($dom[$key]['style']['border-spacing'])) {
16873							$dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
16874						}
16875						// page-break-inside
16876						if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
16877							$dom[$key]['attribute']['nobr'] = 'true';
16878						}
16879						// page-break-before
16880						if (isset($dom[$key]['style']['page-break-before'])) {
16881							if ($dom[$key]['style']['page-break-before'] == 'always') {
16882								$dom[$key]['attribute']['pagebreak'] = 'true';
16883							} elseif ($dom[$key]['style']['page-break-before'] == 'left') {
16884								$dom[$key]['attribute']['pagebreak'] = 'left';
16885							} elseif ($dom[$key]['style']['page-break-before'] == 'right') {
16886								$dom[$key]['attribute']['pagebreak'] = 'right';
16887							}
16888						}
16889						// page-break-after
16890						if (isset($dom[$key]['style']['page-break-after'])) {
16891							if ($dom[$key]['style']['page-break-after'] == 'always') {
16892								$dom[$key]['attribute']['pagebreakafter'] = 'true';
16893							} elseif ($dom[$key]['style']['page-break-after'] == 'left') {
16894								$dom[$key]['attribute']['pagebreakafter'] = 'left';
16895							} elseif ($dom[$key]['style']['page-break-after'] == 'right') {
16896								$dom[$key]['attribute']['pagebreakafter'] = 'right';
16897							}
16898						}
16899					}
16900					if (isset($dom[$key]['attribute']['display'])) {
16901						$dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
16902					}
16903					if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
16904						$borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
16905						if (!empty($borderstyle)) {
16906							$dom[$key]['border']['LTRB'] = $borderstyle;
16907						}
16908					}
16909					// check for font tag
16910					if ($dom[$key]['value'] == 'font') {
16911						// font family
16912						if (isset($dom[$key]['attribute']['face'])) {
16913							$dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
16914						}
16915						// font size
16916						if (isset($dom[$key]['attribute']['size'])) {
16917							if ($key > 0) {
16918								if ($dom[$key]['attribute']['size'][0] == '+') {
16919									$dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
16920								} elseif ($dom[$key]['attribute']['size'][0] == '-') {
16921									$dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
16922								} else {
16923									$dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
16924								}
16925							} else {
16926								$dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
16927							}
16928						}
16929					}
16930					// force natural alignment for lists
16931					if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
16932						AND (!isset($dom[$key]['align']) OR TCPDF_STATIC::empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
16933						if ($this->rtl) {
16934							$dom[$key]['align'] = 'R';
16935						} else {
16936							$dom[$key]['align'] = 'L';
16937						}
16938					}
16939					if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
16940						if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
16941							$dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
16942						}
16943					}
16944					if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
16945						$dom[$key]['fontstyle'] .= 'B';
16946					}
16947					if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
16948						$dom[$key]['fontstyle'] .= 'I';
16949					}
16950					if ($dom[$key]['value'] == 'u') {
16951						$dom[$key]['fontstyle'] .= 'U';
16952					}
16953					if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
16954						$dom[$key]['fontstyle'] .= 'D';
16955					}
16956					if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
16957						$dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
16958					}
16959					if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
16960						$dom[$key]['fontname'] = $this->default_monospaced_font;
16961					}
16962					if (!empty($dom[$key]['value']) AND ($dom[$key]['value'][0] == 'h') AND (intval($dom[$key]['value'][1]) > 0) AND (intval($dom[$key]['value'][1]) < 7)) {
16963						// headings h1, h2, h3, h4, h5, h6
16964						if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
16965							$headsize = (4 - intval($dom[$key]['value'][1])) * 2;
16966							$dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
16967						}
16968						if (!isset($dom[$key]['style']['font-weight'])) {
16969							$dom[$key]['fontstyle'] .= 'B';
16970						}
16971					}
16972					if (($dom[$key]['value'] == 'table')) {
16973						$dom[$key]['rows'] = 0; // number of rows
16974						$dom[$key]['trids'] = array(); // IDs of TR elements
16975						$dom[$key]['thead'] = ''; // table header rows
16976					}
16977					if (($dom[$key]['value'] == 'tr')) {
16978						$dom[$key]['cols'] = 0;
16979						if ($thead) {
16980							$dom[$key]['thead'] = true;
16981							// rows on thead block are printed as a separate table
16982						} else {
16983							$dom[$key]['thead'] = false;
16984							// store the number of rows on table element
16985							++$dom[($dom[$key]['parent'])]['rows'];
16986							// store the TR elements IDs on table element
16987							array_push($dom[($dom[$key]['parent'])]['trids'], $key);
16988						}
16989					}
16990					if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
16991						if (isset($dom[$key]['attribute']['colspan'])) {
16992							$colspan = intval($dom[$key]['attribute']['colspan']);
16993						} else {
16994							$colspan = 1;
16995						}
16996						$dom[$key]['attribute']['colspan'] = $colspan;
16997						$dom[($dom[$key]['parent'])]['cols'] += $colspan;
16998					}
16999					// text direction
17000					if (isset($dom[$key]['attribute']['dir'])) {
17001						$dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
17002					}
17003					// set foreground color attribute
17004					if (isset($dom[$key]['attribute']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['color']))) {
17005						$dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['color'], $this->spot_colors);
17006					} elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
17007						$dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
17008					}
17009					// set background color attribute
17010					if (isset($dom[$key]['attribute']['bgcolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['bgcolor']))) {
17011						$dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['bgcolor'], $this->spot_colors);
17012					}
17013					// set stroke color attribute
17014					if (isset($dom[$key]['attribute']['strokecolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['strokecolor']))) {
17015						$dom[$key]['strokecolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['strokecolor'], $this->spot_colors);
17016					}
17017					// check for width attribute
17018					if (isset($dom[$key]['attribute']['width'])) {
17019						$dom[$key]['width'] = $dom[$key]['attribute']['width'];
17020					}
17021					// check for height attribute
17022					if (isset($dom[$key]['attribute']['height'])) {
17023						$dom[$key]['height'] = $dom[$key]['attribute']['height'];
17024					}
17025					// check for text alignment
17026					if (isset($dom[$key]['attribute']['align']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
17027						$dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align'][0]);
17028					}
17029					// check for text rendering mode (the following attributes do not exist in HTML)
17030					if (isset($dom[$key]['attribute']['stroke'])) {
17031						// font stroke width
17032						$dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
17033					}
17034					if (isset($dom[$key]['attribute']['fill'])) {
17035						// font fill
17036						if ($dom[$key]['attribute']['fill'] == 'true') {
17037							$dom[$key]['fill'] = true;
17038						} else {
17039							$dom[$key]['fill'] = false;
17040						}
17041					}
17042					if (isset($dom[$key]['attribute']['clip'])) {
17043						// clipping mode
17044						if ($dom[$key]['attribute']['clip'] == 'true') {
17045							$dom[$key]['clip'] = true;
17046						} else {
17047							$dom[$key]['clip'] = false;
17048						}
17049					}
17050				} // end opening tag
17051			} else {
17052				// text
17053				$dom[$key]['tag'] = false;
17054				$dom[$key]['block'] = false;
17055				$dom[$key]['parent'] = end($level);
17056				$dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
17057				if (!empty($dom[$dom[$key]['parent']]['text-transform'])) {
17058					// text-transform for unicode requires mb_convert_case (Multibyte String Functions)
17059					if (function_exists('mb_convert_case')) {
17060						$ttm = array('capitalize' => MB_CASE_TITLE, 'uppercase' => MB_CASE_UPPER, 'lowercase' => MB_CASE_LOWER);
17061						if (isset($ttm[$dom[$dom[$key]['parent']]['text-transform']])) {
17062							$element = mb_convert_case($element, $ttm[$dom[$dom[$key]['parent']]['text-transform']], $this->encoding);
17063						}
17064					} elseif (!$this->isunicode) {
17065						switch ($dom[$dom[$key]['parent']]['text-transform']) {
17066							case 'capitalize': {
17067								$element = ucwords(strtolower($element));
17068								break;
17069							}
17070							case 'uppercase': {
17071								$element = strtoupper($element);
17072								break;
17073							}
17074							case 'lowercase': {
17075								$element = strtolower($element);
17076								break;
17077							}
17078						}
17079					}
17080				}
17081				$dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
17082			}
17083			++$elkey;
17084			++$key;
17085		}
17086		return $dom;
17087	}
17088
17089	/**
17090	 * Returns the string used to find spaces
17091	 * @return string
17092	 * @protected
17093	 * @author Nicola Asuni
17094	 * @since 4.8.024 (2010-01-15)
17095	 */
17096	protected function getSpaceString() {
17097		$spacestr = chr(32);
17098		if ($this->isUnicodeFont()) {
17099			$spacestr = chr(0).chr(32);
17100		}
17101		return $spacestr;
17102	}
17103
17104	/**
17105	 * Return an hash code used to ensure that the serialized data has been generated by this TCPDF instance.
17106	 * @param $data (string) serialized data
17107	 * @return string
17108	 * @public static
17109	 */
17110	protected function getHashForTCPDFtagParams($data) {
17111		return md5(strlen($data).$this->file_id.$data);
17112	}
17113
17114	/**
17115	 * Serialize an array of parameters to be used with TCPDF tag in HTML code.
17116	 * @param $data (array) parameters array
17117	 * @return string containing serialized data
17118	 * @public static
17119	 */
17120	public function serializeTCPDFtagParameters($data) {
17121		$encoded = urlencode(json_encode($data));
17122		return $this->getHashForTCPDFtagParams($encoded).$encoded;
17123	}
17124
17125	/**
17126	 * Unserialize parameters to be used with TCPDF tag in HTML code.
17127	 * @param $data (string) serialized data
17128	 * @return array containing unserialized data
17129	 * @protected static
17130	 */
17131	protected function unserializeTCPDFtagParameters($data) {
17132		$hash = substr($data, 0, 32);
17133		$encoded = substr($data, 32);
17134		if ($hash != $this->getHashForTCPDFtagParams($encoded)) {
17135			$this->Error('Invalid parameters');
17136		}
17137		return json_decode(urldecode($encoded), true);
17138	}
17139
17140	/**
17141	 * Prints a cell (rectangular area) with optional borders, background color and html text string.
17142	 * 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 />
17143	 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
17144	 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
17145	 * Supported tags are: a, b, blockquote, br, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, li, ol, p, pre, small, span, strong, sub, sup, table, tcpdf, td, th, thead, tr, tt, u, ul
17146	 * NOTE: all the HTML attributes must be enclosed in double-quote.
17147	 * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
17148	 * @param $h (float) Cell minimum height. The cell extends automatically if needed.
17149	 * @param $x (float) upper-left corner X coordinate
17150	 * @param $y (float) upper-left corner Y coordinate
17151	 * @param $html (string) html text to print. Default value: empty string.
17152	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
17153	 * @param $ln (int) 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>
17154Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
17155	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
17156	 * @param $reseth (boolean) if true reset the last cell height (default true).
17157	 * @param $align (string) 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>
17158	 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
17159	 * @see Multicell(), writeHTML()
17160	 * @public
17161	 */
17162	public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
17163		return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
17164	}
17165
17166	/**
17167	 * Allows to preserve some HTML formatting (limited support).<br />
17168	 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
17169	 * Supported tags are: a, b, blockquote, br, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, li, ol, p, pre, small, span, strong, sub, sup, table, tcpdf, td, th, thead, tr, tt, u, ul
17170	 * NOTE: all the HTML attributes must be enclosed in double-quote.
17171	 * @param $html (string) text to display
17172	 * @param $ln (boolean) if true add a new line after text (default = true)
17173	 * @param $fill (boolean) Indicates if the background must be painted (true) or transparent (false).
17174	 * @param $reseth (boolean) if true reset the last cell height (default false).
17175	 * @param $cell (boolean) if true add the current left (or right for RTL) padding to each Write (default false).
17176	 * @param $align (string) 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>
17177	 * @public
17178	 */
17179	public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
17180		$gvars = $this->getGraphicVars();
17181		// store current values
17182		$prev_cell_margin = $this->cell_margin;
17183		$prev_cell_padding = $this->cell_padding;
17184		$prevPage = $this->page;
17185		$prevlMargin = $this->lMargin;
17186		$prevrMargin = $this->rMargin;
17187		$curfontname = $this->FontFamily;
17188		$curfontstyle = $this->FontStyle;
17189		$curfontsize = $this->FontSizePt;
17190		$curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
17191		$curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
17192		$curfontstretcing = $this->font_stretching;
17193		$curfonttracking = $this->font_spacing;
17194		$this->newline = true;
17195		$newline = true;
17196		$startlinepage = $this->page;
17197		$minstartliney = $this->y;
17198		$maxbottomliney = 0;
17199		$startlinex = $this->x;
17200		$startliney = $this->y;
17201		$yshift = 0;
17202		$loop = 0;
17203		$curpos = 0;
17204		$this_method_vars = array();
17205		$undo = false;
17206		$fontaligned = false;
17207		$reverse_dir = false; // true when the text direction is reversed
17208		$this->premode = false;
17209		if ($this->inxobj) {
17210			// we are inside an XObject template
17211			$pask = count($this->xobjects[$this->xobjid]['annotations']);
17212		} elseif (isset($this->PageAnnots[$this->page])) {
17213			$pask = count($this->PageAnnots[$this->page]);
17214		} else {
17215			$pask = 0;
17216		}
17217		if ($this->inxobj) {
17218			// we are inside an XObject template
17219			$startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
17220		} elseif (!$this->InFooter) {
17221			if (isset($this->footerlen[$this->page])) {
17222				$this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
17223			} else {
17224				$this->footerpos[$this->page] = $this->pagelen[$this->page];
17225			}
17226			$startlinepos = $this->footerpos[$this->page];
17227		} else {
17228			// we are inside the footer
17229			$startlinepos = $this->pagelen[$this->page];
17230		}
17231		$lalign = $align;
17232		$plalign = $align;
17233		if ($this->rtl) {
17234			$w = $this->x - $this->lMargin;
17235		} else {
17236			$w = $this->w - $this->rMargin - $this->x;
17237		}
17238		$w -= ($this->cell_padding['L'] + $this->cell_padding['R']);
17239		if ($cell) {
17240			if ($this->rtl) {
17241				$this->x -= $this->cell_padding['R'];
17242				$this->lMargin += $this->cell_padding['L'];
17243			} else {
17244				$this->x += $this->cell_padding['L'];
17245				$this->rMargin += $this->cell_padding['R'];
17246			}
17247		}
17248		if ($this->customlistindent >= 0) {
17249			$this->listindent = $this->customlistindent;
17250		} else {
17251			$this->listindent = $this->GetStringWidth('000000');
17252		}
17253		$this->listindentlevel = 0;
17254		// save previous states
17255		$prev_cell_height_ratio = $this->cell_height_ratio;
17256		$prev_listnum = $this->listnum;
17257		$prev_listordered = $this->listordered;
17258		$prev_listcount = $this->listcount;
17259		$prev_lispacer = $this->lispacer;
17260		$this->listnum = 0;
17261		$this->listordered = array();
17262		$this->listcount = array();
17263		$this->lispacer = '';
17264		if ((TCPDF_STATIC::empty_string($this->lasth)) OR ($reseth)) {
17265			// reset row height
17266			$this->resetLastH();
17267		}
17268		$dom = $this->getHtmlDomArray($html);
17269		$maxel = count($dom);
17270		$key = 0;
17271		while ($key < $maxel) {
17272			if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND $dom[$key]['hide']) {
17273				// store the node key
17274				$hidden_node_key = $key;
17275				if ($dom[$key]['self']) {
17276					// skip just this self-closing tag
17277					++$key;
17278				} else {
17279					// skip this and all children tags
17280					while (($key < $maxel) AND (!$dom[$key]['tag'] OR $dom[$key]['opening'] OR ($dom[$key]['parent'] != $hidden_node_key))) {
17281						// skip hidden objects
17282						++$key;
17283					}
17284					++$key;
17285				}
17286			}
17287			if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
17288				// check for pagebreak
17289				if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
17290					// add a page (or trig AcceptPageBreak() for multicolumn mode)
17291					$this->checkPageBreak($this->PageBreakTrigger + 1);
17292					$this->htmlvspace = ($this->PageBreakTrigger + 1);
17293				}
17294				if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
17295					OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
17296					// add a page (or trig AcceptPageBreak() for multicolumn mode)
17297					$this->checkPageBreak($this->PageBreakTrigger + 1);
17298					$this->htmlvspace = ($this->PageBreakTrigger + 1);
17299				}
17300			}
17301			if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
17302				if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
17303					$dom[$key]['attribute']['nobr'] = false;
17304				} else {
17305					// store current object
17306					$this->startTransaction();
17307					// save this method vars
17308					$this_method_vars['html'] = $html;
17309					$this_method_vars['ln'] = $ln;
17310					$this_method_vars['fill'] = $fill;
17311					$this_method_vars['reseth'] = $reseth;
17312					$this_method_vars['cell'] = $cell;
17313					$this_method_vars['align'] = $align;
17314					$this_method_vars['gvars'] = $gvars;
17315					$this_method_vars['prevPage'] = $prevPage;
17316					$this_method_vars['prev_cell_margin'] = $prev_cell_margin;
17317					$this_method_vars['prev_cell_padding'] = $prev_cell_padding;
17318					$this_method_vars['prevlMargin'] = $prevlMargin;
17319					$this_method_vars['prevrMargin'] = $prevrMargin;
17320					$this_method_vars['curfontname'] = $curfontname;
17321					$this_method_vars['curfontstyle'] = $curfontstyle;
17322					$this_method_vars['curfontsize'] = $curfontsize;
17323					$this_method_vars['curfontascent'] = $curfontascent;
17324					$this_method_vars['curfontdescent'] = $curfontdescent;
17325					$this_method_vars['curfontstretcing'] = $curfontstretcing;
17326					$this_method_vars['curfonttracking'] = $curfonttracking;
17327					$this_method_vars['minstartliney'] = $minstartliney;
17328					$this_method_vars['maxbottomliney'] = $maxbottomliney;
17329					$this_method_vars['yshift'] = $yshift;
17330					$this_method_vars['startlinepage'] = $startlinepage;
17331					$this_method_vars['startlinepos'] = $startlinepos;
17332					$this_method_vars['startlinex'] = $startlinex;
17333					$this_method_vars['startliney'] = $startliney;
17334					$this_method_vars['newline'] = $newline;
17335					$this_method_vars['loop'] = $loop;
17336					$this_method_vars['curpos'] = $curpos;
17337					$this_method_vars['pask'] = $pask;
17338					$this_method_vars['lalign'] = $lalign;
17339					$this_method_vars['plalign'] = $plalign;
17340					$this_method_vars['w'] = $w;
17341					$this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
17342					$this_method_vars['prev_listnum'] = $prev_listnum;
17343					$this_method_vars['prev_listordered'] = $prev_listordered;
17344					$this_method_vars['prev_listcount'] = $prev_listcount;
17345					$this_method_vars['prev_lispacer'] = $prev_lispacer;
17346					$this_method_vars['fontaligned'] = $fontaligned;
17347					$this_method_vars['key'] = $key;
17348					$this_method_vars['dom'] = $dom;
17349				}
17350			}
17351			// print THEAD block
17352			if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
17353				if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !TCPDF_STATIC::empty_string($dom[$dom[$key]['parent']]['thead'])) {
17354					$this->inthead = true;
17355					// print table header (thead)
17356					$this->writeHTML($this->thead, false, false, false, false, '');
17357					// check if we are on a new page or on a new column
17358					if (($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) {
17359						// we are on a new page or on a new column and the total object height is less than the available vertical space.
17360						// restore previous object
17361						$this->rollbackTransaction(true);
17362						// restore previous values
17363						foreach ($this_method_vars as $vkey => $vval) {
17364							$$vkey = $vval;
17365						}
17366						// disable table header
17367						$tmp_thead = $this->thead;
17368						$this->thead = '';
17369						// add a page (or trig AcceptPageBreak() for multicolumn mode)
17370						$pre_y = $this->y;
17371						if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
17372							// fix for multicolumn mode
17373							$startliney = $this->y;
17374						}
17375						$this->start_transaction_page = $this->page;
17376						$this->start_transaction_y = $this->y;
17377						// restore table header
17378						$this->thead = $tmp_thead;
17379						// fix table border properties
17380						if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
17381							$tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
17382						} elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
17383							$tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
17384						} else {
17385							$tmp_cellspacing = 0;
17386						}
17387						$dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page;
17388						$dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column;
17389						$dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing;
17390						$xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']);
17391						$dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset;
17392						$dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset;
17393						// print table header (thead)
17394						$this->writeHTML($this->thead, false, false, false, false, '');
17395					}
17396				}
17397				// move $key index forward to skip THEAD block
17398				while ( ($key < $maxel) AND (!(
17399					($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
17400					OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
17401					++$key;
17402				}
17403			}
17404			if ($dom[$key]['tag'] OR ($key == 0)) {
17405				if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
17406					$dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
17407				}
17408				// vertically align image in line
17409				if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
17410					// get image height
17411					$imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], ($dom[$key]['fontsize'] / $this->k), 'px');
17412					$autolinebreak = false;
17413					if (!empty($dom[$key]['width'])) {
17414						$imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], ($dom[$key]['fontsize'] / $this->k), 'px', false);
17415						if (($imgw <= ($this->w - $this->lMargin - $this->rMargin - $this->cell_padding['L'] - $this->cell_padding['R']))
17416							AND ((($this->rtl) AND (($this->x - $imgw) < ($this->lMargin + $this->cell_padding['L'])))
17417							OR ((!$this->rtl) AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cell_padding['R']))))) {
17418							// add automatic line break
17419							$autolinebreak = true;
17420							$this->Ln('', $cell);
17421							if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
17422								// go back to evaluate this line break
17423								--$key;
17424							}
17425						}
17426					}
17427					if (!$autolinebreak) {
17428						if ($this->inPageBody()) {
17429							$pre_y = $this->y;
17430							// check for page break
17431							if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) {
17432								// fix for multicolumn mode
17433								$startliney = $this->y;
17434							}
17435						}
17436						if ($this->page > $startlinepage) {
17437							// fix line splitted over two pages
17438							if (isset($this->footerlen[$startlinepage])) {
17439								$curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17440							}
17441							// line to be moved one page forward
17442							$pagebuff = $this->getPageBuffer($startlinepage);
17443							$linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
17444							$tstart = substr($pagebuff, 0, $startlinepos);
17445							$tend = substr($this->getPageBuffer($startlinepage), $curpos);
17446							// remove line from previous page
17447							$this->setPageBuffer($startlinepage, $tstart.''.$tend);
17448							$pagebuff = $this->getPageBuffer($this->page);
17449							$tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
17450							$tend = substr($pagebuff, $this->cntmrk[$this->page]);
17451							// add line start to current page
17452							$yshift = ($minstartliney - $this->y);
17453							if ($fontaligned) {
17454								$yshift += ($curfontsize / $this->k);
17455							}
17456							$try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
17457							$this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
17458							// shift the annotations and links
17459							if (isset($this->PageAnnots[$this->page])) {
17460								$next_pask = count($this->PageAnnots[$this->page]);
17461							} else {
17462								$next_pask = 0;
17463							}
17464							if (isset($this->PageAnnots[$startlinepage])) {
17465								foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
17466									if ($pak >= $pask) {
17467										$this->PageAnnots[$this->page][] = $pac;
17468										unset($this->PageAnnots[$startlinepage][$pak]);
17469										$npak = count($this->PageAnnots[$this->page]) - 1;
17470										$this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
17471									}
17472								}
17473							}
17474							$pask = $next_pask;
17475							$startlinepos = $this->cntmrk[$this->page];
17476							$startlinepage = $this->page;
17477							$startliney = $this->y;
17478							$this->newline = false;
17479						}
17480						$this->y += ($this->getCellHeight($curfontsize / $this->k) - ($curfontdescent * $this->cell_height_ratio) - $imgh);
17481						$minstartliney = min($this->y, $minstartliney);
17482						$maxbottomliney = ($startliney + $this->getCellHeight($curfontsize / $this->k));
17483					}
17484				} elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
17485					// account for different font size
17486					$pfontname = $curfontname;
17487					$pfontstyle = $curfontstyle;
17488					$pfontsize = $curfontsize;
17489					$fontname = (isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname);
17490					$fontstyle = (isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle);
17491					$fontsize = (isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize);
17492					$fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
17493					$fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
17494					if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
17495						OR ($this->cell_height_ratio != $dom[$key]['line-height'])
17496						OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
17497						if (($key < ($maxel - 1)) AND (
17498								($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
17499								OR ($this->cell_height_ratio != $dom[$key]['line-height'])
17500								OR (!$this->newline AND is_numeric($fontsize) AND is_numeric($curfontsize)
17501								AND ($fontsize >= 0) AND ($curfontsize >= 0)
17502								AND (($fontsize != $curfontsize) OR ($fontstyle != $curfontstyle) OR ($fontname != $curfontname)))
17503							)) {
17504							if ($this->page > $startlinepage) {
17505								// fix lines splitted over two pages
17506								if (isset($this->footerlen[$startlinepage])) {
17507									$curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17508								}
17509								// line to be moved one page forward
17510								$pagebuff = $this->getPageBuffer($startlinepage);
17511								$linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
17512								$tstart = substr($pagebuff, 0, $startlinepos);
17513								$tend = substr($this->getPageBuffer($startlinepage), $curpos);
17514								// remove line start from previous page
17515								$this->setPageBuffer($startlinepage, $tstart.''.$tend);
17516								$pagebuff = $this->getPageBuffer($this->page);
17517								$tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
17518								$tend = substr($pagebuff, $this->cntmrk[$this->page]);
17519								// add line start to current page
17520								$yshift = ($minstartliney - $this->y);
17521								$try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
17522								$this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
17523								// shift the annotations and links
17524								if (isset($this->PageAnnots[$this->page])) {
17525									$next_pask = count($this->PageAnnots[$this->page]);
17526								} else {
17527									$next_pask = 0;
17528								}
17529								if (isset($this->PageAnnots[$startlinepage])) {
17530									foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
17531										if ($pak >= $pask) {
17532											$this->PageAnnots[$this->page][] = $pac;
17533											unset($this->PageAnnots[$startlinepage][$pak]);
17534											$npak = count($this->PageAnnots[$this->page]) - 1;
17535											$this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
17536										}
17537									}
17538								}
17539								$pask = $next_pask;
17540								$startlinepos = $this->cntmrk[$this->page];
17541								$startlinepage = $this->page;
17542								$startliney = $this->y;
17543							}
17544							if (!isset($dom[$key]['line-height'])) {
17545								$dom[$key]['line-height'] = $this->cell_height_ratio;
17546							}
17547							if (!$dom[$key]['block']) {
17548								if (!(isset($dom[($key + 1)]) AND $dom[($key + 1)]['tag'] AND (!$dom[($key + 1)]['opening']) AND ($dom[($key + 1)]['value'] != 'li') AND $dom[$key]['tag'] AND (!$dom[$key]['opening']))) {
17549									$this->y += (((($curfontsize * $this->cell_height_ratio) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2;
17550								}
17551								if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
17552									$current_line_align_data = array($key, $minstartliney, $maxbottomliney);
17553									if (isset($line_align_data) AND (($line_align_data[0] == ($key - 1)) OR (($line_align_data[0] == ($key - 2)) AND (isset($dom[($key - 1)])) AND (preg_match('/^([\s]+)$/', $dom[($key - 1)]['value']) > 0)))) {
17554										$minstartliney = min($this->y, $line_align_data[1]);
17555										$maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $line_align_data[2]);
17556									} else {
17557										$minstartliney = min($this->y, $minstartliney);
17558										$maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $maxbottomliney);
17559									}
17560									$line_align_data = $current_line_align_data;
17561								}
17562							}
17563							$this->cell_height_ratio = $dom[$key]['line-height'];
17564							$fontaligned = true;
17565						}
17566						$this->SetFont($fontname, $fontstyle, $fontsize);
17567						// reset row height
17568						$this->resetLastH();
17569						$curfontname = $fontname;
17570						$curfontstyle = $fontstyle;
17571						$curfontsize = $fontsize;
17572						$curfontascent = $fontascent;
17573						$curfontdescent = $fontdescent;
17574					}
17575				}
17576				// set text rendering mode
17577				$textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth;
17578				$textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0);
17579				$textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3);
17580				$this->setTextRenderingMode($textstroke, $textfill, $textclip);
17581				if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
17582					$this->setFontStretching($dom[$key]['font-stretch']);
17583				}
17584				if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
17585					$this->setFontSpacing($dom[$key]['letter-spacing']);
17586				}
17587				if (($plalign == 'J') AND $dom[$key]['block']) {
17588					$plalign = '';
17589				}
17590				// get current position on page buffer
17591				$curpos = $this->pagelen[$startlinepage];
17592				if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
17593					$this->SetFillColorArray($dom[$key]['bgcolor']);
17594					$wfill = true;
17595				} else {
17596					$wfill = $fill | false;
17597				}
17598				if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
17599					$this->SetTextColorArray($dom[$key]['fgcolor']);
17600				}
17601				if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
17602					$this->SetDrawColorArray($dom[$key]['strokecolor']);
17603				}
17604				if (isset($dom[$key]['align'])) {
17605					$lalign = $dom[$key]['align'];
17606				}
17607				if (TCPDF_STATIC::empty_string($lalign)) {
17608					$lalign = $align;
17609				}
17610			}
17611			// align lines
17612			if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
17613				$newline = true;
17614				$fontaligned = false;
17615				// we are at the beginning of a new line
17616				if (isset($startlinex)) {
17617					$yshift = ($minstartliney - $startliney);
17618					if (($yshift > 0) OR ($this->page > $startlinepage)) {
17619						$yshift = 0;
17620					}
17621					$t_x = 0;
17622					// the last line must be shifted to be aligned as requested
17623					$linew = abs($this->endlinex - $startlinex);
17624					if ($this->inxobj) {
17625						// we are inside an XObject template
17626						$pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
17627						if (isset($opentagpos)) {
17628							$midpos = $opentagpos;
17629						} else {
17630							$midpos = 0;
17631						}
17632						if ($midpos > 0) {
17633							$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
17634							$pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
17635						} else {
17636							$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
17637							$pend = '';
17638						}
17639					} else {
17640						$pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
17641						if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
17642							$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17643							$midpos = min($opentagpos, $this->footerpos[$startlinepage]);
17644						} elseif (isset($opentagpos)) {
17645							$midpos = $opentagpos;
17646						} elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
17647							$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17648							$midpos = $this->footerpos[$startlinepage];
17649						} else {
17650							$midpos = 0;
17651						}
17652						if ($midpos > 0) {
17653							$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
17654							$pend = substr($this->getPageBuffer($startlinepage), $midpos);
17655						} else {
17656							$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
17657							$pend = '';
17658						}
17659					}
17660					if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
17661						// calculate shifting amount
17662						$tw = $w;
17663						if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) {
17664							$tw += $this->cell_padding['R'];
17665						}
17666						if ($this->lMargin != $prevlMargin) {
17667							$tw += ($prevlMargin - $this->lMargin);
17668						}
17669						if ($this->rMargin != $prevrMargin) {
17670							$tw += ($prevrMargin - $this->rMargin);
17671						}
17672						$one_space_width = $this->GetStringWidth(chr(32));
17673						$no = 0; // number of spaces on a line contained on a single block
17674						if ($this->isRTLTextDir()) { // RTL
17675							// remove left space if exist
17676							$pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
17677							if ($pos1 > 0) {
17678								$pos1 = intval($pos1);
17679								if ($this->isUnicodeFont()) {
17680									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
17681									$spacelen = 2;
17682								} else {
17683									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
17684									$spacelen = 1;
17685								}
17686								if ($pos1 == $pos2) {
17687									$pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
17688									if (substr($pmid, $pos1, 4) == '[()]') {
17689										$linew -= $one_space_width;
17690									} elseif ($pos1 == strpos($pmid, '[(')) {
17691										$no = 1;
17692									}
17693								}
17694							}
17695						} else { // LTR
17696							// remove right space if exist
17697							$pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
17698							if ($pos1 > 0) {
17699								$pos1 = intval($pos1);
17700								if ($this->isUnicodeFont()) {
17701									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
17702									$spacelen = 2;
17703								} else {
17704									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
17705									$spacelen = 1;
17706								}
17707								if ($pos1 == $pos2) {
17708									$pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
17709									$linew -= $one_space_width;
17710								}
17711							}
17712						}
17713						$mdiff = ($tw - $linew);
17714						if ($plalign == 'C') {
17715							if ($this->rtl) {
17716								$t_x = -($mdiff / 2);
17717							} else {
17718								$t_x = ($mdiff / 2);
17719							}
17720						} elseif ($plalign == 'R') {
17721							// right alignment on LTR document
17722							$t_x = $mdiff;
17723						} elseif ($plalign == 'L') {
17724							// left alignment on RTL document
17725							$t_x = -$mdiff;
17726						} elseif (($plalign == 'J') AND ($plalign == $lalign)) {
17727							// Justification
17728							if ($this->isRTLTextDir()) {
17729								// align text on the left
17730								$t_x = -$mdiff;
17731							}
17732							$ns = 0; // number of spaces
17733							$pmidtemp = $pmid;
17734							// escape special characters
17735							$pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
17736							$pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
17737							// search spaces
17738							if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
17739								$spacestr = $this->getSpaceString();
17740								$maxkk = count($lnstring[1]) - 1;
17741								for ($kk=0; $kk <= $maxkk; ++$kk) {
17742									// restore special characters
17743									$lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
17744									$lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
17745									// store number of spaces on the strings
17746									$lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
17747									// count total spaces on line
17748									$ns += $lnstring[2][$kk];
17749									$lnstring[3][$kk] = $ns;
17750								}
17751								if ($ns == 0) {
17752									$ns = 1;
17753								}
17754								// calculate additional space to add to each existing space
17755								$spacewidth = ($mdiff / ($ns - $no)) * $this->k;
17756								if ($this->FontSize <= 0) {
17757									$this->FontSize = 1;
17758								}
17759								$spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize;
17760								if ($this->font_spacing != 0) {
17761									// fixed spacing mode
17762									$osw = -1000 * $this->font_spacing / $this->FontSize;
17763									$spacewidthu += $osw;
17764								}
17765								$nsmax = $ns;
17766								$ns = 0;
17767								reset($lnstring);
17768								$offset = 0;
17769								$strcount = 0;
17770								$prev_epsposbeg = 0;
17771								$textpos = 0;
17772								if ($this->isRTLTextDir()) {
17773									$textpos = $this->wPt;
17774								}
17775								while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
17776									// check if we are inside a string section '[( ... )]'
17777									$stroffset = strpos($pmid, '[(', $offset);
17778									if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
17779										// set offset to the end of string section
17780										$offset = strpos($pmid, ')]', $stroffset);
17781										while (($offset !== false) AND ($pmid[($offset - 1)] == '\\')) {
17782											$offset = strpos($pmid, ')]', ($offset + 1));
17783										}
17784										if ($offset === false) {
17785											$this->Error('HTML Justification: malformed PDF code.');
17786										}
17787										continue;
17788									}
17789									if ($this->isRTLTextDir()) {
17790										$spacew = ($spacewidth * ($nsmax - $ns));
17791									} else {
17792										$spacew = ($spacewidth * $ns);
17793									}
17794									$offset = $strpiece[2][1] + strlen($strpiece[2][0]);
17795									$epsposend = strpos($pmid, $this->epsmarker.'Q', $offset);
17796									if ($epsposend !== null) {
17797										$epsposend += strlen($this->epsmarker.'Q');
17798										$epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
17799										if ($epsposbeg === null) {
17800											$epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
17801											$prev_epsposbeg = $epsposbeg;
17802										}
17803										if (($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend)) {
17804											// shift EPS images
17805											$trx = sprintf('1 0 0 1 %F 0 cm', $spacew);
17806											$pmid_b = substr($pmid, 0, $epsposbeg);
17807											$pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
17808											$pmid_e = substr($pmid, $epsposend);
17809											$pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
17810											$offset = $epsposend;
17811											continue;
17812										}
17813									}
17814									$currentxpos = 0;
17815									// shift blocks of code
17816									switch ($strpiece[2][0]) {
17817										case 'Td':
17818										case 'cm':
17819										case 'm':
17820										case 'l': {
17821											// get current X position
17822											preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
17823											if (!isset($xmatches[1])) {
17824												break;
17825											}
17826											$currentxpos = $xmatches[1];
17827											$textpos = $currentxpos;
17828											if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
17829												$ns = $lnstring[3][$strcount];
17830												if ($this->isRTLTextDir()) {
17831													$spacew = ($spacewidth * ($nsmax - $ns));
17832												}
17833												++$strcount;
17834											}
17835											// justify block
17836											if (preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $pmatch) == 1) {
17837												$newpmid = sprintf('%F',(floatval($pmatch[1]) + $spacew)).' '.$pmatch[2].' x*#!#*x'.$pmatch[3].$pmatch[4];
17838												$pmid = str_replace($pmatch[0], $newpmid, $pmid);
17839												unset($pmatch, $newpmid);
17840											}
17841											break;
17842										}
17843										case 're': {
17844											// justify block
17845											if (!TCPDF_STATIC::empty_string($this->lispacer)) {
17846												$this->lispacer = '';
17847												break;
17848											}
17849											preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
17850											if (!isset($xmatches[1])) {
17851												break;
17852											}
17853											$currentxpos = $xmatches[1];
17854											$x_diff = 0;
17855											$w_diff = 0;
17856											if ($this->isRTLTextDir()) { // RTL
17857												if ($currentxpos < $textpos) {
17858													$x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
17859													$w_diff = ($spacewidth * $lnstring[2][$strcount]);
17860												} else {
17861													if ($strcount > 0) {
17862														$x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
17863														$w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
17864													}
17865												}
17866											} else { // LTR
17867												if ($currentxpos > $textpos) {
17868													if ($strcount > 0) {
17869														$x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
17870													}
17871													$w_diff = ($spacewidth * $lnstring[2][$strcount]);
17872												} else {
17873													if ($strcount > 1) {
17874														$x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
17875													}
17876													if ($strcount > 0) {
17877														$w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
17878													}
17879												}
17880											}
17881											if (preg_match('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $pmatch) == 1) {
17882												$newx = sprintf('%F',(floatval($pmatch[1]) + $x_diff));
17883												$neww = sprintf('%F',(floatval($pmatch[3]) + $w_diff));
17884												$newpmid = $newx.' '.$pmatch[2].' '.$neww.' '.$pmatch[4].' x*#!#*x'.$pmatch[5].$pmatch[6];
17885												$pmid = str_replace($pmatch[0], $newpmid, $pmid);
17886												unset($pmatch, $newpmid, $newx, $neww);
17887											}
17888											break;
17889										}
17890										case 'c': {
17891											// get current X position
17892											preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](c)([\s]*)/x', $pmid, $xmatches);
17893											if (!isset($xmatches[1])) {
17894												break;
17895											}
17896											$currentxpos = $xmatches[1];
17897											// justify block
17898											if (preg_match('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$xmatches[4].')[\s]('.$xmatches[5].')[\s]('.$strpiece[1][0].')[\s](c)([\s]*)/x', $pmid, $pmatch) == 1) {
17899												$newx1 = sprintf('%F',(floatval($pmatch[1]) + $spacew));
17900												$newx2 = sprintf('%F',(floatval($pmatch[3]) + $spacew));
17901												$newx3 = sprintf('%F',(floatval($pmatch[5]) + $spacew));
17902												$newpmid = $newx1.' '.$pmatch[2].' '.$newx2.' '.$pmatch[4].' '.$newx3.' '.$pmatch[6].' x*#!#*x'.$pmatch[7].$pmatch[8];
17903												$pmid = str_replace($pmatch[0], $newpmid, $pmid);
17904												unset($pmatch, $newpmid, $newx1, $newx2, $newx3);
17905											}
17906											break;
17907										}
17908									}
17909									// shift the annotations and links
17910									$cxpos = ($currentxpos / $this->k);
17911									$lmpos = ($this->lMargin + $this->cell_padding['L'] + $this->feps);
17912									if ($this->inxobj) {
17913										// we are inside an XObject template
17914										foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
17915											if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
17916												if ($cxpos > $lmpos) {
17917													$this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += ($spacew / $this->k);
17918													$this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17919												} else {
17920													$this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17921												}
17922												break;
17923											}
17924										}
17925									} elseif (isset($this->PageAnnots[$this->page])) {
17926										foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
17927											if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
17928												if ($cxpos > $lmpos) {
17929													$this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
17930													$this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17931												} else {
17932													$this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17933												}
17934												break;
17935											}
17936										}
17937									}
17938								} // end of while
17939								// remove markers
17940								$pmid = str_replace('x*#!#*x', '', $pmid);
17941								if ($this->isUnicodeFont()) {
17942									// multibyte characters
17943									$spacew = $spacewidthu;
17944									if ($this->font_stretching != 100) {
17945										// word spacing is affected by stretching
17946										$spacew /= ($this->font_stretching / 100);
17947									}
17948									// escape special characters
17949									$pos = 0;
17950									$pmid = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmid);
17951									$pmid = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmid);
17952									if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmid, $pamatch) > 0) {
17953										foreach($pamatch[0] as $pk => $pmatch) {
17954											$replace = $pamatch[1][$pk];
17955											$replace = str_replace('#!#OP#!#', '(', $replace);
17956											$replace = str_replace('#!#CP#!#', ')', $replace);
17957											$newpmid = '[('.str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacew).' (', $replace).')]';
17958											$pos = strpos($pmid, $pmatch, $pos);
17959											if ($pos !== FALSE) {
17960												$pmid = substr_replace($pmid, $newpmid, $pos, strlen($pmatch));
17961											}
17962											++$pos;
17963										}
17964										unset($pamatch);
17965									}
17966									if ($this->inxobj) {
17967										// we are inside an XObject template
17968										$this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\n".$pend;
17969									} else {
17970										$this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
17971									}
17972									$endlinepos = strlen($pstart."\n".$pmid."\n");
17973								} else {
17974									// non-unicode (single-byte characters)
17975									if ($this->font_stretching != 100) {
17976										// word spacing (Tw) is affected by stretching
17977										$spacewidth /= ($this->font_stretching / 100);
17978									}
17979									$rs = sprintf('%F Tw', $spacewidth);
17980									$pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
17981									if ($this->inxobj) {
17982										// we are inside an XObject template
17983										$this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
17984									} else {
17985										$this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
17986									}
17987									$endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
17988								}
17989							}
17990						} // end of J
17991					} // end if $startlinex
17992					if (($t_x != 0) OR ($yshift < 0)) {
17993						// shift the line
17994						$trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
17995						$pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
17996						$endlinepos = strlen($pstart);
17997						if ($this->inxobj) {
17998							// we are inside an XObject template
17999							$this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
18000							foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
18001								if ($pak >= $pask) {
18002									$this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
18003									$this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
18004								}
18005							}
18006						} else {
18007							$this->setPageBuffer($startlinepage, $pstart.$pend);
18008							// shift the annotations and links
18009							if (isset($this->PageAnnots[$this->page])) {
18010								foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
18011									if ($pak >= $pask) {
18012										$this->PageAnnots[$this->page][$pak]['x'] += $t_x;
18013										$this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
18014									}
18015								}
18016							}
18017						}
18018						$this->y -= $yshift;
18019					}
18020				}
18021				$pbrk = $this->checkPageBreak($this->lasth);
18022				$this->newline = false;
18023				$startlinex = $this->x;
18024				$startliney = $this->y;
18025				if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
18026					$startliney -= ((0.3 * $this->FontSizePt) / $this->k);
18027				} elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
18028					$startliney -= (($this->FontSizePt / 0.7) / $this->k);
18029				} else {
18030					$minstartliney = $startliney;
18031					$maxbottomliney = ($this->y + $this->getCellHeight($fontsize / $this->k));
18032				}
18033				$startlinepage = $this->page;
18034				if (isset($endlinepos) AND (!$pbrk)) {
18035					$startlinepos = $endlinepos;
18036				} else {
18037					if ($this->inxobj) {
18038						// we are inside an XObject template
18039						$startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
18040					} elseif (!$this->InFooter) {
18041						if (isset($this->footerlen[$this->page])) {
18042							$this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
18043						} else {
18044							$this->footerpos[$this->page] = $this->pagelen[$this->page];
18045						}
18046						$startlinepos = $this->footerpos[$this->page];
18047					} else {
18048						$startlinepos = $this->pagelen[$this->page];
18049					}
18050				}
18051				unset($endlinepos);
18052				$plalign = $lalign;
18053				if (isset($this->PageAnnots[$this->page])) {
18054					$pask = count($this->PageAnnots[$this->page]);
18055				} else {
18056					$pask = 0;
18057				}
18058				if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
18059					AND (isset($this->emptypagemrk[$this->page]))
18060					AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) {
18061					$this->SetFont($fontname, $fontstyle, $fontsize);
18062					if ($wfill) {
18063						$this->SetFillColorArray($this->bgcolor);
18064					}
18065				}
18066			} // end newline
18067			if (isset($opentagpos)) {
18068				unset($opentagpos);
18069			}
18070			if ($dom[$key]['tag']) {
18071				if ($dom[$key]['opening']) {
18072					// get text indentation (if any)
18073					if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
18074						$this->textindent = $dom[$key]['text-indent'];
18075						$this->newline = true;
18076					}
18077					// table
18078					if (($dom[$key]['value'] == 'table') AND isset($dom[$key]['cols']) AND ($dom[$key]['cols'] > 0)) {
18079						// available page width
18080						if ($this->rtl) {
18081							$wtmp = $this->x - $this->lMargin;
18082						} else {
18083							$wtmp = $this->w - $this->rMargin - $this->x;
18084						}
18085						// get cell spacing
18086						if (isset($dom[$key]['attribute']['cellspacing'])) {
18087							$clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
18088							$cellspacing = array('H' => $clsp, 'V' => $clsp);
18089						} elseif (isset($dom[$key]['border-spacing'])) {
18090							$cellspacing = $dom[$key]['border-spacing'];
18091						} else {
18092							$cellspacing = array('H' => 0, 'V' => 0);
18093						}
18094						// table width
18095						if (isset($dom[$key]['width'])) {
18096							$table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
18097						} else {
18098							$table_width = $wtmp;
18099						}
18100						$table_width -= (2 * $cellspacing['H']);
18101						if (!$this->inthead) {
18102							$this->y += $cellspacing['V'];
18103						}
18104						if ($this->rtl) {
18105							$cellspacingx = -$cellspacing['H'];
18106						} else {
18107							$cellspacingx = $cellspacing['H'];
18108						}
18109						// total table width without cellspaces
18110						$table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
18111						// minimum column width
18112						$table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
18113						// array of custom column widths
18114						$table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
18115					}
18116					// table row
18117					if ($dom[$key]['value'] == 'tr') {
18118						// reset column counter
18119						$colid = 0;
18120					}
18121					// table cell
18122					if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
18123						$trid = $dom[$key]['parent'];
18124						$table_el = $dom[$trid]['parent'];
18125						if (!isset($dom[$table_el]['cols'])) {
18126							$dom[$table_el]['cols'] = $dom[$trid]['cols'];
18127						}
18128						// store border info
18129						$tdborder = 0;
18130						if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
18131							$tdborder = $dom[$key]['border'];
18132						}
18133						$colspan = intval($dom[$key]['attribute']['colspan']);
18134						if ($colspan <= 0) {
18135							$colspan = 1;
18136						}
18137						$old_cell_padding = $this->cell_padding;
18138						if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
18139							$crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
18140							$current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
18141						} elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
18142							$current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
18143						} else {
18144							$current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
18145						}
18146						$this->cell_padding = $current_cell_padding;
18147						if (isset($dom[$key]['height'])) {
18148							// minimum cell height
18149							$cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
18150						} else {
18151							$cellh = 0;
18152						}
18153						if (isset($dom[$key]['content'])) {
18154							$cell_content = $dom[$key]['content'];
18155						} else {
18156							$cell_content = '&nbsp;';
18157						}
18158						$tagtype = $dom[$key]['value'];
18159						$parentid = $key;
18160						while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
18161							// move $key index forward
18162							++$key;
18163						}
18164						if (!isset($dom[$trid]['startpage'])) {
18165							$dom[$trid]['startpage'] = $this->page;
18166						} else {
18167							$this->setPage($dom[$trid]['startpage']);
18168						}
18169						if (!isset($dom[$trid]['startcolumn'])) {
18170							$dom[$trid]['startcolumn'] = $this->current_column;
18171						} elseif ($this->current_column != $dom[$trid]['startcolumn']) {
18172							$tmpx = $this->x;
18173							$this->selectColumn($dom[$trid]['startcolumn']);
18174							$this->x = $tmpx;
18175						}
18176						if (!isset($dom[$trid]['starty'])) {
18177							$dom[$trid]['starty'] = $this->y;
18178						} else {
18179							$this->y = $dom[$trid]['starty'];
18180						}
18181						if (!isset($dom[$trid]['startx'])) {
18182							$dom[$trid]['startx'] = $this->x;
18183							$this->x += $cellspacingx;
18184						} else {
18185							$this->x += ($cellspacingx / 2);
18186						}
18187						if (isset($dom[$parentid]['attribute']['rowspan'])) {
18188							$rowspan = intval($dom[$parentid]['attribute']['rowspan']);
18189						} else {
18190							$rowspan = 1;
18191						}
18192						// skip row-spanned cells started on the previous rows
18193						if (isset($dom[$table_el]['rowspans'])) {
18194							$rsk = 0;
18195							$rskmax = count($dom[$table_el]['rowspans']);
18196							while ($rsk < $rskmax) {
18197								$trwsp = $dom[$table_el]['rowspans'][$rsk];
18198								$rsstartx = $trwsp['startx'];
18199								$rsendx = $trwsp['endx'];
18200								// account for margin changes
18201								if ($trwsp['startpage'] < $this->page) {
18202									if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
18203										$dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
18204										$rsstartx -= $dl;
18205										$rsendx -= $dl;
18206									} elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
18207										$dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
18208										$rsstartx += $dl;
18209										$rsendx += $dl;
18210									}
18211								}
18212								if (($trwsp['rowspan'] > 0)
18213									AND ($rsstartx > ($this->x - $cellspacing['H'] - $current_cell_padding['L'] - $this->feps))
18214									AND ($rsstartx < ($this->x + $cellspacing['H'] + $current_cell_padding['R'] + $this->feps))
18215									AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) {
18216									// set the starting X position of the current cell
18217									$this->x = $rsendx + $cellspacingx;
18218									// increment column indicator
18219									$colid += $trwsp['colspan'];
18220									if (($trwsp['rowspan'] == 1)
18221										AND (isset($dom[$trid]['endy']))
18222										AND (isset($dom[$trid]['endpage']))
18223										AND (isset($dom[$trid]['endcolumn']))
18224										AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
18225										AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
18226										// set ending Y position for row
18227										$dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
18228										$dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
18229									}
18230									$rsk = 0;
18231								} else {
18232									++$rsk;
18233								}
18234							}
18235						}
18236						if (isset($dom[$parentid]['width'])) {
18237							// user specified width
18238							$cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
18239							$tmpcw = ($cellw / $colspan);
18240							for ($i = 0; $i < $colspan; ++$i) {
18241								$table_colwidths[($colid + $i)] = $tmpcw;
18242							}
18243						} else {
18244							// inherit column width
18245							$cellw = 0;
18246							for ($i = 0; $i < $colspan; ++$i) {
18247								$cellw += (isset($table_colwidths[($colid + $i)]) ? $table_colwidths[($colid + $i)] : 0);
18248							}
18249						}
18250						$cellw += (($colspan - 1) * $cellspacing['H']);
18251						// increment column indicator
18252						$colid += $colspan;
18253						// add rowspan information to table element
18254						if ($rowspan > 1) {
18255							$trsid = array_push($dom[$table_el]['rowspans'], array('trid' => $trid, 'rowspan' => $rowspan, 'mrowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startcolumn' => $this->current_column, 'startx' => $this->x, 'starty' => $this->y));
18256						}
18257						$cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
18258						if ($rowspan > 1) {
18259							$dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
18260						}
18261						// push background colors
18262						if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
18263							$dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
18264						}
18265						// store border info
18266						if (isset($tdborder) AND !empty($tdborder)) {
18267							$dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
18268						}
18269						$prevLastH = $this->lasth;
18270						// store some info for multicolumn mode
18271						if ($this->rtl) {
18272							$this->colxshift['x'] = $this->w - $this->x - $this->rMargin;
18273						} else {
18274							$this->colxshift['x'] = $this->x - $this->lMargin;
18275						}
18276						$this->colxshift['s'] = $cellspacing;
18277						$this->colxshift['p'] = $current_cell_padding;
18278						// ****** write the cell content ******
18279						$this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
18280						// restore some values
18281						$this->colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
18282						$this->lasth = $prevLastH;
18283						$this->cell_padding = $old_cell_padding;
18284						$dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
18285						// update the end of row position
18286						if ($rowspan <= 1) {
18287							if (isset($dom[$trid]['endy'])) {
18288								if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) {
18289									$dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
18290								} elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) {
18291									$dom[$trid]['endy'] = $this->y;
18292								}
18293							} else {
18294								$dom[$trid]['endy'] = $this->y;
18295							}
18296							if (isset($dom[$trid]['endpage'])) {
18297								$dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
18298							} else {
18299								$dom[$trid]['endpage'] = $this->page;
18300							}
18301							if (isset($dom[$trid]['endcolumn'])) {
18302								$dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']);
18303							} else {
18304								$dom[$trid]['endcolumn'] = $this->current_column;
18305							}
18306						} else {
18307							// account for row-spanned cells
18308							$dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
18309							$dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
18310							$dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
18311							$dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column;
18312						}
18313						if (isset($dom[$table_el]['rowspans'])) {
18314							// update endy and endpage on rowspanned cells
18315							foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
18316								if ($trwsp['rowspan'] > 0) {
18317									if (isset($dom[$trid]['endpage'])) {
18318										if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
18319											$dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
18320										} elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
18321											$dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
18322											$dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
18323											$dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
18324										} else {
18325											$dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
18326										}
18327									}
18328								}
18329							}
18330						}
18331						$this->x += ($cellspacingx / 2);
18332					} else {
18333						// opening tag (or self-closing tag)
18334						if (!isset($opentagpos)) {
18335							if ($this->inxobj) {
18336								// we are inside an XObject template
18337								$opentagpos = strlen($this->xobjects[$this->xobjid]['outdata']);
18338							} elseif (!$this->InFooter) {
18339								if (isset($this->footerlen[$this->page])) {
18340									$this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
18341								} else {
18342									$this->footerpos[$this->page] = $this->pagelen[$this->page];
18343								}
18344								$opentagpos = $this->footerpos[$this->page];
18345							}
18346						}
18347						$dom = $this->openHTMLTagHandler($dom, $key, $cell);
18348					}
18349				} else { // closing tag
18350					$prev_numpages = $this->numpages;
18351					$old_bordermrk = $this->bordermrk[$this->page];
18352					$dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
18353					if ($this->bordermrk[$this->page] > $old_bordermrk) {
18354						$startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk);
18355					}
18356					if ($prev_numpages > $this->numpages) {
18357						$startlinepage = $this->page;
18358					}
18359				}
18360			} elseif (strlen($dom[$key]['value']) > 0) {
18361				// print list-item
18362				if (!TCPDF_STATIC::empty_string($this->lispacer) AND ($this->lispacer != '^')) {
18363					$this->SetFont($pfontname, $pfontstyle, $pfontsize);
18364					$this->resetLastH();
18365					$minstartliney = $this->y;
18366					$maxbottomliney = ($startliney + $this->getCellHeight($this->FontSize));
18367					if (is_numeric($pfontsize) AND ($pfontsize > 0)) {
18368						$this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
18369					}
18370					$this->SetFont($curfontname, $curfontstyle, $curfontsize);
18371					$this->resetLastH();
18372					if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
18373						$pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
18374						$pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
18375						$this->y += ($this->getCellHeight(($pfontsize - $curfontsize) / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2;
18376						$minstartliney = min($this->y, $minstartliney);
18377						$maxbottomliney = max(($this->y + $this->getCellHeight($pfontsize / $this->k)), $maxbottomliney);
18378					}
18379				}
18380				// text
18381				$this->htmlvspace = 0;
18382				$isRTLString = preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $dom[$key]['value']) || preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $dom[$key]['value']);
18383				if ((!$this->premode) AND $this->isRTLTextDir() AND !$isRTLString) {
18384					// reverse spaces order
18385					$lsp = ''; // left spaces
18386					$rsp = ''; // right spaces
18387					if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
18388						$lsp = $matches[1];
18389					}
18390					if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
18391						$rsp = $matches[1];
18392					}
18393					$dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
18394				}
18395				if ($newline) {
18396					if (!$this->premode) {
18397						$prelen = strlen($dom[$key]['value']);
18398						if ($this->isRTLTextDir() AND !$isRTLString) {
18399							// right trim except non-breaking space
18400							$dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
18401						} else {
18402							// left trim except non-breaking space
18403							$dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
18404						}
18405						$postlen = strlen($dom[$key]['value']);
18406						if (($postlen == 0) AND ($prelen > 0)) {
18407							$dom[$key]['trimmed_space'] = true;
18408						}
18409					}
18410					$newline = false;
18411					$firstblock = true;
18412				} else {
18413					$firstblock = false;
18414					// replace empty multiple spaces string with a single space
18415					$dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']);
18416				}
18417				$strrest = '';
18418				if ($this->rtl) {
18419					$this->x -= $this->textindent;
18420				} else {
18421					$this->x += $this->textindent;
18422				}
18423				if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
18424					$strlinelen = $this->GetStringWidth($dom[$key]['value']);
18425					if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
18426						// HTML <a> Link
18427						$hrefcolor = '';
18428						if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
18429							$hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
18430						}
18431						$hrefstyle = -1;
18432						if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
18433							$hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
18434						}
18435						$strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
18436					} else {
18437						$wadj = 0; // space to leave for block continuity
18438						if ($this->rtl) {
18439							$cwa = ($this->x - $this->lMargin);
18440						} else {
18441							$cwa = ($this->w - $this->rMargin - $this->x);
18442						}
18443						if (($strlinelen < $cwa) AND (isset($dom[($key + 1)])) AND ($dom[($key + 1)]['tag']) AND (!$dom[($key + 1)]['block'])) {
18444							// check the next text blocks for continuity
18445							$nkey = ($key + 1);
18446							$write_block = true;
18447							$same_textdir = true;
18448							$tmp_fontname = $this->FontFamily;
18449							$tmp_fontstyle = $this->FontStyle;
18450							$tmp_fontsize = $this->FontSizePt;
18451							while ($write_block AND isset($dom[$nkey])) {
18452								if ($dom[$nkey]['tag']) {
18453									if ($dom[$nkey]['block']) {
18454										// end of block
18455										$write_block = false;
18456									}
18457									$tmp_fontname = isset($dom[$nkey]['fontname']) ? $dom[$nkey]['fontname'] : $this->FontFamily;
18458									$tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ? $dom[$nkey]['fontstyle'] : $this->FontStyle;
18459									$tmp_fontsize = isset($dom[$nkey]['fontsize']) ? $dom[$nkey]['fontsize'] : $this->FontSizePt;
18460									$same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
18461								} else {
18462									$nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'+/', $this->re_space['m'], $dom[$nkey]['value']);
18463									if (isset($nextstr[0]) AND $same_textdir) {
18464										$wadj += $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
18465										if (isset($nextstr[1])) {
18466											$write_block = false;
18467										}
18468									}
18469								}
18470								++$nkey;
18471							}
18472						}
18473						if (($wadj > 0) AND (($strlinelen + $wadj) >= $cwa)) {
18474							$wadj = 0;
18475							$nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $dom[$key]['value']);
18476							$numblks = count($nextstr);
18477							if ($numblks > 1) {
18478								// try to split on blank spaces
18479								$wadj = ($cwa - $strlinelen + $this->GetStringWidth($nextstr[($numblks - 1)]));
18480							} else {
18481								// set the entire block on new line
18482								$wadj = $this->GetStringWidth($nextstr[0]);
18483							}
18484						}
18485						// check for reversed text direction
18486						if (($wadj > 0) AND (($this->rtl AND ($this->tmprtl === 'L')) OR (!$this->rtl AND ($this->tmprtl === 'R')))) {
18487							// LTR text on RTL direction or RTL text on LTR direction
18488							$reverse_dir = true;
18489							$this->rtl = !$this->rtl;
18490							$revshift = ($strlinelen + $wadj + 0.000001); // add little quantity for rounding problems
18491							if ($this->rtl) {
18492								$this->x += $revshift;
18493							} else {
18494								$this->x -= $revshift;
18495							}
18496							$xws = $this->x;
18497						}
18498						// ****** write only until the end of the line and get the rest ******
18499						$strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
18500						// restore default direction
18501						if ($reverse_dir AND ($wadj == 0)) {
18502							$this->x = $xws;
18503							$this->rtl = !$this->rtl;
18504							$reverse_dir = false;
18505						}
18506					}
18507				}
18508				$this->textindent = 0;
18509				if (strlen($strrest) > 0) {
18510					// store the remaining string on the previous $key position
18511					$this->newline = true;
18512					if ($strrest == $dom[$key]['value']) {
18513						// used to avoid infinite loop
18514						++$loop;
18515					} else {
18516						$loop = 0;
18517					}
18518					$dom[$key]['value'] = $strrest;
18519					if ($cell) {
18520						if ($this->rtl) {
18521							$this->x -= $this->cell_padding['R'];
18522						} else {
18523							$this->x += $this->cell_padding['L'];
18524						}
18525					}
18526					if ($loop < 3) {
18527						--$key;
18528					}
18529				} else {
18530					$loop = 0;
18531					// add the positive font spacing of the last character (if any)
18532					 if ($this->font_spacing > 0) {
18533					 	if ($this->rtl) {
18534							$this->x -= $this->font_spacing;
18535						} else {
18536							$this->x += $this->font_spacing;
18537						}
18538					}
18539				}
18540			}
18541			++$key;
18542			if (isset($dom[$key]['tag']) AND $dom[$key]['tag'] AND (!isset($dom[$key]['opening']) OR !$dom[$key]['opening']) AND isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
18543				// check if we are on a new page or on a new column
18544				if ((!$undo) AND (($this->y < $this->start_transaction_y) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y)))) {
18545					// we are on a new page or on a new column and the total object height is less than the available vertical space.
18546					// restore previous object
18547					$this->rollbackTransaction(true);
18548					// restore previous values
18549					foreach ($this_method_vars as $vkey => $vval) {
18550						$$vkey = $vval;
18551					}
18552					if (!empty($dom[$key]['thead'])) {
18553						$this->inthead = true;
18554					}
18555					// add a page (or trig AcceptPageBreak() for multicolumn mode)
18556					$pre_y = $this->y;
18557					if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
18558						$startliney = $this->y;
18559					}
18560					$undo = true; // avoid infinite loop
18561				} else {
18562					$undo = false;
18563				}
18564			}
18565		} // end for each $key
18566		// align the last line
18567		if (isset($startlinex)) {
18568			$yshift = ($minstartliney - $startliney);
18569			if (($yshift > 0) OR ($this->page > $startlinepage)) {
18570				$yshift = 0;
18571			}
18572			$t_x = 0;
18573			// the last line must be shifted to be aligned as requested
18574			$linew = abs($this->endlinex - $startlinex);
18575			if ($this->inxobj) {
18576				// we are inside an XObject template
18577				$pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
18578				if (isset($opentagpos)) {
18579					$midpos = $opentagpos;
18580				} else {
18581					$midpos = 0;
18582				}
18583				if ($midpos > 0) {
18584					$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
18585					$pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
18586				} else {
18587					$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
18588					$pend = '';
18589				}
18590			} else {
18591				$pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
18592				if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
18593					$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
18594					$midpos = min($opentagpos, $this->footerpos[$startlinepage]);
18595				} elseif (isset($opentagpos)) {
18596					$midpos = $opentagpos;
18597				} elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
18598					$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
18599					$midpos = $this->footerpos[$startlinepage];
18600				} else {
18601					$midpos = 0;
18602				}
18603				if ($midpos > 0) {
18604					$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
18605					$pend = substr($this->getPageBuffer($startlinepage), $midpos);
18606				} else {
18607					$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
18608					$pend = '';
18609				}
18610			}
18611			if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
18612				// calculate shifting amount
18613				$tw = $w;
18614				if ($this->lMargin != $prevlMargin) {
18615					$tw += ($prevlMargin - $this->lMargin);
18616				}
18617				if ($this->rMargin != $prevrMargin) {
18618					$tw += ($prevrMargin - $this->rMargin);
18619				}
18620				$one_space_width = $this->GetStringWidth(chr(32));
18621				$no = 0; // number of spaces on a line contained on a single block
18622				if ($this->isRTLTextDir()) { // RTL
18623					// remove left space if exist
18624					$pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
18625					if ($pos1 > 0) {
18626						$pos1 = intval($pos1);
18627						if ($this->isUnicodeFont()) {
18628							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
18629							$spacelen = 2;
18630						} else {
18631							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
18632							$spacelen = 1;
18633						}
18634						if ($pos1 == $pos2) {
18635							$pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
18636							if (substr($pmid, $pos1, 4) == '[()]') {
18637								$linew -= $one_space_width;
18638							} elseif ($pos1 == strpos($pmid, '[(')) {
18639								$no = 1;
18640							}
18641						}
18642					}
18643				} else { // LTR
18644					// remove right space if exist
18645					$pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
18646					if ($pos1 > 0) {
18647						$pos1 = intval($pos1);
18648						if ($this->isUnicodeFont()) {
18649							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
18650							$spacelen = 2;
18651						} else {
18652							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
18653							$spacelen = 1;
18654						}
18655						if ($pos1 == $pos2) {
18656							$pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
18657							$linew -= $one_space_width;
18658						}
18659					}
18660				}
18661				$mdiff = ($tw - $linew);
18662				if ($plalign == 'C') {
18663					if ($this->rtl) {
18664						$t_x = -($mdiff / 2);
18665					} else {
18666						$t_x = ($mdiff / 2);
18667					}
18668				} elseif ($plalign == 'R') {
18669					// right alignment on LTR document
18670					$t_x = $mdiff;
18671				} elseif ($plalign == 'L') {
18672					// left alignment on RTL document
18673					$t_x = -$mdiff;
18674				}
18675			} // end if startlinex
18676			if (($t_x != 0) OR ($yshift < 0)) {
18677				// shift the line
18678				$trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
18679				$pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
18680				$endlinepos = strlen($pstart);
18681				if ($this->inxobj) {
18682					// we are inside an XObject template
18683					$this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
18684					foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
18685						if ($pak >= $pask) {
18686							$this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
18687							$this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
18688						}
18689					}
18690				} else {
18691					$this->setPageBuffer($startlinepage, $pstart.$pend);
18692					// shift the annotations and links
18693					if (isset($this->PageAnnots[$this->page])) {
18694						foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
18695							if ($pak >= $pask) {
18696								$this->PageAnnots[$this->page][$pak]['x'] += $t_x;
18697								$this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
18698							}
18699						}
18700					}
18701				}
18702				$this->y -= $yshift;
18703				$yshift = 0;
18704			}
18705		}
18706		// restore previous values
18707		$this->setGraphicVars($gvars);
18708		if ($this->num_columns > 1) {
18709			$this->selectColumn();
18710		} elseif ($this->page > $prevPage) {
18711			$this->lMargin = $this->pagedim[$this->page]['olm'];
18712			$this->rMargin = $this->pagedim[$this->page]['orm'];
18713		}
18714		// restore previous list state
18715		$this->cell_height_ratio = $prev_cell_height_ratio;
18716		$this->listnum = $prev_listnum;
18717		$this->listordered = $prev_listordered;
18718		$this->listcount = $prev_listcount;
18719		$this->lispacer = $prev_lispacer;
18720		if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
18721			$this->Ln($this->lasth);
18722			if (($this->y < $maxbottomliney) AND ($startlinepage == $this->page)) {
18723				$this->y = $maxbottomliney;
18724			}
18725		}
18726		unset($dom);
18727	}
18728
18729	/**
18730	 * Process opening tags.
18731	 * @param $dom (array) html dom array
18732	 * @param $key (int) current element id
18733	 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
18734	 * @return $dom array
18735	 * @protected
18736	 */
18737	protected function openHTMLTagHandler($dom, $key, $cell) {
18738		$tag = $dom[$key];
18739		$parent = $dom[($dom[$key]['parent'])];
18740		$firsttag = ($key == 1);
18741		// check for text direction attribute
18742		if (isset($tag['dir'])) {
18743			$this->setTempRTL($tag['dir']);
18744		} else {
18745			$this->tmprtl = false;
18746		}
18747		if ($tag['block']) {
18748			$hbz = 0; // distance from y to line bottom
18749			$hb = 0; // vertical space between block tags
18750			// calculate vertical space for block tags
18751			if (isset($this->tagvspaces[$tag['value']][0]['h']) && !empty($this->tagvspaces[$tag['value']][0]['h']) && ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) {
18752				$cur_h = $this->tagvspaces[$tag['value']][0]['h'];
18753			} elseif (isset($tag['fontsize'])) {
18754				$cur_h = $this->getCellHeight($tag['fontsize'] / $this->k);
18755			} else {
18756				$cur_h = $this->getCellHeight($this->FontSize);
18757			}
18758			if (isset($this->tagvspaces[$tag['value']][0]['n'])) {
18759				$on = $this->tagvspaces[$tag['value']][0]['n'];
18760			} elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
18761				$on = 0.6;
18762			} else {
18763				$on = 1;
18764			}
18765			if ((!isset($this->tagvspaces[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br', 'hr')))) {
18766				$hb = 0;
18767			} else {
18768				$hb = ($on * $cur_h);
18769			}
18770			if (($this->htmlvspace <= 0) AND ($on > 0)) {
18771				if (isset($parent['fontsize'])) {
18772					$hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
18773				} else {
18774					$hbz = $this->getCellHeight($this->FontSize);
18775				}
18776			}
18777			if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == 'table')) {
18778				// fix vertical space after table
18779				$hbz = 0;
18780			}
18781			// closing vertical space
18782			$hbc = 0;
18783			if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
18784				$pre_h = $this->tagvspaces[$tag['value']][1]['h'];
18785			} elseif (isset($parent['fontsize'])) {
18786				$pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
18787			} else {
18788				$pre_h = $this->getCellHeight($this->FontSize);
18789			}
18790			if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
18791				$cn = $this->tagvspaces[$tag['value']][1]['n'];
18792			} elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
18793				$cn = 0.6;
18794			} else {
18795				$cn = 1;
18796			}
18797			if (isset($this->tagvspaces[$tag['value']][1])) {
18798				$hbc = ($cn * $pre_h);
18799			}
18800		}
18801		// Opening tag
18802		switch($tag['value']) {
18803			case 'table': {
18804				$cp = 0;
18805				$cs = 0;
18806				$dom[$key]['rowspans'] = array();
18807				if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
18808					$this->htmlvspace = 0;
18809					// set table header
18810					if (!TCPDF_STATIC::empty_string($dom[$key]['thead'])) {
18811						// set table header
18812						$this->thead = $dom[$key]['thead'];
18813						if (!isset($this->theadMargins) OR (empty($this->theadMargins))) {
18814							$this->theadMargins = array();
18815							$this->theadMargins['cell_padding'] = $this->cell_padding;
18816							$this->theadMargins['lmargin'] = $this->lMargin;
18817							$this->theadMargins['rmargin'] = $this->rMargin;
18818							$this->theadMargins['page'] = $this->page;
18819							$this->theadMargins['cell'] = $cell;
18820							$this->theadMargins['gvars'] = $this->getGraphicVars();
18821						}
18822					}
18823				}
18824				// store current margins and page
18825				$dom[$key]['old_cell_padding'] = $this->cell_padding;
18826				if (isset($tag['attribute']['cellpadding'])) {
18827					$pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
18828					$this->SetCellPadding($pad);
18829				} elseif (isset($tag['padding'])) {
18830					$this->cell_padding = $tag['padding'];
18831				}
18832				if (isset($tag['attribute']['cellspacing'])) {
18833					$cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
18834				} elseif (isset($tag['border-spacing'])) {
18835					$cs = $tag['border-spacing']['V'];
18836				}
18837				$prev_y = $this->y;
18838				if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) {
18839					$this->inthead = true;
18840					// add a page (or trig AcceptPageBreak() for multicolumn mode)
18841					$this->checkPageBreak($this->PageBreakTrigger + 1);
18842				}
18843				break;
18844			}
18845			case 'tr': {
18846				// array of columns positions
18847				$dom[$key]['cellpos'] = array();
18848				break;
18849			}
18850			case 'hr': {
18851				if ((isset($tag['height'])) AND ($tag['height'] != '')) {
18852					$hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
18853				} else {
18854					$hrHeight = $this->GetLineWidth();
18855				}
18856				$this->addHTMLVertSpace($hbz, max($hb, ($hrHeight / 2)), $cell, $firsttag);
18857				$x = $this->GetX();
18858				$y = $this->GetY();
18859				$wtmp = $this->w - $this->lMargin - $this->rMargin;
18860				if ($cell) {
18861					$wtmp -= ($this->cell_padding['L'] + $this->cell_padding['R']);
18862				}
18863				if ((isset($tag['width'])) AND ($tag['width'] != '')) {
18864					$hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
18865				} else {
18866					$hrWidth = $wtmp;
18867				}
18868				$prevlinewidth = $this->GetLineWidth();
18869				$this->SetLineWidth($hrHeight);
18870				$this->Line($x, $y, $x + $hrWidth, $y);
18871				$this->SetLineWidth($prevlinewidth);
18872				$this->addHTMLVertSpace(max($hbc, ($hrHeight / 2)), 0, $cell, !isset($dom[($key + 1)]));
18873				break;
18874			}
18875			case 'a': {
18876				if (array_key_exists('href', $tag['attribute'])) {
18877					$this->HREF['url'] = $tag['attribute']['href'];
18878				}
18879				break;
18880			}
18881			case 'img': {
18882				if (empty($tag['attribute']['src'])) {
18883					break;
18884				}
18885				$imgsrc = $tag['attribute']['src'];
18886				if ($imgsrc[0] === '@') {
18887					// data stream
18888					$imgsrc = '@'.base64_decode(substr($imgsrc, 1));
18889					$type = '';
18890				} else {
18891					// @CHANGE LDR Add support for src="file://..." links
18892					if (strpos($imgsrc, 'file://') === 0) {
18893						$imgsrc = str_replace('file://', '/', $imgsrc);
18894						$imgsrc = urldecode($imgsrc);
18895						$testscrtype = @parse_url($imgsrc);
18896						if (empty($testscrtype['query'])) {
18897							// convert URL to server path
18898							$imgsrc = str_replace(K_PATH_URL, K_PATH_MAIN, $imgsrc);
18899						} elseif (preg_match('|^https?://|', $imgsrc) !== 1) {
18900							// convert URL to server path
18901							$imgsrc = str_replace(K_PATH_MAIN, K_PATH_URL, $imgsrc);
18902						}
18903					}
18904					elseif (($imgsrc[0] === '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
18905							// fix image path
18906						$findroot = strpos($imgsrc, $_SERVER['DOCUMENT_ROOT']);
18907						if (($findroot === false) OR ($findroot > 1)) {
18908							if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
18909								$imgsrc = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$imgsrc;
18910							} else {
18911								$imgsrc = $_SERVER['DOCUMENT_ROOT'].$imgsrc;
18912							}
18913						}
18914						$imgsrc = urldecode($imgsrc);
18915						$testscrtype = @parse_url($imgsrc);
18916						if (empty($testscrtype['query'])) {
18917							// convert URL to server path
18918							$imgsrc = str_replace(K_PATH_URL, K_PATH_MAIN, $imgsrc);
18919						} elseif (preg_match('|^https?://|', $imgsrc) !== 1) {
18920							// convert URL to server path
18921							$imgsrc = str_replace(K_PATH_MAIN, K_PATH_URL, $imgsrc);
18922						}
18923					}
18924
18925					// get image type
18926					$type = TCPDF_IMAGES::getImageFileType($imgsrc);
18927				}
18928				if (!isset($tag['width'])) {
18929					$tag['width'] = 0;
18930				}
18931				if (!isset($tag['height'])) {
18932					$tag['height'] = 0;
18933				}
18934				//if (!isset($tag['attribute']['align'])) {
18935					// the only alignment supported is "bottom"
18936					// further development is required for other modes.
18937					$tag['attribute']['align'] = 'bottom';
18938				//}
18939				switch($tag['attribute']['align']) {
18940					case 'top': {
18941						$align = 'T';
18942						break;
18943					}
18944					case 'middle': {
18945						$align = 'M';
18946						break;
18947					}
18948					case 'bottom': {
18949						$align = 'B';
18950						break;
18951					}
18952					default: {
18953						$align = 'B';
18954						break;
18955					}
18956				}
18957				$prevy = $this->y;
18958				$xpos = $this->x;
18959				$imglink = '';
18960				if (isset($this->HREF['url']) AND !TCPDF_STATIC::empty_string($this->HREF['url'])) {
18961					$imglink = $this->HREF['url'];
18962					if ($imglink[0] == '#') {
18963						// convert url to internal link
18964						$lnkdata = explode(',', $imglink);
18965						if (isset($lnkdata[0])) {
18966							$page = intval(substr($lnkdata[0], 1));
18967							if (empty($page) OR ($page <= 0)) {
18968								$page = $this->page;
18969							}
18970							if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
18971								$lnky = floatval($lnkdata[1]);
18972							} else {
18973								$lnky = 0;
18974							}
18975							$imglink = $this->AddLink();
18976							$this->SetLink($imglink, $lnky, $page);
18977						}
18978					}
18979				}
18980				$border = 0;
18981				if (isset($tag['border']) AND !empty($tag['border'])) {
18982					// currently only support 1 (frame) or a combination of 'LTRB'
18983					$border = $tag['border'];
18984				}
18985				$iw = '';
18986				if (isset($tag['width'])) {
18987					$iw = $this->getHTMLUnitToUnits($tag['width'], ($tag['fontsize'] / $this->k), 'px', false);
18988				}
18989				$ih = '';
18990				if (isset($tag['height'])) {
18991					$ih = $this->getHTMLUnitToUnits($tag['height'], ($tag['fontsize'] / $this->k), 'px', false);
18992				}
18993				if (($type == 'eps') OR ($type == 'ai')) {
18994					$this->ImageEps($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true);
18995				} elseif ($type == 'svg') {
18996					$this->ImageSVG($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true);
18997				} else {
18998					$this->Image($imgsrc, $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
18999				}
19000				switch($align) {
19001					case 'T': {
19002						$this->y = $prevy;
19003						break;
19004					}
19005					case 'M': {
19006						$this->y = (($this->img_rb_y + $prevy - ($this->getCellHeight($tag['fontsize'] / $this->k))) / 2);
19007						break;
19008					}
19009					case 'B': {
19010						$this->y = $this->img_rb_y - ($this->getCellHeight($tag['fontsize'] / $this->k) - ($this->getFontDescent($tag['fontname'], $tag['fontstyle'], $tag['fontsize']) * $this->cell_height_ratio));
19011						break;
19012					}
19013				}
19014				break;
19015			}
19016			case 'dl': {
19017				++$this->listnum;
19018				if ($this->listnum == 1) {
19019					$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19020				} else {
19021					$this->addHTMLVertSpace(0, 0, $cell, $firsttag);
19022				}
19023				break;
19024			}
19025			case 'dt': {
19026				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19027				break;
19028			}
19029			case 'dd': {
19030				if ($this->rtl) {
19031					$this->rMargin += $this->listindent;
19032				} else {
19033					$this->lMargin += $this->listindent;
19034				}
19035				++$this->listindentlevel;
19036				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19037				break;
19038			}
19039			case 'ul':
19040			case 'ol': {
19041				++$this->listnum;
19042				if ($tag['value'] == 'ol') {
19043					$this->listordered[$this->listnum] = true;
19044				} else {
19045					$this->listordered[$this->listnum] = false;
19046				}
19047				if (isset($tag['attribute']['start'])) {
19048					$this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
19049				} else {
19050					$this->listcount[$this->listnum] = 0;
19051				}
19052				if ($this->rtl) {
19053					$this->rMargin += $this->listindent;
19054					$this->x -= $this->listindent;
19055				} else {
19056					$this->lMargin += $this->listindent;
19057					$this->x += $this->listindent;
19058				}
19059				++$this->listindentlevel;
19060				if ($this->listnum == 1) {
19061					if ($key > 1) {
19062						$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19063					}
19064				} else {
19065					$this->addHTMLVertSpace(0, 0, $cell, $firsttag);
19066				}
19067				break;
19068			}
19069			case 'li': {
19070				if ($key > 2) {
19071					$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19072				}
19073				if ($this->listordered[$this->listnum]) {
19074					// ordered item
19075					if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
19076						$this->lispacer = $parent['attribute']['type'];
19077					} elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
19078						$this->lispacer = $parent['listtype'];
19079					} elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
19080						$this->lispacer = $this->lisymbol;
19081					} else {
19082						$this->lispacer = '#';
19083					}
19084					++$this->listcount[$this->listnum];
19085					if (isset($tag['attribute']['value'])) {
19086						$this->listcount[$this->listnum] = intval($tag['attribute']['value']);
19087					}
19088				} else {
19089					// unordered item
19090					if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
19091						$this->lispacer = $parent['attribute']['type'];
19092					} elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
19093						$this->lispacer = $parent['listtype'];
19094					} elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
19095						$this->lispacer = $this->lisymbol;
19096					} else {
19097						$this->lispacer = '!';
19098					}
19099				}
19100				break;
19101			}
19102			case 'blockquote': {
19103				if ($this->rtl) {
19104					$this->rMargin += $this->listindent;
19105				} else {
19106					$this->lMargin += $this->listindent;
19107				}
19108				++$this->listindentlevel;
19109				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19110				break;
19111			}
19112			case 'br': {
19113				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19114				break;
19115			}
19116			case 'div': {
19117				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19118				break;
19119			}
19120			case 'p': {
19121				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19122				break;
19123			}
19124			case 'pre': {
19125				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19126				$this->premode = true;
19127				break;
19128			}
19129			case 'sup': {
19130				$this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
19131				break;
19132			}
19133			case 'sub': {
19134				$this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
19135				break;
19136			}
19137			case 'h1':
19138			case 'h2':
19139			case 'h3':
19140			case 'h4':
19141			case 'h5':
19142			case 'h6': {
19143				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19144				break;
19145			}
19146			// Form fields (since 4.8.000 - 2009-09-07)
19147			case 'form': {
19148				if (isset($tag['attribute']['action'])) {
19149					$this->form_action = $tag['attribute']['action'];
19150				} else {
19151					$this->Error('Please explicitly set action attribute path!');
19152				}
19153				if (isset($tag['attribute']['enctype'])) {
19154					$this->form_enctype = $tag['attribute']['enctype'];
19155				} else {
19156					$this->form_enctype = 'application/x-www-form-urlencoded';
19157				}
19158				if (isset($tag['attribute']['method'])) {
19159					$this->form_mode = $tag['attribute']['method'];
19160				} else {
19161					$this->form_mode = 'post';
19162				}
19163				break;
19164			}
19165			case 'input': {
19166				if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
19167					$name = $tag['attribute']['name'];
19168				} else {
19169					break;
19170				}
19171				$prop = array();
19172				$opt = array();
19173				if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
19174					$prop['readonly'] = true;
19175				}
19176				if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
19177					$value = $tag['attribute']['value'];
19178				}
19179				if (isset($tag['attribute']['maxlength']) AND !TCPDF_STATIC::empty_string($tag['attribute']['maxlength'])) {
19180					$opt['maxlen'] = intval($tag['attribute']['maxlength']);
19181				}
19182				$h = $this->getCellHeight($this->FontSize);
19183				if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
19184					$w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
19185				} else {
19186					$w = $h;
19187				}
19188				if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
19189					$checked = true;
19190				} else {
19191					$checked = false;
19192				}
19193				if (isset($tag['align'])) {
19194					switch ($tag['align']) {
19195						case 'C': {
19196							$opt['q'] = 1;
19197							break;
19198						}
19199						case 'R': {
19200							$opt['q'] = 2;
19201							break;
19202						}
19203						case 'L':
19204						default: {
19205							break;
19206						}
19207					}
19208				}
19209				switch ($tag['attribute']['type']) {
19210					case 'text': {
19211						if (isset($value)) {
19212							$opt['v'] = $value;
19213						}
19214						$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19215						break;
19216					}
19217					case 'password': {
19218						if (isset($value)) {
19219							$opt['v'] = $value;
19220						}
19221						$prop['password'] = 'true';
19222						$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19223						break;
19224					}
19225					case 'checkbox': {
19226						if (!isset($value)) {
19227							break;
19228						}
19229						$this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
19230						break;
19231					}
19232					case 'radio': {
19233						if (!isset($value)) {
19234							break;
19235						}
19236						$this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
19237						break;
19238					}
19239					case 'submit': {
19240						if (!isset($value)) {
19241							$value = 'submit';
19242						}
19243						$w = $this->GetStringWidth($value) * 1.5;
19244						$h *= 1.6;
19245						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19246						$action = array();
19247						$action['S'] = 'SubmitForm';
19248						$action['F'] = $this->form_action;
19249						if ($this->form_enctype != 'FDF') {
19250							$action['Flags'] = array('ExportFormat');
19251						}
19252						if ($this->form_mode == 'get') {
19253							$action['Flags'] = array('GetMethod');
19254						}
19255						$this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
19256						break;
19257					}
19258					case 'reset': {
19259						if (!isset($value)) {
19260							$value = 'reset';
19261						}
19262						$w = $this->GetStringWidth($value) * 1.5;
19263						$h *= 1.6;
19264						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19265						$this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
19266						break;
19267					}
19268					case 'file': {
19269						$prop['fileSelect'] = 'true';
19270						$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19271						if (!isset($value)) {
19272							$value = '*';
19273						}
19274						$w = $this->GetStringWidth($value) * 2;
19275						$h *= 1.2;
19276						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19277						$jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
19278						$this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19279						break;
19280					}
19281					case 'hidden': {
19282						if (isset($value)) {
19283							$opt['v'] = $value;
19284						}
19285						$opt['f'] = array('invisible', 'hidden');
19286						$this->TextField($name, 0, 0, $prop, $opt, '', '', false);
19287						break;
19288					}
19289					case 'image': {
19290						// THIS TYPE MUST BE FIXED
19291						if (isset($tag['attribute']['src']) AND !TCPDF_STATIC::empty_string($tag['attribute']['src'])) {
19292							$img = $tag['attribute']['src'];
19293						} else {
19294							break;
19295						}
19296						$value = 'img';
19297						//$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
19298						if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
19299							$jsaction = $tag['attribute']['onclick'];
19300						} else {
19301							$jsaction = '';
19302						}
19303						$this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19304						break;
19305					}
19306					case 'button': {
19307						if (!isset($value)) {
19308							$value = ' ';
19309						}
19310						$w = $this->GetStringWidth($value) * 1.5;
19311						$h *= 1.6;
19312						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19313						if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
19314							$jsaction = $tag['attribute']['onclick'];
19315						} else {
19316							$jsaction = '';
19317						}
19318						$this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19319						break;
19320					}
19321				}
19322				break;
19323			}
19324			case 'textarea': {
19325				$prop = array();
19326				$opt = array();
19327				if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
19328					$prop['readonly'] = true;
19329				}
19330				if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
19331					$name = $tag['attribute']['name'];
19332				} else {
19333					break;
19334				}
19335				if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
19336					$opt['v'] = $tag['attribute']['value'];
19337				}
19338				if (isset($tag['attribute']['cols']) AND !TCPDF_STATIC::empty_string($tag['attribute']['cols'])) {
19339					$w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
19340				} else {
19341					$w = 40;
19342				}
19343				if (isset($tag['attribute']['rows']) AND !TCPDF_STATIC::empty_string($tag['attribute']['rows'])) {
19344					$h = intval($tag['attribute']['rows']) * $this->getCellHeight($this->FontSize);
19345				} else {
19346					$h = 10;
19347				}
19348				$prop['multiline'] = 'true';
19349				$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19350				break;
19351			}
19352			case 'select': {
19353				$h = $this->getCellHeight($this->FontSize);
19354				if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
19355					$h *= ($tag['attribute']['size'] + 1);
19356				}
19357				$prop = array();
19358				$opt = array();
19359				if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
19360					$name = $tag['attribute']['name'];
19361				} else {
19362					break;
19363				}
19364				$w = 0;
19365				if (isset($tag['attribute']['opt']) AND !TCPDF_STATIC::empty_string($tag['attribute']['opt'])) {
19366					$options = explode('#!NwL!#', $tag['attribute']['opt']);
19367					$values = array();
19368					foreach ($options as $val) {
19369						if (strpos($val, '#!TaB!#') !== false) {
19370							$opts = explode('#!TaB!#', $val);
19371							$values[] = $opts;
19372							$w = max($w, $this->GetStringWidth($opts[1]));
19373						} else {
19374							$values[] = $val;
19375							$w = max($w, $this->GetStringWidth($val));
19376						}
19377					}
19378				} else {
19379					break;
19380				}
19381				$w *= 2;
19382				if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
19383					$prop['multipleSelection'] = 'true';
19384					$this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
19385				} else {
19386					$this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
19387				}
19388				break;
19389			}
19390			case 'tcpdf': {
19391				if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
19392					// Special tag used to call TCPDF methods
19393					if (isset($tag['attribute']['method'])) {
19394						$tcpdf_method = $tag['attribute']['method'];
19395						if (method_exists($this, $tcpdf_method)) {
19396							if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
19397								$params = $this->unserializeTCPDFtagParameters($tag['attribute']['params']);
19398								call_user_func_array(array($this, $tcpdf_method), $params);
19399							} else {
19400								$this->$tcpdf_method();
19401							}
19402							$this->newline = true;
19403						}
19404					}
19405				}
19406				break;
19407			}
19408			default: {
19409				break;
19410			}
19411		}
19412		// define tags that support borders and background colors
19413		$bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
19414		if (in_array($tag['value'], $bordertags)) {
19415			// set border
19416			$dom[$key]['borderposition'] = $this->getBorderStartPosition();
19417		}
19418		if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
19419			$pba = $dom[$key]['attribute']['pagebreakafter'];
19420			// check for pagebreak
19421			if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
19422				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19423				$this->checkPageBreak($this->PageBreakTrigger + 1);
19424			}
19425			if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
19426				OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
19427				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19428				$this->checkPageBreak($this->PageBreakTrigger + 1);
19429			}
19430		}
19431		return $dom;
19432	}
19433
19434	/**
19435	 * Process closing tags.
19436	 * @param $dom (array) html dom array
19437	 * @param $key (int) current element id
19438	 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
19439	 * @param $maxbottomliney (int) maximum y value of current line
19440	 * @return $dom array
19441	 * @protected
19442	 */
19443	protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
19444		$tag = $dom[$key];
19445		$parent = $dom[($dom[$key]['parent'])];
19446		$lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
19447		$in_table_head = false;
19448		// maximum x position (used to draw borders)
19449		if ($this->rtl) {
19450			$xmax = $this->w;
19451		} else {
19452			$xmax = 0;
19453		}
19454		if ($tag['block']) {
19455			$hbz = 0; // distance from y to line bottom
19456			$hb = 0; // vertical space between block tags
19457			// calculate vertical space for block tags
19458			if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
19459				$pre_h = $this->tagvspaces[$tag['value']][1]['h'];
19460			} elseif (isset($parent['fontsize'])) {
19461				$pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
19462			} else {
19463				$pre_h = $this->getCellHeight($this->FontSize);
19464			}
19465			if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
19466				$cn = $this->tagvspaces[$tag['value']][1]['n'];
19467			} elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
19468				$cn = 0.6;
19469			} else {
19470				$cn = 1;
19471			}
19472			if ((!isset($this->tagvspaces[$tag['value']])) AND ($tag['value'] == 'div')) {
19473				$hb = 0;
19474			} else {
19475				$hb = ($cn * $pre_h);
19476			}
19477			if ($maxbottomliney > $this->PageBreakTrigger) {
19478				$hbz = $this->getCellHeight($this->FontSize);
19479			} elseif ($this->y < $maxbottomliney) {
19480				$hbz = ($maxbottomliney - $this->y);
19481			}
19482		}
19483		// Closing tag
19484		switch($tag['value']) {
19485			case 'tr': {
19486				$table_el = $dom[($dom[$key]['parent'])]['parent'];
19487				if (!isset($parent['endy'])) {
19488					$dom[($dom[$key]['parent'])]['endy'] = $this->y;
19489					$parent['endy'] = $this->y;
19490				}
19491				if (!isset($parent['endpage'])) {
19492					$dom[($dom[$key]['parent'])]['endpage'] = $this->page;
19493					$parent['endpage'] = $this->page;
19494				}
19495				if (!isset($parent['endcolumn'])) {
19496					$dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column;
19497					$parent['endcolumn'] = $this->current_column;
19498				}
19499				// update row-spanned cells
19500				if (isset($dom[$table_el]['rowspans'])) {
19501					foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19502						$dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
19503						if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19504							if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
19505								$dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
19506							} elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
19507								$dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
19508								$dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
19509								$dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
19510							}
19511						}
19512					}
19513					// report new endy and endpage to the rowspanned cells
19514					foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19515						if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19516							$dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
19517							$dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
19518							$dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
19519							$dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
19520							$dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
19521							$dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
19522						}
19523					}
19524					// update remaining rowspanned cells
19525					foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19526						if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19527							$dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
19528							$dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
19529							$dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
19530						}
19531					}
19532				}
19533				$prev_page = $this->page;
19534				$this->setPage($dom[($dom[$key]['parent'])]['endpage']);
19535				if ($this->num_columns > 1) {
19536					if (($prev_page < $this->page)
19537						AND ((($this->current_column == 0) AND ($dom[($dom[$key]['parent'])]['endcolumn'] == ($this->num_columns - 1)))
19538							OR ($this->current_column == $dom[($dom[$key]['parent'])]['endcolumn']))) {
19539						// page jump
19540						$this->selectColumn(0);
19541						$dom[($dom[$key]['parent'])]['endcolumn'] = 0;
19542						$dom[($dom[$key]['parent'])]['endy'] = $this->y;
19543					} else {
19544						$this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
19545						$this->y = $dom[($dom[$key]['parent'])]['endy'];
19546					}
19547				} else {
19548					$this->y = $dom[($dom[$key]['parent'])]['endy'];
19549				}
19550				if (isset($dom[$table_el]['attribute']['cellspacing'])) {
19551					$this->y += $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
19552				} elseif (isset($dom[$table_el]['border-spacing'])) {
19553					$this->y += $dom[$table_el]['border-spacing']['V'];
19554				}
19555				$this->Ln(0, $cell);
19556				if ($this->current_column == $parent['startcolumn']) {
19557					$this->x = $parent['startx'];
19558				}
19559				// account for booklet mode
19560				if ($this->page > $parent['startpage']) {
19561					if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
19562						$this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
19563					} elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
19564						$this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
19565					}
19566				}
19567				break;
19568			}
19569			case 'tablehead':
19570				// closing tag used for the thead part
19571				$in_table_head = true;
19572				$this->inthead = false;
19573			case 'table': {
19574				$table_el = $parent;
19575				// set default border
19576				if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
19577					// set default border
19578					$border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
19579				} else {
19580					$border = 0;
19581				}
19582				$default_border = $border;
19583				// fix bottom line alignment of last line before page break
19584				foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
19585					// update row-spanned cells
19586					if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
19587						foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
19588							if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] > 0)) {
19589								$dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
19590							}
19591							if ($dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] == $trkey) {
19592								$dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
19593							}
19594						}
19595					}
19596					if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
19597						$pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
19598						$dom[$prevtrkey]['endy'] = $pgendy;
19599						// update row-spanned cells
19600						if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
19601							foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
19602								if (($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
19603									$dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
19604									$dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
19605								}
19606							}
19607						}
19608					}
19609					$prevtrkey = $trkey;
19610					$table_el = $dom[($dom[$key]['parent'])];
19611				}
19612				// for each row
19613				if (count($table_el['trids']) > 0) {
19614					unset($xmax);
19615				}
19616				foreach ($table_el['trids'] as $j => $trkey) {
19617					$parent = $dom[$trkey];
19618					if (!isset($xmax)) {
19619						$xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
19620					}
19621					// for each cell on the row
19622					foreach ($parent['cellpos'] as $k => $cellpos) {
19623						if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
19624							$cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
19625							$cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
19626							$endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
19627							$startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
19628							$endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
19629							$startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
19630							$endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
19631						} else {
19632							$endy = $parent['endy'];
19633							$startpage = $parent['startpage'];
19634							$endpage = $parent['endpage'];
19635							$startcolumn = $parent['startcolumn'];
19636							$endcolumn = $parent['endcolumn'];
19637						}
19638						if ($this->num_columns == 0) {
19639							$this->num_columns = 1;
19640						}
19641						if (isset($cellpos['border'])) {
19642							$border = $cellpos['border'];
19643						}
19644						if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
19645							$this->SetFillColorArray($cellpos['bgcolor']);
19646							$fill = true;
19647						} else {
19648							$fill = false;
19649						}
19650						$x = $cellpos['startx'];
19651						$y = $parent['starty'];
19652						$starty = $y;
19653						$w = abs($cellpos['endx'] - $cellpos['startx']);
19654						// get border modes
19655						$border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
19656						$border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
19657						$border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
19658						// design borders around HTML cells.
19659						for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
19660							$ccode = '';
19661							$this->setPage($page);
19662							if ($this->num_columns < 2) {
19663								// single-column mode
19664								$this->x = $x;
19665								$this->y = $this->tMargin;
19666							}
19667							// account for margin changes
19668							if ($page > $startpage) {
19669								if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
19670									$this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
19671								} elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
19672									$this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
19673								}
19674							}
19675							if ($startpage == $endpage) { // single page
19676								$deltacol = 0;
19677								$deltath = 0;
19678								for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
19679									$this->selectColumn($column);
19680									if ($startcolumn == $endcolumn) { // single column
19681										$cborder = $border;
19682										$h = $endy - $parent['starty'];
19683										$this->y = $y;
19684										$this->x = $x;
19685									} elseif ($column == $startcolumn) { // first column
19686										$cborder = $border_start;
19687										$this->y = $starty;
19688										$this->x = $x;
19689										$h = $this->h - $this->y - $this->bMargin;
19690										if ($this->rtl) {
19691											$deltacol = $this->x + $this->rMargin - $this->w;
19692										} else {
19693											$deltacol = $this->x - $this->lMargin;
19694										}
19695									} elseif ($column == $endcolumn) { // end column
19696										$cborder = $border_end;
19697										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19698											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19699										}
19700										$this->x += $deltacol;
19701										$h = $endy - $this->y;
19702									} else { // middle column
19703										$cborder = $border_middle;
19704										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19705											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19706										}
19707										$this->x += $deltacol;
19708										$h = $this->h - $this->y - $this->bMargin;
19709									}
19710									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19711								} // end for each column
19712							} elseif ($page == $startpage) { // first page
19713								$deltacol = 0;
19714								$deltath = 0;
19715								for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
19716									$this->selectColumn($column);
19717									if ($column == $startcolumn) { // first column
19718										$cborder = $border_start;
19719										$this->y = $starty;
19720										$this->x = $x;
19721										$h = $this->h - $this->y - $this->bMargin;
19722										if ($this->rtl) {
19723											$deltacol = $this->x + $this->rMargin - $this->w;
19724										} else {
19725											$deltacol = $this->x - $this->lMargin;
19726										}
19727									} else { // middle column
19728										$cborder = $border_middle;
19729										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19730											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19731										}
19732										$this->x += $deltacol;
19733										$h = $this->h - $this->y - $this->bMargin;
19734									}
19735									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19736								} // end for each column
19737							} elseif ($page == $endpage) { // last page
19738								$deltacol = 0;
19739								$deltath = 0;
19740								for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
19741									$this->selectColumn($column);
19742									if ($column == $endcolumn) { // end column
19743										$cborder = $border_end;
19744										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19745											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19746										}
19747										$this->x += $deltacol;
19748										$h = $endy - $this->y;
19749									} else { // middle column
19750										$cborder = $border_middle;
19751										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19752											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19753										}
19754										$this->x += $deltacol;
19755										$h = $this->h - $this->y - $this->bMargin;
19756									}
19757									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19758								} // end for each column
19759							} else { // middle page
19760								$deltacol = 0;
19761								$deltath = 0;
19762								for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
19763									$this->selectColumn($column);
19764									$cborder = $border_middle;
19765									if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19766										$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19767									}
19768									$this->x += $deltacol;
19769									$h = $this->h - $this->y - $this->bMargin;
19770									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19771								} // end for each column
19772							}
19773							if (!empty($cborder) OR !empty($fill)) {
19774								$offsetlen = strlen($ccode);
19775								// draw border and fill
19776								if ($this->inxobj) {
19777									// we are inside an XObject template
19778									if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
19779										$pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
19780										$pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
19781										$this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
19782									} else {
19783										$pagemark = $this->xobjects[$this->xobjid]['intmrk'];
19784										$this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
19785									}
19786									$pagebuff = $this->xobjects[$this->xobjid]['outdata'];
19787									$pstart = substr($pagebuff, 0, $pagemark);
19788									$pend = substr($pagebuff, $pagemark);
19789									$this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
19790								} else {
19791									// draw border and fill
19792									if (end($this->transfmrk[$this->page]) !== false) {
19793										$pagemarkkey = key($this->transfmrk[$this->page]);
19794										$pagemark = $this->transfmrk[$this->page][$pagemarkkey];
19795									} elseif ($this->InFooter) {
19796										$pagemark = $this->footerpos[$this->page];
19797									} else {
19798										$pagemark = $this->intmrk[$this->page];
19799									}
19800									$pagebuff = $this->getPageBuffer($this->page);
19801									$pstart = substr($pagebuff, 0, $pagemark);
19802									$pend = substr($pagebuff, $pagemark);
19803									$this->setPageBuffer($this->page, $pstart.$ccode.$pend);
19804								}
19805							}
19806						} // end for each page
19807						// restore default border
19808						$border = $default_border;
19809					} // end for each cell on the row
19810					if (isset($table_el['attribute']['cellspacing'])) {
19811						$this->y += $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
19812					} elseif (isset($table_el['border-spacing'])) {
19813						$this->y += $table_el['border-spacing']['V'];
19814					}
19815					$this->Ln(0, $cell);
19816					$this->x = $parent['startx'];
19817					if ($endpage > $startpage) {
19818						if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
19819							$this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
19820						} elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
19821							$this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
19822						}
19823					}
19824				}
19825				if (!$in_table_head) { // we are not inside a thead section
19826					$this->cell_padding = $table_el['old_cell_padding'];
19827					// reset row height
19828					$this->resetLastH();
19829					if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages])) {
19830						$plendiff = ($this->pagelen[$this->numpages] - $this->emptypagemrk[$this->numpages]);
19831						if (($plendiff > 0) AND ($plendiff < 60)) {
19832							$pagediff = substr($this->getPageBuffer($this->numpages), $this->emptypagemrk[$this->numpages], $plendiff);
19833							if (substr($pagediff, 0, 5) == 'BT /F') {
19834								// the difference is only a font setting
19835								$plendiff = 0;
19836							}
19837						}
19838						if ($plendiff == 0) {
19839							// remove last blank page
19840							$this->deletePage($this->numpages);
19841						}
19842					}
19843					if (isset($this->theadMargins['top'])) {
19844						// restore top margin
19845						$this->tMargin = $this->theadMargins['top'];
19846					}
19847					if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
19848						// reset main table header
19849						$this->thead = '';
19850						$this->theadMargins = array();
19851						$this->pagedim[$this->page]['tm'] = $this->tMargin;
19852					}
19853				}
19854				$parent = $table_el;
19855				break;
19856			}
19857			case 'a': {
19858				$this->HREF = array();
19859				break;
19860			}
19861			case 'sup': {
19862				$this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
19863				break;
19864			}
19865			case 'sub': {
19866				$this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize']) / $this->k));
19867				break;
19868			}
19869			case 'div': {
19870				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19871				break;
19872			}
19873			case 'blockquote': {
19874				if ($this->rtl) {
19875					$this->rMargin -= $this->listindent;
19876				} else {
19877					$this->lMargin -= $this->listindent;
19878				}
19879				--$this->listindentlevel;
19880				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19881				break;
19882			}
19883			case 'p': {
19884				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19885				break;
19886			}
19887			case 'pre': {
19888				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19889				$this->premode = false;
19890				break;
19891			}
19892			case 'dl': {
19893				--$this->listnum;
19894				if ($this->listnum <= 0) {
19895					$this->listnum = 0;
19896					$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19897				} else {
19898					$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19899				}
19900				$this->resetLastH();
19901				break;
19902			}
19903			case 'dt': {
19904				$this->lispacer = '';
19905				$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19906				break;
19907			}
19908			case 'dd': {
19909				$this->lispacer = '';
19910				if ($this->rtl) {
19911					$this->rMargin -= $this->listindent;
19912				} else {
19913					$this->lMargin -= $this->listindent;
19914				}
19915				--$this->listindentlevel;
19916				$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19917				break;
19918			}
19919			case 'ul':
19920			case 'ol': {
19921				--$this->listnum;
19922				$this->lispacer = '';
19923				if ($this->rtl) {
19924					$this->rMargin -= $this->listindent;
19925				} else {
19926					$this->lMargin -= $this->listindent;
19927				}
19928				--$this->listindentlevel;
19929				if ($this->listnum <= 0) {
19930					$this->listnum = 0;
19931					$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19932				} else {
19933					$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19934				}
19935				$this->resetLastH();
19936				break;
19937			}
19938			case 'li': {
19939				$this->lispacer = '';
19940				$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19941				break;
19942			}
19943			case 'h1':
19944			case 'h2':
19945			case 'h3':
19946			case 'h4':
19947			case 'h5':
19948			case 'h6': {
19949				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19950				break;
19951			}
19952			// Form fields (since 4.8.000 - 2009-09-07)
19953			case 'form': {
19954				$this->form_action = '';
19955				$this->form_enctype = 'application/x-www-form-urlencoded';
19956				break;
19957			}
19958			default : {
19959				break;
19960			}
19961		}
19962		// draw border and background (if any)
19963		$this->drawHTMLTagBorder($parent, $xmax);
19964		if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
19965			$pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
19966			// check for pagebreak
19967			if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
19968				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19969				$this->checkPageBreak($this->PageBreakTrigger + 1);
19970			}
19971			if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
19972				OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
19973				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19974				$this->checkPageBreak($this->PageBreakTrigger + 1);
19975			}
19976		}
19977		$this->tmprtl = false;
19978		return $dom;
19979	}
19980
19981	/**
19982	 * Add vertical spaces if needed.
19983	 * @param $hbz (string) Distance between current y and line bottom.
19984	 * @param $hb (string) The height of the break.
19985	 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
19986	 * @param $firsttag (boolean) set to true when the tag is the first.
19987	 * @param $lasttag (boolean) set to true when the tag is the last.
19988	 * @protected
19989	 */
19990	protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
19991		if ($firsttag) {
19992			$this->Ln(0, $cell);
19993			$this->htmlvspace = 0;
19994			return;
19995		}
19996		if ($lasttag) {
19997			$this->Ln($hbz, $cell);
19998			$this->htmlvspace = 0;
19999			return;
20000		}
20001		if ($hb < $this->htmlvspace) {
20002			$hd = 0;
20003		} else {
20004			$hd = $hb - $this->htmlvspace;
20005			$this->htmlvspace = $hb;
20006		}
20007		$this->Ln(($hbz + $hd), $cell);
20008	}
20009
20010	/**
20011	 * Return the starting coordinates to draw an html border
20012	 * @return array containing top-left border coordinates
20013	 * @protected
20014	 * @since 5.7.000 (2010-08-03)
20015	 */
20016	protected function getBorderStartPosition() {
20017		if ($this->rtl) {
20018			$xmax = $this->lMargin;
20019		} else {
20020			$xmax = $this->w - $this->rMargin;
20021		}
20022		return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax);
20023	}
20024
20025	/**
20026	 * Draw an HTML block border and fill
20027	 * @param $tag (array) array of tag properties.
20028	 * @param $xmax (int) end X coordinate for border.
20029	 * @protected
20030	 * @since 5.7.000 (2010-08-03)
20031	 */
20032	protected function drawHTMLTagBorder($tag, $xmax) {
20033		if (!isset($tag['borderposition'])) {
20034			// nothing to draw
20035			return;
20036		}
20037		$prev_x = $this->x;
20038		$prev_y = $this->y;
20039		$prev_lasth = $this->lasth;
20040		$border = 0;
20041		$fill = false;
20042		$this->lasth = 0;
20043		if (isset($tag['border']) AND !empty($tag['border'])) {
20044			// get border style
20045			$border = $tag['border'];
20046			if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
20047				// border for table header
20048				$border = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
20049			}
20050		}
20051		if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
20052			// get background color
20053			$old_bgcolor = $this->bgcolor;
20054			$this->SetFillColorArray($tag['bgcolor']);
20055			$fill = true;
20056		}
20057		if (!$border AND !$fill) {
20058			// nothing to draw
20059			return;
20060		}
20061		if (isset($tag['attribute']['cellspacing'])) {
20062			$clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
20063			$cellspacing = array('H' => $clsp, 'V' => $clsp);
20064		} elseif (isset($tag['border-spacing'])) {
20065			$cellspacing = $tag['border-spacing'];
20066		} else {
20067			$cellspacing = array('H' => 0, 'V' => 0);
20068		}
20069		if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
20070			// draw the border externally respect the sqare edge.
20071			$border['mode'] = 'ext';
20072		}
20073		if ($this->rtl) {
20074			if ($xmax >= $tag['borderposition']['x']) {
20075				$xmax = $tag['borderposition']['xmax'];
20076			}
20077			$w = ($tag['borderposition']['x'] - $xmax);
20078		} else {
20079			if ($xmax <= $tag['borderposition']['x']) {
20080				$xmax = $tag['borderposition']['xmax'];
20081			}
20082			$w = ($xmax - $tag['borderposition']['x']);
20083		}
20084		if ($w <= 0) {
20085			return;
20086		}
20087		$w += $cellspacing['H'];
20088		$startpage = $tag['borderposition']['page'];
20089		$startcolumn = $tag['borderposition']['column'];
20090		$x = $tag['borderposition']['x'];
20091		$y = $tag['borderposition']['y'];
20092		$endpage = $this->page;
20093		$starty = $tag['borderposition']['y'] - $cellspacing['V'];
20094		$currentY = $this->y;
20095		$this->x = $x;
20096		// get latest column
20097		$endcolumn = $this->current_column;
20098		if ($this->num_columns == 0) {
20099			$this->num_columns = 1;
20100		}
20101		// get border modes
20102		$border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
20103		$border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
20104		$border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
20105		// temporary disable page regions
20106		$temp_page_regions = $this->page_regions;
20107		$this->page_regions = array();
20108		// design borders around HTML cells.
20109		for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
20110			$ccode = '';
20111			$this->setPage($page);
20112			if ($this->num_columns < 2) {
20113				// single-column mode
20114				$this->x = $x;
20115				$this->y = $this->tMargin;
20116			}
20117			// account for margin changes
20118			if ($page > $startpage) {
20119				if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
20120					$this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
20121				} elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
20122					$this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
20123				}
20124			}
20125			if ($startpage == $endpage) {
20126				// single page
20127				for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
20128					$this->selectColumn($column);
20129					if ($startcolumn == $endcolumn) { // single column
20130						$cborder = $border;
20131						$h = ($currentY - $y) + $cellspacing['V'];
20132						$this->y = $starty;
20133					} elseif ($column == $startcolumn) { // first column
20134						$cborder = $border_start;
20135						$this->y = $starty;
20136						$h = $this->h - $this->y - $this->bMargin;
20137					} elseif ($column == $endcolumn) { // end column
20138						$cborder = $border_end;
20139						$h = $currentY - $this->y;
20140					} else { // middle column
20141						$cborder = $border_middle;
20142						$h = $this->h - $this->y - $this->bMargin;
20143					}
20144					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20145				} // end for each column
20146			} elseif ($page == $startpage) { // first page
20147				for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
20148					$this->selectColumn($column);
20149					if ($column == $startcolumn) { // first column
20150						$cborder = $border_start;
20151						$this->y = $starty;
20152						$h = $this->h - $this->y - $this->bMargin;
20153					} else { // middle column
20154						$cborder = $border_middle;
20155						$h = $this->h - $this->y - $this->bMargin;
20156					}
20157					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20158				} // end for each column
20159			} elseif ($page == $endpage) { // last page
20160				for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
20161					$this->selectColumn($column);
20162					if ($column == $endcolumn) {
20163						// end column
20164						$cborder = $border_end;
20165						$h = $currentY - $this->y;
20166					} else {
20167						// middle column
20168						$cborder = $border_middle;
20169						$h = $this->h - $this->y - $this->bMargin;
20170					}
20171					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20172				} // end for each column
20173			} else { // middle page
20174				for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
20175					$this->selectColumn($column);
20176					$cborder = $border_middle;
20177					$h = $this->h - $this->y - $this->bMargin;
20178					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20179				} // end for each column
20180			}
20181			if ($cborder OR $fill) {
20182				$offsetlen = strlen($ccode);
20183				// draw border and fill
20184				if ($this->inxobj) {
20185					// we are inside an XObject template
20186					if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
20187						$pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
20188						$pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
20189						$this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
20190					} else {
20191						$pagemark = $this->xobjects[$this->xobjid]['intmrk'];
20192						$this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
20193					}
20194					$pagebuff = $this->xobjects[$this->xobjid]['outdata'];
20195					$pstart = substr($pagebuff, 0, $pagemark);
20196					$pend = substr($pagebuff, $pagemark);
20197					$this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
20198				} else {
20199					if (end($this->transfmrk[$this->page]) !== false) {
20200						$pagemarkkey = key($this->transfmrk[$this->page]);
20201						$pagemark = $this->transfmrk[$this->page][$pagemarkkey];
20202					} elseif ($this->InFooter) {
20203						$pagemark = $this->footerpos[$this->page];
20204					} else {
20205						$pagemark = $this->intmrk[$this->page];
20206					}
20207					$pagebuff = $this->getPageBuffer($this->page);
20208					$pstart = substr($pagebuff, 0, $pagemark);
20209					$pend = substr($pagebuff, $pagemark);
20210					$this->setPageBuffer($this->page, $pstart.$ccode.$pend);
20211					$this->bordermrk[$this->page] += $offsetlen;
20212					$this->cntmrk[$this->page] += $offsetlen;
20213				}
20214			}
20215		} // end for each page
20216		// restore page regions
20217		$this->page_regions = $temp_page_regions;
20218		if (isset($old_bgcolor)) {
20219			// restore background color
20220			$this->SetFillColorArray($old_bgcolor);
20221		}
20222		// restore pointer position
20223		$this->x = $prev_x;
20224		$this->y = $prev_y;
20225		$this->lasth = $prev_lasth;
20226	}
20227
20228	/**
20229	 * Set the default bullet to be used as LI bullet symbol
20230	 * @param $symbol (string) character or string to be used (legal values are: '' = automatic, '!' = auto bullet, '#' = auto numbering, 'disc', 'disc', 'circle', 'square', '1', 'decimal', 'decimal-leading-zero', 'i', 'lower-roman', 'I', 'upper-roman', 'a', 'lower-alpha', 'lower-latin', 'A', 'upper-alpha', 'upper-latin', 'lower-greek', 'img|type|width|height|image.ext')
20231	 * @public
20232	 * @since 4.0.028 (2008-09-26)
20233	 */
20234	public function setLIsymbol($symbol='!') {
20235		// check for custom image symbol
20236		if (substr($symbol, 0, 4) == 'img|') {
20237			$this->lisymbol = $symbol;
20238			return;
20239		}
20240		$symbol = strtolower($symbol);
20241		$valid_symbols = array('!', '#', 'disc', 'circle', 'square', '1', 'decimal', 'decimal-leading-zero', 'i', 'lower-roman', 'I', 'upper-roman', 'a', 'lower-alpha', 'lower-latin', 'A', 'upper-alpha', 'upper-latin', 'lower-greek');
20242		if (in_array($symbol, $valid_symbols)) {
20243			$this->lisymbol = $symbol;
20244		} else {
20245			$this->lisymbol = '';
20246		}
20247	}
20248
20249	/**
20250	 * Set the booklet mode for double-sided pages.
20251	 * @param $booklet (boolean) true set the booklet mode on, false otherwise.
20252	 * @param $inner (float) Inner page margin.
20253	 * @param $outer (float) Outer page margin.
20254	 * @public
20255	 * @since 4.2.000 (2008-10-29)
20256	 */
20257	public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
20258		$this->booklet = $booklet;
20259		if ($inner >= 0) {
20260			$this->lMargin = $inner;
20261		}
20262		if ($outer >= 0) {
20263			$this->rMargin = $outer;
20264		}
20265	}
20266
20267	/**
20268	 * Swap the left and right margins.
20269	 * @param $reverse (boolean) if true swap left and right margins.
20270	 * @protected
20271	 * @since 4.2.000 (2008-10-29)
20272	 */
20273	protected function swapMargins($reverse=true) {
20274		if ($reverse) {
20275			// swap left and right margins
20276			$mtemp = $this->original_lMargin;
20277			$this->original_lMargin = $this->original_rMargin;
20278			$this->original_rMargin = $mtemp;
20279			$deltam = $this->original_lMargin - $this->original_rMargin;
20280			$this->lMargin += $deltam;
20281			$this->rMargin -= $deltam;
20282		}
20283	}
20284
20285	/**
20286	 * Set the vertical spaces for HTML tags.
20287	 * The array must have the following structure (example):
20288	 * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
20289	 * The first array level contains the tag names,
20290	 * the second level contains 0 for opening tags or 1 for closing tags,
20291	 * the third level contains the vertical space unit (h) and the number spaces to add (n).
20292	 * If the h parameter is not specified, default values are used.
20293	 * @param $tagvs (array) array of tags and relative vertical spaces.
20294	 * @public
20295	 * @since 4.2.001 (2008-10-30)
20296	 */
20297	public function setHtmlVSpace($tagvs) {
20298		$this->tagvspaces = $tagvs;
20299	}
20300
20301	/**
20302	 * Set custom width for list indentation.
20303	 * @param $width (float) width of the indentation. Use negative value to disable it.
20304	 * @public
20305	 * @since 4.2.007 (2008-11-12)
20306	 */
20307	public function setListIndentWidth($width) {
20308		return $this->customlistindent = floatval($width);
20309	}
20310
20311	/**
20312	 * Set the top/bottom cell sides to be open or closed when the cell cross the page.
20313	 * @param $isopen (boolean) if true keeps the top/bottom border open for the cell sides that cross the page.
20314	 * @public
20315	 * @since 4.2.010 (2008-11-14)
20316	 */
20317	public function setOpenCell($isopen) {
20318		$this->opencell = $isopen;
20319	}
20320
20321	/**
20322	 * Set the color and font style for HTML links.
20323	 * @param $color (array) RGB array of colors
20324	 * @param $fontstyle (string) additional font styles to add
20325	 * @public
20326	 * @since 4.4.003 (2008-12-09)
20327	 */
20328	public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
20329		$this->htmlLinkColorArray = $color;
20330		$this->htmlLinkFontStyle = $fontstyle;
20331	}
20332
20333	/**
20334	 * Convert HTML string containing value and unit of measure to user's units or points.
20335	 * @param $htmlval (string) String containing values and unit.
20336	 * @param $refsize (string) Reference value in points.
20337	 * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
20338	 * @param $points (boolean) If true returns points, otherwise returns value in user's units.
20339	 * @return float value in user's unit or point if $points=true
20340	 * @public
20341	 * @since 4.4.004 (2008-12-10)
20342	 */
20343	public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
20344		$supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
20345		$retval = 0;
20346		$value = 0;
20347		$unit = 'px';
20348		if ($points) {
20349			$k = 1;
20350		} else {
20351			$k = $this->k;
20352		}
20353		if (in_array($defaultunit, $supportedunits)) {
20354			$unit = $defaultunit;
20355		}
20356		if (is_numeric($htmlval)) {
20357			$value = floatval($htmlval);
20358		} elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
20359			$value = floatval($mnum[1]);
20360			if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
20361				if (in_array($munit[1], $supportedunits)) {
20362					$unit = $munit[1];
20363				}
20364			}
20365		}
20366		switch ($unit) {
20367			// percentage
20368			case '%': {
20369				$retval = (($value * $refsize) / 100);
20370				break;
20371			}
20372			// relative-size
20373			case 'em': {
20374				$retval = ($value * $refsize);
20375				break;
20376			}
20377			// height of lower case 'x' (about half the font-size)
20378			case 'ex': {
20379				$retval = ($value * ($refsize / 2));
20380				break;
20381			}
20382			// absolute-size
20383			case 'in': {
20384				$retval = (($value * $this->dpi) / $k);
20385				break;
20386			}
20387			// centimeters
20388			case 'cm': {
20389				$retval = (($value / 2.54 * $this->dpi) / $k);
20390				break;
20391			}
20392			// millimeters
20393			case 'mm': {
20394				$retval = (($value / 25.4 * $this->dpi) / $k);
20395				break;
20396			}
20397			// one pica is 12 points
20398			case 'pc': {
20399				$retval = (($value * 12) / $k);
20400				break;
20401			}
20402			// points
20403			case 'pt': {
20404				$retval = ($value / $k);
20405				break;
20406			}
20407			// pixels
20408			case 'px': {
20409				$retval = $this->pixelsToUnits($value);
20410				if ($points) {
20411					$retval *= $this->k;
20412				}
20413				break;
20414			}
20415		}
20416		return $retval;
20417	}
20418
20419	/**
20420	 * Output an HTML list bullet or ordered item symbol
20421	 * @param $listdepth (int) list nesting level
20422	 * @param $listtype (string) type of list
20423	 * @param $size (float) current font size
20424	 * @protected
20425	 * @since 4.4.004 (2008-12-10)
20426	 */
20427	protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
20428		if ($this->state != 2) {
20429			return;
20430		}
20431		$size /= $this->k;
20432		$fill = '';
20433		$bgcolor = $this->bgcolor;
20434		$color = $this->fgcolor;
20435		$strokecolor = $this->strokecolor;
20436		$width = 0;
20437		$textitem = '';
20438		$tmpx = $this->x;
20439		$lspace = $this->GetStringWidth('  ');
20440		if ($listtype == '^') {
20441			// special symbol used for avoid justification of rect bullet
20442			$this->lispacer = '';
20443			return;
20444		} elseif ($listtype == '!') {
20445			// set default list type for unordered list
20446			$deftypes = array('disc', 'circle', 'square');
20447			$listtype = $deftypes[($listdepth - 1) % 3];
20448		} elseif ($listtype == '#') {
20449			// set default list type for ordered list
20450			$listtype = 'decimal';
20451		} elseif (substr($listtype, 0, 4) == 'img|') {
20452			// custom image type ('img|type|width|height|image.ext')
20453			$img = explode('|', $listtype);
20454			$listtype = 'img';
20455		}
20456		switch ($listtype) {
20457			// unordered types
20458			case 'none': {
20459				break;
20460			}
20461			case 'disc': {
20462				$r = $size / 6;
20463				$lspace += (2 * $r);
20464				if ($this->rtl) {
20465					$this->x += $lspace;
20466				} else {
20467					$this->x -= $lspace;
20468				}
20469				$this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, 'F', array(), $color, 8);
20470				break;
20471			}
20472			case 'circle': {
20473				$r = $size / 6;
20474				$lspace += (2 * $r);
20475				if ($this->rtl) {
20476					$this->x += $lspace;
20477				} else {
20478					$this->x -= $lspace;
20479				}
20480				$prev_line_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor;
20481				$new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
20482				$this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
20483				$this->_out($prev_line_style); // restore line settings
20484				break;
20485			}
20486			case 'square': {
20487				$l = $size / 3;
20488				$lspace += $l;
20489				if ($this->rtl) {;
20490					$this->x += $lspace;
20491				} else {
20492					$this->x -= $lspace;
20493				}
20494				$this->Rect($this->x, ($this->y + (($this->lasth - $l) / 2)), $l, $l, 'F', array(), $color);
20495				break;
20496			}
20497			case 'img': {
20498				// 1=>type, 2=>width, 3=>height, 4=>image.ext
20499				$lspace += $img[2];
20500				if ($this->rtl) {;
20501					$this->x += $lspace;
20502				} else {
20503					$this->x -= $lspace;
20504				}
20505				$imgtype = strtolower($img[1]);
20506				$prev_y = $this->y;
20507				switch ($imgtype) {
20508					case 'svg': {
20509						$this->ImageSVG($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
20510						break;
20511					}
20512					case 'ai':
20513					case 'eps': {
20514						$this->ImageEps($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
20515						break;
20516					}
20517					default: {
20518						$this->Image($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], $img[1], '', 'T', false, 300, '', false, false, 0, false, false, false);
20519						break;
20520					}
20521				}
20522				$this->y = $prev_y;
20523				break;
20524			}
20525			// ordered types
20526			// $this->listcount[$this->listnum];
20527			// $textitem
20528			case '1':
20529			case 'decimal': {
20530				$textitem = $this->listcount[$this->listnum];
20531				break;
20532			}
20533			case 'decimal-leading-zero': {
20534				$textitem = sprintf('%02d', $this->listcount[$this->listnum]);
20535				break;
20536			}
20537			case 'i':
20538			case 'lower-roman': {
20539				$textitem = strtolower(TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]));
20540				break;
20541			}
20542			case 'I':
20543			case 'upper-roman': {
20544				$textitem = TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]);
20545				break;
20546			}
20547			case 'a':
20548			case 'lower-alpha':
20549			case 'lower-latin': {
20550				$textitem = chr(97 + $this->listcount[$this->listnum] - 1);
20551				break;
20552			}
20553			case 'A':
20554			case 'upper-alpha':
20555			case 'upper-latin': {
20556				$textitem = chr(65 + $this->listcount[$this->listnum] - 1);
20557				break;
20558			}
20559			case 'lower-greek': {
20560				$textitem = TCPDF_FONTS::unichr((945 + $this->listcount[$this->listnum] - 1), $this->isunicode);
20561				break;
20562			}
20563			/*
20564			// Types to be implemented (special handling)
20565			case 'hebrew': {
20566				break;
20567			}
20568			case 'armenian': {
20569				break;
20570			}
20571			case 'georgian': {
20572				break;
20573			}
20574			case 'cjk-ideographic': {
20575				break;
20576			}
20577			case 'hiragana': {
20578				break;
20579			}
20580			case 'katakana': {
20581				break;
20582			}
20583			case 'hiragana-iroha': {
20584				break;
20585			}
20586			case 'katakana-iroha': {
20587				break;
20588			}
20589			*/
20590			default: {
20591				$textitem = $this->listcount[$this->listnum];
20592			}
20593		}
20594		if (!TCPDF_STATIC::empty_string($textitem)) {
20595			// Check whether we need a new page or new column
20596			$prev_y = $this->y;
20597			$h = $this->getCellHeight($this->FontSize);
20598			if ($this->checkPageBreak($h) OR ($this->y < $prev_y)) {
20599				$tmpx = $this->x;
20600			}
20601			// print ordered item
20602			if ($this->rtl) {
20603				$textitem = '.'.$textitem;
20604			} else {
20605				$textitem = $textitem.'.';
20606			}
20607			$lspace += $this->GetStringWidth($textitem);
20608			if ($this->rtl) {
20609				$this->x += $lspace;
20610			} else {
20611				$this->x -= $lspace;
20612			}
20613			$this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
20614		}
20615		$this->x = $tmpx;
20616		$this->lispacer = '^';
20617		// restore colors
20618		$this->SetFillColorArray($bgcolor);
20619		$this->SetDrawColorArray($strokecolor);
20620		$this->SettextColorArray($color);
20621	}
20622
20623	/**
20624	 * Returns current graphic variables as array.
20625	 * @return array of graphic variables
20626	 * @protected
20627	 * @since 4.2.010 (2008-11-14)
20628	 */
20629	protected function getGraphicVars() {
20630		$grapvars = array(
20631			'FontFamily' => $this->FontFamily,
20632			'FontStyle' => $this->FontStyle,
20633			'FontSizePt' => $this->FontSizePt,
20634			'rMargin' => $this->rMargin,
20635			'lMargin' => $this->lMargin,
20636			'cell_padding' => $this->cell_padding,
20637			'cell_margin' => $this->cell_margin,
20638			'LineWidth' => $this->LineWidth,
20639			'linestyleWidth' => $this->linestyleWidth,
20640			'linestyleCap' => $this->linestyleCap,
20641			'linestyleJoin' => $this->linestyleJoin,
20642			'linestyleDash' => $this->linestyleDash,
20643			'textrendermode' => $this->textrendermode,
20644			'textstrokewidth' => $this->textstrokewidth,
20645			'DrawColor' => $this->DrawColor,
20646			'FillColor' => $this->FillColor,
20647			'TextColor' => $this->TextColor,
20648			'ColorFlag' => $this->ColorFlag,
20649			'bgcolor' => $this->bgcolor,
20650			'fgcolor' => $this->fgcolor,
20651			'htmlvspace' => $this->htmlvspace,
20652			'listindent' => $this->listindent,
20653			'listindentlevel' => $this->listindentlevel,
20654			'listnum' => $this->listnum,
20655			'listordered' => $this->listordered,
20656			'listcount' => $this->listcount,
20657			'lispacer' => $this->lispacer,
20658			'cell_height_ratio' => $this->cell_height_ratio,
20659			'font_stretching' => $this->font_stretching,
20660			'font_spacing' => $this->font_spacing,
20661			'alpha' => $this->alpha,
20662			// extended
20663			'lasth' => $this->lasth,
20664			'tMargin' => $this->tMargin,
20665			'bMargin' => $this->bMargin,
20666			'AutoPageBreak' => $this->AutoPageBreak,
20667			'PageBreakTrigger' => $this->PageBreakTrigger,
20668			'x' => $this->x,
20669			'y' => $this->y,
20670			'w' => $this->w,
20671			'h' => $this->h,
20672			'wPt' => $this->wPt,
20673			'hPt' => $this->hPt,
20674			'fwPt' => $this->fwPt,
20675			'fhPt' => $this->fhPt,
20676			'page' => $this->page,
20677			'current_column' => $this->current_column,
20678			'num_columns' => $this->num_columns
20679			);
20680		return $grapvars;
20681	}
20682
20683	/**
20684	 * Set graphic variables.
20685	 * @param $gvars (array) array of graphic variablesto restore
20686	 * @param $extended (boolean) if true restore extended graphic variables
20687	 * @protected
20688	 * @since 4.2.010 (2008-11-14)
20689	 */
20690	protected function setGraphicVars($gvars, $extended=false) {
20691		if ($this->state != 2) {
20692			 return;
20693		}
20694		$this->FontFamily = $gvars['FontFamily'];
20695		$this->FontStyle = $gvars['FontStyle'];
20696		$this->FontSizePt = $gvars['FontSizePt'];
20697		$this->rMargin = $gvars['rMargin'];
20698		$this->lMargin = $gvars['lMargin'];
20699		$this->cell_padding = $gvars['cell_padding'];
20700		$this->cell_margin = $gvars['cell_margin'];
20701		$this->LineWidth = $gvars['LineWidth'];
20702		$this->linestyleWidth = $gvars['linestyleWidth'];
20703		$this->linestyleCap = $gvars['linestyleCap'];
20704		$this->linestyleJoin = $gvars['linestyleJoin'];
20705		$this->linestyleDash = $gvars['linestyleDash'];
20706		$this->textrendermode = $gvars['textrendermode'];
20707		$this->textstrokewidth = $gvars['textstrokewidth'];
20708		$this->DrawColor = $gvars['DrawColor'];
20709		$this->FillColor = $gvars['FillColor'];
20710		$this->TextColor = $gvars['TextColor'];
20711		$this->ColorFlag = $gvars['ColorFlag'];
20712		$this->bgcolor = $gvars['bgcolor'];
20713		$this->fgcolor = $gvars['fgcolor'];
20714		$this->htmlvspace = $gvars['htmlvspace'];
20715		$this->listindent = $gvars['listindent'];
20716		$this->listindentlevel = $gvars['listindentlevel'];
20717		$this->listnum = $gvars['listnum'];
20718		$this->listordered = $gvars['listordered'];
20719		$this->listcount = $gvars['listcount'];
20720		$this->lispacer = $gvars['lispacer'];
20721		$this->cell_height_ratio = $gvars['cell_height_ratio'];
20722		$this->font_stretching = $gvars['font_stretching'];
20723		$this->font_spacing = $gvars['font_spacing'];
20724		$this->alpha = $gvars['alpha'];
20725		if ($extended) {
20726			// restore extended values
20727			$this->lasth = $gvars['lasth'];
20728			$this->tMargin = $gvars['tMargin'];
20729			$this->bMargin = $gvars['bMargin'];
20730			$this->AutoPageBreak = $gvars['AutoPageBreak'];
20731			$this->PageBreakTrigger = $gvars['PageBreakTrigger'];
20732			$this->x = $gvars['x'];
20733			$this->y = $gvars['y'];
20734			$this->w = $gvars['w'];
20735			$this->h = $gvars['h'];
20736			$this->wPt = $gvars['wPt'];
20737			$this->hPt = $gvars['hPt'];
20738			$this->fwPt = $gvars['fwPt'];
20739			$this->fhPt = $gvars['fhPt'];
20740			$this->page = $gvars['page'];
20741			$this->current_column = $gvars['current_column'];
20742			$this->num_columns = $gvars['num_columns'];
20743		}
20744		$this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
20745		if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
20746			$this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
20747		}
20748	}
20749
20750	/**
20751	 * Outputs the "save graphics state" operator 'q'
20752	 * @protected
20753	 */
20754	protected function _outSaveGraphicsState() {
20755		$this->_out('q');
20756	}
20757
20758	/**
20759	 * Outputs the "restore graphics state" operator 'Q'
20760	 * @protected
20761	 */
20762	protected function _outRestoreGraphicsState() {
20763		$this->_out('Q');
20764	}
20765
20766	/**
20767	 * Set buffer content (always append data).
20768	 * @param $data (string) data
20769	 * @protected
20770	 * @since 4.5.000 (2009-01-02)
20771	 */
20772	protected function setBuffer($data) {
20773		$this->bufferlen += strlen($data);
20774		$this->buffer .= $data;
20775	}
20776
20777	/**
20778	 * Replace the buffer content
20779	 * @param $data (string) data
20780	 * @protected
20781	 * @since 5.5.000 (2010-06-22)
20782	 */
20783	protected function replaceBuffer($data) {
20784		$this->bufferlen = strlen($data);
20785		$this->buffer = $data;
20786	}
20787
20788	/**
20789	 * Get buffer content.
20790	 * @return string buffer content
20791	 * @protected
20792	 * @since 4.5.000 (2009-01-02)
20793	 */
20794	protected function getBuffer() {
20795		return $this->buffer;
20796	}
20797
20798	/**
20799	 * Set page buffer content.
20800	 * @param $page (int) page number
20801	 * @param $data (string) page data
20802	 * @param $append (boolean) if true append data, false replace.
20803	 * @protected
20804	 * @since 4.5.000 (2008-12-31)
20805	 */
20806	protected function setPageBuffer($page, $data, $append=false) {
20807		if ($append) {
20808			$this->pages[$page] .= $data;
20809		} else {
20810			$this->pages[$page] = $data;
20811		}
20812		if ($append AND isset($this->pagelen[$page])) {
20813			$this->pagelen[$page] += strlen($data);
20814		} else {
20815			$this->pagelen[$page] = strlen($data);
20816		}
20817	}
20818
20819	/**
20820	 * Get page buffer content.
20821	 * @param $page (int) page number
20822	 * @return string page buffer content or false in case of error
20823	 * @protected
20824	 * @since 4.5.000 (2008-12-31)
20825	 */
20826	protected function getPageBuffer($page) {
20827		if (isset($this->pages[$page])) {
20828			return $this->pages[$page];
20829		}
20830		return false;
20831	}
20832
20833	/**
20834	 * Set image buffer content.
20835	 * @param $image (string) image key
20836	 * @param $data (array) image data
20837	 * @return int image index number
20838	 * @protected
20839	 * @since 4.5.000 (2008-12-31)
20840	 */
20841	protected function setImageBuffer($image, $data) {
20842		if (($data['i'] = array_search($image, $this->imagekeys)) === FALSE) {
20843			$this->imagekeys[$this->numimages] = $image;
20844			$data['i'] = $this->numimages;
20845			++$this->numimages;
20846		}
20847		$this->images[$image] = $data;
20848		return $data['i'];
20849	}
20850
20851	/**
20852	 * Set image buffer content for a specified sub-key.
20853	 * @param $image (string) image key
20854	 * @param $key (string) image sub-key
20855	 * @param $data (array) image data
20856	 * @protected
20857	 * @since 4.5.000 (2008-12-31)
20858	 */
20859	protected function setImageSubBuffer($image, $key, $data) {
20860		if (!isset($this->images[$image])) {
20861			$this->setImageBuffer($image, array());
20862		}
20863		$this->images[$image][$key] = $data;
20864	}
20865
20866	/**
20867	 * Get image buffer content.
20868	 * @param $image (string) image key
20869	 * @return string image buffer content or false in case of error
20870	 * @protected
20871	 * @since 4.5.000 (2008-12-31)
20872	 */
20873	protected function getImageBuffer($image) {
20874		if (isset($this->images[$image])) {
20875			return $this->images[$image];
20876		}
20877		return false;
20878	}
20879
20880	/**
20881	 * Set font buffer content.
20882	 * @param $font (string) font key
20883	 * @param $data (array) font data
20884	 * @protected
20885	 * @since 4.5.000 (2009-01-02)
20886	 */
20887	protected function setFontBuffer($font, $data) {
20888		$this->fonts[$font] = $data;
20889		if (!in_array($font, $this->fontkeys)) {
20890			$this->fontkeys[] = $font;
20891			// store object ID for current font
20892			++$this->n;
20893			$this->font_obj_ids[$font] = $this->n;
20894			$this->setFontSubBuffer($font, 'n', $this->n);
20895		}
20896	}
20897
20898	/**
20899	 * Set font buffer content.
20900	 * @param $font (string) font key
20901	 * @param $key (string) font sub-key
20902	 * @param $data (array) font data
20903	 * @protected
20904	 * @since 4.5.000 (2009-01-02)
20905	 */
20906	protected function setFontSubBuffer($font, $key, $data) {
20907		if (!isset($this->fonts[$font])) {
20908			$this->setFontBuffer($font, array());
20909		}
20910		$this->fonts[$font][$key] = $data;
20911	}
20912
20913	/**
20914	 * Get font buffer content.
20915	 * @param $font (string) font key
20916	 * @return string font buffer content or false in case of error
20917	 * @protected
20918	 * @since 4.5.000 (2009-01-02)
20919	 */
20920	protected function getFontBuffer($font) {
20921		if (isset($this->fonts[$font])) {
20922			return $this->fonts[$font];
20923		}
20924		return false;
20925	}
20926
20927	/**
20928	 * Move a page to a previous position.
20929	 * @param $frompage (int) number of the source page
20930	 * @param $topage (int) number of the destination page (must be less than $frompage)
20931	 * @return true in case of success, false in case of error.
20932	 * @public
20933	 * @since 4.5.000 (2009-01-02)
20934	 */
20935	public function movePage($frompage, $topage) {
20936		if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
20937			return false;
20938		}
20939		if ($frompage == $this->page) {
20940			// close the page before moving it
20941			$this->endPage();
20942		}
20943		// move all page-related states
20944		$tmppage = $this->getPageBuffer($frompage);
20945		$tmppagedim = $this->pagedim[$frompage];
20946		$tmppagelen = $this->pagelen[$frompage];
20947		$tmpintmrk = $this->intmrk[$frompage];
20948		$tmpbordermrk = $this->bordermrk[$frompage];
20949		$tmpcntmrk = $this->cntmrk[$frompage];
20950		$tmppageobjects = $this->pageobjects[$frompage];
20951		if (isset($this->footerpos[$frompage])) {
20952			$tmpfooterpos = $this->footerpos[$frompage];
20953		}
20954		if (isset($this->footerlen[$frompage])) {
20955			$tmpfooterlen = $this->footerlen[$frompage];
20956		}
20957		if (isset($this->transfmrk[$frompage])) {
20958			$tmptransfmrk = $this->transfmrk[$frompage];
20959		}
20960		if (isset($this->PageAnnots[$frompage])) {
20961			$tmpannots = $this->PageAnnots[$frompage];
20962		}
20963		if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
20964			for ($i = $frompage; $i > $topage; --$i) {
20965				if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $frompage)) {
20966					--$this->pagegroups[$this->newpagegroup[$i]];
20967					break;
20968				}
20969			}
20970			for ($i = $topage; $i > 0; --$i) {
20971				if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $topage)) {
20972					++$this->pagegroups[$this->newpagegroup[$i]];
20973					break;
20974				}
20975			}
20976		}
20977		for ($i = $frompage; $i > $topage; --$i) {
20978			$j = $i - 1;
20979			// shift pages down
20980			$this->setPageBuffer($i, $this->getPageBuffer($j));
20981			$this->pagedim[$i] = $this->pagedim[$j];
20982			$this->pagelen[$i] = $this->pagelen[$j];
20983			$this->intmrk[$i] = $this->intmrk[$j];
20984			$this->bordermrk[$i] = $this->bordermrk[$j];
20985			$this->cntmrk[$i] = $this->cntmrk[$j];
20986			$this->pageobjects[$i] = $this->pageobjects[$j];
20987			if (isset($this->footerpos[$j])) {
20988				$this->footerpos[$i] = $this->footerpos[$j];
20989			} elseif (isset($this->footerpos[$i])) {
20990				unset($this->footerpos[$i]);
20991			}
20992			if (isset($this->footerlen[$j])) {
20993				$this->footerlen[$i] = $this->footerlen[$j];
20994			} elseif (isset($this->footerlen[$i])) {
20995				unset($this->footerlen[$i]);
20996			}
20997			if (isset($this->transfmrk[$j])) {
20998				$this->transfmrk[$i] = $this->transfmrk[$j];
20999			} elseif (isset($this->transfmrk[$i])) {
21000				unset($this->transfmrk[$i]);
21001			}
21002			if (isset($this->PageAnnots[$j])) {
21003				$this->PageAnnots[$i] = $this->PageAnnots[$j];
21004			} elseif (isset($this->PageAnnots[$i])) {
21005				unset($this->PageAnnots[$i]);
21006			}
21007			if (isset($this->newpagegroup[$j])) {
21008				$this->newpagegroup[$i] = $this->newpagegroup[$j];
21009				unset($this->newpagegroup[$j]);
21010			}
21011			if ($this->currpagegroup == $j) {
21012				$this->currpagegroup = $i;
21013			}
21014		}
21015		$this->setPageBuffer($topage, $tmppage);
21016		$this->pagedim[$topage] = $tmppagedim;
21017		$this->pagelen[$topage] = $tmppagelen;
21018		$this->intmrk[$topage] = $tmpintmrk;
21019		$this->bordermrk[$topage] = $tmpbordermrk;
21020		$this->cntmrk[$topage] = $tmpcntmrk;
21021		$this->pageobjects[$topage] = $tmppageobjects;
21022		if (isset($tmpfooterpos)) {
21023			$this->footerpos[$topage] = $tmpfooterpos;
21024		} elseif (isset($this->footerpos[$topage])) {
21025			unset($this->footerpos[$topage]);
21026		}
21027		if (isset($tmpfooterlen)) {
21028			$this->footerlen[$topage] = $tmpfooterlen;
21029		} elseif (isset($this->footerlen[$topage])) {
21030			unset($this->footerlen[$topage]);
21031		}
21032		if (isset($tmptransfmrk)) {
21033			$this->transfmrk[$topage] = $tmptransfmrk;
21034		} elseif (isset($this->transfmrk[$topage])) {
21035			unset($this->transfmrk[$topage]);
21036		}
21037		if (isset($tmpannots)) {
21038			$this->PageAnnots[$topage] = $tmpannots;
21039		} elseif (isset($this->PageAnnots[$topage])) {
21040			unset($this->PageAnnots[$topage]);
21041		}
21042		// adjust outlines
21043		$tmpoutlines = $this->outlines;
21044		foreach ($tmpoutlines as $key => $outline) {
21045			if (!$outline['f']) {
21046				if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
21047					$this->outlines[$key]['p'] = ($outline['p'] + 1);
21048				} elseif ($outline['p'] == $frompage) {
21049					$this->outlines[$key]['p'] = $topage;
21050				}
21051			}
21052		}
21053		// adjust dests
21054		$tmpdests = $this->dests;
21055		foreach ($tmpdests as $key => $dest) {
21056			if (!$dest['f']) {
21057				if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
21058					$this->dests[$key]['p'] = ($dest['p'] + 1);
21059				} elseif ($dest['p'] == $frompage) {
21060					$this->dests[$key]['p'] = $topage;
21061				}
21062			}
21063		}
21064		// adjust links
21065		$tmplinks = $this->links;
21066		foreach ($tmplinks as $key => $link) {
21067			if (!$link['f']) {
21068				if (($link['p'] >= $topage) AND ($link['p'] < $frompage)) {
21069					$this->links[$key]['p'] = ($link['p'] + 1);
21070				} elseif ($link['p'] == $frompage) {
21071					$this->links[$key]['p'] = $topage;
21072				}
21073			}
21074		}
21075		// adjust javascript
21076		$jfrompage = $frompage;
21077		$jtopage = $topage;
21078		if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
21079			foreach($pamatch[0] as $pk => $pmatch) {
21080				$pagenum = intval($pamatch[3][$pk]) + 1;
21081				if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
21082					$newpage = ($pagenum + 1);
21083				} elseif ($pagenum == $jfrompage) {
21084					$newpage = $jtopage;
21085				} else {
21086					$newpage = $pagenum;
21087				}
21088				--$newpage;
21089				$newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
21090				$this->javascript = str_replace($pmatch, $newjs, $this->javascript);
21091			}
21092			unset($pamatch);
21093		}
21094		// return to last page
21095		$this->lastPage(true);
21096		return true;
21097	}
21098
21099	/**
21100	 * Remove the specified page.
21101	 * @param $page (int) page to remove
21102	 * @return true in case of success, false in case of error.
21103	 * @public
21104	 * @since 4.6.004 (2009-04-23)
21105	 */
21106	public function deletePage($page) {
21107		if (($page < 1) OR ($page > $this->numpages)) {
21108			return false;
21109		}
21110		// delete current page
21111		unset($this->pages[$page]);
21112		unset($this->pagedim[$page]);
21113		unset($this->pagelen[$page]);
21114		unset($this->intmrk[$page]);
21115		unset($this->bordermrk[$page]);
21116		unset($this->cntmrk[$page]);
21117		foreach ($this->pageobjects[$page] as $oid) {
21118			if (isset($this->offsets[$oid])){
21119				unset($this->offsets[$oid]);
21120			}
21121		}
21122		unset($this->pageobjects[$page]);
21123		if (isset($this->footerpos[$page])) {
21124			unset($this->footerpos[$page]);
21125		}
21126		if (isset($this->footerlen[$page])) {
21127			unset($this->footerlen[$page]);
21128		}
21129		if (isset($this->transfmrk[$page])) {
21130			unset($this->transfmrk[$page]);
21131		}
21132		if (isset($this->PageAnnots[$page])) {
21133			unset($this->PageAnnots[$page]);
21134		}
21135		if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
21136			for ($i = $page; $i > 0; --$i) {
21137				if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $page)) {
21138					--$this->pagegroups[$this->newpagegroup[$i]];
21139					break;
21140				}
21141			}
21142		}
21143		if (isset($this->pageopen[$page])) {
21144			unset($this->pageopen[$page]);
21145		}
21146		if ($page < $this->numpages) {
21147			// update remaining pages
21148			for ($i = $page; $i < $this->numpages; ++$i) {
21149				$j = $i + 1;
21150				// shift pages
21151				$this->setPageBuffer($i, $this->getPageBuffer($j));
21152				$this->pagedim[$i] = $this->pagedim[$j];
21153				$this->pagelen[$i] = $this->pagelen[$j];
21154				$this->intmrk[$i] = $this->intmrk[$j];
21155				$this->bordermrk[$i] = $this->bordermrk[$j];
21156				$this->cntmrk[$i] = $this->cntmrk[$j];
21157				$this->pageobjects[$i] = $this->pageobjects[$j];
21158				if (isset($this->footerpos[$j])) {
21159					$this->footerpos[$i] = $this->footerpos[$j];
21160				} elseif (isset($this->footerpos[$i])) {
21161					unset($this->footerpos[$i]);
21162				}
21163				if (isset($this->footerlen[$j])) {
21164					$this->footerlen[$i] = $this->footerlen[$j];
21165				} elseif (isset($this->footerlen[$i])) {
21166					unset($this->footerlen[$i]);
21167				}
21168				if (isset($this->transfmrk[$j])) {
21169					$this->transfmrk[$i] = $this->transfmrk[$j];
21170				} elseif (isset($this->transfmrk[$i])) {
21171					unset($this->transfmrk[$i]);
21172				}
21173				if (isset($this->PageAnnots[$j])) {
21174					$this->PageAnnots[$i] = $this->PageAnnots[$j];
21175				} elseif (isset($this->PageAnnots[$i])) {
21176					unset($this->PageAnnots[$i]);
21177				}
21178				if (isset($this->newpagegroup[$j])) {
21179					$this->newpagegroup[$i] = $this->newpagegroup[$j];
21180					unset($this->newpagegroup[$j]);
21181				}
21182				if ($this->currpagegroup == $j) {
21183					$this->currpagegroup = $i;
21184				}
21185				if (isset($this->pageopen[$j])) {
21186					$this->pageopen[$i] = $this->pageopen[$j];
21187				} elseif (isset($this->pageopen[$i])) {
21188					unset($this->pageopen[$i]);
21189				}
21190			}
21191			// remove last page
21192			unset($this->pages[$this->numpages]);
21193			unset($this->pagedim[$this->numpages]);
21194			unset($this->pagelen[$this->numpages]);
21195			unset($this->intmrk[$this->numpages]);
21196			unset($this->bordermrk[$this->numpages]);
21197			unset($this->cntmrk[$this->numpages]);
21198			foreach ($this->pageobjects[$this->numpages] as $oid) {
21199				if (isset($this->offsets[$oid])){
21200					unset($this->offsets[$oid]);
21201				}
21202			}
21203			unset($this->pageobjects[$this->numpages]);
21204			if (isset($this->footerpos[$this->numpages])) {
21205				unset($this->footerpos[$this->numpages]);
21206			}
21207			if (isset($this->footerlen[$this->numpages])) {
21208				unset($this->footerlen[$this->numpages]);
21209			}
21210			if (isset($this->transfmrk[$this->numpages])) {
21211				unset($this->transfmrk[$this->numpages]);
21212			}
21213			if (isset($this->PageAnnots[$this->numpages])) {
21214				unset($this->PageAnnots[$this->numpages]);
21215			}
21216			if (isset($this->newpagegroup[$this->numpages])) {
21217				unset($this->newpagegroup[$this->numpages]);
21218			}
21219			if ($this->currpagegroup == $this->numpages) {
21220				$this->currpagegroup = ($this->numpages - 1);
21221			}
21222			if (isset($this->pagegroups[$this->numpages])) {
21223				unset($this->pagegroups[$this->numpages]);
21224			}
21225			if (isset($this->pageopen[$this->numpages])) {
21226				unset($this->pageopen[$this->numpages]);
21227			}
21228		}
21229		--$this->numpages;
21230		$this->page = $this->numpages;
21231		// adjust outlines
21232		$tmpoutlines = $this->outlines;
21233		foreach ($tmpoutlines as $key => $outline) {
21234			if (!$outline['f']) {
21235				if ($outline['p'] > $page) {
21236					$this->outlines[$key]['p'] = $outline['p'] - 1;
21237				} elseif ($outline['p'] == $page) {
21238					unset($this->outlines[$key]);
21239				}
21240			}
21241		}
21242		// adjust dests
21243		$tmpdests = $this->dests;
21244		foreach ($tmpdests as $key => $dest) {
21245			if (!$dest['f']) {
21246				if ($dest['p'] > $page) {
21247					$this->dests[$key]['p'] = $dest['p'] - 1;
21248				} elseif ($dest['p'] == $page) {
21249					unset($this->dests[$key]);
21250				}
21251			}
21252		}
21253		// adjust links
21254		$tmplinks = $this->links;
21255		foreach ($tmplinks as $key => $link) {
21256			if (!$link['f']) {
21257				if ($link['p'] > $page) {
21258					$this->links[$key]['p'] = $link['p'] - 1;
21259				} elseif ($link['p'] == $page) {
21260					unset($this->links[$key]);
21261				}
21262			}
21263		}
21264		// adjust javascript
21265		$jpage = $page;
21266		if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
21267			foreach($pamatch[0] as $pk => $pmatch) {
21268				$pagenum = intval($pamatch[3][$pk]) + 1;
21269				if ($pagenum >= $jpage) {
21270					$newpage = ($pagenum - 1);
21271				} elseif ($pagenum == $jpage) {
21272					$newpage = 1;
21273				} else {
21274					$newpage = $pagenum;
21275				}
21276				--$newpage;
21277				$newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
21278				$this->javascript = str_replace($pmatch, $newjs, $this->javascript);
21279			}
21280			unset($pamatch);
21281		}
21282		// return to last page
21283		if ($this->numpages > 0) {
21284			$this->lastPage(true);
21285		}
21286		return true;
21287	}
21288
21289	/**
21290	 * Clone the specified page to a new page.
21291	 * @param $page (int) number of page to copy (0 = current page)
21292	 * @return true in case of success, false in case of error.
21293	 * @public
21294	 * @since 4.9.015 (2010-04-20)
21295	 */
21296	public function copyPage($page=0) {
21297		if ($page == 0) {
21298			// default value
21299			$page = $this->page;
21300		}
21301		if (($page < 1) OR ($page > $this->numpages)) {
21302			return false;
21303		}
21304		// close the last page
21305		$this->endPage();
21306		// copy all page-related states
21307		++$this->numpages;
21308		$this->page = $this->numpages;
21309		$this->setPageBuffer($this->page, $this->getPageBuffer($page));
21310		$this->pagedim[$this->page] = $this->pagedim[$page];
21311		$this->pagelen[$this->page] = $this->pagelen[$page];
21312		$this->intmrk[$this->page] = $this->intmrk[$page];
21313		$this->bordermrk[$this->page] = $this->bordermrk[$page];
21314		$this->cntmrk[$this->page] = $this->cntmrk[$page];
21315		$this->pageobjects[$this->page] = $this->pageobjects[$page];
21316		$this->pageopen[$this->page] = false;
21317		if (isset($this->footerpos[$page])) {
21318			$this->footerpos[$this->page] = $this->footerpos[$page];
21319		}
21320		if (isset($this->footerlen[$page])) {
21321			$this->footerlen[$this->page] = $this->footerlen[$page];
21322		}
21323		if (isset($this->transfmrk[$page])) {
21324			$this->transfmrk[$this->page] = $this->transfmrk[$page];
21325		}
21326		if (isset($this->PageAnnots[$page])) {
21327			$this->PageAnnots[$this->page] = $this->PageAnnots[$page];
21328		}
21329		if (isset($this->newpagegroup[$page])) {
21330			// start a new group
21331			$this->newpagegroup[$this->page] = sizeof($this->newpagegroup) + 1;
21332			$this->currpagegroup = $this->newpagegroup[$this->page];
21333			$this->pagegroups[$this->currpagegroup] = 1;
21334		} elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
21335			++$this->pagegroups[$this->currpagegroup];
21336		}
21337		// copy outlines
21338		$tmpoutlines = $this->outlines;
21339		foreach ($tmpoutlines as $key => $outline) {
21340			if ($outline['p'] == $page) {
21341				$this->outlines[] = array('t' => $outline['t'], 'l' => $outline['l'], 'x' => $outline['x'], 'y' => $outline['y'], 'p' => $this->page, 'f' => $outline['f'], 's' => $outline['s'], 'c' => $outline['c']);
21342			}
21343		}
21344		// copy links
21345		$tmplinks = $this->links;
21346		foreach ($tmplinks as $key => $link) {
21347			if ($link['p'] == $page) {
21348				$this->links[] = array('p' => $this->page, 'y' => $link['y'], 'f' => $link['f']);
21349			}
21350		}
21351		// return to last page
21352		$this->lastPage(true);
21353		return true;
21354	}
21355
21356	/**
21357	 * Output a Table of Content Index (TOC).
21358	 * This method must be called after all Bookmarks were set.
21359	 * Before calling this method you have to open the page using the addTOCPage() method.
21360	 * After calling this method you have to call endTOCPage() to close the TOC page.
21361	 * You can override this method to achieve different styles.
21362	 * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
21363	 * @param $numbersfont (string) set the font for page numbers (please use monospaced font for better alignment).
21364	 * @param $filler (string) string used to fill the space between text and page number.
21365	 * @param $toc_name (string) name to use for TOC bookmark.
21366	 * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
21367	 * @param $color (array) RGB color array for bookmark title (values from 0 to 255).
21368	 * @public
21369	 * @author Nicola Asuni
21370	 * @since 4.5.000 (2009-01-02)
21371	 * @see addTOCPage(), endTOCPage(), addHTMLTOC()
21372	 */
21373	public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
21374		$fontsize = $this->FontSizePt;
21375		$fontfamily = $this->FontFamily;
21376		$fontstyle = $this->FontStyle;
21377		$w = $this->w - $this->lMargin - $this->rMargin;
21378		$spacer = $this->GetStringWidth(chr(32)) * 4;
21379		$lmargin = $this->lMargin;
21380		$rmargin = $this->rMargin;
21381		$x_start = $this->GetX();
21382		$page_first = $this->page;
21383		$current_page = $this->page;
21384		$page_fill_start = false;
21385		$page_fill_end = false;
21386		$current_column = $this->current_column;
21387		if (TCPDF_STATIC::empty_string($numbersfont)) {
21388			$numbersfont = $this->default_monospaced_font;
21389		}
21390		if (TCPDF_STATIC::empty_string($filler)) {
21391			$filler = ' ';
21392		}
21393		if (TCPDF_STATIC::empty_string($page)) {
21394			$gap = ' ';
21395		} else {
21396			$gap = '';
21397			if ($page < 1) {
21398				$page = 1;
21399			}
21400		}
21401		$this->SetFont($numbersfont, $fontstyle, $fontsize);
21402		$numwidth = $this->GetStringWidth('00000');
21403		$maxpage = 0; //used for pages on attached documents
21404		foreach ($this->outlines as $key => $outline) {
21405			// check for extra pages (used for attachments)
21406			if (($this->page > $page_first) AND ($outline['p'] >= $this->numpages)) {
21407				$outline['p'] += ($this->page - $page_first);
21408			}
21409			if ($this->rtl) {
21410				$aligntext = 'R';
21411				$alignnum = 'L';
21412			} else {
21413				$aligntext = 'L';
21414				$alignnum = 'R';
21415			}
21416			if ($outline['l'] == 0) {
21417				$this->SetFont($fontfamily, $outline['s'].'B', $fontsize);
21418			} else {
21419				$this->SetFont($fontfamily, $outline['s'], $fontsize - $outline['l']);
21420			}
21421			$this->SetTextColorArray($outline['c']);
21422			// check for page break
21423			$this->checkPageBreak(2 * $this->getCellHeight($this->FontSize));
21424			// set margins and X position
21425			if (($this->page == $current_page) AND ($this->current_column == $current_column)) {
21426				$this->lMargin = $lmargin;
21427				$this->rMargin = $rmargin;
21428			} else {
21429				if ($this->current_column != $current_column) {
21430					if ($this->rtl) {
21431						$x_start = $this->w - $this->columns[$this->current_column]['x'];
21432					} else {
21433						$x_start = $this->columns[$this->current_column]['x'];
21434					}
21435				}
21436				$lmargin = $this->lMargin;
21437				$rmargin = $this->rMargin;
21438				$current_page = $this->page;
21439				$current_column = $this->current_column;
21440			}
21441			$this->SetX($x_start);
21442			$indent = ($spacer * $outline['l']);
21443			if ($this->rtl) {
21444				$this->x -= $indent;
21445				$this->rMargin = $this->w - $this->x;
21446			} else {
21447				$this->x += $indent;
21448				$this->lMargin = $this->x;
21449			}
21450			$link = $this->AddLink();
21451			$this->SetLink($link, $outline['y'], $outline['p']);
21452			// write the text
21453			if ($this->rtl) {
21454				$txt = ' '.$outline['t'];
21455			} else {
21456				$txt = $outline['t'].' ';
21457			}
21458			$this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
21459			if ($this->rtl) {
21460				$tw = $this->x - $this->lMargin;
21461			} else {
21462				$tw = $this->w - $this->rMargin - $this->x;
21463			}
21464			$this->SetFont($numbersfont, $fontstyle, $fontsize);
21465			if (TCPDF_STATIC::empty_string($page)) {
21466				$pagenum = $outline['p'];
21467			} else {
21468				// placemark to be replaced with the correct number
21469				$pagenum = '{#'.($outline['p']).'}';
21470				if ($this->isUnicodeFont()) {
21471					$pagenum = '{'.$pagenum.'}';
21472				}
21473				$maxpage = max($maxpage, $outline['p']);
21474			}
21475			$fw = ($tw - $this->GetStringWidth($pagenum.$filler));
21476			$wfiller = $this->GetStringWidth($filler);
21477			if ($wfiller > 0) {
21478				$numfills = floor($fw / $wfiller);
21479			} else {
21480				$numfills = 0;
21481			}
21482			if ($numfills > 0) {
21483				$rowfill = str_repeat($filler, $numfills);
21484			} else {
21485				$rowfill = '';
21486			}
21487			if ($this->rtl) {
21488				$pagenum = $pagenum.$gap.$rowfill;
21489			} else {
21490				$pagenum = $rowfill.$gap.$pagenum;
21491			}
21492			// write the number
21493			$this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
21494		}
21495		$page_last = $this->getPage();
21496		$numpages = ($page_last - $page_first + 1);
21497		// account for booklet mode
21498		if ($this->booklet) {
21499			// check if a blank page is required before TOC
21500			$page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
21501			$page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
21502			if ($page_fill_start) {
21503				// add a page at the end (to be moved before TOC)
21504				$this->addPage();
21505				++$page_last;
21506				++$numpages;
21507			}
21508			if ($page_fill_end) {
21509				// add a page at the end
21510				$this->addPage();
21511				++$page_last;
21512				++$numpages;
21513			}
21514		}
21515		$maxpage = max($maxpage, $page_last);
21516		if (!TCPDF_STATIC::empty_string($page)) {
21517			for ($p = $page_first; $p <= $page_last; ++$p) {
21518				// get page data
21519				$temppage = $this->getPageBuffer($p);
21520				for ($n = 1; $n <= $maxpage; ++$n) {
21521					// update page numbers
21522					$a = '{#'.$n.'}';
21523					// get page number aliases
21524					$pnalias = $this->getInternalPageNumberAliases($a);
21525					// calculate replacement number
21526					if (($n >= $page) AND ($n <= $this->numpages)) {
21527						$np = $n + $numpages;
21528					} else {
21529						$np = $n;
21530					}
21531					$na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
21532					$nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
21533					// replace aliases with numbers
21534					foreach ($pnalias['u'] as $u) {
21535						$sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
21536						if ($this->rtl) {
21537							$nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
21538						} else {
21539							$nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
21540						}
21541						$temppage = str_replace($u, $nr, $temppage);
21542					}
21543					foreach ($pnalias['a'] as $a) {
21544						$sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
21545						if ($this->rtl) {
21546							$nr = $na.' '.$sfill;
21547						} else {
21548							$nr = $sfill.' '.$na;
21549						}
21550						$temppage = str_replace($a, $nr, $temppage);
21551					}
21552				}
21553				// save changes
21554				$this->setPageBuffer($p, $temppage);
21555			}
21556			// move pages
21557			$this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
21558			if ($page_fill_start) {
21559				$this->movePage($page_last, $page_first);
21560			}
21561			for ($i = 0; $i < $numpages; ++$i) {
21562				$this->movePage($page_last, $page);
21563			}
21564		}
21565	}
21566
21567	/**
21568	 * Output a Table Of Content Index (TOC) using HTML templates.
21569	 * This method must be called after all Bookmarks were set.
21570	 * Before calling this method you have to open the page using the addTOCPage() method.
21571	 * After calling this method you have to call endTOCPage() to close the TOC page.
21572	 * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
21573	 * @param $toc_name (string) name to use for TOC bookmark.
21574	 * @param $templates (array) array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
21575	 * @param $correct_align (boolean) if true correct the number alignment (numbers must be in monospaced font like courier and right aligned on LTR, or left aligned on RTL)
21576	 * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
21577	 * @param $color (array) RGB color array for title (values from 0 to 255).
21578	 * @public
21579	 * @author Nicola Asuni
21580	 * @since 5.0.001 (2010-05-06)
21581	 * @see addTOCPage(), endTOCPage(), addTOC()
21582	 */
21583	public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
21584		$filler = ' ';
21585		$prev_htmlLinkColorArray = $this->htmlLinkColorArray;
21586		$prev_htmlLinkFontStyle = $this->htmlLinkFontStyle;
21587		// set new style for link
21588		$this->htmlLinkColorArray = array();
21589		$this->htmlLinkFontStyle = '';
21590		$page_first = $this->getPage();
21591		$page_fill_start = false;
21592		$page_fill_end = false;
21593		// get the font type used for numbers in each template
21594		$current_font = $this->FontFamily;
21595		foreach ($templates as $level => $html) {
21596			$dom = $this->getHtmlDomArray($html);
21597			foreach ($dom as $key => $value) {
21598				if ($value['value'] == '#TOC_PAGE_NUMBER#') {
21599					$this->SetFont($dom[($key - 1)]['fontname']);
21600					$templates['F'.$level] = $this->isUnicodeFont();
21601				}
21602			}
21603		}
21604		$this->SetFont($current_font);
21605		$maxpage = 0; //used for pages on attached documents
21606		foreach ($this->outlines as $key => $outline) {
21607			// get HTML template
21608			$row = $templates[$outline['l']];
21609			if (TCPDF_STATIC::empty_string($page)) {
21610				$pagenum = $outline['p'];
21611			} else {
21612				// placemark to be replaced with the correct number
21613				$pagenum = '{#'.($outline['p']).'}';
21614				if (isset($templates['F'.$outline['l']]) && $templates['F'.$outline['l']]) {
21615					$pagenum = '{'.$pagenum.'}';
21616				}
21617				$maxpage = max($maxpage, $outline['p']);
21618			}
21619			// replace templates with current values
21620			$row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
21621			$row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
21622			// add link to page
21623			$row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
21624			// write bookmark entry
21625			$this->writeHTML($row, false, false, true, false, '');
21626		}
21627		// restore link styles
21628		$this->htmlLinkColorArray = $prev_htmlLinkColorArray;
21629		$this->htmlLinkFontStyle = $prev_htmlLinkFontStyle;
21630		// move TOC page and replace numbers
21631		$page_last = $this->getPage();
21632		$numpages = ($page_last - $page_first + 1);
21633		// account for booklet mode
21634		if ($this->booklet) {
21635			// check if a blank page is required before TOC
21636			$page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
21637			$page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
21638			if ($page_fill_start) {
21639				// add a page at the end (to be moved before TOC)
21640				$this->addPage();
21641				++$page_last;
21642				++$numpages;
21643			}
21644			if ($page_fill_end) {
21645				// add a page at the end
21646				$this->addPage();
21647				++$page_last;
21648				++$numpages;
21649			}
21650		}
21651		$maxpage = max($maxpage, $page_last);
21652		if (!TCPDF_STATIC::empty_string($page)) {
21653			for ($p = $page_first; $p <= $page_last; ++$p) {
21654				// get page data
21655				$temppage = $this->getPageBuffer($p);
21656				for ($n = 1; $n <= $maxpage; ++$n) {
21657					// update page numbers
21658					$a = '{#'.$n.'}';
21659					// get page number aliases
21660					$pnalias = $this->getInternalPageNumberAliases($a);
21661					// calculate replacement number
21662					if ($n >= $page) {
21663						$np = $n + $numpages;
21664					} else {
21665						$np = $n;
21666					}
21667					$na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
21668					$nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
21669					// replace aliases with numbers
21670					foreach ($pnalias['u'] as $u) {
21671						if ($correct_align) {
21672							$sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
21673							if ($this->rtl) {
21674								$nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
21675							} else {
21676								$nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
21677							}
21678						} else {
21679							$nr = $nu;
21680						}
21681						$temppage = str_replace($u, $nr, $temppage);
21682					}
21683					foreach ($pnalias['a'] as $a) {
21684						if ($correct_align) {
21685							$sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
21686							if ($this->rtl) {
21687								$nr = $na.' '.$sfill;
21688							} else {
21689								$nr = $sfill.' '.$na;
21690							}
21691						} else {
21692							$nr = $na;
21693						}
21694						$temppage = str_replace($a, $nr, $temppage);
21695					}
21696				}
21697				// save changes
21698				$this->setPageBuffer($p, $temppage);
21699			}
21700			// move pages
21701			$this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
21702			if ($page_fill_start) {
21703				$this->movePage($page_last, $page_first);
21704			}
21705			for ($i = 0; $i < $numpages; ++$i) {
21706				$this->movePage($page_last, $page);
21707			}
21708		}
21709	}
21710
21711	/**
21712	 * Stores a copy of the current TCPDF object used for undo operation.
21713	 * @public
21714	 * @since 4.5.029 (2009-03-19)
21715	 */
21716	public function startTransaction() {
21717		if (isset($this->objcopy)) {
21718			// remove previous copy
21719			$this->commitTransaction();
21720		}
21721		// record current page number and Y position
21722		$this->start_transaction_page = $this->page;
21723		$this->start_transaction_y = $this->y;
21724		// clone current object
21725		$this->objcopy = TCPDF_STATIC::objclone($this);
21726	}
21727
21728	/**
21729	 * Delete the copy of the current TCPDF object used for undo operation.
21730	 * @public
21731	 * @since 4.5.029 (2009-03-19)
21732	 */
21733	public function commitTransaction() {
21734		if (isset($this->objcopy)) {
21735			$this->objcopy->_destroy(true, true);
21736			unset($this->objcopy);
21737		}
21738	}
21739
21740	/**
21741	 * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
21742	 * @param $self (boolean) if true restores current class object to previous state without the need of reassignment via the returned value.
21743	 * @return TCPDF object.
21744	 * @public
21745	 * @since 4.5.029 (2009-03-19)
21746	 */
21747	public function rollbackTransaction($self=false) {
21748		if (isset($this->objcopy)) {
21749			$this->_destroy(true, true);
21750			if ($self) {
21751				$objvars = get_object_vars($this->objcopy);
21752				foreach ($objvars as $key => $value) {
21753					$this->$key = $value;
21754				}
21755			}
21756			return $this->objcopy;
21757		}
21758		return $this;
21759	}
21760
21761	// --- MULTI COLUMNS METHODS -----------------------
21762
21763	/**
21764	 * Set multiple columns of the same size
21765	 * @param $numcols (int) number of columns (set to zero to disable columns mode)
21766	 * @param $width (int) column width
21767	 * @param $y (int) column starting Y position (leave empty for current Y position)
21768	 * @public
21769	 * @since 4.9.001 (2010-03-28)
21770	 */
21771	public function setEqualColumns($numcols=0, $width=0, $y='') {
21772		$this->columns = array();
21773		if ($numcols < 2) {
21774			$numcols = 0;
21775			$this->columns = array();
21776		} else {
21777			// maximum column width
21778			$maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols;
21779			if (($width == 0) OR ($width > $maxwidth)) {
21780				$width = $maxwidth;
21781			}
21782			if (TCPDF_STATIC::empty_string($y)) {
21783				$y = $this->y;
21784			}
21785			// space between columns
21786			$space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1));
21787			// fill the columns array (with, space, starting Y position)
21788			for ($i = 0; $i < $numcols; ++$i) {
21789				$this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y);
21790			}
21791		}
21792		$this->num_columns = $numcols;
21793		$this->current_column = 0;
21794		$this->column_start_page = $this->page;
21795		$this->selectColumn(0);
21796	}
21797
21798	/**
21799	 * Remove columns and reset page margins.
21800	 * @public
21801	 * @since 5.9.072 (2011-04-26)
21802	 */
21803	public function resetColumns() {
21804		$this->lMargin = $this->original_lMargin;
21805		$this->rMargin = $this->original_rMargin;
21806		$this->setEqualColumns();
21807	}
21808
21809	/**
21810	 * Set columns array.
21811	 * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
21812	 * @param $columns (array)
21813	 * @public
21814	 * @since 4.9.001 (2010-03-28)
21815	 */
21816	public function setColumnsArray($columns) {
21817		$this->columns = $columns;
21818		$this->num_columns = count($columns);
21819		$this->current_column = 0;
21820		$this->column_start_page = $this->page;
21821		$this->selectColumn(0);
21822	}
21823
21824	/**
21825	 * Set position at a given column
21826	 * @param $col (int) column number (from 0 to getNumberOfColumns()-1); empty string = current column.
21827	 * @public
21828	 * @since 4.9.001 (2010-03-28)
21829	 */
21830	public function selectColumn($col='') {
21831		if (is_string($col)) {
21832			$col = $this->current_column;
21833		} elseif ($col >= $this->num_columns) {
21834			$col = 0;
21835		}
21836		$xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
21837		$enable_thead = false;
21838		if ($this->num_columns > 1) {
21839			if ($col != $this->current_column) {
21840				// move Y pointer at the top of the column
21841				if ($this->column_start_page == $this->page) {
21842					$this->y = $this->columns[$col]['y'];
21843				} else {
21844					$this->y = $this->tMargin;
21845				}
21846				// Avoid to write table headers more than once
21847				if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) {
21848					$enable_thead = true;
21849					$this->maxselcol['page'] = $this->page;
21850					$this->maxselcol['column'] = $col;
21851				}
21852			}
21853			$xshift = $this->colxshift;
21854			// set X position of the current column by case
21855			$listindent = ($this->listindentlevel * $this->listindent);
21856			// calculate column X position
21857			$colpos = 0;
21858			for ($i = 0; $i < $col; ++$i) {
21859				$colpos += ($this->columns[$i]['w'] + $this->columns[$i]['s']);
21860			}
21861			if ($this->rtl) {
21862				$x = $this->w - $this->original_rMargin - $colpos;
21863				$this->rMargin = ($this->w - $x + $listindent);
21864				$this->lMargin = ($x - $this->columns[$col]['w']);
21865				$this->x = $x - $listindent;
21866			} else {
21867				$x = $this->original_lMargin + $colpos;
21868				$this->lMargin = ($x + $listindent);
21869				$this->rMargin = ($this->w - $x - $this->columns[$col]['w']);
21870				$this->x = $x + $listindent;
21871			}
21872			$this->columns[$col]['x'] = $x;
21873		}
21874		$this->current_column = $col;
21875		// fix for HTML mode
21876		$this->newline = true;
21877		// print HTML table header (if any)
21878		if ((!TCPDF_STATIC::empty_string($this->thead)) AND (!$this->inthead)) {
21879			if ($enable_thead) {
21880				// print table header
21881				$this->writeHTML($this->thead, false, false, false, false, '');
21882				$this->y += $xshift['s']['V'];
21883				// store end of header position
21884				if (!isset($this->columns[$col]['th'])) {
21885					$this->columns[$col]['th'] = array();
21886				}
21887				$this->columns[$col]['th']['\''.$this->page.'\''] = $this->y;
21888				$this->lasth = 0;
21889			} elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) {
21890				$this->y = $this->columns[$col]['th']['\''.$this->page.'\''];
21891			}
21892		}
21893		// account for an html table cell over multiple columns
21894		if ($this->rtl) {
21895			$this->rMargin += $xshift['x'];
21896			$this->x -= ($xshift['x'] + $xshift['p']['R']);
21897		} else {
21898			$this->lMargin += $xshift['x'];
21899			$this->x += $xshift['x'] + $xshift['p']['L'];
21900		}
21901	}
21902
21903	/**
21904	 * Return the current column number
21905	 * @return int current column number
21906	 * @public
21907	 * @since 5.5.011 (2010-07-08)
21908	 */
21909	public function getColumn() {
21910		return $this->current_column;
21911	}
21912
21913	/**
21914	 * Return the current number of columns.
21915	 * @return int number of columns
21916	 * @public
21917	 * @since 5.8.018 (2010-08-25)
21918	 */
21919	public function getNumberOfColumns() {
21920		return $this->num_columns;
21921	}
21922
21923	/**
21924	 * Set Text rendering mode.
21925	 * @param $stroke (int) outline size in user units (0 = disable).
21926	 * @param $fill (boolean) if true fills the text (default).
21927	 * @param $clip (boolean) if true activate clipping mode
21928	 * @public
21929	 * @since 4.9.008 (2009-04-02)
21930	 */
21931	public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
21932		// Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
21933		// convert text rendering parameters
21934		if ($stroke < 0) {
21935			$stroke = 0;
21936		}
21937		if ($fill === true) {
21938			if ($stroke > 0) {
21939				if ($clip === true) {
21940					// Fill, then stroke text and add to path for clipping
21941					$textrendermode = 6;
21942				} else {
21943					// Fill, then stroke text
21944					$textrendermode = 2;
21945				}
21946				$textstrokewidth = $stroke;
21947			} else {
21948				if ($clip === true) {
21949					// Fill text and add to path for clipping
21950					$textrendermode = 4;
21951				} else {
21952					// Fill text
21953					$textrendermode = 0;
21954				}
21955			}
21956		} else {
21957			if ($stroke > 0) {
21958				if ($clip === true) {
21959					// Stroke text and add to path for clipping
21960					$textrendermode = 5;
21961				} else {
21962					// Stroke text
21963					$textrendermode = 1;
21964				}
21965				$textstrokewidth = $stroke;
21966			} else {
21967				if ($clip === true) {
21968					// Add text to path for clipping
21969					$textrendermode = 7;
21970				} else {
21971					// Neither fill nor stroke text (invisible)
21972					$textrendermode = 3;
21973				}
21974			}
21975		}
21976		$this->textrendermode = $textrendermode;
21977		$this->textstrokewidth = $stroke;
21978	}
21979
21980	/**
21981	 * Set parameters for drop shadow effect for text.
21982	 * @param $params (array) Array of parameters: enabled (boolean) set to true to enable shadow; depth_w (float) shadow width in user units; depth_h (float) shadow height in user units; color (array) shadow color or false to use the stroke color; opacity (float) Alpha value: real value from 0 (transparent) to 1 (opaque); blend_mode (string) blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity.
21983	 * @since 5.9.174 (2012-07-25)
21984	 * @public
21985	*/
21986	public function setTextShadow($params=array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal')) {
21987		if (isset($params['enabled'])) {
21988			$this->txtshadow['enabled'] = $params['enabled']?true:false;
21989		} else {
21990			$this->txtshadow['enabled'] = false;
21991		}
21992		if (isset($params['depth_w'])) {
21993			$this->txtshadow['depth_w'] = floatval($params['depth_w']);
21994		} else {
21995			$this->txtshadow['depth_w'] = 0;
21996		}
21997		if (isset($params['depth_h'])) {
21998			$this->txtshadow['depth_h'] = floatval($params['depth_h']);
21999		} else {
22000			$this->txtshadow['depth_h'] = 0;
22001		}
22002		if (isset($params['color']) AND ($params['color'] !== false) AND is_array($params['color'])) {
22003			$this->txtshadow['color'] = $params['color'];
22004		} else {
22005			$this->txtshadow['color'] = $this->strokecolor;
22006		}
22007		if (isset($params['opacity'])) {
22008			$this->txtshadow['opacity'] = min(1, max(0, floatval($params['opacity'])));
22009		} else {
22010			$this->txtshadow['opacity'] = 1;
22011		}
22012		if (isset($params['blend_mode']) AND in_array($params['blend_mode'], array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
22013			$this->txtshadow['blend_mode'] = $params['blend_mode'];
22014		} else {
22015			$this->txtshadow['blend_mode'] = 'Normal';
22016		}
22017		if ((($this->txtshadow['depth_w'] == 0) AND ($this->txtshadow['depth_h'] == 0)) OR ($this->txtshadow['opacity'] == 0)) {
22018			$this->txtshadow['enabled'] = false;
22019		}
22020	}
22021
22022	/**
22023	 * Return the text shadow parameters array.
22024	 * @return Array of parameters.
22025	 * @since 5.9.174 (2012-07-25)
22026	 * @public
22027	 */
22028	public function getTextShadow() {
22029		return $this->txtshadow;
22030	}
22031
22032	/**
22033	 * Returns an array of chars containing soft hyphens.
22034	 * @param $word (array) array of chars
22035	 * @param $patterns (array) Array of hypenation patterns.
22036	 * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
22037	 * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
22038	 * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
22039	 * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
22040	 * @param $charmax (int) Maximum length of broken piece of word.
22041	 * @return array text with soft hyphens
22042	 * @author Nicola Asuni
22043	 * @since 4.9.012 (2010-04-12)
22044	 * @protected
22045	 */
22046	protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
22047		$hyphenword = array(); // hyphens positions
22048		$numchars = count($word);
22049		if ($numchars <= $charmin) {
22050			return $word;
22051		}
22052		$word_string = TCPDF_FONTS::UTF8ArrSubString($word, '', '', $this->isunicode);
22053		// some words will be returned as-is
22054		$pattern = '/^([a-zA-Z0-9_\.\-]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/';
22055		if (preg_match($pattern, $word_string) > 0) {
22056			// email
22057			return $word;
22058		}
22059		$pattern = '/(([a-zA-Z0-9\-]+\.)?)((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/';
22060		if (preg_match($pattern, $word_string) > 0) {
22061			// URL
22062			return $word;
22063		}
22064		if (isset($dictionary[$word_string])) {
22065			return TCPDF_FONTS::UTF8StringToArray($dictionary[$word_string], $this->isunicode, $this->CurrentFont);
22066		}
22067		// surround word with '_' characters
22068		$tmpword = array_merge(array(46), $word, array(46));
22069		$tmpnumchars = $numchars + 2;
22070		$maxpos = $tmpnumchars - 1;
22071		for ($pos = 0; $pos < $maxpos; ++$pos) {
22072			$imax = min(($tmpnumchars - $pos), $charmax);
22073			for ($i = 1; $i <= $imax; ++$i) {
22074				$subword = strtolower(TCPDF_FONTS::UTF8ArrSubString($tmpword, $pos, ($pos + $i), $this->isunicode));
22075				if (isset($patterns[$subword])) {
22076					$pattern = TCPDF_FONTS::UTF8StringToArray($patterns[$subword], $this->isunicode, $this->CurrentFont);
22077					$pattern_length = count($pattern);
22078					$digits = 1;
22079					for ($j = 0; $j < $pattern_length; ++$j) {
22080						// check if $pattern[$j] is a number = hyphenation level (only numbers from 1 to 5 are valid)
22081						if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
22082							if ($j == 0) {
22083								$zero = $pos - 1;
22084							} else {
22085								$zero = $pos + $j - $digits;
22086							}
22087							// get hyphenation level
22088							$level = ($pattern[$j] - 48);
22089							// if two levels from two different patterns match at the same point, the higher one is selected.
22090							if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] < $level)) {
22091								$hyphenword[$zero] = $level;
22092							}
22093							++$digits;
22094						}
22095					}
22096				}
22097			}
22098		}
22099		$inserted = 0;
22100		$maxpos = $numchars - $rightmin;
22101		for ($i = $leftmin; $i <= $maxpos; ++$i) {
22102			// only odd levels indicate allowed hyphenation points
22103			if (isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) {
22104				// 173 = soft hyphen character
22105				array_splice($word, $i + $inserted, 0, 173);
22106				++$inserted;
22107			}
22108		}
22109		return $word;
22110	}
22111
22112	/**
22113	 * Returns text with soft hyphens.
22114	 * @param $text (string) text to process
22115	 * @param $patterns (mixed) Array of hypenation patterns or a TEX file containing hypenation patterns. TEX patterns can be downloaded from http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/
22116	 * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
22117	 * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
22118	 * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
22119	 * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
22120	 * @param $charmax (int) Maximum length of broken piece of word.
22121	 * @return array text with soft hyphens
22122	 * @author Nicola Asuni
22123	 * @since 4.9.012 (2010-04-12)
22124	 * @public
22125	 */
22126	public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
22127		$text = $this->unhtmlentities($text);
22128		$word = array(); // last word
22129		$txtarr = array(); // text to be returned
22130		$intag = false; // true if we are inside an HTML tag
22131		$skip = false; // true to skip hyphenation
22132		if (!is_array($patterns)) {
22133			$patterns = TCPDF_STATIC::getHyphenPatternsFromTEX($patterns);
22134		}
22135		// get array of characters
22136		$unichars = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
22137		// for each char
22138		foreach ($unichars as $char) {
22139			if ((!$intag) AND (!$skip) AND TCPDF_FONT_DATA::$uni_type[$char] == 'L') {
22140				// letter character
22141				$word[] = $char;
22142			} else {
22143				// other type of character
22144				if (!TCPDF_STATIC::empty_string($word)) {
22145					// hypenate the word
22146					$txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
22147					$word = array();
22148				}
22149				$txtarr[] = $char;
22150				if (chr($char) == '<') {
22151					// we are inside an HTML tag
22152					$intag = true;
22153				} elseif ($intag AND (chr($char) == '>')) {
22154					// end of HTML tag
22155					$intag = false;
22156					// check for style tag
22157					$expected = array(115, 116, 121, 108, 101); // = 'style'
22158					$current = array_slice($txtarr, -6, 5); // last 5 chars
22159					$compare = array_diff($expected, $current);
22160					if (empty($compare)) {
22161						// check if it is a closing tag
22162						$expected = array(47); // = '/'
22163						$current = array_slice($txtarr, -7, 1);
22164						$compare = array_diff($expected, $current);
22165						if (empty($compare)) {
22166							// closing style tag
22167							$skip = false;
22168						} else {
22169							// opening style tag
22170							$skip = true;
22171						}
22172					}
22173				}
22174			}
22175		}
22176		if (!TCPDF_STATIC::empty_string($word)) {
22177			// hypenate the word
22178			$txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
22179		}
22180		// convert char array to string and return
22181		return TCPDF_FONTS::UTF8ArrSubString($txtarr, '', '', $this->isunicode);
22182	}
22183
22184	/**
22185	 * Enable/disable rasterization of vector images using ImageMagick library.
22186	 * @param $mode (boolean) if true enable rasterization, false otherwise.
22187	 * @public
22188	 * @since 5.0.000 (2010-04-27)
22189	 */
22190	public function setRasterizeVectorImages($mode) {
22191		$this->rasterize_vector_images = $mode;
22192	}
22193
22194	/**
22195	 * Enable or disable default option for font subsetting.
22196	 * @param $enable (boolean) if true enable font subsetting by default.
22197	 * @author Nicola Asuni
22198	 * @public
22199	 * @since 5.3.002 (2010-06-07)
22200	 */
22201	public function setFontSubsetting($enable=true) {
22202		if ($this->pdfa_mode) {
22203			$this->font_subsetting = false;
22204		} else {
22205			$this->font_subsetting = $enable ? true : false;
22206		}
22207	}
22208
22209	/**
22210	 * Return the default option for font subsetting.
22211	 * @return boolean default font subsetting state.
22212	 * @author Nicola Asuni
22213	 * @public
22214	 * @since 5.3.002 (2010-06-07)
22215	 */
22216	public function getFontSubsetting() {
22217		return $this->font_subsetting;
22218	}
22219
22220	/**
22221	 * Left trim the input string
22222	 * @param $str (string) string to trim
22223	 * @param $replace (string) string that replace spaces.
22224	 * @return left trimmed string
22225	 * @author Nicola Asuni
22226	 * @public
22227	 * @since 5.8.000 (2010-08-11)
22228	 */
22229	public function stringLeftTrim($str, $replace='') {
22230		return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str);
22231	}
22232
22233	/**
22234	 * Right trim the input string
22235	 * @param $str (string) string to trim
22236	 * @param $replace (string) string that replace spaces.
22237	 * @return right trimmed string
22238	 * @author Nicola Asuni
22239	 * @public
22240	 * @since 5.8.000 (2010-08-11)
22241	 */
22242	public function stringRightTrim($str, $replace='') {
22243		return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str);
22244	}
22245
22246	/**
22247	 * Trim the input string
22248	 * @param $str (string) string to trim
22249	 * @param $replace (string) string that replace spaces.
22250	 * @return trimmed string
22251	 * @author Nicola Asuni
22252	 * @public
22253	 * @since 5.8.000 (2010-08-11)
22254	 */
22255	public function stringTrim($str, $replace='') {
22256		$str = $this->stringLeftTrim($str, $replace);
22257		$str = $this->stringRightTrim($str, $replace);
22258		return $str;
22259	}
22260
22261	/**
22262	 * Return true if the current font is unicode type.
22263	 * @return true for unicode font, false otherwise.
22264	 * @author Nicola Asuni
22265	 * @public
22266	 * @since 5.8.002 (2010-08-14)
22267	 */
22268	public function isUnicodeFont() {
22269		return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0'));
22270	}
22271
22272	/**
22273	 * Return normalized font name
22274	 * @param $fontfamily (string) property string containing font family names
22275	 * @return string normalized font name
22276	 * @author Nicola Asuni
22277	 * @public
22278	 * @since 5.8.004 (2010-08-17)
22279	 */
22280	public function getFontFamilyName($fontfamily) {
22281		// remove spaces and symbols
22282		$fontfamily = preg_replace('/[^a-z0-9_\,]/', '', strtolower($fontfamily));
22283		// extract all font names
22284		$fontslist = preg_split('/[,]/', $fontfamily);
22285		// find first valid font name
22286		foreach ($fontslist as $font) {
22287			// replace font variations
22288			$font = preg_replace('/regular$/', '', $font);
22289			$font = preg_replace('/italic$/', 'I', $font);
22290			$font = preg_replace('/oblique$/', 'I', $font);
22291			$font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
22292			// replace common family names and core fonts
22293			$pattern = array();
22294			$replacement = array();
22295			$pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
22296			$replacement[] = 'times';
22297			$pattern[] = '/^sansserif/';
22298			$replacement[] = 'helvetica';
22299			$pattern[] = '/^monospace/';
22300			$replacement[] = 'courier';
22301			$font = preg_replace($pattern, $replacement, $font);
22302			if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) {
22303				return $font;
22304			}
22305		}
22306		// return current font as default
22307		return $this->CurrentFont['fontkey'];
22308	}
22309
22310	/**
22311	 * Start a new XObject Template.
22312	 * An XObject Template is a PDF block that is a self-contained description of any sequence of graphics objects (including path objects, text objects, and sampled images).
22313	 * An XObject Template may be painted multiple times, either on several pages or at several locations on the same page and produces the same results each time, subject only to the graphics state at the time it is invoked.
22314	 * Note: X,Y coordinates will be reset to 0,0.
22315	 * @param $w (int) Template width in user units (empty string or zero = page width less margins).
22316	 * @param $h (int) Template height in user units (empty string or zero = page height less margins).
22317	 * @param $group (mixed) Set transparency group. Can be a boolean value or an array specifying optional parameters: 'CS' (solour space name), 'I' (boolean flag to indicate isolated group) and 'K' (boolean flag to indicate knockout group).
22318	 * @return int the XObject Template ID in case of success or false in case of error.
22319	 * @author Nicola Asuni
22320	 * @public
22321	 * @since 5.8.017 (2010-08-24)
22322	 * @see endTemplate(), printTemplate()
22323	 */
22324	public function startTemplate($w=0, $h=0, $group=false) {
22325		if ($this->inxobj) {
22326			// we are already inside an XObject template
22327			return false;
22328		}
22329		$this->inxobj = true;
22330		++$this->n;
22331		// XObject ID
22332		$this->xobjid = 'XT'.$this->n;
22333		// object ID
22334		$this->xobjects[$this->xobjid] = array('n' => $this->n);
22335		// store current graphic state
22336		$this->xobjects[$this->xobjid]['gvars'] = $this->getGraphicVars();
22337		// initialize data
22338		$this->xobjects[$this->xobjid]['intmrk'] = 0;
22339		$this->xobjects[$this->xobjid]['transfmrk'] = array();
22340		$this->xobjects[$this->xobjid]['outdata'] = '';
22341		$this->xobjects[$this->xobjid]['xobjects'] = array();
22342		$this->xobjects[$this->xobjid]['images'] = array();
22343		$this->xobjects[$this->xobjid]['fonts'] = array();
22344		$this->xobjects[$this->xobjid]['annotations'] = array();
22345		$this->xobjects[$this->xobjid]['extgstates'] = array();
22346		$this->xobjects[$this->xobjid]['gradients'] = array();
22347		$this->xobjects[$this->xobjid]['spot_colors'] = array();
22348		// set new environment
22349		$this->num_columns = 1;
22350		$this->current_column = 0;
22351		$this->SetAutoPageBreak(false);
22352		if (($w === '') OR ($w <= 0)) {
22353			$w = $this->w - $this->lMargin - $this->rMargin;
22354		}
22355		if (($h === '') OR ($h <= 0)) {
22356			$h = $this->h - $this->tMargin - $this->bMargin;
22357		}
22358		$this->xobjects[$this->xobjid]['x'] = 0;
22359		$this->xobjects[$this->xobjid]['y'] = 0;
22360		$this->xobjects[$this->xobjid]['w'] = $w;
22361		$this->xobjects[$this->xobjid]['h'] = $h;
22362		$this->w = $w;
22363		$this->h = $h;
22364		$this->wPt = $this->w * $this->k;
22365		$this->hPt = $this->h * $this->k;
22366		$this->fwPt = $this->wPt;
22367		$this->fhPt = $this->hPt;
22368		$this->x = 0;
22369		$this->y = 0;
22370		$this->lMargin = 0;
22371		$this->rMargin = 0;
22372		$this->tMargin = 0;
22373		$this->bMargin = 0;
22374		// set group mode
22375		$this->xobjects[$this->xobjid]['group'] = $group;
22376		return $this->xobjid;
22377	}
22378
22379	/**
22380	 * End the current XObject Template started with startTemplate() and restore the previous graphic state.
22381	 * An XObject Template is a PDF block that is a self-contained description of any sequence of graphics objects (including path objects, text objects, and sampled images).
22382	 * An XObject Template may be painted multiple times, either on several pages or at several locations on the same page and produces the same results each time, subject only to the graphics state at the time it is invoked.
22383	 * @return int the XObject Template ID in case of success or false in case of error.
22384	 * @author Nicola Asuni
22385	 * @public
22386	 * @since 5.8.017 (2010-08-24)
22387	 * @see startTemplate(), printTemplate()
22388	 */
22389	public function endTemplate() {
22390		if (!$this->inxobj) {
22391			// we are not inside a template
22392			return false;
22393		}
22394		$this->inxobj = false;
22395		// restore previous graphic state
22396		$this->setGraphicVars($this->xobjects[$this->xobjid]['gvars'], true);
22397		return $this->xobjid;
22398	}
22399
22400	/**
22401	 * Print an XObject Template.
22402	 * You can print an XObject Template inside the currently opened Template.
22403	 * An XObject Template is a PDF block that is a self-contained description of any sequence of graphics objects (including path objects, text objects, and sampled images).
22404	 * An XObject Template may be painted multiple times, either on several pages or at several locations on the same page and produces the same results each time, subject only to the graphics state at the time it is invoked.
22405	 * @param $id (string) The ID of XObject Template to print.
22406	 * @param $x (int) X position in user units (empty string = current x position)
22407	 * @param $y (int) Y position in user units (empty string = current y position)
22408	 * @param $w (int) Width in user units (zero = remaining page width)
22409	 * @param $h (int) Height in user units (zero = remaining page height)
22410	 * @param $align (string) Indicates the alignment of the pointer next to template insertion relative to template 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>
22411	 * @param $palign (string) Allows to center or align the template 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>
22412	 * @param $fitonpage (boolean) If true the template is resized to not exceed page dimensions.
22413	 * @author Nicola Asuni
22414	 * @public
22415	 * @since 5.8.017 (2010-08-24)
22416	 * @see startTemplate(), endTemplate()
22417	 */
22418	public function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) {
22419		if ($this->state != 2) {
22420			 return;
22421		}
22422		if (!isset($this->xobjects[$id])) {
22423			$this->Error('The XObject Template \''.$id.'\' doesn\'t exist!');
22424		}
22425		if ($this->inxobj) {
22426			if ($id == $this->xobjid) {
22427				// close current template
22428				$this->endTemplate();
22429			} else {
22430				// use the template as resource for the template currently opened
22431				$this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id];
22432			}
22433		}
22434		// set default values
22435		if ($x === '') {
22436			$x = $this->x;
22437		}
22438		if ($y === '') {
22439			$y = $this->y;
22440		}
22441		// check page for no-write regions and adapt page margins if necessary
22442		list($x, $y) = $this->checkPageRegions($h, $x, $y);
22443		$ow = $this->xobjects[$id]['w'];
22444		if ($ow <= 0) {
22445			$ow = 1;
22446		}
22447		$oh = $this->xobjects[$id]['h'];
22448		if ($oh <= 0) {
22449			$oh = 1;
22450		}
22451		// calculate template width and height on document
22452		if (($w <= 0) AND ($h <= 0)) {
22453			$w = $ow;
22454			$h = $oh;
22455		} elseif ($w <= 0) {
22456			$w = $h * $ow / $oh;
22457		} elseif ($h <= 0) {
22458			$h = $w * $oh / $ow;
22459		}
22460		// fit the template on available space
22461		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
22462		// set page alignment
22463		$rb_y = $y + $h;
22464		// set alignment
22465		if ($this->rtl) {
22466			if ($palign == 'L') {
22467				$xt = $this->lMargin;
22468			} elseif ($palign == 'C') {
22469				$xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22470			} elseif ($palign == 'R') {
22471				$xt = $this->w - $this->rMargin - $w;
22472			} else {
22473				$xt = $x - $w;
22474			}
22475			$rb_x = $xt;
22476		} else {
22477			if ($palign == 'L') {
22478				$xt = $this->lMargin;
22479			} elseif ($palign == 'C') {
22480				$xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22481			} elseif ($palign == 'R') {
22482				$xt = $this->w - $this->rMargin - $w;
22483			} else {
22484				$xt = $x;
22485			}
22486			$rb_x = $xt + $w;
22487		}
22488		// print XObject Template + Transformation matrix
22489		$this->StartTransform();
22490		// translate and scale
22491		$sx = ($w / $ow);
22492		$sy = ($h / $oh);
22493		$tm = array();
22494		$tm[0] = $sx;
22495		$tm[1] = 0;
22496		$tm[2] = 0;
22497		$tm[3] = $sy;
22498		$tm[4] = $xt * $this->k;
22499		$tm[5] = ($this->h - $h - $y) * $this->k;
22500		$this->Transform($tm);
22501		// set object
22502		$this->_out('/'.$id.' Do');
22503		$this->StopTransform();
22504		// add annotations
22505		if (!empty($this->xobjects[$id]['annotations'])) {
22506			foreach ($this->xobjects[$id]['annotations'] as $annot) {
22507				// transform original coordinates
22508				$coordlt = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k)));
22509				$ax = ($coordlt[4] / $this->k);
22510				$ay = ($this->h - $h - ($coordlt[5] / $this->k));
22511				$coordrb = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k)));
22512				$aw = ($coordrb[4] / $this->k) - $ax;
22513				$ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay;
22514				$this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);
22515			}
22516		}
22517		// set pointer to align the next text/objects
22518		switch($align) {
22519			case 'T': {
22520				$this->y = $y;
22521				$this->x = $rb_x;
22522				break;
22523			}
22524			case 'M': {
22525				$this->y = $y + round($h/2);
22526				$this->x = $rb_x;
22527				break;
22528			}
22529			case 'B': {
22530				$this->y = $rb_y;
22531				$this->x = $rb_x;
22532				break;
22533			}
22534			case 'N': {
22535				$this->SetY($rb_y);
22536				break;
22537			}
22538			default:{
22539				break;
22540			}
22541		}
22542	}
22543
22544	/**
22545	 * Set the percentage of character stretching.
22546	 * @param $perc (int) percentage of stretching (100 = no stretching)
22547	 * @author Nicola Asuni
22548	 * @public
22549	 * @since 5.9.000 (2010-09-29)
22550	 */
22551	public function setFontStretching($perc=100) {
22552		$this->font_stretching = $perc;
22553	}
22554
22555	/**
22556	 * Get the percentage of character stretching.
22557	 * @return float stretching value
22558	 * @author Nicola Asuni
22559	 * @public
22560	 * @since 5.9.000 (2010-09-29)
22561	 */
22562	public function getFontStretching() {
22563		return $this->font_stretching;
22564	}
22565
22566	/**
22567	 * Set the amount to increase or decrease the space between characters in a text.
22568	 * @param $spacing (float) amount to increase or decrease the space between characters in a text (0 = default spacing)
22569	 * @author Nicola Asuni
22570	 * @public
22571	 * @since 5.9.000 (2010-09-29)
22572	 */
22573	public function setFontSpacing($spacing=0) {
22574		$this->font_spacing = $spacing;
22575	}
22576
22577	/**
22578	 * Get the amount to increase or decrease the space between characters in a text.
22579	 * @return int font spacing (tracking) value
22580	 * @author Nicola Asuni
22581	 * @public
22582	 * @since 5.9.000 (2010-09-29)
22583	 */
22584	public function getFontSpacing() {
22585		return $this->font_spacing;
22586	}
22587
22588	/**
22589	 * Return an array of no-write page regions
22590	 * @return array of no-write page regions
22591	 * @author Nicola Asuni
22592	 * @public
22593	 * @since 5.9.003 (2010-10-13)
22594	 * @see setPageRegions(), addPageRegion()
22595	 */
22596	public function getPageRegions() {
22597		return $this->page_regions;
22598	}
22599
22600	/**
22601	 * Set no-write regions on page.
22602	 * A no-write region is a portion of the page with a rectangular or trapezium shape that will not be covered when writing text or html code.
22603	 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22604	 * You can set multiple regions for the same page.
22605	 * @param $regions (array) array of no-write regions. For each region you can define an array as follow: ('page' => page number or empy for current page, 'xt' => X top, 'yt' => Y top, 'xb' => X bottom, 'yb' => Y bottom, 'side' => page side 'L' = left or 'R' = right). Omit this parameter to remove all regions.
22606	 * @author Nicola Asuni
22607	 * @public
22608	 * @since 5.9.003 (2010-10-13)
22609	 * @see addPageRegion(), getPageRegions()
22610	 */
22611	public function setPageRegions($regions=array()) {
22612		// empty current regions array
22613		$this->page_regions = array();
22614		// add regions
22615		foreach ($regions as $data) {
22616			$this->addPageRegion($data);
22617		}
22618	}
22619
22620	/**
22621	 * Add a single no-write region on selected page.
22622	 * A no-write region is a portion of the page with a rectangular or trapezium shape that will not be covered when writing text or html code.
22623	 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22624	 * You can set multiple regions for the same page.
22625	 * @param $region (array) array of a single no-write region array: ('page' => page number or empy for current page, 'xt' => X top, 'yt' => Y top, 'xb' => X bottom, 'yb' => Y bottom, 'side' => page side 'L' = left or 'R' = right).
22626	 * @author Nicola Asuni
22627	 * @public
22628	 * @since 5.9.003 (2010-10-13)
22629	 * @see setPageRegions(), getPageRegions()
22630	 */
22631	public function addPageRegion($region) {
22632		if (!isset($region['page']) OR empty($region['page'])) {
22633			$region['page'] = $this->page;
22634		}
22635		if (isset($region['xt']) AND isset($region['xb']) AND ($region['xt'] > 0) AND ($region['xb'] > 0)
22636			AND isset($region['yt'])  AND isset($region['yb']) AND ($region['yt'] >= 0) AND ($region['yt'] < $region['yb'])
22637			AND isset($region['side']) AND (($region['side'] == 'L') OR ($region['side'] == 'R'))) {
22638			$this->page_regions[] = $region;
22639		}
22640	}
22641
22642	/**
22643	 * Remove a single no-write region.
22644	 * @param $key (int) region key
22645	 * @author Nicola Asuni
22646	 * @public
22647	 * @since 5.9.003 (2010-10-13)
22648	 * @see setPageRegions(), getPageRegions()
22649	 */
22650	public function removePageRegion($key) {
22651		if (isset($this->page_regions[$key])) {
22652			unset($this->page_regions[$key]);
22653		}
22654	}
22655
22656	/**
22657	 * Check page for no-write regions and adapt current coordinates and page margins if necessary.
22658	 * A no-write region is a portion of the page with a rectangular or trapezium shape that will not be covered when writing text or html code.
22659	 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22660	 * @param $h (float) height of the text/image/object to print in user units
22661	 * @param $x (float) current X coordinate in user units
22662	 * @param $y (float) current Y coordinate in user units
22663	 * @return array($x, $y)
22664	 * @author Nicola Asuni
22665	 * @protected
22666	 * @since 5.9.003 (2010-10-13)
22667	 */
22668	protected function checkPageRegions($h, $x, $y) {
22669		// set default values
22670		if ($x === '') {
22671			$x = $this->x;
22672		}
22673		if ($y === '') {
22674			$y = $this->y;
22675		}
22676		if (!$this->check_page_regions OR empty($this->page_regions)) {
22677			// no page regions defined
22678			return array($x, $y);
22679		}
22680		if (empty($h)) {
22681			$h = $this->getCellHeight($this->FontSize);
22682		}
22683		// check for page break
22684		if ($this->checkPageBreak($h, $y)) {
22685			// the content will be printed on a new page
22686			$x = $this->x;
22687			$y = $this->y;
22688		}
22689		if ($this->num_columns > 1) {
22690			if ($this->rtl) {
22691				$this->lMargin = ($this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
22692			} else {
22693				$this->rMargin = ($this->w - $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
22694			}
22695		} else {
22696			if ($this->rtl) {
22697				$this->lMargin = max($this->clMargin, $this->original_lMargin);
22698			} else {
22699				$this->rMargin = max($this->crMargin, $this->original_rMargin);
22700			}
22701		}
22702		// adjust coordinates and page margins
22703		foreach ($this->page_regions as $regid => $regdata) {
22704			if ($regdata['page'] == $this->page) {
22705				// check region boundaries
22706				if (($y > ($regdata['yt'] - $h)) AND ($y <= $regdata['yb'])) {
22707					// Y is inside the region
22708					$minv = ($regdata['xb'] - $regdata['xt']) / ($regdata['yb'] - $regdata['yt']); // inverse of angular coefficient
22709					$yt = max($y, $regdata['yt']);
22710					$yb = min(($yt + $h), $regdata['yb']);
22711					$xt = (($yt - $regdata['yt']) * $minv) + $regdata['xt'];
22712					$xb = (($yb - $regdata['yt']) * $minv) + $regdata['xt'];
22713					if ($regdata['side'] == 'L') { // left side
22714						$new_margin = max($xt, $xb);
22715						if ($this->lMargin < $new_margin) {
22716							if ($this->rtl) {
22717								// adjust left page margin
22718								$this->lMargin = max(0, $new_margin);
22719							}
22720							if ($x < $new_margin) {
22721								// adjust x position
22722								$x = $new_margin;
22723								if ($new_margin > ($this->w - $this->rMargin)) {
22724									// adjust y position
22725									$y = $regdata['yb'] - $h;
22726								}
22727							}
22728						}
22729					} elseif ($regdata['side'] == 'R') { // right side
22730						$new_margin = min($xt, $xb);
22731						if (($this->w - $this->rMargin) > $new_margin) {
22732							if (!$this->rtl) {
22733								// adjust right page margin
22734								$this->rMargin = max(0, ($this->w - $new_margin));
22735							}
22736							if ($x > $new_margin) {
22737								// adjust x position
22738								$x = $new_margin;
22739								if ($new_margin > $this->lMargin) {
22740									// adjust y position
22741									$y = $regdata['yb'] - $h;
22742								}
22743							}
22744						}
22745					}
22746				}
22747			}
22748		}
22749		return array($x, $y);
22750	}
22751
22752	// --- SVG METHODS ---------------------------------------------------------
22753
22754	/**
22755	 * Embedd a Scalable Vector Graphics (SVG) image.
22756	 * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
22757	 * @param $file (string) Name of the SVG file or a '@' character followed by the SVG data string.
22758	 * @param $x (float) Abscissa of the upper-left corner.
22759	 * @param $y (float) Ordinate of the upper-left corner.
22760	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
22761	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
22762	 * @param $link (mixed) URL or identifier returned by AddLink().
22763	 * @param $align (string) 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> If the alignment is an empty string, then the pointer will be restored on the starting SVG position.
22764	 * @param $palign (string) 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>
22765	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be 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> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
22766	 * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
22767	 * @author Nicola Asuni
22768	 * @since 5.0.000 (2010-05-02)
22769	 * @public
22770	 */
22771	public function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {
22772		if ($this->state != 2) {
22773			 return;
22774		}
22775		// reset SVG vars
22776		$this->svggradients = array();
22777		$this->svggradientid = 0;
22778		$this->svgdefsmode = false;
22779		$this->svgdefs = array();
22780		$this->svgclipmode = false;
22781		$this->svgclippaths = array();
22782		$this->svgcliptm = array();
22783		$this->svgclipid = 0;
22784		$this->svgtext = '';
22785		$this->svgtextmode = array();
22786		if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
22787			// convert SVG to raster image using GD or ImageMagick libraries
22788			return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
22789		}
22790		if ($file[0] === '@') { // image from string
22791			$this->svgdir = '';
22792			$svgdata = substr($file, 1);
22793		} else { // SVG file
22794			$this->svgdir = dirname($file);
22795			$svgdata = TCPDF_STATIC::fileGetContents($file);
22796		}
22797		if ($svgdata === FALSE) {
22798			$this->Error('SVG file not found: '.$file);
22799		}
22800		if ($x === '') {
22801			$x = $this->x;
22802		}
22803		if ($y === '') {
22804			$y = $this->y;
22805		}
22806		// check page for no-write regions and adapt page margins if necessary
22807		list($x, $y) = $this->checkPageRegions($h, $x, $y);
22808		$k = $this->k;
22809		$ox = 0;
22810		$oy = 0;
22811		$ow = $w;
22812		$oh = $h;
22813		$aspect_ratio_align = 'xMidYMid';
22814		$aspect_ratio_ms = 'meet';
22815		$regs = array();
22816		// get original image width and height
22817		preg_match('/<svg([^\>]*)>/si', $svgdata, $regs);
22818		if (isset($regs[1]) AND !empty($regs[1])) {
22819			$tmp = array();
22820			if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22821				$ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
22822			}
22823			$tmp = array();
22824			if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22825				$oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
22826			}
22827			$tmp = array();
22828			if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22829				$ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
22830			}
22831			$tmp = array();
22832			if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22833				$oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
22834			}
22835			$tmp = array();
22836			$view_box = array();
22837			if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) {
22838				if (count($tmp) == 5) {
22839					array_shift($tmp);
22840					foreach ($tmp as $key => $val) {
22841						$view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
22842					}
22843					$ox = $view_box[0];
22844					$oy = $view_box[1];
22845				}
22846				// get aspect ratio
22847				$tmp = array();
22848				if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22849					$aspect_ratio = preg_split('/[\s]+/si', $tmp[1]);
22850					switch (count($aspect_ratio)) {
22851						case 3: {
22852							$aspect_ratio_align = $aspect_ratio[1];
22853							$aspect_ratio_ms = $aspect_ratio[2];
22854							break;
22855						}
22856						case 2: {
22857							$aspect_ratio_align = $aspect_ratio[0];
22858							$aspect_ratio_ms = $aspect_ratio[1];
22859							break;
22860						}
22861						case 1: {
22862							$aspect_ratio_align = $aspect_ratio[0];
22863							$aspect_ratio_ms = 'meet';
22864							break;
22865						}
22866					}
22867				}
22868			}
22869		}
22870		if ($ow <= 0) {
22871			$ow = 1;
22872		}
22873		if ($oh <= 0) {
22874			$oh = 1;
22875		}
22876		// calculate image width and height on document
22877		if (($w <= 0) AND ($h <= 0)) {
22878			// convert image size to document unit
22879			$w = $ow;
22880			$h = $oh;
22881		} elseif ($w <= 0) {
22882			$w = $h * $ow / $oh;
22883		} elseif ($h <= 0) {
22884			$h = $w * $oh / $ow;
22885		}
22886		// fit the image on available space
22887		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
22888		if ($this->rasterize_vector_images) {
22889			// convert SVG to raster image using GD or ImageMagick libraries
22890			return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
22891		}
22892		// set alignment
22893		$this->img_rb_y = $y + $h;
22894		// set alignment
22895		if ($this->rtl) {
22896			if ($palign == 'L') {
22897				$ximg = $this->lMargin;
22898			} elseif ($palign == 'C') {
22899				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22900			} elseif ($palign == 'R') {
22901				$ximg = $this->w - $this->rMargin - $w;
22902			} else {
22903				$ximg = $x - $w;
22904			}
22905			$this->img_rb_x = $ximg;
22906		} else {
22907			if ($palign == 'L') {
22908				$ximg = $this->lMargin;
22909			} elseif ($palign == 'C') {
22910				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22911			} elseif ($palign == 'R') {
22912				$ximg = $this->w - $this->rMargin - $w;
22913			} else {
22914				$ximg = $x;
22915			}
22916			$this->img_rb_x = $ximg + $w;
22917		}
22918		// store current graphic vars
22919		$gvars = $this->getGraphicVars();
22920		// store SVG position and scale factors
22921		$svgoffset_x = ($ximg - $ox) * $this->k;
22922		$svgoffset_y = -($y - $oy) * $this->k;
22923		if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {
22924			$ow = $view_box[2];
22925			$oh = $view_box[3];
22926		} else {
22927			if ($ow <= 0) {
22928				$ow = $w;
22929			}
22930			if ($oh <= 0) {
22931				$oh = $h;
22932			}
22933		}
22934		$svgscale_x = $w / $ow;
22935		$svgscale_y = $h / $oh;
22936		// scaling and alignment
22937		if ($aspect_ratio_align != 'none') {
22938			// store current scaling values
22939			$svgscale_old_x = $svgscale_x;
22940			$svgscale_old_y = $svgscale_y;
22941			// force uniform scaling
22942			if ($aspect_ratio_ms == 'slice') {
22943				// the entire viewport is covered by the viewBox
22944				if ($svgscale_x > $svgscale_y) {
22945					$svgscale_y = $svgscale_x;
22946				} elseif ($svgscale_x < $svgscale_y) {
22947					$svgscale_x = $svgscale_y;
22948				}
22949			} else { // meet
22950				// the entire viewBox is visible within the viewport
22951				if ($svgscale_x < $svgscale_y) {
22952					$svgscale_y = $svgscale_x;
22953				} elseif ($svgscale_x > $svgscale_y) {
22954					$svgscale_x = $svgscale_y;
22955				}
22956			}
22957			// correct X alignment
22958			switch (substr($aspect_ratio_align, 1, 3)) {
22959				case 'Min': {
22960					// do nothing
22961					break;
22962				}
22963				case 'Max': {
22964					$svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x));
22965					break;
22966				}
22967				default:
22968				case 'Mid': {
22969					$svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2);
22970					break;
22971				}
22972			}
22973			// correct Y alignment
22974			switch (substr($aspect_ratio_align, 5)) {
22975				case 'Min': {
22976					// do nothing
22977					break;
22978				}
22979				case 'Max': {
22980					$svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y));
22981					break;
22982				}
22983				default:
22984				case 'Mid': {
22985					$svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2);
22986					break;
22987				}
22988			}
22989		}
22990		// store current page break mode
22991		$page_break_mode = $this->AutoPageBreak;
22992		$page_break_margin = $this->getBreakMargin();
22993		$cell_padding = $this->cell_padding;
22994		$this->SetCellPadding(0);
22995		$this->SetAutoPageBreak(false);
22996		// save the current graphic state
22997		$this->_out('q'.$this->epsmarker);
22998		// set initial clipping mask
22999		$this->Rect($ximg, $y, $w, $h, 'CNZ', array(), array());
23000		// scale and translate
23001		$e = $ox * $this->k * (1 - $svgscale_x);
23002		$f = ($this->h - $oy) * $this->k * (1 - $svgscale_y);
23003		$this->_out(sprintf('%F %F %F %F %F %F cm', $svgscale_x, 0, 0, $svgscale_y, ($e + $svgoffset_x), ($f + $svgoffset_y)));
23004		// creates a new XML parser to be used by the other XML functions
23005		$this->parser = xml_parser_create('UTF-8');
23006		// the following function allows to use parser inside object
23007		xml_set_object($this->parser, $this);
23008		// disable case-folding for this XML parser
23009		xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
23010		// sets the element handler functions for the XML parser
23011		xml_set_element_handler($this->parser, 'startSVGElementHandler', 'endSVGElementHandler');
23012		// sets the character data handler function for the XML parser
23013		xml_set_character_data_handler($this->parser, 'segSVGContentHandler');
23014		// start parsing an XML document
23015		if (!xml_parse($this->parser, $svgdata)) {
23016			$error_message = sprintf('SVG Error: %s at line %d', xml_error_string(xml_get_error_code($this->parser)), xml_get_current_line_number($this->parser));
23017			$this->Error($error_message);
23018		}
23019		// free this XML parser
23020		xml_parser_free($this->parser);
23021		// restore previous graphic state
23022		$this->_out($this->epsmarker.'Q');
23023		// restore graphic vars
23024		$this->setGraphicVars($gvars);
23025		$this->lasth = $gvars['lasth'];
23026		if (!empty($border)) {
23027			$bx = $this->x;
23028			$by = $this->y;
23029			$this->x = $ximg;
23030			if ($this->rtl) {
23031				$this->x += $w;
23032			}
23033			$this->y = $y;
23034			$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
23035			$this->x = $bx;
23036			$this->y = $by;
23037		}
23038		if ($link) {
23039			$this->Link($ximg, $y, $w, $h, $link, 0);
23040		}
23041		// set pointer to align the next text/objects
23042		switch($align) {
23043			case 'T':{
23044				$this->y = $y;
23045				$this->x = $this->img_rb_x;
23046				break;
23047			}
23048			case 'M':{
23049				$this->y = $y + round($h/2);
23050				$this->x = $this->img_rb_x;
23051				break;
23052			}
23053			case 'B':{
23054				$this->y = $this->img_rb_y;
23055				$this->x = $this->img_rb_x;
23056				break;
23057			}
23058			case 'N':{
23059				$this->SetY($this->img_rb_y);
23060				break;
23061			}
23062			default:{
23063				// restore pointer to starting position
23064				$this->x = $gvars['x'];
23065				$this->y = $gvars['y'];
23066				$this->page = $gvars['page'];
23067				$this->current_column = $gvars['current_column'];
23068				$this->tMargin = $gvars['tMargin'];
23069				$this->bMargin = $gvars['bMargin'];
23070				$this->w = $gvars['w'];
23071				$this->h = $gvars['h'];
23072				$this->wPt = $gvars['wPt'];
23073				$this->hPt = $gvars['hPt'];
23074				$this->fwPt = $gvars['fwPt'];
23075				$this->fhPt = $gvars['fhPt'];
23076				break;
23077			}
23078		}
23079		$this->endlinex = $this->img_rb_x;
23080		// restore page break
23081		$this->SetAutoPageBreak($page_break_mode, $page_break_margin);
23082		$this->cell_padding = $cell_padding;
23083	}
23084
23085	/**
23086	 * Convert SVG transformation matrix to PDF.
23087	 * @param $tm (array) original SVG transformation matrix
23088	 * @return array transformation matrix
23089	 * @protected
23090	 * @since 5.0.000 (2010-05-02)
23091	 */
23092	protected function convertSVGtMatrix($tm) {
23093		$a = $tm[0];
23094		$b = -$tm[1];
23095		$c = -$tm[2];
23096		$d = $tm[3];
23097		$e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit, false) * $this->k;
23098		$f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit, false) * $this->k;
23099		$x = 0;
23100		$y = $this->h * $this->k;
23101		$e = ($x * (1 - $a)) - ($y * $c) + $e;
23102		$f = ($y * (1 - $d)) - ($x * $b) + $f;
23103		return array($a, $b, $c, $d, $e, $f);
23104	}
23105
23106	/**
23107	 * Apply SVG graphic transformation matrix.
23108	 * @param $tm (array) original SVG transformation matrix
23109	 * @protected
23110	 * @since 5.0.000 (2010-05-02)
23111	 */
23112	protected function SVGTransform($tm) {
23113		$this->Transform($this->convertSVGtMatrix($tm));
23114	}
23115
23116	/**
23117	 * Apply the requested SVG styles (*** TO BE COMPLETED ***)
23118	 * @param $svgstyle (array) array of SVG styles to apply
23119	 * @param $prevsvgstyle (array) array of previous SVG style
23120	 * @param $x (int) X origin of the bounding box
23121	 * @param $y (int) Y origin of the bounding box
23122	 * @param $w (int) width of the bounding box
23123	 * @param $h (int) height of the bounding box
23124	 * @param $clip_function (string) clip function
23125	 * @param $clip_params (array) array of parameters for clipping function
23126	 * @return object style
23127	 * @author Nicola Asuni
23128	 * @since 5.0.000 (2010-05-02)
23129	 * @protected
23130	 */
23131	protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {
23132		if ($this->state != 2) {
23133			 return;
23134		}
23135		$objstyle = '';
23136		$minlen = (0.01 / $this->k); // minimum acceptable length
23137		if (!isset($svgstyle['opacity'])) {
23138			return $objstyle;
23139		}
23140		// clip-path
23141		$regs = array();
23142		if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) {
23143			$clip_path = $this->svgclippaths[$regs[1]];
23144			foreach ($clip_path as $cp) {
23145				$this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);
23146			}
23147		}
23148		// opacity
23149		if ($svgstyle['opacity'] != 1) {
23150			$this->setAlpha($svgstyle['opacity'], 'Normal', $svgstyle['opacity'], false);
23151		}
23152		// color
23153		$fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['color'], $this->spot_colors);
23154		$this->SetFillColorArray($fill_color);
23155		// text color
23156		$text_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['text-color'], $this->spot_colors);
23157		$this->SetTextColorArray($text_color);
23158		// clip
23159		if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) {
23160			$top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0);
23161			$right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0);
23162			$bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0);
23163			$left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0);
23164			$cx = $x + $left;
23165			$cy = $y + $top;
23166			$cw = $w - $left - $right;
23167			$ch = $h - $top - $bottom;
23168			if ($svgstyle['clip-rule'] == 'evenodd') {
23169				$clip_rule = 'CNZ';
23170			} else {
23171				$clip_rule = 'CEO';
23172			}
23173			$this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());
23174		}
23175		// fill
23176		$regs = array();
23177		if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) {
23178			// gradient
23179			$gradient = $this->svggradients[$regs[1]];
23180			if (isset($gradient['xref'])) {
23181				// reference to another gradient definition
23182				$newgradient = $this->svggradients[$gradient['xref']];
23183				$newgradient['coords'] = $gradient['coords'];
23184				$newgradient['mode'] = $gradient['mode'];
23185				$newgradient['type'] = $gradient['type'];
23186				$newgradient['gradientUnits'] = $gradient['gradientUnits'];
23187				if (isset($gradient['gradientTransform'])) {
23188					$newgradient['gradientTransform'] = $gradient['gradientTransform'];
23189				}
23190				$gradient = $newgradient;
23191			}
23192			//save current Graphic State
23193			$this->_outSaveGraphicsState();
23194			//set clipping area
23195			if (!empty($clip_function) AND method_exists($this, $clip_function)) {
23196				$bbox = call_user_func_array(array($this, $clip_function), $clip_params);
23197				if ((!isset($gradient['type']) OR ($gradient['type'] != 3)) AND is_array($bbox) AND (count($bbox) == 4)) {
23198					list($x, $y, $w, $h) = $bbox;
23199				}
23200			}
23201			if ($gradient['mode'] == 'measure') {
23202				if (!isset($gradient['coords'][4])) {
23203					$gradient['coords'][4] = 0.5;
23204				}
23205				if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {
23206					$gtm = $gradient['gradientTransform'];
23207					// apply transformation matrix
23208					$xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4];
23209					$ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5];
23210					$xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4];
23211					$yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5];
23212					$r = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2));
23213					$gradient['coords'][0] = $xa;
23214					$gradient['coords'][1] = $ya;
23215					$gradient['coords'][2] = $xb;
23216					$gradient['coords'][3] = $yb;
23217					$gradient['coords'][4] = $r;
23218				}
23219				// convert SVG coordinates to user units
23220				$gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false);
23221				$gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false);
23222				$gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false);
23223				$gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false);
23224				$gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false);
23225				if ($w <= $minlen) {
23226					$w = $minlen;
23227				}
23228				if ($h <= $minlen) {
23229					$h = $minlen;
23230				}
23231				// shift units
23232				if ($gradient['gradientUnits'] == 'objectBoundingBox') {
23233					// convert to SVG coordinate system
23234					$gradient['coords'][0] += $x;
23235					$gradient['coords'][1] += $y;
23236					$gradient['coords'][2] += $x;
23237					$gradient['coords'][3] += $y;
23238				}
23239				// calculate percentages
23240				$gradient['coords'][0] = (($gradient['coords'][0] - $x) / $w);
23241				$gradient['coords'][1] = (($gradient['coords'][1] - $y) / $h);
23242				$gradient['coords'][2] = (($gradient['coords'][2] - $x) / $w);
23243				$gradient['coords'][3] = (($gradient['coords'][3] - $y) / $h);
23244				$gradient['coords'][4] /= $w;
23245			} elseif ($gradient['mode'] == 'percentage') {
23246				foreach($gradient['coords'] as $key => $val) {
23247					$gradient['coords'][$key] = (intval($val) / 100);
23248					if ($val < 0) {
23249						$gradient['coords'][$key] = 0;
23250					} elseif ($val > 1) {
23251						$gradient['coords'][$key] = 1;
23252					}
23253				}
23254			}
23255			if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {
23256				// single color (no shading)
23257				$gradient['coords'][0] = 1;
23258				$gradient['coords'][1] = 0;
23259				$gradient['coords'][2] = 0.999;
23260				$gradient['coords'][3] = 0;
23261			}
23262			// swap Y coordinates
23263			$tmp = $gradient['coords'][1];
23264			$gradient['coords'][1] = $gradient['coords'][3];
23265			$gradient['coords'][3] = $tmp;
23266			// set transformation map for gradient
23267			$cy = ($this->h - $y);
23268			if ($gradient['type'] == 3) {
23269				// circular gradient
23270				$cy -= ($gradient['coords'][1] * ($w + $h));
23271				$h = $w = max($w, $h);
23272			} else {
23273				$cy -= $h;
23274			}
23275			$this->_out(sprintf('%F 0 0 %F %F %F cm', ($w * $this->k), ($h * $this->k), ($x * $this->k), ($cy * $this->k)));
23276			if (count($gradient['stops']) > 1) {
23277				$this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);
23278			}
23279		} elseif ($svgstyle['fill'] != 'none') {
23280			$fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['fill'], $this->spot_colors);
23281			if ($svgstyle['fill-opacity'] != 1) {
23282				$this->setAlpha($this->alpha['CA'], 'Normal', $svgstyle['fill-opacity'], false);
23283			}
23284			$this->SetFillColorArray($fill_color);
23285			if ($svgstyle['fill-rule'] == 'evenodd') {
23286				$objstyle .= 'F*';
23287			} else {
23288				$objstyle .= 'F';
23289			}
23290		}
23291		// stroke
23292		if ($svgstyle['stroke'] != 'none') {
23293			if ($svgstyle['stroke-opacity'] != 1) {
23294				$this->setAlpha($svgstyle['stroke-opacity'], 'Normal', $this->alpha['ca'], false);
23295			} elseif (preg_match('/rgba\(\d+%?,\s*\d+%?,\s*\d+%?,\s*(\d+(?:\.\d+)?)\)/i', $svgstyle['stroke'], $rgba_matches)) {
23296				$this->setAlpha($rgba_matches[1], 'Normal', $this->alpha['ca'], false);
23297			}
23298			$stroke_style = array(
23299				'color' => TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stroke'], $this->spot_colors),
23300				'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false),
23301				'cap' => $svgstyle['stroke-linecap'],
23302				'join' => $svgstyle['stroke-linejoin']
23303				);
23304			if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {
23305				$stroke_style['dash'] = $svgstyle['stroke-dasharray'];
23306			}
23307			$this->SetLineStyle($stroke_style);
23308			$objstyle .= 'D';
23309		}
23310		// font
23311		$regs = array();
23312		if (!empty($svgstyle['font'])) {
23313			if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) {
23314				$font_family = $this->getFontFamilyName($regs[1]);
23315			} else {
23316				$font_family = $svgstyle['font-family'];
23317			}
23318			if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23319				$font_size = trim($regs[1]);
23320			} else {
23321				$font_size = $svgstyle['font-size'];
23322			}
23323			if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23324				$font_style = trim($regs[1]);
23325			} else {
23326				$font_style = $svgstyle['font-style'];
23327			}
23328			if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23329				$font_weight = trim($regs[1]);
23330			} else {
23331				$font_weight = $svgstyle['font-weight'];
23332			}
23333			if (preg_match('/font-stretch[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23334				$font_stretch = trim($regs[1]);
23335			} else {
23336				$font_stretch = $svgstyle['font-stretch'];
23337			}
23338			if (preg_match('/letter-spacing[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23339				$font_spacing = trim($regs[1]);
23340			} else {
23341				$font_spacing = $svgstyle['letter-spacing'];
23342			}
23343		} else {
23344			$font_family = $this->getFontFamilyName($svgstyle['font-family']);
23345			$font_size = $svgstyle['font-size'];
23346			$font_style = $svgstyle['font-style'];
23347			$font_weight = $svgstyle['font-weight'];
23348			$font_stretch = $svgstyle['font-stretch'];
23349			$font_spacing = $svgstyle['letter-spacing'];
23350		}
23351		$font_size = $this->getHTMLFontUnits($font_size, $this->svgstyles[0]['font-size'], $prevsvgstyle['font-size'], $this->svgunit);
23352		$font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);
23353		$font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);
23354		switch ($font_style) {
23355			case 'italic': {
23356				$font_style = 'I';
23357				break;
23358			}
23359			case 'oblique': {
23360				$font_style = 'I';
23361				break;
23362			}
23363			default:
23364			case 'normal': {
23365				$font_style = '';
23366				break;
23367			}
23368		}
23369		switch ($font_weight) {
23370			case 'bold':
23371			case 'bolder': {
23372				$font_style .= 'B';
23373				break;
23374			}
23375			case 'normal': {
23376				if ((substr($font_family, -1) == 'I') AND (substr($font_family, -2, 1) == 'B')) {
23377					$font_family = substr($font_family, 0, -2).'I';
23378				} elseif (substr($font_family, -1) == 'B') {
23379					$font_family = substr($font_family, 0, -1);
23380				}
23381				break;
23382			}
23383		}
23384		switch ($svgstyle['text-decoration']) {
23385			case 'underline': {
23386				$font_style .= 'U';
23387				break;
23388			}
23389			case 'overline': {
23390				$font_style .= 'O';
23391				break;
23392			}
23393			case 'line-through': {
23394				$font_style .= 'D';
23395				break;
23396			}
23397			default:
23398			case 'none': {
23399				break;
23400			}
23401		}
23402		$this->SetFont($font_family, $font_style, $font_size);
23403		$this->setFontStretching($font_stretch);
23404		$this->setFontSpacing($font_spacing);
23405		return $objstyle;
23406	}
23407
23408	/**
23409	 * Draws an SVG path
23410	 * @param $d (string) attribute d of the path SVG element
23411	 * @param $style (string) Style of rendering. Possible values are:
23412	 * <ul>
23413	 *	 <li>D or empty string: Draw (default).</li>
23414	 *	 <li>F: Fill.</li>
23415	 *	 <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
23416	 *	 <li>DF or FD: Draw and fill.</li>
23417	 *	 <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
23418	 *	 <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
23419	 *	 <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
23420	 * </ul>
23421	 * @return array of container box measures (x, y, w, h)
23422	 * @author Nicola Asuni
23423	 * @since 5.0.000 (2010-05-02)
23424	 * @protected
23425	 */
23426	protected function SVGPath($d, $style='') {
23427		if ($this->state != 2) {
23428			 return;
23429		}
23430		// set fill/stroke style
23431		$op = TCPDF_STATIC::getPathPaintOperator($style, '');
23432		if (empty($op)) {
23433			return;
23434		}
23435		$paths = array();
23436		$d = preg_replace('/([0-9ACHLMQSTVZ])([\-\+])/si', '\\1 \\2', $d);
23437		preg_match_all('/([ACHLMQSTVZ])[\s]*([^ACHLMQSTVZ\"]*)/si', $d, $paths, PREG_SET_ORDER);
23438		$x = 0;
23439		$y = 0;
23440		$x1 = 0;
23441		$y1 = 0;
23442		$x2 = 0;
23443		$y2 = 0;
23444		$xmin = 2147483647;
23445		$xmax = 0;
23446		$ymin = 2147483647;
23447		$ymax = 0;
23448		$relcoord = false;
23449		$minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
23450		$firstcmd = true; // used to print first point
23451		// draw curve pieces
23452		foreach ($paths as $key => $val) {
23453			// get curve type
23454			$cmd = trim($val[1]);
23455			if (strtolower($cmd) == $cmd) {
23456				// use relative coordinated instead of absolute
23457				$relcoord = true;
23458				$xoffset = $x;
23459				$yoffset = $y;
23460			} else {
23461				$relcoord = false;
23462				$xoffset = 0;
23463				$yoffset = 0;
23464			}
23465			$params = array();
23466			if (isset($val[2])) {
23467				// get curve parameters
23468				$rawparams = preg_split('/([\,\s]+)/si', trim($val[2]));
23469				$params = array();
23470				foreach ($rawparams as $ck => $cp) {
23471					$params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit, false);
23472					if (abs($params[$ck]) < $minlen) {
23473						// approximate little values to zero
23474						$params[$ck] = 0;
23475					}
23476				}
23477			}
23478			// store current origin point
23479			$x0 = $x;
23480			$y0 = $y;
23481			switch (strtoupper($cmd)) {
23482				case 'M': { // moveto
23483					foreach ($params as $ck => $cp) {
23484						if (($ck % 2) == 0) {
23485							$x = $cp + $xoffset;
23486						} else {
23487							$y = $cp + $yoffset;
23488							if ($firstcmd OR (abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23489								if ($ck == 1) {
23490									$this->_outPoint($x, $y);
23491									$firstcmd = false;
23492								} else {
23493									$this->_outLine($x, $y);
23494								}
23495								$x0 = $x;
23496								$y0 = $y;
23497							}
23498							$xmin = min($xmin, $x);
23499							$ymin = min($ymin, $y);
23500							$xmax = max($xmax, $x);
23501							$ymax = max($ymax, $y);
23502							if ($relcoord) {
23503								$xoffset = $x;
23504								$yoffset = $y;
23505							}
23506						}
23507					}
23508					break;
23509				}
23510				case 'L': { // lineto
23511					foreach ($params as $ck => $cp) {
23512						if (($ck % 2) == 0) {
23513							$x = $cp + $xoffset;
23514						} else {
23515							$y = $cp + $yoffset;
23516							if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23517								$this->_outLine($x, $y);
23518								$x0 = $x;
23519								$y0 = $y;
23520							}
23521							$xmin = min($xmin, $x);
23522							$ymin = min($ymin, $y);
23523							$xmax = max($xmax, $x);
23524							$ymax = max($ymax, $y);
23525							if ($relcoord) {
23526								$xoffset = $x;
23527								$yoffset = $y;
23528							}
23529						}
23530					}
23531					break;
23532				}
23533				case 'H': { // horizontal lineto
23534					foreach ($params as $ck => $cp) {
23535						$x = $cp + $xoffset;
23536						if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23537							$this->_outLine($x, $y);
23538							$x0 = $x;
23539							$y0 = $y;
23540						}
23541						$xmin = min($xmin, $x);
23542						$xmax = max($xmax, $x);
23543						if ($relcoord) {
23544							$xoffset = $x;
23545						}
23546					}
23547					break;
23548				}
23549				case 'V': { // vertical lineto
23550					foreach ($params as $ck => $cp) {
23551						$y = $cp + $yoffset;
23552						if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23553							$this->_outLine($x, $y);
23554							$x0 = $x;
23555							$y0 = $y;
23556						}
23557						$ymin = min($ymin, $y);
23558						$ymax = max($ymax, $y);
23559						if ($relcoord) {
23560							$yoffset = $y;
23561						}
23562					}
23563					break;
23564				}
23565				case 'C': { // curveto
23566					foreach ($params as $ck => $cp) {
23567						$params[$ck] = $cp;
23568						if ((($ck + 1) % 6) == 0) {
23569							$x1 = $params[($ck - 5)] + $xoffset;
23570							$y1 = $params[($ck - 4)] + $yoffset;
23571							$x2 = $params[($ck - 3)] + $xoffset;
23572							$y2 = $params[($ck - 2)] + $yoffset;
23573							$x = $params[($ck - 1)] + $xoffset;
23574							$y = $params[($ck)] + $yoffset;
23575							$this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
23576							$xmin = min($xmin, $x, $x1, $x2);
23577							$ymin = min($ymin, $y, $y1, $y2);
23578							$xmax = max($xmax, $x, $x1, $x2);
23579							$ymax = max($ymax, $y, $y1, $y2);
23580							if ($relcoord) {
23581								$xoffset = $x;
23582								$yoffset = $y;
23583							}
23584						}
23585					}
23586					break;
23587				}
23588				case 'S': { // shorthand/smooth curveto
23589					foreach ($params as $ck => $cp) {
23590						$params[$ck] = $cp;
23591						if ((($ck + 1) % 4) == 0) {
23592							if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) {
23593								$x1 = (2 * $x) - $x2;
23594								$y1 = (2 * $y) - $y2;
23595							} else {
23596								$x1 = $x;
23597								$y1 = $y;
23598							}
23599							$x2 = $params[($ck - 3)] + $xoffset;
23600							$y2 = $params[($ck - 2)] + $yoffset;
23601							$x = $params[($ck - 1)] + $xoffset;
23602							$y = $params[($ck)] + $yoffset;
23603							$this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
23604							$xmin = min($xmin, $x, $x1, $x2);
23605							$ymin = min($ymin, $y, $y1, $y2);
23606							$xmax = max($xmax, $x, $x1, $x2);
23607							$ymax = max($ymax, $y, $y1, $y2);
23608							if ($relcoord) {
23609								$xoffset = $x;
23610								$yoffset = $y;
23611							}
23612						}
23613					}
23614					break;
23615				}
23616				case 'Q': { // quadratic Bezier curveto
23617					foreach ($params as $ck => $cp) {
23618						$params[$ck] = $cp;
23619						if ((($ck + 1) % 4) == 0) {
23620							// convert quadratic points to cubic points
23621							$x1 = $params[($ck - 3)] + $xoffset;
23622							$y1 = $params[($ck - 2)] + $yoffset;
23623							$xa = ($x + (2 * $x1)) / 3;
23624							$ya = ($y + (2 * $y1)) / 3;
23625							$x = $params[($ck - 1)] + $xoffset;
23626							$y = $params[($ck)] + $yoffset;
23627							$xb = ($x + (2 * $x1)) / 3;
23628							$yb = ($y + (2 * $y1)) / 3;
23629							$this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
23630							$xmin = min($xmin, $x, $xa, $xb);
23631							$ymin = min($ymin, $y, $ya, $yb);
23632							$xmax = max($xmax, $x, $xa, $xb);
23633							$ymax = max($ymax, $y, $ya, $yb);
23634							if ($relcoord) {
23635								$xoffset = $x;
23636								$yoffset = $y;
23637							}
23638						}
23639					}
23640					break;
23641				}
23642				case 'T': { // shorthand/smooth quadratic Bezier curveto
23643					foreach ($params as $ck => $cp) {
23644						$params[$ck] = $cp;
23645						if (($ck % 2) != 0) {
23646							if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) {
23647								$x1 = (2 * $x) - $x1;
23648								$y1 = (2 * $y) - $y1;
23649							} else {
23650								$x1 = $x;
23651								$y1 = $y;
23652							}
23653							// convert quadratic points to cubic points
23654							$xa = ($x + (2 * $x1)) / 3;
23655							$ya = ($y + (2 * $y1)) / 3;
23656							$x = $params[($ck - 1)] + $xoffset;
23657							$y = $params[($ck)] + $yoffset;
23658							$xb = ($x + (2 * $x1)) / 3;
23659							$yb = ($y + (2 * $y1)) / 3;
23660							$this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
23661							$xmin = min($xmin, $x, $xa, $xb);
23662							$ymin = min($ymin, $y, $ya, $yb);
23663							$xmax = max($xmax, $x, $xa, $xb);
23664							$ymax = max($ymax, $y, $ya, $yb);
23665							if ($relcoord) {
23666								$xoffset = $x;
23667								$yoffset = $y;
23668							}
23669						}
23670					}
23671					break;
23672				}
23673				case 'A': { // elliptical arc
23674					foreach ($params as $ck => $cp) {
23675						$params[$ck] = $cp;
23676						if ((($ck + 1) % 7) == 0) {
23677							$x0 = $x;
23678							$y0 = $y;
23679							$rx = abs($params[($ck - 6)]);
23680							$ry = abs($params[($ck - 5)]);
23681							$ang = -$rawparams[($ck - 4)];
23682							$angle = deg2rad($ang);
23683							$fa = $rawparams[($ck - 3)]; // large-arc-flag
23684							$fs = $rawparams[($ck - 2)]; // sweep-flag
23685							$x = $params[($ck - 1)] + $xoffset;
23686							$y = $params[$ck] + $yoffset;
23687							if ((abs($x0 - $x) < $minlen) AND (abs($y0 - $y) < $minlen)) {
23688								// endpoints are almost identical
23689								$xmin = min($xmin, $x);
23690								$ymin = min($ymin, $y);
23691								$xmax = max($xmax, $x);
23692								$ymax = max($ymax, $y);
23693							} else {
23694								$cos_ang = cos($angle);
23695								$sin_ang = sin($angle);
23696								$a = (($x0 - $x) / 2);
23697								$b = (($y0 - $y) / 2);
23698								$xa = ($a * $cos_ang) - ($b * $sin_ang);
23699								$ya = ($a * $sin_ang) + ($b * $cos_ang);
23700								$rx2 = $rx * $rx;
23701								$ry2 = $ry * $ry;
23702								$xa2 = $xa * $xa;
23703								$ya2 = $ya * $ya;
23704								$delta = ($xa2 / $rx2) + ($ya2 / $ry2);
23705								if ($delta > 1) {
23706									$rx *= sqrt($delta);
23707									$ry *= sqrt($delta);
23708									$rx2 = $rx * $rx;
23709									$ry2 = $ry * $ry;
23710								}
23711								$numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2));
23712								if ($numerator < 0) {
23713									$root = 0;
23714								} else {
23715									$root = sqrt($numerator / (($rx2 * $ya2) + ($ry2 * $xa2)));
23716								}
23717								if ($fa == $fs){
23718									$root *= -1;
23719								}
23720								$cax = $root * (($rx * $ya) / $ry);
23721								$cay = -$root * (($ry * $xa) / $rx);
23722								// coordinates of ellipse center
23723								$cx = ($cax * $cos_ang) - ($cay * $sin_ang) + (($x0 + $x) / 2);
23724								$cy = ($cax * $sin_ang) + ($cay * $cos_ang) + (($y0 + $y) / 2);
23725								// get angles
23726								$angs = TCPDF_STATIC::getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry));
23727								$dang = TCPDF_STATIC::getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry));
23728								if (($fs == 0) AND ($dang > 0)) {
23729									$dang -= (2 * M_PI);
23730								} elseif (($fs == 1) AND ($dang < 0)) {
23731									$dang += (2 * M_PI);
23732								}
23733								$angf = $angs - $dang;
23734								if ((($fs == 0) AND ($angs > $angf)) OR (($fs == 1) AND ($angs < $angf))) {
23735									// reverse angles
23736									$tmp = $angs;
23737									$angs = $angf;
23738									$angf = $tmp;
23739								}
23740								$angs = round(rad2deg($angs), 6);
23741								$angf = round(rad2deg($angf), 6);
23742								// covent angles to positive values
23743								if (($angs < 0) AND ($angf < 0)) {
23744									$angs += 360;
23745									$angf += 360;
23746								}
23747								$pie = false;
23748								if (($key == 0) AND (isset($paths[($key + 1)][1])) AND (trim($paths[($key + 1)][1]) == 'z')) {
23749									$pie = true;
23750								}
23751								list($axmin, $aymin, $axmax, $aymax) = $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2, false, ($fs == 0), true);
23752								$xmin = min($xmin, $x, $axmin);
23753								$ymin = min($ymin, $y, $aymin);
23754								$xmax = max($xmax, $x, $axmax);
23755								$ymax = max($ymax, $y, $aymax);
23756							}
23757							if ($relcoord) {
23758								$xoffset = $x;
23759								$yoffset = $y;
23760							}
23761						}
23762					}
23763					break;
23764				}
23765				case 'Z': {
23766					$this->_out('h');
23767					break;
23768				}
23769			}
23770			$firstcmd = false;
23771		} // end foreach
23772		if (!empty($op)) {
23773			$this->_out($op);
23774		}
23775		return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin));
23776	}
23777
23778	/**
23779	 * Return the tag name without the namespace
23780	 * @param $name (string) Tag name
23781	 * @protected
23782	 */
23783	protected function removeTagNamespace($name) {
23784		if(strpos($name, ':') !== false) {
23785			$parts = explode(':', $name);
23786			return $parts[(sizeof($parts) - 1)];
23787		}
23788		return $name;
23789	}
23790
23791	/**
23792	 * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***)
23793	 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
23794	 * @param $name (string) The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
23795	 * @param $attribs (array) The third parameter, attribs, contains an associative array with the element's attributes (if any). The keys of this array are the attribute names, the values are the attribute values. Attribute names are case-folded on the same criteria as element names. Attribute values are not case-folded. The original order of the attributes can be retrieved by walking through attribs the normal way, using each(). The first key in the array was the first attribute, and so on.
23796	 * @param $ctm (array) tranformation matrix for clipping mode (starting transformation matrix).
23797	 * @author Nicola Asuni
23798	 * @since 5.0.000 (2010-05-02)
23799	 * @protected
23800	 */
23801	protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) {
23802		$name = $this->removeTagNamespace($name);
23803		// check if we are in clip mode
23804		if ($this->svgclipmode) {
23805			$this->svgclippaths[$this->svgclipid][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm[$this->svgclipid]);
23806			return;
23807		}
23808		if ($this->svgdefsmode AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) {
23809			if (isset($attribs['id'])) {
23810				$attribs['child_elements'] = array();
23811				$this->svgdefs[$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
23812				return;
23813			}
23814			if (end($this->svgdefs) !== FALSE) {
23815				$last_svgdefs_id = key($this->svgdefs);
23816				if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
23817					$attribs['id'] = 'DF_'.(count($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements']) + 1);
23818					$this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
23819					return;
23820				}
23821			}
23822			return;
23823		}
23824		$clipping = false;
23825		if ($parser == 'clip-path') {
23826			// set clipping mode
23827			$clipping = true;
23828		}
23829		// get styling properties
23830		$prev_svgstyle = $this->svgstyles[max(0,(count($this->svgstyles) - 1))]; // previous style
23831		$svgstyle = $this->svgstyles[0]; // set default style
23832		if ($clipping AND !isset($attribs['fill']) AND (!isset($attribs['style']) OR (!preg_match('/[;\"\s]{1}fill[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval)))) {
23833			// default fill attribute for clipping
23834			$attribs['fill'] = 'none';
23835		}
23836		if (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style']) AND ($attribs['style'][0] != ';')) {
23837			// fix style for regular expression
23838			$attribs['style'] = ';'.$attribs['style'];
23839		}
23840		foreach ($prev_svgstyle as $key => $val) {
23841			if (in_array($key, TCPDF_IMAGES::$svginheritprop)) {
23842				// inherit previous value
23843				$svgstyle[$key] = $val;
23844			}
23845			if (isset($attribs[$key]) AND !TCPDF_STATIC::empty_string($attribs[$key])) {
23846				// specific attribute settings
23847				if ($attribs[$key] == 'inherit') {
23848					$svgstyle[$key] = $val;
23849				} else {
23850					$svgstyle[$key] = $attribs[$key];
23851				}
23852			} elseif (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style'])) {
23853				// CSS style syntax
23854				$attrval = array();
23855				if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) {
23856					if ($attrval[1] == 'inherit') {
23857						$svgstyle[$key] = $val;
23858					} else {
23859						$svgstyle[$key] = $attrval[1];
23860					}
23861				}
23862			}
23863		}
23864		// transformation matrix
23865		if (!empty($ctm)) {
23866			$tm = $ctm;
23867		} else {
23868			$tm = array(1,0,0,1,0,0);
23869		}
23870		if (isset($attribs['transform']) AND !empty($attribs['transform'])) {
23871			$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, TCPDF_STATIC::getSVGTransformMatrix($attribs['transform']));
23872		}
23873		$svgstyle['transfmatrix'] = $tm;
23874		$invisible = false;
23875		if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) {
23876			// the current graphics element is invisible (nothing is painted)
23877			$invisible = true;
23878		}
23879		// process tag
23880		switch($name) {
23881			case 'defs': {
23882				$this->svgdefsmode = true;
23883				break;
23884			}
23885			// clipPath
23886			case 'clipPath': {
23887				if ($invisible) {
23888					break;
23889				}
23890				$this->svgclipmode = true;
23891				if (!isset($attribs['id'])) {
23892					$attribs['id'] = 'CP_'.(count($this->svgcliptm) + 1);
23893				}
23894				$this->svgclipid = $attribs['id'];
23895				$this->svgclippaths[$this->svgclipid] = array();
23896				$this->svgcliptm[$this->svgclipid] = $tm;
23897				break;
23898			}
23899			case 'svg': {
23900				// start of SVG object
23901				if(++$this->svg_tag_depth <= 1) {
23902					break;
23903				}
23904				// inner SVG
23905				array_push($this->svgstyles, $svgstyle);
23906				$this->StartTransform();
23907				$svgX = (isset($attribs['x'])?$attribs['x']:0);
23908				$svgY = (isset($attribs['y'])?$attribs['y']:0);
23909				$svgW = (isset($attribs['width'])?$attribs['width']:0);
23910				$svgH = (isset($attribs['height'])?$attribs['height']:0);
23911				// set x, y position using transform matrix
23912				$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array( 1, 0, 0, 1, $svgX, $svgY));
23913				$this->SVGTransform($tm);
23914				// set clipping for width and height
23915				$x = 0;
23916				$y = 0;
23917				$w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):$this->w);
23918				$h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):$this->h);
23919				// draw clipping rect
23920				$this->Rect($x, $y, $w, $h, 'CNZ', array(), array());
23921				// parse viewbox, calculate extra transformation matrix
23922				if (isset($attribs['viewBox'])) {
23923					$tmp = array();
23924					preg_match_all("/[0-9]+/", $attribs['viewBox'], $tmp);
23925					$tmp = $tmp[0];
23926					if (sizeof($tmp) == 4) {
23927						$vx = $tmp[0];
23928						$vy = $tmp[1];
23929						$vw = $tmp[2];
23930						$vh = $tmp[3];
23931						// get aspect ratio
23932						$tmp = array();
23933						$aspectX = 'xMid';
23934						$aspectY = 'YMid';
23935						$fit = 'meet';
23936						if (isset($attribs['preserveAspectRatio'])) {
23937							if($attribs['preserveAspectRatio'] == 'none') {
23938								$fit = 'none';
23939							} else {
23940								preg_match_all('/[a-zA-Z]+/', $attribs['preserveAspectRatio'], $tmp);
23941								$tmp = $tmp[0];
23942								if ((sizeof($tmp) == 2) AND (strlen($tmp[0]) == 8) AND (in_array($tmp[1], array('meet', 'slice', 'none')))) {
23943									$aspectX = substr($tmp[0], 0, 4);
23944									$aspectY = substr($tmp[0], 4, 4);
23945									$fit = $tmp[1];
23946								}
23947							}
23948						}
23949						$wr = ($svgW / $vw);
23950						$hr = ($svgH / $vh);
23951						$ax = $ay = 0;
23952						if ((($fit == 'meet') AND ($hr < $wr)) OR (($fit == 'slice') AND ($hr > $wr))) {
23953							if ($aspectX == 'xMax') {
23954								$ax = (($vw * ($wr / $hr)) - $vw);
23955							}
23956							if ($aspectX == 'xMid') {
23957								$ax = ((($vw * ($wr / $hr)) - $vw) / 2);
23958							}
23959							$wr = $hr;
23960						} elseif ((($fit == 'meet') AND ($hr > $wr)) OR (($fit == 'slice') AND ($hr < $wr))) {
23961							if ($aspectY == 'YMax') {
23962								$ay = (($vh * ($hr / $wr)) - $vh);
23963							}
23964							if ($aspectY == 'YMid') {
23965								$ay = ((($vh * ($hr / $wr)) - $vh) / 2);
23966							}
23967							$hr = $wr;
23968						}
23969						$newtm = array($wr, 0, 0, $hr, (($wr * ($ax - $vx)) - $svgX), (($hr * ($ay - $vy)) - $svgY));
23970						$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, $newtm);
23971						$this->SVGTransform($tm);
23972					}
23973				}
23974				$this->setSVGStyles($svgstyle, $prev_svgstyle);
23975				break;
23976			}
23977			case 'g': {
23978				// group together related graphics elements
23979				array_push($this->svgstyles, $svgstyle);
23980				$this->StartTransform();
23981				$x = (isset($attribs['x'])?$attribs['x']:0);
23982				$y = (isset($attribs['y'])?$attribs['y']:0);
23983				$w = 1;//(isset($attribs['width'])?$attribs['width']:1);
23984				$h = 1;//(isset($attribs['height'])?$attribs['height']:1);
23985				$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
23986				$this->SVGTransform($tm);
23987				$this->setSVGStyles($svgstyle, $prev_svgstyle);
23988				break;
23989			}
23990			case 'linearGradient': {
23991				if ($this->pdfa_mode) {
23992					break;
23993				}
23994				if (!isset($attribs['id'])) {
23995					$attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
23996				}
23997				$this->svggradientid = $attribs['id'];
23998				$this->svggradients[$this->svggradientid] = array();
23999				$this->svggradients[$this->svggradientid]['type'] = 2;
24000				$this->svggradients[$this->svggradientid]['stops'] = array();
24001				if (isset($attribs['gradientUnits'])) {
24002					$this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
24003				} else {
24004					$this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
24005				}
24006				//$attribs['spreadMethod']
24007				if (((!isset($attribs['x1'])) AND (!isset($attribs['y1'])) AND (!isset($attribs['x2'])) AND (!isset($attribs['y2'])))
24008					OR ((isset($attribs['x1']) AND (substr($attribs['x1'], -1) == '%'))
24009						OR (isset($attribs['y1']) AND (substr($attribs['y1'], -1) == '%'))
24010						OR (isset($attribs['x2']) AND (substr($attribs['x2'], -1) == '%'))
24011						OR (isset($attribs['y2']) AND (substr($attribs['y2'], -1) == '%')))) {
24012					$this->svggradients[$this->svggradientid]['mode'] = 'percentage';
24013				} else {
24014					$this->svggradients[$this->svggradientid]['mode'] = 'measure';
24015				}
24016				$x1 = (isset($attribs['x1'])?$attribs['x1']:'0');
24017				$y1 = (isset($attribs['y1'])?$attribs['y1']:'0');
24018				$x2 = (isset($attribs['x2'])?$attribs['x2']:'100');
24019				$y2 = (isset($attribs['y2'])?$attribs['y2']:'0');
24020				if (isset($attribs['gradientTransform'])) {
24021					$this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
24022				}
24023				$this->svggradients[$this->svggradientid]['coords'] = array($x1, $y1, $x2, $y2);
24024				if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24025					// gradient is defined on another place
24026					$this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
24027				}
24028				break;
24029			}
24030			case 'radialGradient': {
24031				if ($this->pdfa_mode) {
24032					break;
24033				}
24034				if (!isset($attribs['id'])) {
24035					$attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
24036				}
24037				$this->svggradientid = $attribs['id'];
24038				$this->svggradients[$this->svggradientid] = array();
24039				$this->svggradients[$this->svggradientid]['type'] = 3;
24040				$this->svggradients[$this->svggradientid]['stops'] = array();
24041				if (isset($attribs['gradientUnits'])) {
24042					$this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
24043				} else {
24044					$this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
24045				}
24046				//$attribs['spreadMethod']
24047				if (((!isset($attribs['cx'])) AND (!isset($attribs['cy'])))
24048					OR ((isset($attribs['cx']) AND (substr($attribs['cx'], -1) == '%'))
24049					OR (isset($attribs['cy']) AND (substr($attribs['cy'], -1) == '%')))) {
24050					$this->svggradients[$this->svggradientid]['mode'] = 'percentage';
24051				} elseif (isset($attribs['r']) AND is_numeric($attribs['r']) AND ($attribs['r']) <= 1) {
24052					$this->svggradients[$this->svggradientid]['mode'] = 'ratio';
24053				} else {
24054					$this->svggradients[$this->svggradientid]['mode'] = 'measure';
24055				}
24056				$cx = (isset($attribs['cx']) ? $attribs['cx'] : 0.5);
24057				$cy = (isset($attribs['cy']) ? $attribs['cy'] : 0.5);
24058				$fx = (isset($attribs['fx']) ? $attribs['fx'] : $cx);
24059				$fy = (isset($attribs['fy']) ? $attribs['fy'] : $cy);
24060				$r = (isset($attribs['r']) ? $attribs['r'] : 0.5);
24061				if (isset($attribs['gradientTransform'])) {
24062					$this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
24063				}
24064				$this->svggradients[$this->svggradientid]['coords'] = array($cx, $cy, $fx, $fy, $r);
24065				if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24066					// gradient is defined on another place
24067					$this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
24068				}
24069				break;
24070			}
24071			case 'stop': {
24072				// gradient stops
24073				if (substr($attribs['offset'], -1) == '%') {
24074					$offset = floatval(substr($attribs['offset'], 0, -1)) / 100;
24075				} else {
24076					$offset = floatval($attribs['offset']);
24077					if ($offset > 1) {
24078						$offset /= 100;
24079					}
24080				}
24081				$stop_color = isset($svgstyle['stop-color'])?TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stop-color'], $this->spot_colors):'black';
24082				$opacity = isset($svgstyle['stop-opacity'])?$svgstyle['stop-opacity']:1;
24083				$this->svggradients[$this->svggradientid]['stops'][] = array('offset' => $offset, 'color' => $stop_color, 'opacity' => $opacity);
24084				break;
24085			}
24086			// paths
24087			case 'path': {
24088				if ($invisible) {
24089					break;
24090				}
24091				if (isset($attribs['d'])) {
24092					$d = trim($attribs['d']);
24093					if (!empty($d)) {
24094						$x = (isset($attribs['x'])?$attribs['x']:0);
24095						$y = (isset($attribs['y'])?$attribs['y']:0);
24096						$w = (isset($attribs['width'])?$attribs['width']:1);
24097						$h = (isset($attribs['height'])?$attribs['height']:1);
24098						$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
24099						if ($clipping) {
24100							$this->SVGTransform($tm);
24101							$this->SVGPath($d, 'CNZ');
24102						} else {
24103							$this->StartTransform();
24104							$this->SVGTransform($tm);
24105							$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'SVGPath', array($d, 'CNZ'));
24106							if (!empty($obstyle)) {
24107								$this->SVGPath($d, $obstyle);
24108							}
24109							$this->StopTransform();
24110						}
24111					}
24112				}
24113				break;
24114			}
24115			// shapes
24116			case 'rect': {
24117				if ($invisible) {
24118					break;
24119				}
24120				$x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
24121				$y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
24122				$w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
24123				$h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
24124				$rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
24125				$ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):$rx);
24126				if ($clipping) {
24127					$this->SVGTransform($tm);
24128					$this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ', array(), array());
24129				} else {
24130					$this->StartTransform();
24131					$this->SVGTransform($tm);
24132					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'RoundedRectXY', array($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ'));
24133					if (!empty($obstyle)) {
24134						$this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', $obstyle, array(), array());
24135					}
24136					$this->StopTransform();
24137				}
24138				break;
24139			}
24140			case 'circle': {
24141				if ($invisible) {
24142					break;
24143				}
24144				$r = (isset($attribs['r']) ? $this->getHTMLUnitToUnits($attribs['r'], 0, $this->svgunit, false) : 0);
24145				$cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
24146				$cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
24147				$x = ($cx - $r);
24148				$y = ($cy - $r);
24149				$w = (2 * $r);
24150				$h = $w;
24151				if ($clipping) {
24152					$this->SVGTransform($tm);
24153					$this->Circle($cx, $cy, $r, 0, 360, 'CNZ', array(), array(), 8);
24154				} else {
24155					$this->StartTransform();
24156					$this->SVGTransform($tm);
24157					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Circle', array($cx, $cy, $r, 0, 360, 'CNZ'));
24158					if (!empty($obstyle)) {
24159						$this->Circle($cx, $cy, $r, 0, 360, $obstyle, array(), array(), 8);
24160					}
24161					$this->StopTransform();
24162				}
24163				break;
24164			}
24165			case 'ellipse': {
24166				if ($invisible) {
24167					break;
24168				}
24169				$rx = (isset($attribs['rx']) ? $this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false) : 0);
24170				$ry = (isset($attribs['ry']) ? $this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false) : 0);
24171				$cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
24172				$cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
24173				$x = ($cx - $rx);
24174				$y = ($cy - $ry);
24175				$w = (2 * $rx);
24176				$h = (2 * $ry);
24177				if ($clipping) {
24178					$this->SVGTransform($tm);
24179					$this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ', array(), array(), 8);
24180				} else {
24181					$this->StartTransform();
24182					$this->SVGTransform($tm);
24183					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Ellipse', array($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ'));
24184					if (!empty($obstyle)) {
24185						$this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, $obstyle, array(), array(), 8);
24186					}
24187					$this->StopTransform();
24188				}
24189				break;
24190			}
24191			case 'line': {
24192				if ($invisible) {
24193					break;
24194				}
24195				$x1 = (isset($attribs['x1'])?$this->getHTMLUnitToUnits($attribs['x1'], 0, $this->svgunit, false):0);
24196				$y1 = (isset($attribs['y1'])?$this->getHTMLUnitToUnits($attribs['y1'], 0, $this->svgunit, false):0);
24197				$x2 = (isset($attribs['x2'])?$this->getHTMLUnitToUnits($attribs['x2'], 0, $this->svgunit, false):0);
24198				$y2 = (isset($attribs['y2'])?$this->getHTMLUnitToUnits($attribs['y2'], 0, $this->svgunit, false):0);
24199				$x = $x1;
24200				$y = $y1;
24201				$w = abs($x2 - $x1);
24202				$h = abs($y2 - $y1);
24203				if (!$clipping) {
24204					$this->StartTransform();
24205					$this->SVGTransform($tm);
24206					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Line', array($x1, $y1, $x2, $y2));
24207					$this->Line($x1, $y1, $x2, $y2);
24208					$this->StopTransform();
24209				}
24210				break;
24211			}
24212			case 'polyline':
24213			case 'polygon': {
24214				if ($invisible) {
24215					break;
24216				}
24217				$points = (isset($attribs['points'])?$attribs['points']:'0 0');
24218				$points = trim($points);
24219				// note that point may use a complex syntax not covered here
24220				$points = preg_split('/[\,\s]+/si', $points);
24221				if (count($points) < 4) {
24222					break;
24223				}
24224				$p = array();
24225				$xmin = 2147483647;
24226				$xmax = 0;
24227				$ymin = 2147483647;
24228				$ymax = 0;
24229				foreach ($points as $key => $val) {
24230					$p[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
24231					if (($key % 2) == 0) {
24232						// X coordinate
24233						$xmin = min($xmin, $p[$key]);
24234						$xmax = max($xmax, $p[$key]);
24235					} else {
24236						// Y coordinate
24237						$ymin = min($ymin, $p[$key]);
24238						$ymax = max($ymax, $p[$key]);
24239					}
24240				}
24241				$x = $xmin;
24242				$y = $ymin;
24243				$w = ($xmax - $xmin);
24244				$h = ($ymax - $ymin);
24245				if ($name == 'polyline') {
24246					$this->StartTransform();
24247					$this->SVGTransform($tm);
24248					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'PolyLine', array($p, 'CNZ'));
24249					if (!empty($obstyle)) {
24250						$this->PolyLine($p, $obstyle, array(), array());
24251					}
24252					$this->StopTransform();
24253				} else { // polygon
24254					if ($clipping) {
24255						$this->SVGTransform($tm);
24256						$this->Polygon($p, 'CNZ', array(), array(), true);
24257					} else {
24258						$this->StartTransform();
24259						$this->SVGTransform($tm);
24260						$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Polygon', array($p, 'CNZ'));
24261						if (!empty($obstyle)) {
24262							$this->Polygon($p, $obstyle, array(), array(), true);
24263						}
24264						$this->StopTransform();
24265					}
24266				}
24267				break;
24268			}
24269			// image
24270			case 'image': {
24271				if ($invisible) {
24272					break;
24273				}
24274				if (!isset($attribs['xlink:href']) OR empty($attribs['xlink:href'])) {
24275					break;
24276				}
24277				$x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
24278				$y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
24279				$w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
24280				$h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
24281				$img = $attribs['xlink:href'];
24282				if (!$clipping) {
24283					$this->StartTransform();
24284					$this->SVGTransform($tm);
24285					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h);
24286					if (preg_match('/^data:image\/[^;]+;base64,/', $img, $m) > 0) {
24287						// embedded image encoded as base64
24288						$img = '@'.base64_decode(substr($img, strlen($m[0])));
24289					} else {
24290						// fix image path
24291						if (!TCPDF_STATIC::empty_string($this->svgdir) AND (($img[0] == '.') OR (basename($img) == $img))) {
24292							// replace relative path with full server path
24293							$img = $this->svgdir.'/'.$img;
24294						}
24295						if (($img[0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
24296							$findroot = strpos($img, $_SERVER['DOCUMENT_ROOT']);
24297							if (($findroot === false) OR ($findroot > 1)) {
24298								if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
24299									$img = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$img;
24300								} else {
24301									$img = $_SERVER['DOCUMENT_ROOT'].$img;
24302								}
24303							}
24304						}
24305						$img = urldecode($img);
24306						$testscrtype = @parse_url($img);
24307						if (empty($testscrtype['query'])) {
24308							// convert URL to server path
24309							$img = str_replace(K_PATH_URL, K_PATH_MAIN, $img);
24310						} elseif (preg_match('|^https?://|', $img) !== 1) {
24311							// convert server path to URL
24312							$img = str_replace(K_PATH_MAIN, K_PATH_URL, $img);
24313						}
24314					}
24315					// get image type
24316					$imgtype = TCPDF_IMAGES::getImageFileType($img);
24317					if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
24318						$this->ImageEps($img, $x, $y, $w, $h);
24319					} elseif ($imgtype == 'svg') {
24320						// store SVG vars
24321						$svggradients = $this->svggradients;
24322						$svggradientid = $this->svggradientid;
24323						$svgdefsmode = $this->svgdefsmode;
24324						$svgdefs = $this->svgdefs;
24325						$svgclipmode = $this->svgclipmode;
24326						$svgclippaths = $this->svgclippaths;
24327						$svgcliptm = $this->svgcliptm;
24328						$svgclipid = $this->svgclipid;
24329						$svgtext = $this->svgtext;
24330						$svgtextmode = $this->svgtextmode;
24331						$this->ImageSVG($img, $x, $y, $w, $h);
24332						// restore SVG vars
24333						$this->svggradients = $svggradients;
24334						$this->svggradientid = $svggradientid;
24335						$this->svgdefsmode = $svgdefsmode;
24336						$this->svgdefs = $svgdefs;
24337						$this->svgclipmode = $svgclipmode;
24338						$this->svgclippaths = $svgclippaths;
24339						$this->svgcliptm = $svgcliptm;
24340						$this->svgclipid = $svgclipid;
24341						$this->svgtext = $svgtext;
24342						$this->svgtextmode = $svgtextmode;
24343					} else {
24344						$this->Image($img, $x, $y, $w, $h);
24345					}
24346					$this->StopTransform();
24347				}
24348				break;
24349			}
24350			// text
24351			case 'text':
24352			case 'tspan': {
24353				if (isset($this->svgtextmode['text-anchor']) AND !empty($this->svgtext)) {
24354					// @TODO: unsupported feature
24355				}
24356				// only basic support - advanced features must be implemented
24357				$this->svgtextmode['invisible'] = $invisible;
24358				if ($invisible) {
24359					break;
24360				}
24361				array_push($this->svgstyles, $svgstyle);
24362				if (isset($attribs['x'])) {
24363					$x = $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false);
24364				} elseif ($name == 'tspan') {
24365					$x = $this->x;
24366				} else {
24367					$x = 0;
24368				}
24369				if (isset($attribs['dx'])) {
24370					$x += $this->getHTMLUnitToUnits($attribs['dx'], 0, $this->svgunit, false);
24371				}
24372				if (isset($attribs['y'])) {
24373					$y = $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false);
24374				} elseif ($name == 'tspan') {
24375					$y = $this->y;
24376				} else {
24377					$y = 0;
24378				}
24379				if (isset($attribs['dy'])) {
24380					$y += $this->getHTMLUnitToUnits($attribs['dy'], 0, $this->svgunit, false);
24381				}
24382				$svgstyle['text-color'] = $svgstyle['fill'];
24383				$this->svgtext = '';
24384				if (isset($svgstyle['text-anchor'])) {
24385					$this->svgtextmode['text-anchor'] = $svgstyle['text-anchor'];
24386				} else {
24387					$this->svgtextmode['text-anchor'] = 'start';
24388				}
24389				if (isset($svgstyle['direction'])) {
24390					if ($svgstyle['direction'] == 'rtl') {
24391						$this->svgtextmode['rtl'] = true;
24392					} else {
24393						$this->svgtextmode['rtl'] = false;
24394					}
24395				} else {
24396					$this->svgtextmode['rtl'] = false;
24397				}
24398				if (isset($svgstyle['stroke']) AND ($svgstyle['stroke'] != 'none') AND isset($svgstyle['stroke-width']) AND ($svgstyle['stroke-width'] > 0)) {
24399					$this->svgtextmode['stroke'] = $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false);
24400				} else {
24401					$this->svgtextmode['stroke'] = false;
24402				}
24403				$this->StartTransform();
24404				$this->SVGTransform($tm);
24405				$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, 1, 1);
24406				$this->x = $x;
24407				$this->y = $y;
24408				break;
24409			}
24410			// use
24411			case 'use': {
24412				if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24413					$svgdefid = substr($attribs['xlink:href'], 1);
24414					if (isset($this->svgdefs[$svgdefid])) {
24415						$use = $this->svgdefs[$svgdefid];
24416						if (isset($attribs['xlink:href'])) {
24417							unset($attribs['xlink:href']);
24418						}
24419						if (isset($attribs['id'])) {
24420							unset($attribs['id']);
24421						}
24422						if (isset($use['attribs']['x']) AND isset($attribs['x'])) {
24423							$attribs['x'] += $use['attribs']['x'];
24424						}
24425						if (isset($use['attribs']['y']) AND isset($attribs['y'])) {
24426							$attribs['y'] += $use['attribs']['y'];
24427						}
24428						if (empty($attribs['style'])) {
24429							$attribs['style'] = '';
24430						}
24431						if (!empty($use['attribs']['style'])) {
24432							// merge styles
24433							$attribs['style'] = str_replace(';;',';',';'.$use['attribs']['style'].$attribs['style']);
24434						}
24435						$attribs = array_merge($use['attribs'], $attribs);
24436						$this->startSVGElementHandler($parser, $use['name'], $attribs);
24437						return;
24438					}
24439				}
24440				break;
24441			}
24442			default: {
24443				break;
24444			}
24445		} // end of switch
24446		// process child elements
24447		if (!empty($attribs['child_elements'])) {
24448			$child_elements = $attribs['child_elements'];
24449			unset($attribs['child_elements']);
24450			foreach($child_elements as $child_element) {
24451				if (empty($child_element['attribs']['closing_tag'])) {
24452					$this->startSVGElementHandler('child-tag', $child_element['name'], $child_element['attribs']);
24453				} else {
24454					if (isset($child_element['attribs']['content'])) {
24455						$this->svgtext = $child_element['attribs']['content'];
24456					}
24457					$this->endSVGElementHandler('child-tag', $child_element['name']);
24458				}
24459			}
24460		}
24461	}
24462
24463	/**
24464	 * Sets the closing SVG element handler function for the XML parser.
24465	 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
24466	 * @param $name (string) The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
24467	 * @author Nicola Asuni
24468	 * @since 5.0.000 (2010-05-02)
24469	 * @protected
24470	 */
24471	protected function endSVGElementHandler($parser, $name) {
24472		$name = $this->removeTagNamespace($name);
24473		if ($this->svgdefsmode AND !in_array($name, array('defs', 'clipPath', 'linearGradient', 'radialGradient', 'stop'))) {;
24474			if (end($this->svgdefs) !== FALSE) {
24475				$last_svgdefs_id = key($this->svgdefs);
24476				if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
24477					foreach($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'] as $child_element) {
24478						if (isset($child_element['attribs']['id']) AND ($child_element['name'] == $name)) {
24479							$this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$child_element['attribs']['id'].'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
24480							return;
24481						}
24482					}
24483					if ($this->svgdefs[$last_svgdefs_id]['name'] == $name) {
24484						$this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$last_svgdefs_id.'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
24485						return;
24486					}
24487				}
24488			}
24489			return;
24490		}
24491		switch($name) {
24492			case 'defs': {
24493				$this->svgdefsmode = false;
24494				break;
24495			}
24496			// clipPath
24497			case 'clipPath': {
24498				$this->svgclipmode = false;
24499				break;
24500			}
24501			case 'svg': {
24502				if (--$this->svg_tag_depth <= 0) {
24503					break;
24504				}
24505			}
24506			case 'g': {
24507				// ungroup: remove last style from array
24508				array_pop($this->svgstyles);
24509				$this->StopTransform();
24510				break;
24511			}
24512			case 'text':
24513			case 'tspan': {
24514				if ($this->svgtextmode['invisible']) {
24515					// This implementation must be fixed to following the rule:
24516					// If the 'visibility' property is set to hidden on a 'tspan', 'tref' or 'altGlyph' element, then the text is invisible but still takes up space in text layout calculations.
24517					break;
24518				}
24519				// print text
24520				$text = $this->svgtext;
24521				//$text = $this->stringTrim($text);
24522				$textlen = $this->GetStringWidth($text);
24523				if ($this->svgtextmode['text-anchor'] != 'start') {
24524					// check if string is RTL text
24525					if ($this->svgtextmode['text-anchor'] == 'end') {
24526						if ($this->svgtextmode['rtl']) {
24527							$this->x += $textlen;
24528						} else {
24529							$this->x -= $textlen;
24530						}
24531					} elseif ($this->svgtextmode['text-anchor'] == 'middle') {
24532						if ($this->svgtextmode['rtl']) {
24533							$this->x += ($textlen / 2);
24534						} else {
24535							$this->x -= ($textlen / 2);
24536						}
24537					}
24538				}
24539				$textrendermode = $this->textrendermode;
24540				$textstrokewidth = $this->textstrokewidth;
24541				$this->setTextRenderingMode($this->svgtextmode['stroke'], true, false);
24542				if ($name == 'text') {
24543					// store current coordinates
24544					$tmpx = $this->x;
24545					$tmpy = $this->y;
24546				}
24547				// print the text
24548				$this->Cell($textlen, 0, $text, 0, 0, '', false, '', 0, false, 'L', 'T');
24549				if ($name == 'text') {
24550					// restore coordinates
24551					$this->x = $tmpx;
24552					$this->y = $tmpy;
24553				}
24554				// restore previous rendering mode
24555				$this->textrendermode = $textrendermode;
24556				$this->textstrokewidth = $textstrokewidth;
24557				$this->svgtext = '';
24558				$this->StopTransform();
24559				if (!$this->svgdefsmode) {
24560					array_pop($this->svgstyles);
24561				}
24562				break;
24563			}
24564			default: {
24565				break;
24566			}
24567		}
24568	}
24569
24570	/**
24571	 * Sets the character data handler function for the XML parser.
24572	 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
24573	 * @param $data (string) The second parameter, data, contains the character data as a string.
24574	 * @author Nicola Asuni
24575	 * @since 5.0.000 (2010-05-02)
24576	 * @protected
24577	 */
24578	protected function segSVGContentHandler($parser, $data) {
24579		$this->svgtext .= $data;
24580	}
24581
24582	// --- END SVG METHODS -----------------------------------------------------
24583
24584} // END OF TCPDF CLASS
24585
24586//============================================================+
24587// END OF FILE
24588//============================================================+
24589