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 = 'courier';
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|string) 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 (substr($page, 0, 1) == '*')) {
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				return false;
6882			}
6883			if (($imsize = @getimagesize($file)) === FALSE) {
6884				if (in_array($file, $this->imagekeys)) {
6885					// get existing image data
6886					$info = $this->getImageBuffer($file);
6887					$imsize = array($info['w'], $info['h']);
6888				} elseif (strpos($file, '__tcpdf_'.$this->file_id.'_img') === FALSE) {
6889					$imgdata = TCPDF_STATIC::fileGetContents($file);
6890				}
6891			}
6892		}
6893		if (!empty($imgdata)) {
6894			// copy image to cache
6895			$original_file = $file;
6896			$file = TCPDF_STATIC::getObjFilename('img', $this->file_id);
6897			$fp = TCPDF_STATIC::fopenLocal($file, 'w');
6898			if (!$fp) {
6899				$this->Error('Unable to write file: '.$file);
6900			}
6901			fwrite($fp, $imgdata);
6902			fclose($fp);
6903			unset($imgdata);
6904			$imsize = @getimagesize($file);
6905			if ($imsize === FALSE) {
6906				unlink($file);
6907				$file = $original_file;
6908			}
6909		}
6910		if ($imsize === FALSE) {
6911			if (($w > 0) AND ($h > 0)) {
6912				// get measures from specified data
6913				$pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
6914				$ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
6915				$imsize = array($pw, $ph);
6916			} else {
6917				$this->Error('[Image] Unable to get the size of the image: '.$file);
6918			}
6919		}
6920		// file hash
6921		$filehash = md5($file);
6922		// get original image width and height in pixels
6923		list($pixw, $pixh) = $imsize;
6924		// calculate image width and height on document
6925		if (($w <= 0) AND ($h <= 0)) {
6926			// convert image size to document unit
6927			$w = $this->pixelsToUnits($pixw);
6928			$h = $this->pixelsToUnits($pixh);
6929		} elseif ($w <= 0) {
6930			$w = $h * $pixw / $pixh;
6931		} elseif ($h <= 0) {
6932			$h = $w * $pixh / $pixw;
6933		} elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
6934			if (strlen($fitbox) !== 2) {
6935				// set default alignment
6936				$fitbox = '--';
6937			}
6938			// scale image dimensions proportionally to fit within the ($w, $h) box
6939			if ((($w * $pixh) / ($h * $pixw)) < 1) {
6940				// store current height
6941				$oldh = $h;
6942				// calculate new height
6943				$h = $w * $pixh / $pixw;
6944				// height difference
6945				$hdiff = ($oldh - $h);
6946				// vertical alignment
6947				switch (strtoupper($fitbox[1])) {
6948					case 'T': {
6949						break;
6950					}
6951					case 'M': {
6952						$y += ($hdiff / 2);
6953						break;
6954					}
6955					case 'B': {
6956						$y += $hdiff;
6957						break;
6958					}
6959				}
6960			} else {
6961				// store current width
6962				$oldw = $w;
6963				// calculate new width
6964				$w = $h * $pixw / $pixh;
6965				// width difference
6966				$wdiff = ($oldw - $w);
6967				// horizontal alignment
6968				switch (strtoupper($fitbox[0])) {
6969					case 'L': {
6970						if ($this->rtl) {
6971							$x -= $wdiff;
6972						}
6973						break;
6974					}
6975					case 'C': {
6976						if ($this->rtl) {
6977							$x -= ($wdiff / 2);
6978						} else {
6979							$x += ($wdiff / 2);
6980						}
6981						break;
6982					}
6983					case 'R': {
6984						if (!$this->rtl) {
6985							$x += $wdiff;
6986						}
6987						break;
6988					}
6989				}
6990			}
6991		}
6992		// fit the image on available space
6993		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
6994		// calculate new minimum dimensions in pixels
6995		$neww = round($w * $this->k * $dpi / $this->dpi);
6996		$newh = round($h * $this->k * $dpi / $this->dpi);
6997		// check if resize is necessary (resize is used only to reduce the image)
6998		$newsize = ($neww * $newh);
6999		$pixsize = ($pixw * $pixh);
7000		if (intval($resize) == 2) {
7001			$resize = true;
7002		} elseif ($newsize >= $pixsize) {
7003			$resize = false;
7004		}
7005		// check if image has been already added on document
7006		$newimage = true;
7007		if (in_array($file, $this->imagekeys)) {
7008			$newimage = false;
7009			// get existing image data
7010			$info = $this->getImageBuffer($file);
7011			if (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE) {
7012				// check if the newer image is larger
7013				$oldsize = ($info['w'] * $info['h']);
7014				if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
7015					$newimage = true;
7016				}
7017			}
7018		} elseif (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)) {
7019			// create temp image file (without alpha channel)
7020			$tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
7021			// create temp alpha file
7022			$tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
7023			// check for cached images
7024			if (in_array($tempfile_plain, $this->imagekeys)) {
7025				// get existing image data
7026				$info = $this->getImageBuffer($tempfile_plain);
7027				// check if the newer image is larger
7028				$oldsize = ($info['w'] * $info['h']);
7029				if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
7030					$newimage = true;
7031				} else {
7032					$newimage = false;
7033					// embed mask image
7034					$imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
7035					// embed image, masked with previously embedded mask
7036					return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
7037				}
7038			}
7039		}
7040		if ($newimage) {
7041			//First use of image, get info
7042			$type = strtolower($type);
7043			if ($type == '') {
7044				$type = TCPDF_IMAGES::getImageFileType($file, $imsize);
7045			} elseif ($type == 'jpg') {
7046				$type = 'jpeg';
7047			}
7048			$mqr = TCPDF_STATIC::get_mqr();
7049			TCPDF_STATIC::set_mqr(false);
7050			// Specific image handlers (defined on TCPDF_IMAGES CLASS)
7051			$mtd = '_parse'.$type;
7052			// GD image handler function
7053			$gdfunction = 'imagecreatefrom'.$type;
7054			$info = false;
7055			if ((method_exists('TCPDF_IMAGES', $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
7056				// TCPDF image functions
7057				$info = TCPDF_IMAGES::$mtd($file);
7058				if (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)
7059					AND (($info === 'pngalpha') OR (isset($info['trns']) AND !empty($info['trns'])))) {
7060					return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
7061				}
7062			}
7063			if (($info === false) AND function_exists($gdfunction)) {
7064				try {
7065					// GD library
7066					$img = $gdfunction($file);
7067					if ($img !== false) {
7068						if ($resize) {
7069							$imgr = imagecreatetruecolor($neww, $newh);
7070							if (($type == 'gif') OR ($type == 'png')) {
7071								$imgr = TCPDF_IMAGES::setGDImageTransparency($imgr, $img);
7072							}
7073							imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
7074							$img = $imgr;
7075						}
7076						if (($type == 'gif') OR ($type == 'png')) {
7077							$info = TCPDF_IMAGES::_toPNG($img, TCPDF_STATIC::getObjFilename('img', $this->file_id));
7078						} else {
7079							$info = TCPDF_IMAGES::_toJPEG($img, $this->jpeg_quality, TCPDF_STATIC::getObjFilename('img', $this->file_id));
7080						}
7081					}
7082				} catch(Exception $e) {
7083					$info = false;
7084				}
7085			}
7086			if (($info === false) AND extension_loaded('imagick')) {
7087				try {
7088					// ImageMagick library
7089					$img = new Imagick();
7090					if ($type == 'svg') {
7091						if ($file[0] === '@') {
7092							// image from string
7093							$svgimg = substr($file, 1);
7094						} else {
7095							// get SVG file content
7096							$svgimg = TCPDF_STATIC::fileGetContents($file);
7097						}
7098						if ($svgimg !== FALSE) {
7099							// get width and height
7100							$regs = array();
7101							if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
7102								$svgtag = $regs[1];
7103								$tmp = array();
7104								if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
7105									$ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
7106									$owu = sprintf('%F', ($ow * $dpi / 72)).$this->pdfunit;
7107									$svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
7108								} else {
7109									$ow = $w;
7110								}
7111								$tmp = array();
7112								if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
7113									$oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
7114									$ohu = sprintf('%F', ($oh * $dpi / 72)).$this->pdfunit;
7115									$svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
7116								} else {
7117									$oh = $h;
7118								}
7119								$tmp = array();
7120								if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
7121									$vbw = ($ow * $this->imgscale * $this->k);
7122									$vbh = ($oh * $this->imgscale * $this->k);
7123									$vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
7124									$svgtag = $vbox.$svgtag;
7125								}
7126								$svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
7127							}
7128							$img->readImageBlob($svgimg);
7129						}
7130					} else {
7131						$img->readImage($file);
7132					}
7133					if ($resize) {
7134						$img->resizeImage($neww, $newh, 10, 1, false);
7135					}
7136					$img->setCompressionQuality($this->jpeg_quality);
7137					$img->setImageFormat('jpeg');
7138					$tempname = TCPDF_STATIC::getObjFilename('img', $this->file_id);
7139					$img->writeImage($tempname);
7140					$info = TCPDF_IMAGES::_parsejpeg($tempname);
7141					unlink($tempname);
7142					$img->destroy();
7143				} catch(Exception $e) {
7144					$info = false;
7145				}
7146			}
7147			if ($info === false) {
7148				// unable to process image
7149				return;
7150			}
7151			TCPDF_STATIC::set_mqr($mqr);
7152			if ($ismask) {
7153				// force grayscale
7154				$info['cs'] = 'DeviceGray';
7155			}
7156			if ($imgmask !== false) {
7157				$info['masked'] = $imgmask;
7158			}
7159			if (!empty($exurl)) {
7160				$info['exurl'] = $exurl;
7161			}
7162			// array of alternative images
7163			$info['altimgs'] = $altimgs;
7164			// add image to document
7165			$info['i'] = $this->setImageBuffer($file, $info);
7166		}
7167		// set alignment
7168		$this->img_rb_x = $x + $w;
7169		$this->img_rb_y = $y + $h;
7170
7171		// set alignment
7172		if ($palign == 'L') {
7173			$ximg = $this->lMargin;
7174		} elseif ($palign == 'C') {
7175			$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
7176		} elseif ($palign == 'R') {
7177			$ximg = $this->w - $this->rMargin - $w;
7178		} else {
7179			$ximg = $x;
7180		}
7181
7182		if ($ismask OR $hidden) {
7183			// image is not displayed
7184			return $info['i'];
7185		}
7186		$xkimg = $ximg * $this->k;
7187		if (!$alt) {
7188			// only non-alternative immages will be set
7189			$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']));
7190		}
7191		if (!empty($border)) {
7192			$bx = $this->x;
7193			$by = $this->y;
7194			$this->x = $ximg;
7195			if ($this->rtl) {
7196				$this->x += $w;
7197			}
7198			$this->y = $y;
7199			$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
7200			$this->x = $bx;
7201			$this->y = $by;
7202		}
7203		if ($link) {
7204			$this->Link($ximg, $y, $w, $h, $link, 0);
7205		}
7206		// set pointer to align the next text/objects
7207		switch($align) {
7208			case 'T': {
7209				$this->y = $y;
7210				$this->x = $this->img_rb_x;
7211				break;
7212			}
7213			case 'M': {
7214				$this->y = $y + round($h/2);
7215				$this->x = $this->img_rb_x;
7216				break;
7217			}
7218			case 'B': {
7219				$this->y = $this->img_rb_y;
7220				$this->x = $this->img_rb_x;
7221				break;
7222			}
7223			case 'N': {
7224				$this->SetY($this->img_rb_y);
7225				break;
7226			}
7227			default:{
7228				break;
7229			}
7230		}
7231		$this->endlinex = $this->img_rb_x;
7232		if ($this->inxobj) {
7233			// we are inside an XObject template
7234			$this->xobjects[$this->xobjid]['images'][] = $info['i'];
7235		}
7236		return $info['i'];
7237	}
7238
7239	/**
7240	 * Extract info from a PNG image with alpha channel using the Imagick or GD library.
7241	 * @param $file (string) Name of the file containing the image.
7242	 * @param $x (float) Abscissa of the upper-left corner.
7243	 * @param $y (float) Ordinate of the upper-left corner.
7244	 * @param $wpx (float) Original width of the image in pixels.
7245	 * @param $hpx (float) original height of the image in pixels.
7246	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
7247	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
7248	 * @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.
7249	 * @param $link (mixed) URL or identifier returned by AddLink().
7250	 * @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>
7251	 * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
7252	 * @param $dpi (int) dot-per-inch resolution used on resize
7253	 * @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>
7254	 * @param $filehash (string) File hash used to build unique file names.
7255	 * @author Nicola Asuni
7256	 * @protected
7257	 * @since 4.3.007 (2008-12-04)
7258	 * @see Image()
7259	 */
7260	protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
7261		// create temp images
7262		if (empty($filehash)) {
7263			$filehash = md5($file);
7264		}
7265		// create temp image file (without alpha channel)
7266		$tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
7267		// create temp alpha file
7268		$tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
7269		$parsed = false;
7270		$parse_error = '';
7271		// ImageMagick extension
7272		if (($parsed === false) AND extension_loaded('imagick')) {
7273			try {
7274				// ImageMagick library
7275				$img = new Imagick();
7276				$img->readImage($file);
7277				// clone image object
7278				$imga = TCPDF_STATIC::objclone($img);
7279				// extract alpha channel
7280				if (method_exists($img, 'setImageAlphaChannel') AND defined('Imagick::ALPHACHANNEL_EXTRACT')) {
7281					$img->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
7282				} else {
7283					$img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
7284					$img->negateImage(true);
7285				}
7286				$img->setImageFormat('png');
7287				$img->writeImage($tempfile_alpha);
7288				// remove alpha channel
7289				if (method_exists($imga, 'setImageMatte')) {
7290					$imga->setImageMatte(false);
7291				} else {
7292					$imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
7293				}
7294				$imga->setImageFormat('png');
7295				$imga->writeImage($tempfile_plain);
7296				$parsed = true;
7297			} catch (Exception $e) {
7298				// Imagemagick fails, try with GD
7299				$parse_error = 'Imagick library error: '.$e->getMessage();
7300			}
7301		}
7302		// GD extension
7303		if (($parsed === false) AND function_exists('imagecreatefrompng')) {
7304			try {
7305				// generate images
7306				$img = imagecreatefrompng($file);
7307				$imgalpha = imagecreate($wpx, $hpx);
7308				// generate gray scale palette (0 -> 255)
7309				for ($c = 0; $c < 256; ++$c) {
7310					ImageColorAllocate($imgalpha, $c, $c, $c);
7311				}
7312				// extract alpha channel
7313				for ($xpx = 0; $xpx < $wpx; ++$xpx) {
7314					for ($ypx = 0; $ypx < $hpx; ++$ypx) {
7315						$color = imagecolorat($img, $xpx, $ypx);
7316						// get and correct gamma color
7317						$alpha = $this->getGDgamma($img, $color);
7318						imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
7319					}
7320				}
7321				imagepng($imgalpha, $tempfile_alpha);
7322				imagedestroy($imgalpha);
7323				// extract image without alpha channel
7324				$imgplain = imagecreatetruecolor($wpx, $hpx);
7325				imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
7326				imagepng($imgplain, $tempfile_plain);
7327				imagedestroy($imgplain);
7328				$parsed = true;
7329			} catch (Exception $e) {
7330				// GD fails
7331				$parse_error = 'GD library error: '.$e->getMessage();
7332			}
7333		}
7334		if ($parsed === false) {
7335			if (empty($parse_error)) {
7336				$this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
7337			} else {
7338				$this->Error($parse_error);
7339			}
7340		}
7341		// embed mask image
7342		$imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
7343		// embed image, masked with previously embedded mask
7344		$this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
7345	}
7346
7347	/**
7348	 * Get the GD-corrected PNG gamma value from alpha color
7349	 * @param $img (int) GD image Resource ID.
7350	 * @param $c (int) alpha color
7351	 * @protected
7352	 * @since 4.3.007 (2008-12-04)
7353	 */
7354	protected function getGDgamma($img, $c) {
7355		if (!isset($this->gdgammacache['#'.$c])) {
7356			$colors = imagecolorsforindex($img, $c);
7357			// GD alpha is only 7 bit (0 -> 127)
7358			$this->gdgammacache['#'.$c] = (((127 - $colors['alpha']) / 127) * 255);
7359			// correct gamma
7360			$this->gdgammacache['#'.$c] = (pow(($this->gdgammacache['#'.$c] / 255), 2.2) * 255);
7361			// store the latest values on cache to improve performances
7362			if (count($this->gdgammacache) > 8) {
7363				// remove one element from the cache array
7364				array_shift($this->gdgammacache);
7365			}
7366		}
7367		return $this->gdgammacache['#'.$c];
7368	}
7369
7370	/**
7371	 * Performs a line break.
7372	 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
7373	 * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
7374	 * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
7375	 * @public
7376	 * @since 1.0
7377	 * @see Cell()
7378	 */
7379	public function Ln($h='', $cell=false) {
7380		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'])) {
7381			// revove vertical space from the top of the column
7382			return;
7383		}
7384		if ($cell) {
7385			if ($this->rtl) {
7386				$cellpadding = $this->cell_padding['R'];
7387			} else {
7388				$cellpadding = $this->cell_padding['L'];
7389			}
7390		} else {
7391			$cellpadding = 0;
7392		}
7393		if ($this->rtl) {
7394			$this->x = $this->w - $this->rMargin - $cellpadding;
7395		} else {
7396			$this->x = $this->lMargin + $cellpadding;
7397		}
7398		if (is_string($h)) {
7399			$h = $this->lasth;
7400		}
7401		$this->y += $h;
7402		$this->newline = true;
7403	}
7404
7405	/**
7406	 * Returns the relative X value of current position.
7407	 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
7408	 * @return float
7409	 * @public
7410	 * @since 1.2
7411	 * @see SetX(), GetY(), SetY()
7412	 */
7413	public function GetX() {
7414		//Get x position
7415		if ($this->rtl) {
7416			return ($this->w - $this->x);
7417		} else {
7418			return $this->x;
7419		}
7420	}
7421
7422	/**
7423	 * Returns the absolute X value of current position.
7424	 * @return float
7425	 * @public
7426	 * @since 1.2
7427	 * @see SetX(), GetY(), SetY()
7428	 */
7429	public function GetAbsX() {
7430		return $this->x;
7431	}
7432
7433	/**
7434	 * Returns the ordinate of the current position.
7435	 * @return float
7436	 * @public
7437	 * @since 1.0
7438	 * @see SetY(), GetX(), SetX()
7439	 */
7440	public function GetY() {
7441		return $this->y;
7442	}
7443
7444	/**
7445	 * Defines the abscissa of the current position.
7446	 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
7447	 * @param $x (float) The value of the abscissa in user units.
7448	 * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
7449	 * @public
7450	 * @since 1.2
7451	 * @see GetX(), GetY(), SetY(), SetXY()
7452	 */
7453	public function SetX($x, $rtloff=false) {
7454		$x = floatval($x);
7455		if (!$rtloff AND $this->rtl) {
7456			if ($x >= 0) {
7457				$this->x = $this->w - $x;
7458			} else {
7459				$this->x = abs($x);
7460			}
7461		} else {
7462			if ($x >= 0) {
7463				$this->x = $x;
7464			} else {
7465				$this->x = $this->w + $x;
7466			}
7467		}
7468		if ($this->x < 0) {
7469			$this->x = 0;
7470		}
7471		if ($this->x > $this->w) {
7472			$this->x = $this->w;
7473		}
7474	}
7475
7476	/**
7477	 * Moves the current abscissa back to the left margin and sets the ordinate.
7478	 * If the passed value is negative, it is relative to the bottom of the page.
7479	 * @param $y (float) The value of the ordinate in user units.
7480	 * @param $resetx (bool) if true (default) reset the X position.
7481	 * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
7482	 * @public
7483	 * @since 1.0
7484	 * @see GetX(), GetY(), SetY(), SetXY()
7485	 */
7486	public function SetY($y, $resetx=true, $rtloff=false) {
7487		$y = floatval($y);
7488		if ($resetx) {
7489			//reset x
7490			if (!$rtloff AND $this->rtl) {
7491				$this->x = $this->w - $this->rMargin;
7492			} else {
7493				$this->x = $this->lMargin;
7494			}
7495		}
7496		if ($y >= 0) {
7497			$this->y = $y;
7498		} else {
7499			$this->y = $this->h + $y;
7500		}
7501		if ($this->y < 0) {
7502			$this->y = 0;
7503		}
7504		if ($this->y > $this->h) {
7505			$this->y = $this->h;
7506		}
7507	}
7508
7509	/**
7510	 * Defines the abscissa and ordinate of the current position.
7511	 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
7512	 * @param $x (float) The value of the abscissa.
7513	 * @param $y (float) The value of the ordinate.
7514	 * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
7515	 * @public
7516	 * @since 1.2
7517	 * @see SetX(), SetY()
7518	 */
7519	public function SetXY($x, $y, $rtloff=false) {
7520		$this->SetY($y, false, $rtloff);
7521		$this->SetX($x, $rtloff);
7522	}
7523
7524	/**
7525	 * Set the absolute X coordinate of the current pointer.
7526	 * @param $x (float) The value of the abscissa in user units.
7527	 * @public
7528	 * @since 5.9.186 (2012-09-13)
7529	 * @see setAbsX(), setAbsY(), SetAbsXY()
7530	 */
7531	public function SetAbsX($x) {
7532		$this->x = floatval($x);
7533	}
7534
7535	/**
7536	 * Set the absolute Y coordinate of the current pointer.
7537	 * @param $y (float) (float) The value of the ordinate in user units.
7538	 * @public
7539	 * @since 5.9.186 (2012-09-13)
7540	 * @see setAbsX(), setAbsY(), SetAbsXY()
7541	 */
7542	public function SetAbsY($y) {
7543		$this->y = floatval($y);
7544	}
7545
7546	/**
7547	 * Set the absolute X and Y coordinates of the current pointer.
7548	 * @param $x (float) The value of the abscissa in user units.
7549	 * @param $y (float) (float) The value of the ordinate in user units.
7550	 * @public
7551	 * @since 5.9.186 (2012-09-13)
7552	 * @see setAbsX(), setAbsY(), SetAbsXY()
7553	 */
7554	public function SetAbsXY($x, $y) {
7555		$this->SetAbsX($x);
7556		$this->SetAbsY($y);
7557	}
7558
7559	/**
7560	 * Send the document to a given destination: string, local file or browser.
7561	 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
7562	 * The method first calls Close() if necessary to terminate the document.
7563	 * @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.
7564	 * @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>
7565	 * @return string
7566	 * @public
7567	 * @since 1.0
7568	 * @see Close()
7569	 */
7570	public function Output($name='doc.pdf', $dest='I') {
7571		//Output PDF to some destination
7572		//Finish document if necessary
7573		if ($this->state < 3) {
7574			$this->Close();
7575		}
7576		//Normalize parameters
7577		if (is_bool($dest)) {
7578			$dest = $dest ? 'D' : 'F';
7579		}
7580		$dest = strtoupper($dest);
7581		if ($dest[0] != 'F') {
7582			$name = preg_replace('/[\s]+/', '_', $name);
7583			$name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
7584		}
7585		if ($this->sign) {
7586			// *** apply digital signature to the document ***
7587			// get the document content
7588			$pdfdoc = $this->getBuffer();
7589			// remove last newline
7590			$pdfdoc = substr($pdfdoc, 0, -1);
7591			// remove filler space
7592			$byterange_string_len = strlen(TCPDF_STATIC::$byterange_string);
7593			// define the ByteRange
7594			$byte_range = array();
7595			$byte_range[0] = 0;
7596			$byte_range[1] = strpos($pdfdoc, TCPDF_STATIC::$byterange_string) + $byterange_string_len + 10;
7597			$byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
7598			$byte_range[3] = strlen($pdfdoc) - $byte_range[2];
7599			$pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
7600			// replace the ByteRange
7601			$byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
7602			$byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
7603			$pdfdoc = str_replace(TCPDF_STATIC::$byterange_string, $byterange, $pdfdoc);
7604			// write the document to a temporary folder
7605			$tempdoc = TCPDF_STATIC::getObjFilename('doc', $this->file_id);
7606			$f = TCPDF_STATIC::fopenLocal($tempdoc, 'wb');
7607			if (!$f) {
7608				$this->Error('Unable to create temporary file: '.$tempdoc);
7609			}
7610			$pdfdoc_length = strlen($pdfdoc);
7611			fwrite($f, $pdfdoc, $pdfdoc_length);
7612			fclose($f);
7613			// get digital signature via openssl library
7614			$tempsign = TCPDF_STATIC::getObjFilename('sig', $this->file_id);
7615			if (empty($this->signature_data['extracerts'])) {
7616				openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
7617			} else {
7618				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']);
7619			}
7620			// read signature
7621			$signature = file_get_contents($tempsign);
7622			// extract signature
7623			$signature = substr($signature, $pdfdoc_length);
7624			$signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
7625			$tmparr = explode("\n\n", $signature);
7626			$signature = $tmparr[1];
7627			// decode signature
7628			$signature = base64_decode(trim($signature));
7629			// add TSA timestamp to signature
7630			$signature = $this->applyTSA($signature);
7631			// convert signature to hex
7632			$signature = current(unpack('H*', $signature));
7633			$signature = str_pad($signature, $this->signature_max_length, '0');
7634			// Add signature to the document
7635			$this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
7636			$this->bufferlen = strlen($this->buffer);
7637		}
7638		switch($dest) {
7639			case 'I': {
7640				// Send PDF to the standard output
7641				if (ob_get_contents()) {
7642					$this->Error('Some data has already been output, can\'t send PDF file');
7643				}
7644				if (php_sapi_name() != 'cli') {
7645					// send output to a browser
7646					header('Content-Type: application/pdf');
7647					if (headers_sent()) {
7648						$this->Error('Some data has already been output to browser, can\'t send PDF file');
7649					}
7650					header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7651					//header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
7652					header('Pragma: public');
7653					header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7654					header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7655					header('Content-Disposition: inline; filename="'.basename($name).'"');
7656					TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
7657				} else {
7658					echo $this->getBuffer();
7659				}
7660				break;
7661			}
7662			case 'D': {
7663				// download PDF as file
7664				if (ob_get_contents()) {
7665					$this->Error('Some data has already been output, can\'t send PDF file');
7666				}
7667				header('Content-Description: File Transfer');
7668				if (headers_sent()) {
7669					$this->Error('Some data has already been output to browser, can\'t send PDF file');
7670				}
7671				header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7672				//header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
7673				header('Pragma: public');
7674				header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7675				header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7676				// force download dialog
7677				if (strpos(php_sapi_name(), 'cgi') === false) {
7678					header('Content-Type: application/force-download');
7679					header('Content-Type: application/octet-stream', false);
7680					header('Content-Type: application/download', false);
7681					header('Content-Type: application/pdf', false);
7682				} else {
7683					header('Content-Type: application/pdf');
7684				}
7685				// use the Content-Disposition header to supply a recommended filename
7686				header('Content-Disposition: attachment; filename="'.basename($name).'"');
7687				header('Content-Transfer-Encoding: binary');
7688				TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
7689				break;
7690			}
7691			case 'F':
7692			case 'FI':
7693			case 'FD': {
7694				// save PDF to a local file
7695				$f = TCPDF_STATIC::fopenLocal($name, 'wb');
7696				if (!$f) {
7697					$this->Error('Unable to create output file: '.$name);
7698				}
7699				fwrite($f, $this->getBuffer(), $this->bufferlen);
7700				fclose($f);
7701				if ($dest == 'FI') {
7702					// send headers to browser
7703					header('Content-Type: application/pdf');
7704					header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7705					//header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
7706					header('Pragma: public');
7707					header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7708					header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7709					header('Content-Disposition: inline; filename="'.basename($name).'"');
7710					TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
7711				} elseif ($dest == 'FD') {
7712					// send headers to browser
7713					if (ob_get_contents()) {
7714						$this->Error('Some data has already been output, can\'t send PDF file');
7715					}
7716					header('Content-Description: File Transfer');
7717					if (headers_sent()) {
7718						$this->Error('Some data has already been output to browser, can\'t send PDF file');
7719					}
7720					header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7721					header('Pragma: public');
7722					header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7723					header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7724					// force download dialog
7725					if (strpos(php_sapi_name(), 'cgi') === false) {
7726						header('Content-Type: application/force-download');
7727						header('Content-Type: application/octet-stream', false);
7728						header('Content-Type: application/download', false);
7729						header('Content-Type: application/pdf', false);
7730					} else {
7731						header('Content-Type: application/pdf');
7732					}
7733					// use the Content-Disposition header to supply a recommended filename
7734					header('Content-Disposition: attachment; filename="'.basename($name).'"');
7735					header('Content-Transfer-Encoding: binary');
7736					TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
7737				}
7738				break;
7739			}
7740			case 'E': {
7741				// return PDF as base64 mime multi-part email attachment (RFC 2045)
7742				$retval = 'Content-Type: application/pdf;'."\r\n";
7743				$retval .= ' name="'.$name.'"'."\r\n";
7744				$retval .= 'Content-Transfer-Encoding: base64'."\r\n";
7745				$retval .= 'Content-Disposition: attachment;'."\r\n";
7746				$retval .= ' filename="'.$name.'"'."\r\n\r\n";
7747				$retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
7748				return $retval;
7749			}
7750			case 'S': {
7751				// returns PDF as a string
7752				return $this->getBuffer();
7753			}
7754			default: {
7755				$this->Error('Incorrect output destination: '.$dest);
7756			}
7757		}
7758		return '';
7759	}
7760
7761	protected static $cleaned_ids = array();
7762	/**
7763	 * Unset all class variables except the following critical variables.
7764	 * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
7765	 * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
7766	 * @public
7767	 * @since 4.5.016 (2009-02-24)
7768	 */
7769	public function _destroy($destroyall=false, $preserve_objcopy=false) {
7770		// restore internal encoding
7771		if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
7772			mb_internal_encoding($this->internal_encoding);
7773		}
7774		if (isset(self::$cleaned_ids[$this->file_id])) {
7775			$destroyall = false;
7776		}
7777		if ($destroyall AND !$preserve_objcopy) {
7778			self::$cleaned_ids[$this->file_id] = true;
7779			// remove all temporary files
7780			if ($handle = @opendir(K_PATH_CACHE)) {
7781				while ( false !== ( $file_name = readdir( $handle ) ) ) {
7782					if (strpos($file_name, '__tcpdf_'.$this->file_id.'_') === 0) {
7783						unlink(K_PATH_CACHE.$file_name);
7784					}
7785				}
7786				closedir($handle);
7787			}
7788			if (isset($this->imagekeys)) {
7789				foreach($this->imagekeys as $file) {
7790					if (strpos($file, K_PATH_CACHE) === 0) {
7791						@unlink($file);
7792					}
7793				}
7794			}
7795		}
7796		$preserve = array(
7797			'file_id',
7798			'internal_encoding',
7799			'state',
7800			'bufferlen',
7801			'buffer',
7802			'cached_files',
7803			'imagekeys',
7804			'sign',
7805			'signature_data',
7806			'signature_max_length',
7807			'byterange_string',
7808			'tsa_timestamp',
7809			'tsa_data'
7810		);
7811		foreach (array_keys(get_object_vars($this)) as $val) {
7812			if ($destroyall OR !in_array($val, $preserve)) {
7813				if ((!$preserve_objcopy OR ($val != 'objcopy')) AND ($val != 'file_id') AND isset($this->$val)) {
7814					unset($this->$val);
7815				}
7816			}
7817		}
7818	}
7819
7820	/**
7821	 * Check for locale-related bug
7822	 * @protected
7823	 */
7824	protected function _dochecks() {
7825		//Check for locale-related bug
7826		if (1.1 == 1) {
7827			$this->Error('Don\'t alter the locale before including class file');
7828		}
7829		//Check for decimal separator
7830		if (sprintf('%.1F', 1.0) != '1.0') {
7831			setlocale(LC_NUMERIC, 'C');
7832		}
7833	}
7834
7835	/**
7836	 * Return an array containing variations for the basic page number alias.
7837	 * @param $a (string) Base alias.
7838	 * @return array of page number aliases
7839	 * @protected
7840	 */
7841	protected function getInternalPageNumberAliases($a= '') {
7842		$alias = array();
7843		// build array of Unicode + ASCII variants (the order is important)
7844		$alias = array('u' => array(), 'a' => array());
7845		$u = '{'.$a.'}';
7846		$alias['u'][] = TCPDF_STATIC::_escape($u);
7847		if ($this->isunicode) {
7848			$alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($u, $this->isunicode, $this->CurrentFont));
7849			$alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($u, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
7850			$alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($a, $this->isunicode, $this->CurrentFont));
7851			$alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($a, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
7852		}
7853		$alias['a'][] = TCPDF_STATIC::_escape($a);
7854		return $alias;
7855	}
7856
7857	/**
7858	 * Return an array containing all internal page aliases.
7859	 * @return array of page number aliases
7860	 * @protected
7861	 */
7862	protected function getAllInternalPageNumberAliases() {
7863		$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);
7864		$pnalias = array();
7865		foreach($basic_alias as $k => $a) {
7866			$pnalias[$k] = $this->getInternalPageNumberAliases($a);
7867		}
7868		return $pnalias;
7869	}
7870
7871	/**
7872	 * Replace right shift page number aliases with spaces to correct right alignment.
7873	 * This works perfectly only when using monospaced fonts.
7874	 * @param $page (string) Page content.
7875	 * @param $aliases (array) Array of page aliases.
7876	 * @param $diff (int) initial difference to add.
7877	 * @return replaced page content.
7878	 * @protected
7879	 */
7880	protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
7881		foreach ($aliases as $type => $alias) {
7882			foreach ($alias as $a) {
7883				// find position of compensation factor
7884				$startnum = (strpos($a, ':') + 1);
7885				$a = substr($a, 0, $startnum);
7886				if (($pos = strpos($page, $a)) !== false) {
7887					// end of alias
7888					$endnum = strpos($page, '}', $pos);
7889					// string to be replaced
7890					$aa = substr($page, $pos, ($endnum - $pos + 1));
7891					// get compensation factor
7892					$ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
7893					$ratio = preg_replace('/[^0-9\.]/', '', $ratio);
7894					$ratio = floatval($ratio);
7895					if ($type == 'u') {
7896						$chrdiff = floor(($diff + 12) * $ratio);
7897						$shift = str_repeat(' ', $chrdiff);
7898						$shift = TCPDF_FONTS::UTF8ToUTF16BE($shift, false, $this->isunicode, $this->CurrentFont);
7899					} else {
7900						$chrdiff = floor(($diff + 11) * $ratio);
7901						$shift = str_repeat(' ', $chrdiff);
7902					}
7903					$page = str_replace($aa, $shift, $page);
7904				}
7905			}
7906		}
7907		return $page;
7908	}
7909
7910	/**
7911	 * Set page boxes to be included on page descriptions.
7912	 * @param $boxes (array) Array of page boxes to set on document: ('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox').
7913	 * @protected
7914	 */
7915	protected function setPageBoxTypes($boxes) {
7916		$this->page_boxes = array();
7917		foreach ($boxes as $box) {
7918			if (in_array($box, TCPDF_STATIC::$pageboxes)) {
7919				$this->page_boxes[] = $box;
7920			}
7921		}
7922	}
7923
7924	/**
7925	 * Output pages (and replace page number aliases).
7926	 * @protected
7927	 */
7928	protected function _putpages() {
7929		$filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
7930		// get internal aliases for page numbers
7931		$pnalias = $this->getAllInternalPageNumberAliases();
7932		$num_pages = $this->numpages;
7933		$ptpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $num_pages - 1));
7934		$ptpu = TCPDF_FONTS::UTF8ToUTF16BE($ptpa, false, $this->isunicode, $this->CurrentFont);
7935		$ptp_num_chars = $this->GetNumChars($ptpa);
7936		$pagegroupnum = 0;
7937		$groupnum = 0;
7938		$ptgu = 1;
7939		$ptga = 1;
7940		$ptg_num_chars = 1;
7941		for ($n = 1; $n <= $num_pages; ++$n) {
7942			// get current page
7943			$temppage = $this->getPageBuffer($n);
7944			$pagelen = strlen($temppage);
7945			// set replacements for total pages number
7946			$pnpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $n - 1));
7947			$pnpu = TCPDF_FONTS::UTF8ToUTF16BE($pnpa, false, $this->isunicode, $this->CurrentFont);
7948			$pnp_num_chars = $this->GetNumChars($pnpa);
7949			$pdiff = 0; // difference used for right shift alignment of page numbers
7950			$gdiff = 0; // difference used for right shift alignment of page group numbers
7951			if (!empty($this->pagegroups)) {
7952				if (isset($this->newpagegroup[$n])) {
7953					$pagegroupnum = 0;
7954					++$groupnum;
7955					$ptga = TCPDF_STATIC::formatPageNumber($this->pagegroups[$groupnum]);
7956					$ptgu = TCPDF_FONTS::UTF8ToUTF16BE($ptga, false, $this->isunicode, $this->CurrentFont);
7957					$ptg_num_chars = $this->GetNumChars($ptga);
7958				}
7959				++$pagegroupnum;
7960				$pnga = TCPDF_STATIC::formatPageNumber($pagegroupnum);
7961				$pngu = TCPDF_FONTS::UTF8ToUTF16BE($pnga, false, $this->isunicode, $this->CurrentFont);
7962				$png_num_chars = $this->GetNumChars($pnga);
7963				// replace page numbers
7964				$replace = array();
7965				$replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
7966				$replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
7967				$replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
7968				$replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
7969				list($temppage, $gdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $gdiff);
7970			}
7971			// replace page numbers
7972			$replace = array();
7973			$replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
7974			$replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
7975			$replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
7976			$replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
7977			list($temppage, $pdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $pdiff);
7978			// replace right shift alias
7979			$temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
7980			// replace EPS marker
7981			$temppage = str_replace($this->epsmarker, '', $temppage);
7982			//Page
7983			$this->page_obj_id[$n] = $this->_newobj();
7984			$out = '<<';
7985			$out .= ' /Type /Page';
7986			$out .= ' /Parent 1 0 R';
7987			if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
7988				$out .= ' /LastModified '.$this->_datestring(0, $this->doc_modification_timestamp);
7989			}
7990			$out .= ' /Resources 2 0 R';
7991			foreach ($this->page_boxes as $box) {
7992				$out .= ' /'.$box;
7993				$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']);
7994			}
7995			if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
7996				$out .= ' /BoxColorInfo <<';
7997				foreach ($this->page_boxes as $box) {
7998					if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
7999						$out .= ' /'.$box.' <<';
8000						if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
8001							$color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
8002							$out .= ' /C [';
8003							$out .= sprintf(' %F %F %F', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
8004							$out .= ' ]';
8005						}
8006						if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
8007							$out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
8008						}
8009						if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
8010							$out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
8011						}
8012						if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
8013							$dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
8014							$out .= ' /D [';
8015							foreach ($dashes as $dash) {
8016								$out .= sprintf(' %F', ($dash * $this->k));
8017							}
8018							$out .= ' ]';
8019						}
8020						$out .= ' >>';
8021					}
8022				}
8023				$out .= ' >>';
8024			}
8025			$out .= ' /Contents '.($this->n + 1).' 0 R';
8026			$out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
8027			if (!$this->pdfa_mode) {
8028				$out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
8029			}
8030			if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
8031				// page transitions
8032				if (isset($this->pagedim[$n]['trans']['Dur'])) {
8033					$out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
8034				}
8035				$out .= ' /Trans <<';
8036				$out .= ' /Type /Trans';
8037				if (isset($this->pagedim[$n]['trans']['S'])) {
8038					$out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
8039				}
8040				if (isset($this->pagedim[$n]['trans']['D'])) {
8041					$out .= ' /D '.$this->pagedim[$n]['trans']['D'];
8042				}
8043				if (isset($this->pagedim[$n]['trans']['Dm'])) {
8044					$out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
8045				}
8046				if (isset($this->pagedim[$n]['trans']['M'])) {
8047					$out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
8048				}
8049				if (isset($this->pagedim[$n]['trans']['Di'])) {
8050					$out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
8051				}
8052				if (isset($this->pagedim[$n]['trans']['SS'])) {
8053					$out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
8054				}
8055				if (isset($this->pagedim[$n]['trans']['B'])) {
8056					$out .= ' /B '.$this->pagedim[$n]['trans']['B'];
8057				}
8058				$out .= ' >>';
8059			}
8060			$out .= $this->_getannotsrefs($n);
8061			$out .= ' /PZ '.$this->pagedim[$n]['PZ'];
8062			$out .= ' >>';
8063			$out .= "\n".'endobj';
8064			$this->_out($out);
8065			//Page content
8066			$p = ($this->compress) ? gzcompress($temppage) : $temppage;
8067			$this->_newobj();
8068			$p = $this->_getrawstream($p);
8069			$this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
8070		}
8071		//Pages root
8072		$out = $this->_getobj(1)."\n";
8073		$out .= '<< /Type /Pages /Kids [';
8074		foreach($this->page_obj_id as $page_obj) {
8075			$out .= ' '.$page_obj.' 0 R';
8076		}
8077		$out .= ' ] /Count '.$num_pages.' >>';
8078		$out .= "\n".'endobj';
8079		$this->_out($out);
8080	}
8081
8082	/**
8083	 * Get references to page annotations.
8084	 * @param $n (int) page number
8085	 * @return string
8086	 * @protected
8087	 * @author Nicola Asuni
8088	 * @since 5.0.010 (2010-05-17)
8089	 */
8090	protected function _getannotsrefs($n) {
8091		if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
8092			return '';
8093		}
8094		$out = ' /Annots [';
8095		if (isset($this->PageAnnots[$n])) {
8096			foreach ($this->PageAnnots[$n] as $key => $val) {
8097				if (!in_array($val['n'], $this->radio_groups)) {
8098					$out .= ' '.$val['n'].' 0 R';
8099				}
8100			}
8101			// add radiobutton groups
8102			if (isset($this->radiobutton_groups[$n])) {
8103				foreach ($this->radiobutton_groups[$n] as $key => $data) {
8104					if (isset($data['n'])) {
8105						$out .= ' '.$data['n'].' 0 R';
8106					}
8107				}
8108			}
8109		}
8110		if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
8111			// set reference for signature object
8112			$out .= ' '.$this->sig_obj_id.' 0 R';
8113		}
8114		if (!empty($this->empty_signature_appearance)) {
8115			foreach ($this->empty_signature_appearance as $esa) {
8116				if ($esa['page'] == $n) {
8117					// set reference for empty signature objects
8118					$out .= ' '.$esa['objid'].' 0 R';
8119				}
8120			}
8121		}
8122		$out .= ' ]';
8123		return $out;
8124	}
8125
8126	/**
8127	 * Output annotations objects for all pages.
8128	 * !!! THIS METHOD IS NOT YET COMPLETED !!!
8129	 * See section 12.5 of PDF 32000_2008 reference.
8130	 * @protected
8131	 * @author Nicola Asuni
8132	 * @since 4.0.018 (2008-08-06)
8133	 */
8134	protected function _putannotsobjs() {
8135		// reset object counter
8136		for ($n=1; $n <= $this->numpages; ++$n) {
8137			if (isset($this->PageAnnots[$n])) {
8138				// set page annotations
8139				foreach ($this->PageAnnots[$n] as $key => $pl) {
8140					$annot_obj_id = $this->PageAnnots[$n][$key]['n'];
8141					// create annotation object for grouping radiobuttons
8142					if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
8143						$radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
8144						$annots = '<<';
8145						$annots .= ' /Type /Annot';
8146						$annots .= ' /Subtype /Widget';
8147						$annots .= ' /Rect [0 0 0 0]';
8148						if ($this->radiobutton_groups[$n][$pl['txt']]['#readonly#']) {
8149							// read only
8150							$annots .= ' /F 68';
8151							$annots .= ' /Ff 49153';
8152						} else {
8153							$annots .= ' /F 4'; // default print for PDF/A
8154							$annots .= ' /Ff 49152';
8155						}
8156						$annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
8157						if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
8158							$annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $radio_button_obj_id);
8159						}
8160						$annots .= ' /FT /Btn';
8161						$annots .= ' /Kids [';
8162						$defval = '';
8163						foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
8164							if (isset($data['kid'])) {
8165								$annots .= ' '.$data['kid'].' 0 R';
8166								if ($data['def'] !== 'Off') {
8167									$defval = $data['def'];
8168								}
8169							}
8170						}
8171						$annots .= ' ]';
8172						if (!empty($defval)) {
8173							$annots .= ' /V /'.$defval;
8174						}
8175						$annots .= ' >>';
8176						$this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
8177						$this->form_obj_id[] = $radio_button_obj_id;
8178						// store object id to be used on Parent entry of Kids
8179						$this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
8180					}
8181					$formfield = false;
8182					$pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
8183					$a = $pl['x'] * $this->k;
8184					$b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
8185					$c = $pl['w'] * $this->k;
8186					$d = $pl['h'] * $this->k;
8187					$rect = sprintf('%F %F %F %F', $a, $b, $a+$c, $b+$d);
8188					// create new annotation object
8189					$annots = '<</Type /Annot';
8190					$annots .= ' /Subtype /'.$pl['opt']['subtype'];
8191					$annots .= ' /Rect ['.$rect.']';
8192					$ft = array('Btn', 'Tx', 'Ch', 'Sig');
8193					if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
8194						$annots .= ' /FT /'.$pl['opt']['ft'];
8195						$formfield = true;
8196					}
8197					if ($pl['opt']['subtype'] !== 'Link') {
8198						$annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
8199					}
8200					$annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
8201					$annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
8202					$annots .= ' /M '.$this->_datestring($annot_obj_id, $this->doc_modification_timestamp);
8203					if (isset($pl['opt']['f'])) {
8204						$fval = 0;
8205						if (is_array($pl['opt']['f'])) {
8206							foreach ($pl['opt']['f'] as $f) {
8207								switch (strtolower($f)) {
8208									case 'invisible': {
8209										$fval += 1 << 0;
8210										break;
8211									}
8212									case 'hidden': {
8213										$fval += 1 << 1;
8214										break;
8215									}
8216									case 'print': {
8217										$fval += 1 << 2;
8218										break;
8219									}
8220									case 'nozoom': {
8221										$fval += 1 << 3;
8222										break;
8223									}
8224									case 'norotate': {
8225										$fval += 1 << 4;
8226										break;
8227									}
8228									case 'noview': {
8229										$fval += 1 << 5;
8230										break;
8231									}
8232									case 'readonly': {
8233										$fval += 1 << 6;
8234										break;
8235									}
8236									case 'locked': {
8237										$fval += 1 << 8;
8238										break;
8239									}
8240									case 'togglenoview': {
8241										$fval += 1 << 9;
8242										break;
8243									}
8244									case 'lockedcontents': {
8245										$fval += 1 << 10;
8246										break;
8247									}
8248									default: {
8249										break;
8250									}
8251								}
8252							}
8253						} else {
8254							$fval = intval($pl['opt']['f']);
8255						}
8256					} else {
8257						$fval = 4;
8258					}
8259					if ($this->pdfa_mode) {
8260						// force print flag for PDF/A mode
8261						$fval |= 4;
8262					}
8263					$annots .= ' /F '.intval($fval);
8264					if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
8265						$annots .= ' /AS /'.$pl['opt']['as'];
8266					}
8267					if (isset($pl['opt']['ap'])) {
8268						// appearance stream
8269						$annots .= ' /AP <<';
8270						if (is_array($pl['opt']['ap'])) {
8271							foreach ($pl['opt']['ap'] as $apmode => $apdef) {
8272								// $apmode can be: n = normal; r = rollover; d = down;
8273								$annots .= ' /'.strtoupper($apmode);
8274								if (is_array($apdef)) {
8275									$annots .= ' <<';
8276									foreach ($apdef as $apstate => $stream) {
8277										// reference to XObject that define the appearance for this mode-state
8278										$apsobjid = $this->_putAPXObject($c, $d, $stream);
8279										$annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
8280									}
8281									$annots .= ' >>';
8282								} else {
8283									// reference to XObject that define the appearance for this mode
8284									$apsobjid = $this->_putAPXObject($c, $d, $apdef);
8285									$annots .= ' '.$apsobjid.' 0 R';
8286								}
8287							}
8288						} else {
8289							$annots .= $pl['opt']['ap'];
8290						}
8291						$annots .= ' >>';
8292					}
8293					if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
8294						$annots .= ' /BS <<';
8295						$annots .= ' /Type /Border';
8296						if (isset($pl['opt']['bs']['w'])) {
8297							$annots .= ' /W '.intval($pl['opt']['bs']['w']);
8298						}
8299						$bstyles = array('S', 'D', 'B', 'I', 'U');
8300						if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
8301							$annots .= ' /S /'.$pl['opt']['bs']['s'];
8302						}
8303						if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
8304							$annots .= ' /D [';
8305							foreach ($pl['opt']['bs']['d'] as $cord) {
8306								$annots .= ' '.intval($cord);
8307							}
8308							$annots .= ']';
8309						}
8310						$annots .= ' >>';
8311					} else {
8312						$annots .= ' /Border [';
8313						if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
8314							$annots .= intval($pl['opt']['border'][0]).' ';
8315							$annots .= intval($pl['opt']['border'][1]).' ';
8316							$annots .= intval($pl['opt']['border'][2]);
8317							if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
8318								$annots .= ' [';
8319								foreach ($pl['opt']['border'][3] as $dash) {
8320									$annots .= intval($dash).' ';
8321								}
8322								$annots .= ']';
8323							}
8324						} else {
8325							$annots .= '0 0 0';
8326						}
8327						$annots .= ']';
8328					}
8329					if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
8330						$annots .= ' /BE <<';
8331						$bstyles = array('S', 'C');
8332						if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $bstyles)) {
8333							$annots .= ' /S /'.$pl['opt']['bs']['s'];
8334						} else {
8335							$annots .= ' /S /S';
8336						}
8337						if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
8338							$annots .= ' /I '.sprintf(' %F', $pl['opt']['be']['i']);
8339						}
8340						$annots .= '>>';
8341					}
8342					if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
8343						$annots .= ' /C '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['c']);
8344					}
8345					//$annots .= ' /StructParent ';
8346					//$annots .= ' /OC ';
8347					$markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
8348					if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
8349						// this is a markup type
8350						if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
8351							$annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
8352						}
8353						//$annots .= ' /Popup ';
8354						if (isset($pl['opt']['ca'])) {
8355							$annots .= ' /CA '.sprintf('%F', floatval($pl['opt']['ca']));
8356						}
8357						if (isset($pl['opt']['rc'])) {
8358							$annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
8359						}
8360						$annots .= ' /CreationDate '.$this->_datestring($annot_obj_id, $this->doc_creation_timestamp);
8361						//$annots .= ' /IRT ';
8362						if (isset($pl['opt']['subj'])) {
8363							$annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
8364						}
8365						//$annots .= ' /RT ';
8366						//$annots .= ' /IT ';
8367						//$annots .= ' /ExData ';
8368					}
8369					$lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
8370					// Annotation types
8371					switch (strtolower($pl['opt']['subtype'])) {
8372						case 'text': {
8373							if (isset($pl['opt']['open'])) {
8374								$annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
8375							}
8376							$iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
8377							if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
8378								$annots .= ' /Name /'.$pl['opt']['name'];
8379							} else {
8380								$annots .= ' /Name /Note';
8381							}
8382							$statemodels = array('Marked', 'Review');
8383							if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
8384								$annots .= ' /StateModel /'.$pl['opt']['statemodel'];
8385							} else {
8386								$pl['opt']['statemodel'] = 'Marked';
8387								$annots .= ' /StateModel /'.$pl['opt']['statemodel'];
8388							}
8389							if ($pl['opt']['statemodel'] == 'Marked') {
8390								$states = array('Accepted', 'Unmarked');
8391							} else {
8392								$states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
8393							}
8394							if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
8395								$annots .= ' /State /'.$pl['opt']['state'];
8396							} else {
8397								if ($pl['opt']['statemodel'] == 'Marked') {
8398									$annots .= ' /State /Unmarked';
8399								} else {
8400									$annots .= ' /State /None';
8401								}
8402							}
8403							break;
8404						}
8405						case 'link': {
8406							if (is_string($pl['txt']) && !empty($pl['txt'])) {
8407								if ($pl['txt'][0] == '#') {
8408									// internal destination
8409									$annots .= ' /A <</S /GoTo /D '.TCPDF_STATIC::encodeNameObject(substr($pl['txt'], 1)).'>>';
8410								} elseif ($pl['txt'][0] == '%') {
8411									// embedded PDF file
8412									$filename = basename(substr($pl['txt'], 1));
8413									$annots .= ' /A << /S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($n - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
8414								} elseif ($pl['txt'][0] == '*') {
8415									// embedded generic file
8416									$filename = basename(substr($pl['txt'], 1));
8417									$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});';
8418									$annots .= ' /A << /S /JavaScript /JS '.$this->_textstring($jsa, $annot_obj_id).'>>';
8419								} else {
8420									$parsedUrl = parse_url($pl['txt']);
8421									if (empty($parsedUrl['scheme']) AND (!empty($parsedUrl['path']) && strtolower(substr($parsedUrl['path'], -4)) == '.pdf')) {
8422										// relative link to a PDF file
8423										$dest = '[0 /Fit]'; // default page 0
8424										if (!empty($parsedUrl['fragment'])) {
8425											// check for named destination
8426											$tmp = explode('=', $parsedUrl['fragment']);
8427											$dest = '('.((count($tmp) == 2) ? $tmp[1] : $tmp[0]).')';
8428										}
8429										$annots .= ' /A <</S /GoToR /D '.$dest.' /F '.$this->_datastring($this->unhtmlentities($parsedUrl['path']), $annot_obj_id).' /NewWindow true>>';
8430									} else {
8431										// external URI link
8432										$annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
8433									}
8434								}
8435							} elseif (isset($this->links[$pl['txt']])) {
8436								// internal link ID
8437								$l = $this->links[$pl['txt']];
8438								if (isset($this->page_obj_id[($l['p'])])) {
8439									$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)));
8440								}
8441							}
8442							$hmodes = array('N', 'I', 'O', 'P');
8443							if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
8444								$annots .= ' /H /'.$pl['opt']['h'];
8445							} else {
8446								$annots .= ' /H /I';
8447							}
8448							//$annots .= ' /PA ';
8449							//$annots .= ' /Quadpoints ';
8450							break;
8451						}
8452						case 'freetext': {
8453							if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
8454								$annots .= ' /DA ('.$pl['opt']['da'].')';
8455							}
8456							if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
8457								$annots .= ' /Q '.intval($pl['opt']['q']);
8458							}
8459							if (isset($pl['opt']['rc'])) {
8460								$annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
8461							}
8462							if (isset($pl['opt']['ds'])) {
8463								$annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
8464							}
8465							if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
8466								$annots .= ' /CL [';
8467								foreach ($pl['opt']['cl'] as $cl) {
8468									$annots .= sprintf('%F ', $cl * $this->k);
8469								}
8470								$annots .= ']';
8471							}
8472							$tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
8473							if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
8474								$annots .= ' /IT /'.$pl['opt']['it'];
8475							}
8476							if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
8477								$l = $pl['opt']['rd'][0] * $this->k;
8478								$r = $pl['opt']['rd'][1] * $this->k;
8479								$t = $pl['opt']['rd'][2] * $this->k;
8480								$b = $pl['opt']['rd'][3] * $this->k;
8481								$annots .= ' /RD ['.sprintf('%F %F %F %F', $l, $r, $t, $b).']';
8482							}
8483							if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
8484								$annots .= ' /LE /'.$pl['opt']['le'];
8485							}
8486							break;
8487						}
8488						case 'line': {
8489							break;
8490						}
8491						case 'square': {
8492							break;
8493						}
8494						case 'circle': {
8495							break;
8496						}
8497						case 'polygon': {
8498							break;
8499						}
8500						case 'polyline': {
8501							break;
8502						}
8503						case 'highlight': {
8504							break;
8505						}
8506						case 'underline': {
8507							break;
8508						}
8509						case 'squiggly': {
8510							break;
8511						}
8512						case 'strikeout': {
8513							break;
8514						}
8515						case 'stamp': {
8516							break;
8517						}
8518						case 'caret': {
8519							break;
8520						}
8521						case 'ink': {
8522							break;
8523						}
8524						case 'popup': {
8525							break;
8526						}
8527						case 'fileattachment': {
8528							if ($this->pdfa_mode && $this->pdfa_version != 3) {
8529								// embedded files are not allowed in PDF/A mode version 1 and 2
8530								break;
8531							}
8532							if (!isset($pl['opt']['fs'])) {
8533								break;
8534							}
8535							$filename = basename($pl['opt']['fs']);
8536							if (isset($this->embeddedfiles[$filename]['f'])) {
8537								$annots .= ' /FS '.$this->embeddedfiles[$filename]['f'].' 0 R';
8538								$iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
8539								if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
8540									$annots .= ' /Name /'.$pl['opt']['name'];
8541								} else {
8542									$annots .= ' /Name /PushPin';
8543								}
8544								// index (zero-based) of the annotation in the Annots array of this page
8545								$this->embeddedfiles[$filename]['a'] = $key;
8546							}
8547							break;
8548						}
8549						case 'sound': {
8550							if (!isset($pl['opt']['fs'])) {
8551								break;
8552							}
8553							$filename = basename($pl['opt']['fs']);
8554							if (isset($this->embeddedfiles[$filename]['f'])) {
8555								// ... TO BE COMPLETED ...
8556								// /R /C /B /E /CO /CP
8557								$annots .= ' /Sound '.$this->embeddedfiles[$filename]['f'].' 0 R';
8558								$iconsapp = array('Speaker', 'Mic');
8559								if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
8560									$annots .= ' /Name /'.$pl['opt']['name'];
8561								} else {
8562									$annots .= ' /Name /Speaker';
8563								}
8564							}
8565							break;
8566						}
8567						case 'movie': {
8568							break;
8569						}
8570						case 'widget': {
8571							$hmode = array('N', 'I', 'O', 'P', 'T');
8572							if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
8573								$annots .= ' /H /'.$pl['opt']['h'];
8574							}
8575							if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
8576								$annots .= ' /MK <<';
8577								if (isset($pl['opt']['mk']['r'])) {
8578									$annots .= ' /R '.$pl['opt']['mk']['r'];
8579								}
8580								if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
8581									$annots .= ' /BC '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bc']);
8582								}
8583								if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
8584									$annots .= ' /BG '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bg']);
8585								}
8586								if (isset($pl['opt']['mk']['ca'])) {
8587									$annots .= ' /CA '.$pl['opt']['mk']['ca'];
8588								}
8589								if (isset($pl['opt']['mk']['rc'])) {
8590									$annots .= ' /RC '.$pl['opt']['mk']['rc'];
8591								}
8592								if (isset($pl['opt']['mk']['ac'])) {
8593									$annots .= ' /AC '.$pl['opt']['mk']['ac'];
8594								}
8595								if (isset($pl['opt']['mk']['i'])) {
8596									$info = $this->getImageBuffer($pl['opt']['mk']['i']);
8597									if ($info !== false) {
8598										$annots .= ' /I '.$info['n'].' 0 R';
8599									}
8600								}
8601								if (isset($pl['opt']['mk']['ri'])) {
8602									$info = $this->getImageBuffer($pl['opt']['mk']['ri']);
8603									if ($info !== false) {
8604										$annots .= ' /RI '.$info['n'].' 0 R';
8605									}
8606								}
8607								if (isset($pl['opt']['mk']['ix'])) {
8608									$info = $this->getImageBuffer($pl['opt']['mk']['ix']);
8609									if ($info !== false) {
8610										$annots .= ' /IX '.$info['n'].' 0 R';
8611									}
8612								}
8613								if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
8614									$annots .= ' /IF <<';
8615									$if_sw = array('A', 'B', 'S', 'N');
8616									if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
8617										$annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
8618									}
8619									$if_s = array('A', 'P');
8620									if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
8621										$annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
8622									}
8623									if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
8624										$annots .= sprintf(' /A [%F %F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
8625									}
8626									if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
8627										$annots .= ' /FB true';
8628									}
8629									$annots .= '>>';
8630								}
8631								if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
8632									$annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
8633								}
8634								$annots .= '>>';
8635							} // end MK
8636							// --- Entries for field dictionaries ---
8637							if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
8638								// set parent
8639								$annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
8640							}
8641							if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
8642								$annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
8643							}
8644							if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
8645								$annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
8646							}
8647							if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
8648								$annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
8649							}
8650							if (isset($pl['opt']['ff'])) {
8651								if (is_array($pl['opt']['ff'])) {
8652									// array of bit settings
8653									$flag = 0;
8654									foreach($pl['opt']['ff'] as $val) {
8655										$flag += 1 << ($val - 1);
8656									}
8657								} else {
8658									$flag = intval($pl['opt']['ff']);
8659								}
8660								$annots .= ' /Ff '.$flag;
8661							}
8662							if (isset($pl['opt']['maxlen'])) {
8663								$annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
8664							}
8665							if (isset($pl['opt']['v'])) {
8666								$annots .= ' /V';
8667								if (is_array($pl['opt']['v'])) {
8668									foreach ($pl['opt']['v'] AS $optval) {
8669										if (is_float($optval)) {
8670											$optval = sprintf('%F', $optval);
8671										}
8672										$annots .= ' '.$optval;
8673									}
8674								} else {
8675									$annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
8676								}
8677							}
8678							if (isset($pl['opt']['dv'])) {
8679								$annots .= ' /DV';
8680								if (is_array($pl['opt']['dv'])) {
8681									foreach ($pl['opt']['dv'] 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']['dv'], $annot_obj_id);
8689								}
8690							}
8691							if (isset($pl['opt']['rv'])) {
8692								$annots .= ' /RV';
8693								if (is_array($pl['opt']['rv'])) {
8694									foreach ($pl['opt']['rv'] 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']['rv'], $annot_obj_id);
8702								}
8703							}
8704							if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
8705								$annots .= ' /A << '.$pl['opt']['a'].' >>';
8706							}
8707							if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
8708								$annots .= ' /AA << '.$pl['opt']['aa'].' >>';
8709							}
8710							if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
8711								$annots .= ' /DA ('.$pl['opt']['da'].')';
8712							}
8713							if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
8714								$annots .= ' /Q '.intval($pl['opt']['q']);
8715							}
8716							if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
8717								$annots .= ' /Opt [';
8718								foreach($pl['opt']['opt'] AS $copt) {
8719									if (is_array($copt)) {
8720										$annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
8721									} else {
8722										$annots .= ' '.$this->_textstring($copt, $annot_obj_id);
8723									}
8724								}
8725								$annots .= ']';
8726							}
8727							if (isset($pl['opt']['ti'])) {
8728								$annots .= ' /TI '.intval($pl['opt']['ti']);
8729							}
8730							if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
8731								$annots .= ' /I [';
8732								foreach($pl['opt']['i'] AS $copt) {
8733									$annots .= intval($copt).' ';
8734								}
8735								$annots .= ']';
8736							}
8737							break;
8738						}
8739						case 'screen': {
8740							break;
8741						}
8742						case 'printermark': {
8743							break;
8744						}
8745						case 'trapnet': {
8746							break;
8747						}
8748						case 'watermark': {
8749							break;
8750						}
8751						case '3d': {
8752							break;
8753						}
8754						default: {
8755							break;
8756						}
8757					}
8758					$annots .= '>>';
8759					// create new annotation object
8760					$this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
8761					if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
8762						// store reference of form object
8763						$this->form_obj_id[] = $annot_obj_id;
8764					}
8765				}
8766			}
8767		} // end for each page
8768	}
8769
8770	/**
8771	 * Put appearance streams XObject used to define annotation's appearance states.
8772	 * @param $w (int) annotation width
8773	 * @param $h (int) annotation height
8774	 * @param $stream (string) appearance stream
8775	 * @return int object ID
8776	 * @protected
8777	 * @since 4.8.001 (2009-09-09)
8778	 */
8779	protected function _putAPXObject($w=0, $h=0, $stream='') {
8780		$stream = trim($stream);
8781		$out = $this->_getobj()."\n";
8782		$this->xobjects['AX'.$this->n] = array('n' => $this->n);
8783		$out .= '<<';
8784		$out .= ' /Type /XObject';
8785		$out .= ' /Subtype /Form';
8786		$out .= ' /FormType 1';
8787		if ($this->compress) {
8788			$stream = gzcompress($stream);
8789			$out .= ' /Filter /FlateDecode';
8790		}
8791		$rect = sprintf('%F %F', $w, $h);
8792		$out .= ' /BBox [0 0 '.$rect.']';
8793		$out .= ' /Matrix [1 0 0 1 0 0]';
8794		$out .= ' /Resources 2 0 R';
8795		$stream = $this->_getrawstream($stream);
8796		$out .= ' /Length '.strlen($stream);
8797		$out .= ' >>';
8798		$out .= ' stream'."\n".$stream."\n".'endstream';
8799		$out .= "\n".'endobj';
8800		$this->_out($out);
8801		return $this->n;
8802	}
8803
8804	/**
8805	 * Output fonts.
8806	 * @author Nicola Asuni
8807	 * @protected
8808	 */
8809	protected function _putfonts() {
8810		$nf = $this->n;
8811		foreach ($this->diffs as $diff) {
8812			//Encodings
8813			$this->_newobj();
8814			$this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
8815		}
8816		$mqr = TCPDF_STATIC::get_mqr();
8817		TCPDF_STATIC::set_mqr(false);
8818		foreach ($this->FontFiles as $file => $info) {
8819			// search and get font file to embedd
8820			$fontfile = TCPDF_FONTS::getFontFullPath($file, $info['fontdir']);
8821			if (!TCPDF_STATIC::empty_string($fontfile)) {
8822				$font = file_get_contents($fontfile);
8823				$compressed = (substr($file, -2) == '.z');
8824				if ((!$compressed) AND (isset($info['length2']))) {
8825					$header = (ord($font[0]) == 128);
8826					if ($header) {
8827						// strip first binary header
8828						$font = substr($font, 6);
8829					}
8830					if ($header AND (ord($font[$info['length1']]) == 128)) {
8831						// strip second binary header
8832						$font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
8833					}
8834				} elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
8835					if ($compressed) {
8836						// uncompress font
8837						$font = gzuncompress($font);
8838					}
8839					// merge subset characters
8840					$subsetchars = array(); // used chars
8841					foreach ($info['fontkeys'] as $fontkey) {
8842						$fontinfo = $this->getFontBuffer($fontkey);
8843						$subsetchars += $fontinfo['subsetchars'];
8844					}
8845					// rebuild a font subset
8846					$font = TCPDF_FONTS::_getTrueTypeFontSubset($font, $subsetchars);
8847					// calculate new font length
8848					$info['length1'] = strlen($font);
8849					if ($compressed) {
8850						// recompress font
8851						$font = gzcompress($font);
8852					}
8853				}
8854				$this->_newobj();
8855				$this->FontFiles[$file]['n'] = $this->n;
8856				$stream = $this->_getrawstream($font);
8857				$out = '<< /Length '.strlen($stream);
8858				if ($compressed) {
8859					$out .= ' /Filter /FlateDecode';
8860				}
8861				$out .= ' /Length1 '.$info['length1'];
8862				if (isset($info['length2'])) {
8863					$out .= ' /Length2 '.$info['length2'].' /Length3 0';
8864				}
8865				$out .= ' >>';
8866				$out .= ' stream'."\n".$stream."\n".'endstream';
8867				$out .= "\n".'endobj';
8868				$this->_out($out);
8869			}
8870		}
8871		TCPDF_STATIC::set_mqr($mqr);
8872		foreach ($this->fontkeys as $k) {
8873			//Font objects
8874			$font = $this->getFontBuffer($k);
8875			$type = $font['type'];
8876			$name = $font['name'];
8877			if ($type == 'core') {
8878				// standard core font
8879				$out = $this->_getobj($this->font_obj_ids[$k])."\n";
8880				$out .= '<</Type /Font';
8881				$out .= ' /Subtype /Type1';
8882				$out .= ' /BaseFont /'.$name;
8883				$out .= ' /Name /F'.$font['i'];
8884				if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
8885					$out .= ' /Encoding /WinAnsiEncoding';
8886				}
8887				if ($k == 'helvetica') {
8888					// add default font for annotations
8889					$this->annotation_fonts[$k] = $font['i'];
8890				}
8891				$out .= ' >>';
8892				$out .= "\n".'endobj';
8893				$this->_out($out);
8894			} elseif (($type == 'Type1') OR ($type == 'TrueType')) {
8895				// additional Type1 or TrueType font
8896				$out = $this->_getobj($this->font_obj_ids[$k])."\n";
8897				$out .= '<</Type /Font';
8898				$out .= ' /Subtype /'.$type;
8899				$out .= ' /BaseFont /'.$name;
8900				$out .= ' /Name /F'.$font['i'];
8901				$out .= ' /FirstChar 32 /LastChar 255';
8902				$out .= ' /Widths '.($this->n + 1).' 0 R';
8903				$out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
8904				if ($font['enc']) {
8905					if (isset($font['diff'])) {
8906						$out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
8907					} else {
8908						$out .= ' /Encoding /WinAnsiEncoding';
8909					}
8910				}
8911				$out .= ' >>';
8912				$out .= "\n".'endobj';
8913				$this->_out($out);
8914				// Widths
8915				$this->_newobj();
8916				$s = '[';
8917				for ($i = 32; $i < 256; ++$i) {
8918					if (isset($font['cw'][$i])) {
8919						$s .= $font['cw'][$i].' ';
8920					} else {
8921						$s .= $font['dw'].' ';
8922					}
8923				}
8924				$s .= ']';
8925				$s .= "\n".'endobj';
8926				$this->_out($s);
8927				//Descriptor
8928				$this->_newobj();
8929				$s = '<</Type /FontDescriptor /FontName /'.$name;
8930				foreach ($font['desc'] as $fdk => $fdv) {
8931					if (is_float($fdv)) {
8932						$fdv = sprintf('%F', $fdv);
8933					}
8934					$s .= ' /'.$fdk.' '.$fdv.'';
8935				}
8936				if (!TCPDF_STATIC::empty_string($font['file'])) {
8937					$s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
8938				}
8939				$s .= '>>';
8940				$s .= "\n".'endobj';
8941				$this->_out($s);
8942			} else {
8943				// additional types
8944				$mtd = '_put'.strtolower($type);
8945				if (!method_exists($this, $mtd)) {
8946					$this->Error('Unsupported font type: '.$type);
8947				}
8948				$this->$mtd($font);
8949			}
8950		}
8951	}
8952
8953	/**
8954	 * Adds unicode fonts.<br>
8955	 * Based on PDF Reference 1.3 (section 5)
8956	 * @param $font (array) font data
8957	 * @protected
8958	 * @author Nicola Asuni
8959	 * @since 1.52.0.TC005 (2005-01-05)
8960	 */
8961	protected function _puttruetypeunicode($font) {
8962		$fontname = '';
8963		if ($font['subset']) {
8964			// change name for font subsetting
8965			$subtag = sprintf('%06u', $font['i']);
8966			$subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
8967			$fontname .= $subtag.'+';
8968		}
8969		$fontname .= $font['name'];
8970		// Type0 Font
8971		// A composite font composed of other fonts, organized hierarchically
8972		$out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
8973		$out .= '<< /Type /Font';
8974		$out .= ' /Subtype /Type0';
8975		$out .= ' /BaseFont /'.$fontname;
8976		$out .= ' /Name /F'.$font['i'];
8977		$out .= ' /Encoding /'.$font['enc'];
8978		$out .= ' /ToUnicode '.($this->n + 1).' 0 R';
8979		$out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
8980		$out .= ' >>';
8981		$out .= "\n".'endobj';
8982		$this->_out($out);
8983		// ToUnicode map for Identity-H
8984		$stream = TCPDF_FONT_DATA::$uni_identity_h;
8985		// ToUnicode Object
8986		$this->_newobj();
8987		$stream = ($this->compress) ? gzcompress($stream) : $stream;
8988		$filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
8989		$stream = $this->_getrawstream($stream);
8990		$this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
8991		// CIDFontType2
8992		// A CIDFont whose glyph descriptions are based on TrueType font technology
8993		$oid = $this->_newobj();
8994		$out = '<< /Type /Font';
8995		$out .= ' /Subtype /CIDFontType2';
8996		$out .= ' /BaseFont /'.$fontname;
8997		// A dictionary containing entries that define the character collection of the CIDFont.
8998		$cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
8999		$cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
9000		$cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
9001		$out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
9002		$out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
9003		$out .= ' /DW '.$font['dw']; // default width
9004		$out .= "\n".TCPDF_FONTS::_putfontwidths($font, 0);
9005		if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
9006			$out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
9007		}
9008		$out .= ' >>';
9009		$out .= "\n".'endobj';
9010		$this->_out($out);
9011		// Font descriptor
9012		// A font descriptor describing the CIDFont default metrics other than its glyph widths
9013		$this->_newobj();
9014		$out = '<< /Type /FontDescriptor';
9015		$out .= ' /FontName /'.$fontname;
9016		foreach ($font['desc'] as $key => $value) {
9017			if (is_float($value)) {
9018				$value = sprintf('%F', $value);
9019			}
9020			$out .= ' /'.$key.' '.$value;
9021		}
9022		$fontdir = false;
9023		if (!TCPDF_STATIC::empty_string($font['file'])) {
9024			// A stream containing a TrueType font
9025			$out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
9026			$fontdir = $this->FontFiles[$font['file']]['fontdir'];
9027		}
9028		$out .= ' >>';
9029		$out .= "\n".'endobj';
9030		$this->_out($out);
9031		if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
9032			$this->_newobj();
9033			// Embed CIDToGIDMap
9034			// A specification of the mapping from CIDs to glyph indices
9035			// search and get CTG font file to embedd
9036			$ctgfile = strtolower($font['ctg']);
9037			// search and get ctg font file to embedd
9038			$fontfile = TCPDF_FONTS::getFontFullPath($ctgfile, $fontdir);
9039			if (TCPDF_STATIC::empty_string($fontfile)) {
9040				$this->Error('Font file not found: '.$ctgfile);
9041			}
9042			$stream = $this->_getrawstream(file_get_contents($fontfile));
9043			$out = '<< /Length '.strlen($stream).'';
9044			if (substr($fontfile, -2) == '.z') { // check file extension
9045				// Decompresses data encoded using the public-domain
9046				// zlib/deflate compression method, reproducing the
9047				// original text or binary data
9048				$out .= ' /Filter /FlateDecode';
9049			}
9050			$out .= ' >>';
9051			$out .= ' stream'."\n".$stream."\n".'endstream';
9052			$out .= "\n".'endobj';
9053			$this->_out($out);
9054		}
9055	}
9056
9057	/**
9058	 * Output CID-0 fonts.
9059	 * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
9060	 * @param $font (array) font data
9061	 * @protected
9062	 * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
9063	 * @since 3.2.000 (2008-06-23)
9064	 */
9065	protected function _putcidfont0($font) {
9066		$cidoffset = 0;
9067		if (!isset($font['cw'][1])) {
9068			$cidoffset = 31;
9069		}
9070		if (isset($font['cidinfo']['uni2cid'])) {
9071			// convert unicode to cid.
9072			$uni2cid = $font['cidinfo']['uni2cid'];
9073			$cw = array();
9074			foreach ($font['cw'] as $uni => $width) {
9075				if (isset($uni2cid[$uni])) {
9076					$cw[($uni2cid[$uni] + $cidoffset)] = $width;
9077				} elseif ($uni < 256) {
9078					$cw[$uni] = $width;
9079				} // else unknown character
9080			}
9081			$font = array_merge($font, array('cw' => $cw));
9082		}
9083		$name = $font['name'];
9084		$enc = $font['enc'];
9085		if ($enc) {
9086			$longname = $name.'-'.$enc;
9087		} else {
9088			$longname = $name;
9089		}
9090		$out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
9091		$out .= '<</Type /Font';
9092		$out .= ' /Subtype /Type0';
9093		$out .= ' /BaseFont /'.$longname;
9094		$out .= ' /Name /F'.$font['i'];
9095		if ($enc) {
9096			$out .= ' /Encoding /'.$enc;
9097		}
9098		$out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
9099		$out .= ' >>';
9100		$out .= "\n".'endobj';
9101		$this->_out($out);
9102		$oid = $this->_newobj();
9103		$out = '<</Type /Font';
9104		$out .= ' /Subtype /CIDFontType0';
9105		$out .= ' /BaseFont /'.$name;
9106		$cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
9107		$cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
9108		$cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
9109		$out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
9110		$out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
9111		$out .= ' /DW '.$font['dw'];
9112		$out .= "\n".TCPDF_FONTS::_putfontwidths($font, $cidoffset);
9113		$out .= ' >>';
9114		$out .= "\n".'endobj';
9115		$this->_out($out);
9116		$this->_newobj();
9117		$s = '<</Type /FontDescriptor /FontName /'.$name;
9118		foreach ($font['desc'] as $k => $v) {
9119			if ($k != 'Style') {
9120				if (is_float($v)) {
9121					$v = sprintf('%F', $v);
9122				}
9123				$s .= ' /'.$k.' '.$v.'';
9124			}
9125		}
9126		$s .= '>>';
9127		$s .= "\n".'endobj';
9128		$this->_out($s);
9129	}
9130
9131	/**
9132	 * Output images.
9133	 * @protected
9134	 */
9135	protected function _putimages() {
9136		$filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
9137		foreach ($this->imagekeys as $file) {
9138			$info = $this->getImageBuffer($file);
9139			// set object for alternate images array
9140			if ((!$this->pdfa_mode) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
9141				$altoid = $this->_newobj();
9142				$out = '[';
9143				foreach ($info['altimgs'] as $altimage) {
9144					if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
9145						$out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
9146						$out .= ' /DefaultForPrinting';
9147						if ($altimage[1] === true) {
9148							$out .= ' true';
9149						} else {
9150							$out .= ' false';
9151						}
9152						$out .= ' >>';
9153					}
9154				}
9155				$out .= ' ]';
9156				$out .= "\n".'endobj';
9157				$this->_out($out);
9158			}
9159			// set image object
9160			$oid = $this->_newobj();
9161			$this->xobjects['I'.$info['i']] = array('n' => $oid);
9162			$this->setImageSubBuffer($file, 'n', $this->n);
9163			$out = '<</Type /XObject';
9164			$out .= ' /Subtype /Image';
9165			$out .= ' /Width '.$info['w'];
9166			$out .= ' /Height '.$info['h'];
9167			if (array_key_exists('masked', $info)) {
9168				$out .= ' /SMask '.($this->n - 1).' 0 R';
9169			}
9170			// set color space
9171			$icc = false;
9172			if (isset($info['icc']) AND ($info['icc'] !== false)) {
9173				// ICC Colour Space
9174				$icc = true;
9175				$out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
9176			} elseif ($info['cs'] == 'Indexed') {
9177				// Indexed Colour Space
9178				$out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
9179			} else {
9180				// Device Colour Space
9181				$out .= ' /ColorSpace /'.$info['cs'];
9182			}
9183			if ($info['cs'] == 'DeviceCMYK') {
9184				$out .= ' /Decode [1 0 1 0 1 0 1 0]';
9185			}
9186			$out .= ' /BitsPerComponent '.$info['bpc'];
9187			if (isset($altoid) AND ($altoid > 0)) {
9188				// reference to alternate images dictionary
9189				$out .= ' /Alternates '.$altoid.' 0 R';
9190			}
9191			if (isset($info['exurl']) AND !empty($info['exurl'])) {
9192				// external stream
9193				$out .= ' /Length 0';
9194				$out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
9195				if (isset($info['f'])) {
9196					$out .= ' /FFilter /'.$info['f'];
9197				}
9198				$out .= ' >>';
9199				$out .= ' stream'."\n".'endstream';
9200			} else {
9201				if (isset($info['f'])) {
9202					$out .= ' /Filter /'.$info['f'];
9203				}
9204				if (isset($info['parms'])) {
9205					$out .= ' '.$info['parms'];
9206				}
9207				if (isset($info['trns']) AND is_array($info['trns'])) {
9208					$trns = '';
9209					$count_info = count($info['trns']);
9210					if ($info['cs'] == 'Indexed') {
9211						$maxval =(pow(2, $info['bpc']) - 1);
9212						for ($i = 0; $i < $count_info; ++$i) {
9213							if (($info['trns'][$i] != 0) AND ($info['trns'][$i] != $maxval)) {
9214								// this is not a binary type mask @TODO: create a SMask
9215								$trns = '';
9216								break;
9217							} elseif (empty($trns) AND ($info['trns'][$i] == 0)) {
9218								// store the first fully transparent value
9219								$trns .= $i.' '.$i.' ';
9220							}
9221						}
9222					} else {
9223						// grayscale or RGB
9224						for ($i = 0; $i < $count_info; ++$i) {
9225							if ($info['trns'][$i] == 0) {
9226								$trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
9227							}
9228						}
9229					}
9230					// Colour Key Masking
9231					if (!empty($trns)) {
9232						$out .= ' /Mask ['.$trns.']';
9233					}
9234				}
9235				$stream = $this->_getrawstream($info['data']);
9236				$out .= ' /Length '.strlen($stream).' >>';
9237				$out .= ' stream'."\n".$stream."\n".'endstream';
9238			}
9239			$out .= "\n".'endobj';
9240			$this->_out($out);
9241			if ($icc) {
9242				// ICC colour profile
9243				$this->_newobj();
9244				$icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
9245				$icc = $this->_getrawstream($icc);
9246				$this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
9247			} elseif ($info['cs'] == 'Indexed') {
9248				// colour palette
9249				$this->_newobj();
9250				$pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
9251				$pal = $this->_getrawstream($pal);
9252				$this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
9253			}
9254		}
9255	}
9256
9257	/**
9258	 * Output Form XObjects Templates.
9259	 * @author Nicola Asuni
9260	 * @since 5.8.017 (2010-08-24)
9261	 * @protected
9262	 * @see startTemplate(), endTemplate(), printTemplate()
9263	 */
9264	protected function _putxobjects() {
9265		foreach ($this->xobjects as $key => $data) {
9266			if (isset($data['outdata'])) {
9267				$stream = str_replace($this->epsmarker, '', trim($data['outdata']));
9268				$out = $this->_getobj($data['n'])."\n";
9269				$out .= '<<';
9270				$out .= ' /Type /XObject';
9271				$out .= ' /Subtype /Form';
9272				$out .= ' /FormType 1';
9273				if ($this->compress) {
9274					$stream = gzcompress($stream);
9275					$out .= ' /Filter /FlateDecode';
9276				}
9277				$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));
9278				$out .= ' /Matrix [1 0 0 1 0 0]';
9279				$out .= ' /Resources <<';
9280				$out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
9281				if (!$this->pdfa_mode) {
9282					// transparency
9283					if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
9284						$out .= ' /ExtGState <<';
9285						foreach ($data['extgstates'] as $k => $extgstate) {
9286							if (isset($this->extgstates[$k]['name'])) {
9287								$out .= ' /'.$this->extgstates[$k]['name'];
9288							} else {
9289								$out .= ' /GS'.$k;
9290							}
9291							$out .= ' '.$this->extgstates[$k]['n'].' 0 R';
9292						}
9293						$out .= ' >>';
9294					}
9295					if (isset($data['gradients']) AND !empty($data['gradients'])) {
9296						$gp = '';
9297						$gs = '';
9298						foreach ($data['gradients'] as $id => $grad) {
9299							// gradient patterns
9300							$gp .= ' /p'.$id.' '.$this->gradients[$id]['pattern'].' 0 R';
9301							// gradient shadings
9302							$gs .= ' /Sh'.$id.' '.$this->gradients[$id]['id'].' 0 R';
9303						}
9304						$out .= ' /Pattern <<'.$gp.' >>';
9305						$out .= ' /Shading <<'.$gs.' >>';
9306					}
9307				}
9308				// spot colors
9309				if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
9310					$out .= ' /ColorSpace <<';
9311					foreach ($data['spot_colors'] as $name => $color) {
9312						$out .= ' /CS'.$color['i'].' '.$this->spot_colors[$name]['n'].' 0 R';
9313					}
9314					$out .= ' >>';
9315				}
9316				// fonts
9317				if (!empty($data['fonts'])) {
9318					$out .= ' /Font <<';
9319					foreach ($data['fonts'] as $fontkey => $fontid) {
9320						$out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
9321					}
9322					$out .= ' >>';
9323				}
9324				// images or nested xobjects
9325				if (!empty($data['images']) OR !empty($data['xobjects'])) {
9326					$out .= ' /XObject <<';
9327					foreach ($data['images'] as $imgid) {
9328						$out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
9329					}
9330					foreach ($data['xobjects'] as $sub_id => $sub_objid) {
9331						$out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
9332					}
9333					$out .= ' >>';
9334				}
9335				$out .= ' >>'; //end resources
9336				if (isset($data['group']) AND ($data['group'] !== false)) {
9337					// set transparency group
9338					$out .= ' /Group << /Type /Group /S /Transparency';
9339					if (is_array($data['group'])) {
9340						if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
9341							$out .= ' /CS /'.$data['group']['CS'];
9342						}
9343						if (isset($data['group']['I'])) {
9344							$out .= ' /I /'.($data['group']['I']===true?'true':'false');
9345						}
9346						if (isset($data['group']['K'])) {
9347							$out .= ' /K /'.($data['group']['K']===true?'true':'false');
9348						}
9349					}
9350					$out .= ' >>';
9351				}
9352				$stream = $this->_getrawstream($stream, $data['n']);
9353				$out .= ' /Length '.strlen($stream);
9354				$out .= ' >>';
9355				$out .= ' stream'."\n".$stream."\n".'endstream';
9356				$out .= "\n".'endobj';
9357				$this->_out($out);
9358			}
9359		}
9360	}
9361
9362	/**
9363	 * Output Spot Colors Resources.
9364	 * @protected
9365	 * @since 4.0.024 (2008-09-12)
9366	 */
9367	protected function _putspotcolors() {
9368		foreach ($this->spot_colors as $name => $color) {
9369			$this->_newobj();
9370			$this->spot_colors[$name]['n'] = $this->n;
9371			$out = '[/Separation /'.str_replace(' ', '#20', $name);
9372			$out .= ' /DeviceCMYK <<';
9373			$out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
9374			$out .= ' '.sprintf('/C1 [%F %F %F %F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
9375			$out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
9376			$out .= "\n".'endobj';
9377			$this->_out($out);
9378		}
9379	}
9380
9381	/**
9382	 * Return XObjects Dictionary.
9383	 * @return string XObjects dictionary
9384	 * @protected
9385	 * @since 5.8.014 (2010-08-23)
9386	 */
9387	protected function _getxobjectdict() {
9388		$out = '';
9389		foreach ($this->xobjects as $id => $objid) {
9390			$out .= ' /'.$id.' '.$objid['n'].' 0 R';
9391		}
9392		return $out;
9393	}
9394
9395	/**
9396	 * Output Resources Dictionary.
9397	 * @protected
9398	 */
9399	protected function _putresourcedict() {
9400		$out = $this->_getobj(2)."\n";
9401		$out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
9402		$out .= ' /Font <<';
9403		foreach ($this->fontkeys as $fontkey) {
9404			$font = $this->getFontBuffer($fontkey);
9405			$out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
9406		}
9407		$out .= ' >>';
9408		$out .= ' /XObject <<';
9409		$out .= $this->_getxobjectdict();
9410		$out .= ' >>';
9411		// layers
9412		if (!empty($this->pdflayers)) {
9413			$out .= ' /Properties <<';
9414			foreach ($this->pdflayers as $layer) {
9415				$out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
9416			}
9417			$out .= ' >>';
9418		}
9419		if (!$this->pdfa_mode) {
9420			// transparency
9421			if (isset($this->extgstates) AND !empty($this->extgstates)) {
9422				$out .= ' /ExtGState <<';
9423				foreach ($this->extgstates as $k => $extgstate) {
9424					if (isset($extgstate['name'])) {
9425						$out .= ' /'.$extgstate['name'];
9426					} else {
9427						$out .= ' /GS'.$k;
9428					}
9429					$out .= ' '.$extgstate['n'].' 0 R';
9430				}
9431				$out .= ' >>';
9432			}
9433			if (isset($this->gradients) AND !empty($this->gradients)) {
9434				$gp = '';
9435				$gs = '';
9436				foreach ($this->gradients as $id => $grad) {
9437					// gradient patterns
9438					$gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
9439					// gradient shadings
9440					$gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
9441				}
9442				$out .= ' /Pattern <<'.$gp.' >>';
9443				$out .= ' /Shading <<'.$gs.' >>';
9444			}
9445		}
9446		// spot colors
9447		if (isset($this->spot_colors) AND !empty($this->spot_colors)) {
9448			$out .= ' /ColorSpace <<';
9449			foreach ($this->spot_colors as $color) {
9450				$out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
9451			}
9452			$out .= ' >>';
9453		}
9454		$out .= ' >>';
9455		$out .= "\n".'endobj';
9456		$this->_out($out);
9457	}
9458
9459	/**
9460	 * Output Resources.
9461	 * @protected
9462	 */
9463	protected function _putresources() {
9464		$this->_putextgstates();
9465		$this->_putocg();
9466		$this->_putfonts();
9467		$this->_putimages();
9468		$this->_putspotcolors();
9469		$this->_putshaders();
9470		$this->_putxobjects();
9471		$this->_putresourcedict();
9472		$this->_putdests();
9473		$this->_putEmbeddedFiles();
9474		$this->_putannotsobjs();
9475		$this->_putjavascript();
9476		$this->_putbookmarks();
9477		$this->_putencryption();
9478	}
9479
9480	/**
9481	 * Adds some Metadata information (Document Information Dictionary)
9482	 * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
9483	 * @return int object id
9484	 * @protected
9485	 */
9486	protected function _putinfo() {
9487		$oid = $this->_newobj();
9488		$out = '<<';
9489		// store current isunicode value
9490		$prev_isunicode = $this->isunicode;
9491		if ($this->docinfounicode) {
9492			$this->isunicode = true;
9493		}
9494		if (!TCPDF_STATIC::empty_string($this->title)) {
9495			// The document's title.
9496			$out .= ' /Title '.$this->_textstring($this->title, $oid);
9497		}
9498		if (!TCPDF_STATIC::empty_string($this->author)) {
9499			// The name of the person who created the document.
9500			$out .= ' /Author '.$this->_textstring($this->author, $oid);
9501		}
9502		if (!TCPDF_STATIC::empty_string($this->subject)) {
9503			// The subject of the document.
9504			$out .= ' /Subject '.$this->_textstring($this->subject, $oid);
9505		}
9506		if (!TCPDF_STATIC::empty_string($this->keywords)) {
9507			// Keywords associated with the document.
9508			$out .= ' /Keywords '.$this->_textstring($this->keywords, $oid);
9509		}
9510		if (!TCPDF_STATIC::empty_string($this->creator)) {
9511			// 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.
9512			$out .= ' /Creator '.$this->_textstring($this->creator, $oid);
9513		}
9514		// restore previous isunicode value
9515		$this->isunicode = $prev_isunicode;
9516		// default producer
9517		$out .= ' /Producer '.$this->_textstring(TCPDF_STATIC::getTCPDFProducer(), $oid);
9518		// The date and time the document was created, in human-readable form
9519		$out .= ' /CreationDate '.$this->_datestring(0, $this->doc_creation_timestamp);
9520		// The date and time the document was most recently modified, in human-readable form
9521		$out .= ' /ModDate '.$this->_datestring(0, $this->doc_modification_timestamp);
9522		// A name object indicating whether the document has been modified to include trapping information
9523		$out .= ' /Trapped /False';
9524		$out .= ' >>';
9525		$out .= "\n".'endobj';
9526		$this->_out($out);
9527		return $oid;
9528	}
9529
9530	/**
9531	 * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
9532	 * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
9533	 * @param $xmp (string) Custom XMP data.
9534	 * @since 5.9.128 (2011-10-06)
9535	 * @public
9536	 */
9537	public function setExtraXMP($xmp) {
9538		$this->custom_xmp = $xmp;
9539	}
9540
9541	/**
9542	 * Set additional XMP data to be added on the default XMP data just before the end of "rdf:RDF" tag.
9543	 * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
9544	 * @param $xmp (string) Custom XMP RDF data.
9545	 * @since 6.3.0 (2019-09-19)
9546	 * @public
9547	 */
9548	public function setExtraXMPRDF($xmp) {
9549		$this->custom_xmp_rdf = $xmp;
9550	}
9551
9552	/**
9553	 * Put XMP data object and return ID.
9554	 * @return (int) The object ID.
9555	 * @since 5.9.121 (2011-09-28)
9556	 * @protected
9557	 */
9558	protected function _putXMP() {
9559		$oid = $this->_newobj();
9560		// store current isunicode value
9561		$prev_isunicode = $this->isunicode;
9562		$this->isunicode = true;
9563		$prev_encrypted = $this->encrypted;
9564		$this->encrypted = false;
9565		// set XMP data
9566		$xmp = '<?xpacket begin="'.TCPDF_FONTS::unichr(0xfeff, $this->isunicode).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
9567		$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";
9568		$xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
9569		$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
9570		$xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
9571		$xmp .= "\t\t\t".'<dc:title>'."\n";
9572		$xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
9573		$xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->title).'</rdf:li>'."\n";
9574		$xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
9575		$xmp .= "\t\t\t".'</dc:title>'."\n";
9576		$xmp .= "\t\t\t".'<dc:creator>'."\n";
9577		$xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
9578		$xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->author).'</rdf:li>'."\n";
9579		$xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
9580		$xmp .= "\t\t\t".'</dc:creator>'."\n";
9581		$xmp .= "\t\t\t".'<dc:description>'."\n";
9582		$xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
9583		$xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->subject).'</rdf:li>'."\n";
9584		$xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
9585		$xmp .= "\t\t\t".'</dc:description>'."\n";
9586		$xmp .= "\t\t\t".'<dc:subject>'."\n";
9587		$xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
9588		$xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->keywords).'</rdf:li>'."\n";
9589		$xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
9590		$xmp .= "\t\t\t".'</dc:subject>'."\n";
9591		$xmp .= "\t\t".'</rdf:Description>'."\n";
9592		// convert doc creation date format
9593		$dcdate = TCPDF_STATIC::getFormattedDate($this->doc_creation_timestamp);
9594		$doccreationdate = substr($dcdate, 0, 4).'-'.substr($dcdate, 4, 2).'-'.substr($dcdate, 6, 2);
9595		$doccreationdate .= 'T'.substr($dcdate, 8, 2).':'.substr($dcdate, 10, 2).':'.substr($dcdate, 12, 2);
9596		$doccreationdate .= substr($dcdate, 14, 3).':'.substr($dcdate, 18, 2);
9597		$doccreationdate = TCPDF_STATIC::_escapeXML($doccreationdate);
9598		// convert doc modification date format
9599		$dmdate = TCPDF_STATIC::getFormattedDate($this->doc_modification_timestamp);
9600		$docmoddate = substr($dmdate, 0, 4).'-'.substr($dmdate, 4, 2).'-'.substr($dmdate, 6, 2);
9601		$docmoddate .= 'T'.substr($dmdate, 8, 2).':'.substr($dmdate, 10, 2).':'.substr($dmdate, 12, 2);
9602		$docmoddate .= substr($dmdate, 14, 3).':'.substr($dmdate, 18, 2);
9603		$docmoddate = TCPDF_STATIC::_escapeXML($docmoddate);
9604		$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
9605		$xmp .= "\t\t\t".'<xmp:CreateDate>'.$doccreationdate.'</xmp:CreateDate>'."\n";
9606		$xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator.'</xmp:CreatorTool>'."\n";
9607		$xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docmoddate.'</xmp:ModifyDate>'."\n";
9608		$xmp .= "\t\t\t".'<xmp:MetadataDate>'.$doccreationdate.'</xmp:MetadataDate>'."\n";
9609		$xmp .= "\t\t".'</rdf:Description>'."\n";
9610		$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
9611		$xmp .= "\t\t\t".'<pdf:Keywords>'.TCPDF_STATIC::_escapeXML($this->keywords).'</pdf:Keywords>'."\n";
9612		$xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC::_escapeXML(TCPDF_STATIC::getTCPDFProducer()).'</pdf:Producer>'."\n";
9613		$xmp .= "\t\t".'</rdf:Description>'."\n";
9614		$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
9615		$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);
9616		$xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
9617		$xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
9618		$xmp .= "\t\t".'</rdf:Description>'."\n";
9619		if ($this->pdfa_mode) {
9620			$xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
9621			$xmp .= "\t\t\t".'<pdfaid:part>'.$this->pdfa_version.'</pdfaid:part>'."\n";
9622			$xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
9623			$xmp .= "\t\t".'</rdf:Description>'."\n";
9624		}
9625		// XMP extension schemas
9626		$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";
9627		$xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
9628		$xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
9629		$xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9630		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
9631		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
9632		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
9633		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
9634		$xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
9635		$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9636		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9637		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Adobe PDF Schema</pdfaProperty:description>'."\n";
9638		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
9639		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
9640		$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9641		$xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
9642		$xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
9643		$xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
9644		$xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9645		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
9646		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
9647		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
9648		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
9649		$xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
9650		$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9651		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9652		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
9653		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
9654		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
9655		$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9656		$xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
9657		$xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
9658		$xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
9659		$xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9660		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
9661		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
9662		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
9663		$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
9664		$xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
9665		$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9666		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9667		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
9668		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
9669		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
9670		$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9671		$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9672		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9673		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
9674		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
9675		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
9676		$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9677		$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9678		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9679		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
9680		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
9681		$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
9682		$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9683		$xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
9684		$xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
9685		$xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
9686		$xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
9687		$xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
9688		$xmp .= "\t\t".'</rdf:Description>'."\n";
9689		$xmp .= $this->custom_xmp_rdf;
9690		$xmp .= "\t".'</rdf:RDF>'."\n";
9691		$xmp .= $this->custom_xmp;
9692		$xmp .= '</x:xmpmeta>'."\n";
9693		$xmp .= '<?xpacket end="w"?>';
9694		$out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
9695		// restore previous isunicode value
9696		$this->isunicode = $prev_isunicode;
9697		$this->encrypted = $prev_encrypted;
9698		$this->_out($out);
9699		return $oid;
9700	}
9701
9702	/**
9703	 * Output Catalog.
9704	 * @return int object id
9705	 * @protected
9706	 */
9707	protected function _putcatalog() {
9708		// put XMP
9709		$xmpobj = $this->_putXMP();
9710		// if required, add standard sRGB ICC colour profile
9711		if ($this->pdfa_mode OR $this->force_srgb) {
9712			$iccobj = $this->_newobj();
9713			$icc = file_get_contents(dirname(__FILE__).'/include/sRGB.icc');
9714			$filter = '';
9715			if ($this->compress) {
9716				$filter = ' /Filter /FlateDecode';
9717				$icc = gzcompress($icc);
9718			}
9719			$icc = $this->_getrawstream($icc);
9720			$this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
9721		}
9722		// start catalog
9723		$oid = $this->_newobj();
9724		$out = '<< /Type /Catalog';
9725		$out .= ' /Version /'.$this->PDFVersion;
9726		//$out .= ' /Extensions <<>>';
9727		$out .= ' /Pages 1 0 R';
9728		//$out .= ' /PageLabels ' //...;
9729		$out .= ' /Names <<';
9730		if ((!$this->pdfa_mode) AND !empty($this->n_js)) {
9731			$out .= ' /JavaScript '.$this->n_js;
9732		}
9733		if (!empty($this->efnames)) {
9734			$out .= ' /EmbeddedFiles <</Names [';
9735			foreach ($this->efnames AS $fn => $fref) {
9736				$out .= ' '.$this->_datastring($fn).' '.$fref;
9737			}
9738			$out .= ' ]>>';
9739		}
9740		$out .= ' >>';
9741		if (!empty($this->dests)) {
9742			$out .= ' /Dests '.($this->n_dests).' 0 R';
9743		}
9744		$out .= $this->_putviewerpreferences();
9745		if (isset($this->LayoutMode) AND (!TCPDF_STATIC::empty_string($this->LayoutMode))) {
9746			$out .= ' /PageLayout /'.$this->LayoutMode;
9747		}
9748		if (isset($this->PageMode) AND (!TCPDF_STATIC::empty_string($this->PageMode))) {
9749			$out .= ' /PageMode /'.$this->PageMode;
9750		}
9751		if (count($this->outlines) > 0) {
9752			$out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
9753			$out .= ' /PageMode /UseOutlines';
9754		}
9755		//$out .= ' /Threads []';
9756		if ($this->ZoomMode == 'fullpage') {
9757			$out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
9758		} elseif ($this->ZoomMode == 'fullwidth') {
9759			$out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
9760		} elseif ($this->ZoomMode == 'real') {
9761			$out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
9762		} elseif (!is_string($this->ZoomMode)) {
9763			$out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %F]', ($this->ZoomMode / 100));
9764		}
9765		//$out .= ' /AA <<>>';
9766		//$out .= ' /URI <<>>';
9767		$out .= ' /Metadata '.$xmpobj.' 0 R';
9768		//$out .= ' /StructTreeRoot <<>>';
9769		//$out .= ' /MarkInfo <<>>';
9770		if (isset($this->l['a_meta_language'])) {
9771			$out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
9772		}
9773		//$out .= ' /SpiderInfo <<>>';
9774		// set OutputIntent to sRGB IEC61966-2.1 if required
9775		if ($this->pdfa_mode OR $this->force_srgb) {
9776			$out .= ' /OutputIntents [<<';
9777			$out .= ' /Type /OutputIntent';
9778			$out .= ' /S /GTS_PDFA1';
9779			$out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
9780			$out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
9781			$out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
9782			$out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
9783			$out .= ' /DestOutputProfile '.$iccobj.' 0 R';
9784			$out .= ' >>]';
9785		}
9786		//$out .= ' /PieceInfo <<>>';
9787		if (!empty($this->pdflayers)) {
9788			$lyrobjs = '';
9789			$lyrobjs_off = '';
9790			$lyrobjs_lock = '';
9791			foreach ($this->pdflayers as $layer) {
9792				$layer_obj_ref = ' '.$layer['objid'].' 0 R';
9793				$lyrobjs .= $layer_obj_ref;
9794				if ($layer['view'] === false) {
9795					$lyrobjs_off .= $layer_obj_ref;
9796				}
9797				if ($layer['lock']) {
9798					$lyrobjs_lock .= $layer_obj_ref;
9799				}
9800			}
9801			$out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
9802			$out .= ' /D <<';
9803			$out .= ' /Name '.$this->_textstring('Layers', $oid);
9804			$out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
9805			$out .= ' /BaseState /ON';
9806			$out .= ' /OFF ['.$lyrobjs_off.']';
9807			$out .= ' /Locked ['.$lyrobjs_lock.']';
9808			$out .= ' /Intent /View';
9809			$out .= ' /AS [';
9810			$out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
9811			$out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
9812			$out .= ' ]';
9813			$out .= ' /Order ['.$lyrobjs.']';
9814			$out .= ' /ListMode /AllPages';
9815			//$out .= ' /RBGroups ['..']';
9816			//$out .= ' /Locked ['..']';
9817			$out .= ' >>';
9818			$out .= ' >>';
9819		}
9820		// AcroForm
9821		if (!empty($this->form_obj_id)
9822			OR ($this->sign AND isset($this->signature_data['cert_type']))
9823			OR !empty($this->empty_signature_appearance)) {
9824			$out .= ' /AcroForm <<';
9825			$objrefs = '';
9826			if ($this->sign AND isset($this->signature_data['cert_type'])) {
9827				// set reference for signature object
9828				$objrefs .= $this->sig_obj_id.' 0 R';
9829			}
9830			if (!empty($this->empty_signature_appearance)) {
9831				foreach ($this->empty_signature_appearance as $esa) {
9832					// set reference for empty signature objects
9833					$objrefs .= ' '.$esa['objid'].' 0 R';
9834				}
9835			}
9836			if (!empty($this->form_obj_id)) {
9837				foreach($this->form_obj_id as $objid) {
9838					$objrefs .= ' '.$objid.' 0 R';
9839				}
9840			}
9841			$out .= ' /Fields ['.$objrefs.']';
9842			// It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
9843			if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
9844				$out .= ' /NeedAppearances false';
9845			}
9846			if ($this->sign AND isset($this->signature_data['cert_type'])) {
9847				if ($this->signature_data['cert_type'] > 0) {
9848					$out .= ' /SigFlags 3';
9849				} else {
9850					$out .= ' /SigFlags 1';
9851				}
9852			}
9853			//$out .= ' /CO ';
9854			if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
9855				$out .= ' /DR <<';
9856				$out .= ' /Font <<';
9857				foreach ($this->annotation_fonts as $fontkey => $fontid) {
9858					$out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
9859				}
9860				$out .= ' >> >>';
9861			}
9862			$font = $this->getFontBuffer('helvetica');
9863			$out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
9864			$out .= ' /Q '.(($this->rtl)?'2':'0');
9865			//$out .= ' /XFA ';
9866			$out .= ' >>';
9867			// signatures
9868			if ($this->sign AND isset($this->signature_data['cert_type'])
9869				AND (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A'))) {
9870				if ($this->signature_data['cert_type'] > 0) {
9871					$out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
9872				} else {
9873					$out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
9874				}
9875			}
9876		}
9877		//$out .= ' /Legal <<>>';
9878		//$out .= ' /Requirements []';
9879		//$out .= ' /Collection <<>>';
9880		//$out .= ' /NeedsRendering true';
9881		$out .= ' >>';
9882		$out .= "\n".'endobj';
9883		$this->_out($out);
9884		return $oid;
9885	}
9886
9887	/**
9888	 * Output viewer preferences.
9889	 * @return string for viewer preferences
9890	 * @author Nicola asuni
9891	 * @since 3.1.000 (2008-06-09)
9892	 * @protected
9893	 */
9894	protected function _putviewerpreferences() {
9895		$vp = $this->viewer_preferences;
9896		$out = ' /ViewerPreferences <<';
9897		if ($this->rtl) {
9898			$out .= ' /Direction /R2L';
9899		} else {
9900			$out .= ' /Direction /L2R';
9901		}
9902		if (isset($vp['HideToolbar']) AND ($vp['HideToolbar'])) {
9903			$out .= ' /HideToolbar true';
9904		}
9905		if (isset($vp['HideMenubar']) AND ($vp['HideMenubar'])) {
9906			$out .= ' /HideMenubar true';
9907		}
9908		if (isset($vp['HideWindowUI']) AND ($vp['HideWindowUI'])) {
9909			$out .= ' /HideWindowUI true';
9910		}
9911		if (isset($vp['FitWindow']) AND ($vp['FitWindow'])) {
9912			$out .= ' /FitWindow true';
9913		}
9914		if (isset($vp['CenterWindow']) AND ($vp['CenterWindow'])) {
9915			$out .= ' /CenterWindow true';
9916		}
9917		if (isset($vp['DisplayDocTitle']) AND ($vp['DisplayDocTitle'])) {
9918			$out .= ' /DisplayDocTitle true';
9919		}
9920		if (isset($vp['NonFullScreenPageMode'])) {
9921			$out .= ' /NonFullScreenPageMode /'.$vp['NonFullScreenPageMode'];
9922		}
9923		if (isset($vp['ViewArea'])) {
9924			$out .= ' /ViewArea /'.$vp['ViewArea'];
9925		}
9926		if (isset($vp['ViewClip'])) {
9927			$out .= ' /ViewClip /'.$vp['ViewClip'];
9928		}
9929		if (isset($vp['PrintArea'])) {
9930			$out .= ' /PrintArea /'.$vp['PrintArea'];
9931		}
9932		if (isset($vp['PrintClip'])) {
9933			$out .= ' /PrintClip /'.$vp['PrintClip'];
9934		}
9935		if (isset($vp['PrintScaling'])) {
9936			$out .= ' /PrintScaling /'.$vp['PrintScaling'];
9937		}
9938		if (isset($vp['Duplex']) AND (!TCPDF_STATIC::empty_string($vp['Duplex']))) {
9939			$out .= ' /Duplex /'.$vp['Duplex'];
9940		}
9941		if (isset($vp['PickTrayByPDFSize'])) {
9942			if ($vp['PickTrayByPDFSize']) {
9943				$out .= ' /PickTrayByPDFSize true';
9944			} else {
9945				$out .= ' /PickTrayByPDFSize false';
9946			}
9947		}
9948		if (isset($vp['PrintPageRange'])) {
9949			$PrintPageRangeNum = '';
9950			foreach ($vp['PrintPageRange'] as $k => $v) {
9951				$PrintPageRangeNum .= ' '.($v - 1).'';
9952			}
9953			$out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
9954		}
9955		if (isset($vp['NumCopies'])) {
9956			$out .= ' /NumCopies '.intval($vp['NumCopies']);
9957		}
9958		$out .= ' >>';
9959		return $out;
9960	}
9961
9962	/**
9963	 * Output PDF File Header (7.5.2).
9964	 * @protected
9965	 */
9966	protected function _putheader() {
9967		$this->_out('%PDF-'.$this->PDFVersion);
9968		$this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
9969	}
9970
9971	/**
9972	 * Output end of document (EOF).
9973	 * @protected
9974	 */
9975	protected function _enddoc() {
9976		if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
9977			// save subset chars of the previous font
9978			$this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
9979		}
9980		$this->state = 1;
9981		$this->_putheader();
9982		$this->_putpages();
9983		$this->_putresources();
9984		// empty signature fields
9985		if (!empty($this->empty_signature_appearance)) {
9986			foreach ($this->empty_signature_appearance as $key => $esa) {
9987				// widget annotation for empty signature
9988				$out = $this->_getobj($esa['objid'])."\n";
9989				$out .= '<< /Type /Annot';
9990				$out .= ' /Subtype /Widget';
9991				$out .= ' /Rect ['.$esa['rect'].']';
9992				$out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
9993				$out .= ' /F 4';
9994				$out .= ' /FT /Sig';
9995				$signame = $esa['name'].sprintf(' [%03d]', ($key + 1));
9996				$out .= ' /T '.$this->_textstring($signame, $esa['objid']);
9997				$out .= ' /Ff 0';
9998				$out .= ' >>';
9999				$out .= "\n".'endobj';
10000				$this->_out($out);
10001			}
10002		}
10003		// Signature
10004		if ($this->sign AND isset($this->signature_data['cert_type'])) {
10005			// widget annotation for signature
10006			$out = $this->_getobj($this->sig_obj_id)."\n";
10007			$out .= '<< /Type /Annot';
10008			$out .= ' /Subtype /Widget';
10009			$out .= ' /Rect ['.$this->signature_appearance['rect'].']';
10010			$out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
10011			$out .= ' /F 4';
10012			$out .= ' /FT /Sig';
10013			$out .= ' /T '.$this->_textstring($this->signature_appearance['name'], $this->sig_obj_id);
10014			$out .= ' /Ff 0';
10015			$out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
10016			$out .= ' >>';
10017			$out .= "\n".'endobj';
10018			$this->_out($out);
10019			// signature
10020			$this->_putsignature();
10021		}
10022		// Info
10023		$objid_info = $this->_putinfo();
10024		// Catalog
10025		$objid_catalog = $this->_putcatalog();
10026		// Cross-ref
10027		$o = $this->bufferlen;
10028		// XREF section
10029		$this->_out('xref');
10030		$this->_out('0 '.($this->n + 1));
10031		$this->_out('0000000000 65535 f ');
10032		$freegen = ($this->n + 2);
10033		for ($i=1; $i <= $this->n; ++$i) {
10034			if (!isset($this->offsets[$i]) AND ($i > 1)) {
10035				$this->_out(sprintf('0000000000 %05d f ', $freegen));
10036				++$freegen;
10037			} else {
10038				$this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
10039			}
10040		}
10041		// TRAILER
10042		$out = 'trailer'."\n";
10043		$out .= '<<';
10044		$out .= ' /Size '.($this->n + 1);
10045		$out .= ' /Root '.$objid_catalog.' 0 R';
10046		$out .= ' /Info '.$objid_info.' 0 R';
10047		if ($this->encrypted) {
10048			$out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
10049		}
10050		$out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
10051		$out .= ' >>';
10052		$this->_out($out);
10053		$this->_out('startxref');
10054		$this->_out($o);
10055		$this->_out('%%EOF');
10056		$this->state = 3; // end-of-doc
10057	}
10058
10059	/**
10060	 * Initialize a new page.
10061	 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
10062	 * @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().
10063	 * @protected
10064	 * @see getPageSizeFromFormat(), setPageFormat()
10065	 */
10066	protected function _beginpage($orientation='', $format='') {
10067		++$this->page;
10068		$this->pageobjects[$this->page] = array();
10069		$this->setPageBuffer($this->page, '');
10070		// initialize array for graphics tranformation positions inside a page buffer
10071		$this->transfmrk[$this->page] = array();
10072		$this->state = 2;
10073		if (TCPDF_STATIC::empty_string($orientation)) {
10074			if (isset($this->CurOrientation)) {
10075				$orientation = $this->CurOrientation;
10076			} elseif ($this->fwPt > $this->fhPt) {
10077				// landscape
10078				$orientation = 'L';
10079			} else {
10080				// portrait
10081				$orientation = 'P';
10082			}
10083		}
10084		if (TCPDF_STATIC::empty_string($format)) {
10085			$this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
10086			$this->setPageOrientation($orientation);
10087		} else {
10088			$this->setPageFormat($format, $orientation);
10089		}
10090		if ($this->rtl) {
10091			$this->x = $this->w - $this->rMargin;
10092		} else {
10093			$this->x = $this->lMargin;
10094		}
10095		$this->y = $this->tMargin;
10096		if (isset($this->newpagegroup[$this->page])) {
10097			// start a new group
10098			$this->currpagegroup = $this->newpagegroup[$this->page];
10099			$this->pagegroups[$this->currpagegroup] = 1;
10100		} elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
10101			++$this->pagegroups[$this->currpagegroup];
10102		}
10103	}
10104
10105	/**
10106	 * Mark end of page.
10107	 * @protected
10108	 */
10109	protected function _endpage() {
10110		$this->setVisibility('all');
10111		$this->state = 1;
10112	}
10113
10114	/**
10115	 * Begin a new object and return the object number.
10116	 * @return int object number
10117	 * @protected
10118	 */
10119	protected function _newobj() {
10120		$this->_out($this->_getobj());
10121		return $this->n;
10122	}
10123
10124	/**
10125	 * Return the starting object string for the selected object ID.
10126	 * @param $objid (int) Object ID (leave empty to get a new ID).
10127	 * @return string the starting object string
10128	 * @protected
10129	 * @since 5.8.009 (2010-08-20)
10130	 */
10131	protected function _getobj($objid='') {
10132		if ($objid === '') {
10133			++$this->n;
10134			$objid = $this->n;
10135		}
10136		$this->offsets[$objid] = $this->bufferlen;
10137		$this->pageobjects[$this->page][] = $objid;
10138		return $objid.' 0 obj';
10139	}
10140
10141	/**
10142	 * Underline text.
10143	 * @param $x (int) X coordinate
10144	 * @param $y (int) Y coordinate
10145	 * @param $txt (string) text to underline
10146	 * @protected
10147	 */
10148	protected function _dounderline($x, $y, $txt) {
10149		$w = $this->GetStringWidth($txt);
10150		return $this->_dounderlinew($x, $y, $w);
10151	}
10152
10153	/**
10154	 * Underline for rectangular text area.
10155	 * @param $x (int) X coordinate
10156	 * @param $y (int) Y coordinate
10157	 * @param $w (int) width to underline
10158	 * @protected
10159	 * @since 4.8.008 (2009-09-29)
10160	 */
10161	protected function _dounderlinew($x, $y, $w) {
10162		$linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
10163		return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
10164	}
10165
10166	/**
10167	 * Line through text.
10168	 * @param $x (int) X coordinate
10169	 * @param $y (int) Y coordinate
10170	 * @param $txt (string) text to linethrough
10171	 * @protected
10172	 */
10173	protected function _dolinethrough($x, $y, $txt) {
10174		$w = $this->GetStringWidth($txt);
10175		return $this->_dolinethroughw($x, $y, $w);
10176	}
10177
10178	/**
10179	 * Line through for rectangular text area.
10180	 * @param $x (int) X coordinate
10181	 * @param $y (int) Y coordinate
10182	 * @param $w (int) line length (width)
10183	 * @protected
10184	 * @since 4.9.008 (2009-09-29)
10185	 */
10186	protected function _dolinethroughw($x, $y, $w) {
10187		$linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
10188		return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
10189	}
10190
10191	/**
10192	 * Overline text.
10193	 * @param $x (int) X coordinate
10194	 * @param $y (int) Y coordinate
10195	 * @param $txt (string) text to overline
10196	 * @protected
10197	 * @since 4.9.015 (2010-04-19)
10198	 */
10199	protected function _dooverline($x, $y, $txt) {
10200		$w = $this->GetStringWidth($txt);
10201		return $this->_dooverlinew($x, $y, $w);
10202	}
10203
10204	/**
10205	 * Overline for rectangular text area.
10206	 * @param $x (int) X coordinate
10207	 * @param $y (int) Y coordinate
10208	 * @param $w (int) width to overline
10209	 * @protected
10210	 * @since 4.9.015 (2010-04-19)
10211	 */
10212	protected function _dooverlinew($x, $y, $w) {
10213		$linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
10214		return sprintf('%F %F %F %F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
10215
10216	}
10217
10218	/**
10219	 * Format a data string for meta information
10220	 * @param $s (string) data string to escape.
10221	 * @param $n (int) object ID
10222	 * @return string escaped string.
10223	 * @protected
10224	 */
10225	protected function _datastring($s, $n=0) {
10226		if ($n == 0) {
10227			$n = $this->n;
10228		}
10229		$s = $this->_encrypt_data($n, $s);
10230		return '('. TCPDF_STATIC::_escape($s).')';
10231	}
10232
10233	/**
10234	 * Set the document creation timestamp
10235	 * @param $time (mixed) Document creation timestamp in seconds or date-time string.
10236	 * @public
10237	 * @since 5.9.152 (2012-03-23)
10238	 */
10239	public function setDocCreationTimestamp($time) {
10240		if (is_string($time)) {
10241			$time = TCPDF_STATIC::getTimestamp($time);
10242		}
10243		$this->doc_creation_timestamp = intval($time);
10244	}
10245
10246	/**
10247	 * Set the document modification timestamp
10248	 * @param $time (mixed) Document modification timestamp in seconds or date-time string.
10249	 * @public
10250	 * @since 5.9.152 (2012-03-23)
10251	 */
10252	public function setDocModificationTimestamp($time) {
10253		if (is_string($time)) {
10254			$time = TCPDF_STATIC::getTimestamp($time);
10255		}
10256		$this->doc_modification_timestamp = intval($time);
10257	}
10258
10259	/**
10260	 * Returns document creation timestamp in seconds.
10261	 * @return (int) Creation timestamp in seconds.
10262	 * @public
10263	 * @since 5.9.152 (2012-03-23)
10264	 */
10265	public function getDocCreationTimestamp() {
10266		return $this->doc_creation_timestamp;
10267	}
10268
10269	/**
10270	 * Returns document modification timestamp in seconds.
10271	 * @return (int) Modfication timestamp in seconds.
10272	 * @public
10273	 * @since 5.9.152 (2012-03-23)
10274	 */
10275	public function getDocModificationTimestamp() {
10276		return $this->doc_modification_timestamp;
10277	}
10278
10279	/**
10280	 * Returns a formatted date for meta information
10281	 * @param $n (int) Object ID.
10282	 * @param $timestamp (int) Timestamp to convert.
10283	 * @return string escaped date string.
10284	 * @protected
10285	 * @since 4.6.028 (2009-08-25)
10286	 */
10287	protected function _datestring($n=0, $timestamp=0) {
10288		if ((empty($timestamp)) OR ($timestamp < 0)) {
10289			$timestamp = $this->doc_creation_timestamp;
10290		}
10291		return $this->_datastring('D:'.TCPDF_STATIC::getFormattedDate($timestamp), $n);
10292	}
10293
10294	/**
10295	 * Format a text string for meta information
10296	 * @param $s (string) string to escape.
10297	 * @param $n (int) object ID
10298	 * @return string escaped string.
10299	 * @protected
10300	 */
10301	protected function _textstring($s, $n=0) {
10302		if ($this->isunicode) {
10303			//Convert string to UTF-16BE
10304			$s = TCPDF_FONTS::UTF8ToUTF16BE($s, true, $this->isunicode, $this->CurrentFont);
10305		}
10306		return $this->_datastring($s, $n);
10307	}
10308
10309	/**
10310	 * get raw output stream.
10311	 * @param $s (string) string to output.
10312	 * @param $n (int) object reference for encryption mode
10313	 * @protected
10314	 * @author Nicola Asuni
10315	 * @since 5.5.000 (2010-06-22)
10316	 */
10317	protected function _getrawstream($s, $n=0) {
10318		if ($n <= 0) {
10319			// default to current object
10320			$n = $this->n;
10321		}
10322		return $this->_encrypt_data($n, $s);
10323	}
10324
10325	/**
10326	 * Output a string to the document.
10327	 * @param $s (string) string to output.
10328	 * @protected
10329	 */
10330	protected function _out($s) {
10331		if ($this->state == 2) {
10332			if ($this->inxobj) {
10333				// we are inside an XObject template
10334				$this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
10335			} elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
10336				// puts data before page footer
10337				$pagebuff = $this->getPageBuffer($this->page);
10338				$page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
10339				$footer = substr($pagebuff, -$this->footerlen[$this->page]);
10340				$this->setPageBuffer($this->page, $page.$s."\n".$footer);
10341				// update footer position
10342				$this->footerpos[$this->page] += strlen($s."\n");
10343			} else {
10344				// set page data
10345				$this->setPageBuffer($this->page, $s."\n", true);
10346			}
10347		} elseif ($this->state > 0) {
10348			// set general data
10349			$this->setBuffer($s."\n");
10350		}
10351	}
10352
10353	/**
10354	 * Set header font.
10355	 * @param $font (array) Array describing the basic font parameters: (family, style, size).
10356	 * @public
10357	 * @since 1.1
10358	 */
10359	public function setHeaderFont($font) {
10360		$this->header_font = $font;
10361	}
10362
10363	/**
10364	 * Get header font.
10365	 * @return array() Array describing the basic font parameters: (family, style, size).
10366	 * @public
10367	 * @since 4.0.012 (2008-07-24)
10368	 */
10369	public function getHeaderFont() {
10370		return $this->header_font;
10371	}
10372
10373	/**
10374	 * Set footer font.
10375	 * @param $font (array) Array describing the basic font parameters: (family, style, size).
10376	 * @public
10377	 * @since 1.1
10378	 */
10379	public function setFooterFont($font) {
10380		$this->footer_font = $font;
10381	}
10382
10383	/**
10384	 * Get Footer font.
10385	 * @return array() Array describing the basic font parameters: (family, style, size).
10386	 * @public
10387	 * @since 4.0.012 (2008-07-24)
10388	 */
10389	public function getFooterFont() {
10390		return $this->footer_font;
10391	}
10392
10393	/**
10394	 * Set language array.
10395	 * @param $language (array)
10396	 * @public
10397	 * @since 1.1
10398	 */
10399	public function setLanguageArray($language) {
10400		$this->l = $language;
10401		if (isset($this->l['a_meta_dir'])) {
10402			$this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
10403		} else {
10404			$this->rtl = false;
10405		}
10406	}
10407
10408	/**
10409	 * Returns the PDF data.
10410	 * @public
10411	 */
10412	public function getPDFData() {
10413		if ($this->state < 3) {
10414			$this->Close();
10415		}
10416		return $this->buffer;
10417	}
10418
10419	/**
10420	 * Output anchor link.
10421	 * @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;)
10422	 * @param $name (string) link name
10423	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
10424	 * @param $firstline (boolean) if true prints only the first line and return the remaining string.
10425	 * @param $color (array) array of RGB text color
10426	 * @param $style (string) font style (U, D, B, I)
10427	 * @param $firstblock (boolean) if true the string is the starting of a line.
10428	 * @return the number of cells used or the remaining text if $firstline = true;
10429	 * @public
10430	 */
10431	public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
10432		if (isset($url[1]) AND ($url[0] == '#') AND is_numeric($url[1])) {
10433			// convert url to internal link
10434			$lnkdata = explode(',', $url);
10435			if (isset($lnkdata[0]) ) {
10436				$page = substr($lnkdata[0], 1);
10437				if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
10438					$lnky = floatval($lnkdata[1]);
10439				} else {
10440					$lnky = 0;
10441				}
10442				$url = $this->AddLink();
10443				$this->SetLink($url, $lnky, $page);
10444			}
10445		}
10446		// store current settings
10447		$prevcolor = $this->fgcolor;
10448		$prevstyle = $this->FontStyle;
10449		if (empty($color)) {
10450			$this->SetTextColorArray($this->htmlLinkColorArray);
10451		} else {
10452			$this->SetTextColorArray($color);
10453		}
10454		if ($style == -1) {
10455			$this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
10456		} else {
10457			$this->SetFont('', $this->FontStyle.$style);
10458		}
10459		$ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
10460		// restore settings
10461		$this->SetFont('', $prevstyle);
10462		$this->SetTextColorArray($prevcolor);
10463		return $ret;
10464	}
10465
10466	/**
10467	 * Converts pixels to User's Units.
10468	 * @param $px (int) pixels
10469	 * @return float value in user's unit
10470	 * @public
10471	 * @see setImageScale(), getImageScale()
10472	 */
10473	public function pixelsToUnits($px) {
10474		return ($px / ($this->imgscale * $this->k));
10475	}
10476
10477	/**
10478	 * Reverse function for htmlentities.
10479	 * Convert entities in UTF-8.
10480	 * @param $text_to_convert (string) Text to convert.
10481	 * @return string converted text string
10482	 * @public
10483	 */
10484	public function unhtmlentities($text_to_convert) {
10485		return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
10486	}
10487
10488	// ENCRYPTION METHODS ----------------------------------
10489
10490	/**
10491	 * Compute encryption key depending on object number where the encrypted data is stored.
10492	 * This is used for all strings and streams without crypt filter specifier.
10493	 * @param $n (int) object number
10494	 * @return int object key
10495	 * @protected
10496	 * @author Nicola Asuni
10497	 * @since 2.0.000 (2008-01-02)
10498	 */
10499	protected function _objectkey($n) {
10500		$objkey = $this->encryptdata['key'].pack('VXxx', $n);
10501		if ($this->encryptdata['mode'] == 2) { // AES-128
10502			// AES padding
10503			$objkey .= "\x73\x41\x6C\x54"; // sAlT
10504		}
10505		$objkey = substr(TCPDF_STATIC::_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
10506		$objkey = substr($objkey, 0, 16);
10507		return $objkey;
10508	}
10509
10510	/**
10511	 * Encrypt the input string.
10512	 * @param $n (int) object number
10513	 * @param $s (string) data string to encrypt
10514	 * @return encrypted string
10515	 * @protected
10516	 * @author Nicola Asuni
10517	 * @since 5.0.005 (2010-05-11)
10518	 */
10519	protected function _encrypt_data($n, $s) {
10520		if (!$this->encrypted) {
10521			return $s;
10522		}
10523		switch ($this->encryptdata['mode']) {
10524			case 0:   // RC4-40
10525			case 1: { // RC4-128
10526				$s = TCPDF_STATIC::_RC4($this->_objectkey($n), $s, $this->last_enc_key, $this->last_enc_key_c);
10527				break;
10528			}
10529			case 2: { // AES-128
10530				$s = TCPDF_STATIC::_AES($this->_objectkey($n), $s);
10531				break;
10532			}
10533			case 3: { // AES-256
10534				$s = TCPDF_STATIC::_AES($this->encryptdata['key'], $s);
10535				break;
10536			}
10537		}
10538		return $s;
10539	}
10540
10541	/**
10542	 * Put encryption on PDF document.
10543	 * @protected
10544	 * @author Nicola Asuni
10545	 * @since 2.0.000 (2008-01-02)
10546	 */
10547	protected function _putencryption() {
10548		if (!$this->encrypted) {
10549			return;
10550		}
10551		$this->encryptdata['objid'] = $this->_newobj();
10552		$out = '<<';
10553		if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
10554			$this->encryptdata['Filter'] = 'Standard';
10555		}
10556		$out .= ' /Filter /'.$this->encryptdata['Filter'];
10557		if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
10558			$out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
10559		}
10560		if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
10561			$this->encryptdata['V'] = 1;
10562		}
10563		// V is a code specifying the algorithm to be used in encrypting and decrypting the document
10564		$out .= ' /V '.$this->encryptdata['V'];
10565		if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
10566			// The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
10567			$out .= ' /Length '.$this->encryptdata['Length'];
10568		} else {
10569			$out .= ' /Length 40';
10570		}
10571		if ($this->encryptdata['V'] >= 4) {
10572			if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
10573				$this->encryptdata['StmF'] = 'Identity';
10574			}
10575			if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
10576				// The name of the crypt filter that shall be used when decrypting all strings in the document.
10577				$this->encryptdata['StrF'] = 'Identity';
10578			}
10579			// A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
10580			if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
10581				$out .= ' /CF <<';
10582				$out .= ' /'.$this->encryptdata['StmF'].' <<';
10583				$out .= ' /Type /CryptFilter';
10584				if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
10585					// The method used
10586					$out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
10587					if ($this->encryptdata['pubkey']) {
10588						$out .= ' /Recipients [';
10589						foreach ($this->encryptdata['Recipients'] as $rec) {
10590							$out .= ' <'.$rec.'>';
10591						}
10592						$out .= ' ]';
10593						if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
10594							$out .= ' /EncryptMetadata false';
10595						} else {
10596							$out .= ' /EncryptMetadata true';
10597						}
10598					}
10599				} else {
10600					$out .= ' /CFM /None';
10601				}
10602				if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
10603					// The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
10604					$out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
10605				} else {
10606					$out .= ' /AuthEvent /DocOpen';
10607				}
10608				if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
10609					// The bit length of the encryption key.
10610					$out .= ' /Length '.$this->encryptdata['CF']['Length'];
10611				}
10612				$out .= ' >> >>';
10613			}
10614			// The name of the crypt filter that shall be used by default when decrypting streams.
10615			$out .= ' /StmF /'.$this->encryptdata['StmF'];
10616			// The name of the crypt filter that shall be used when decrypting all strings in the document.
10617			$out .= ' /StrF /'.$this->encryptdata['StrF'];
10618			if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
10619				// The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
10620				$out .= ' /EFF /'.$this->encryptdata[''];
10621			}
10622		}
10623		// Additional encryption dictionary entries for the standard security handler
10624		if ($this->encryptdata['pubkey']) {
10625			if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
10626				$out .= ' /Recipients [';
10627				foreach ($this->encryptdata['Recipients'] as $rec) {
10628					$out .= ' <'.$rec.'>';
10629				}
10630				$out .= ' ]';
10631			}
10632		} else {
10633			$out .= ' /R';
10634			if ($this->encryptdata['V'] == 5) { // AES-256
10635				$out .= ' 5';
10636				$out .= ' /OE ('.TCPDF_STATIC::_escape($this->encryptdata['OE']).')';
10637				$out .= ' /UE ('.TCPDF_STATIC::_escape($this->encryptdata['UE']).')';
10638				$out .= ' /Perms ('.TCPDF_STATIC::_escape($this->encryptdata['perms']).')';
10639			} elseif ($this->encryptdata['V'] == 4) { // AES-128
10640				$out .= ' 4';
10641			} elseif ($this->encryptdata['V'] < 2) { // RC-40
10642				$out .= ' 2';
10643			} else { // RC-128
10644				$out .= ' 3';
10645			}
10646			$out .= ' /O ('.TCPDF_STATIC::_escape($this->encryptdata['O']).')';
10647			$out .= ' /U ('.TCPDF_STATIC::_escape($this->encryptdata['U']).')';
10648			$out .= ' /P '.$this->encryptdata['P'];
10649			if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
10650				$out .= ' /EncryptMetadata false';
10651			} else {
10652				$out .= ' /EncryptMetadata true';
10653			}
10654		}
10655		$out .= ' >>';
10656		$out .= "\n".'endobj';
10657		$this->_out($out);
10658	}
10659
10660	/**
10661	 * Compute U value (used for encryption)
10662	 * @return string U value
10663	 * @protected
10664	 * @since 2.0.000 (2008-01-02)
10665	 * @author Nicola Asuni
10666	 */
10667	protected function _Uvalue() {
10668		if ($this->encryptdata['mode'] == 0) { // RC4-40
10669			return TCPDF_STATIC::_RC4($this->encryptdata['key'], TCPDF_STATIC::$enc_padding, $this->last_enc_key, $this->last_enc_key_c);
10670		} elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
10671			$tmp = TCPDF_STATIC::_md5_16(TCPDF_STATIC::$enc_padding.$this->encryptdata['fileid']);
10672			$enc = TCPDF_STATIC::_RC4($this->encryptdata['key'], $tmp, $this->last_enc_key, $this->last_enc_key_c);
10673			$len = strlen($tmp);
10674			for ($i = 1; $i <= 19; ++$i) {
10675				$ek = '';
10676				for ($j = 0; $j < $len; ++$j) {
10677					$ek .= chr(ord($this->encryptdata['key'][$j]) ^ $i);
10678				}
10679				$enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
10680			}
10681			$enc .= str_repeat("\x00", 16);
10682			return substr($enc, 0, 32);
10683		} elseif ($this->encryptdata['mode'] == 3) { // AES-256
10684			$seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
10685			// User Validation Salt
10686			$this->encryptdata['UVS'] = substr($seed, 0, 8);
10687			// User Key Salt
10688			$this->encryptdata['UKS'] = substr($seed, 8, 16);
10689			return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
10690		}
10691	}
10692
10693	/**
10694	 * Compute UE value (used for encryption)
10695	 * @return string UE value
10696	 * @protected
10697	 * @since 5.9.006 (2010-10-19)
10698	 * @author Nicola Asuni
10699	 */
10700	protected function _UEvalue() {
10701		$hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
10702		return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
10703	}
10704
10705	/**
10706	 * Compute O value (used for encryption)
10707	 * @return string O value
10708	 * @protected
10709	 * @since 2.0.000 (2008-01-02)
10710	 * @author Nicola Asuni
10711	 */
10712	protected function _Ovalue() {
10713		if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
10714			$tmp = TCPDF_STATIC::_md5_16($this->encryptdata['owner_password']);
10715			if ($this->encryptdata['mode'] > 0) {
10716				for ($i = 0; $i < 50; ++$i) {
10717					$tmp = TCPDF_STATIC::_md5_16($tmp);
10718				}
10719			}
10720			$owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
10721			$enc = TCPDF_STATIC::_RC4($owner_key, $this->encryptdata['user_password'], $this->last_enc_key, $this->last_enc_key_c);
10722			if ($this->encryptdata['mode'] > 0) {
10723				$len = strlen($owner_key);
10724				for ($i = 1; $i <= 19; ++$i) {
10725					$ek = '';
10726					for ($j = 0; $j < $len; ++$j) {
10727						$ek .= chr(ord($owner_key[$j]) ^ $i);
10728					}
10729					$enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
10730				}
10731			}
10732			return $enc;
10733		} elseif ($this->encryptdata['mode'] == 3) { // AES-256
10734			$seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
10735			// Owner Validation Salt
10736			$this->encryptdata['OVS'] = substr($seed, 0, 8);
10737			// Owner Key Salt
10738			$this->encryptdata['OKS'] = substr($seed, 8, 16);
10739			return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
10740		}
10741	}
10742
10743	/**
10744	 * Compute OE value (used for encryption)
10745	 * @return string OE value
10746	 * @protected
10747	 * @since 5.9.006 (2010-10-19)
10748	 * @author Nicola Asuni
10749	 */
10750	protected function _OEvalue() {
10751		$hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
10752		return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
10753	}
10754
10755	/**
10756	 * Convert password for AES-256 encryption mode
10757	 * @param $password (string) password
10758	 * @return string password
10759	 * @protected
10760	 * @since 5.9.006 (2010-10-19)
10761	 * @author Nicola Asuni
10762	 */
10763	protected function _fixAES256Password($password) {
10764		$psw = ''; // password to be returned
10765		$psw_array = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($password, $this->isunicode, $this->CurrentFont), $password, $this->rtl, $this->isunicode, $this->CurrentFont);
10766		foreach ($psw_array as $c) {
10767			$psw .= TCPDF_FONTS::unichr($c, $this->isunicode);
10768		}
10769		return substr($psw, 0, 127);
10770	}
10771
10772	/**
10773	 * Compute encryption key
10774	 * @protected
10775	 * @since 2.0.000 (2008-01-02)
10776	 * @author Nicola Asuni
10777	 */
10778	protected function _generateencryptionkey() {
10779		$keybytelen = ($this->encryptdata['Length'] / 8);
10780		if (!$this->encryptdata['pubkey']) { // standard mode
10781			if ($this->encryptdata['mode'] == 3) { // AES-256
10782				// generate 256 bit random key
10783				$this->encryptdata['key'] = substr(hash('sha256', TCPDF_STATIC::getRandomSeed(), true), 0, $keybytelen);
10784				// truncate passwords
10785				$this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
10786				$this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
10787				// Compute U value
10788				$this->encryptdata['U'] = $this->_Uvalue();
10789				// Compute UE value
10790				$this->encryptdata['UE'] = $this->_UEvalue();
10791				// Compute O value
10792				$this->encryptdata['O'] = $this->_Ovalue();
10793				// Compute OE value
10794				$this->encryptdata['OE'] = $this->_OEvalue();
10795				// Compute P value
10796				$this->encryptdata['P'] = $this->encryptdata['protection'];
10797				// Computing the encryption dictionary's Perms (permissions) value
10798				$perms = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
10799				$perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
10800				if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
10801					$perms .= 'F';
10802				} else {
10803					$perms .= 'T';
10804				}
10805				$perms .= 'adb'; // bytes 9-11
10806				$perms .= 'nick'; // bytes 12-15
10807				$this->encryptdata['perms'] = TCPDF_STATIC::_AESnopad($this->encryptdata['key'], $perms);
10808			} else { // RC4-40, RC4-128, AES-128
10809				// Pad passwords
10810				$this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].TCPDF_STATIC::$enc_padding, 0, 32);
10811				$this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].TCPDF_STATIC::$enc_padding, 0, 32);
10812				// Compute O value
10813				$this->encryptdata['O'] = $this->_Ovalue();
10814				// get default permissions (reverse byte order)
10815				$permissions = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']);
10816				// Compute encryption key
10817				$tmp = TCPDF_STATIC::_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
10818				if ($this->encryptdata['mode'] > 0) {
10819					for ($i = 0; $i < 50; ++$i) {
10820						$tmp = TCPDF_STATIC::_md5_16(substr($tmp, 0, $keybytelen));
10821					}
10822				}
10823				$this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
10824				// Compute U value
10825				$this->encryptdata['U'] = $this->_Uvalue();
10826				// Compute P value
10827				$this->encryptdata['P'] = $this->encryptdata['protection'];
10828			}
10829		} else { // Public-Key mode
10830			// random 20-byte seed
10831			$seed = sha1(TCPDF_STATIC::getRandomSeed(), true);
10832			$recipient_bytes = '';
10833			foreach ($this->encryptdata['pubkeys'] as $pubkey) {
10834				// for each public certificate
10835				if (isset($pubkey['p'])) {
10836					$pkprotection = TCPDF_STATIC::getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
10837				} else {
10838					$pkprotection = $this->encryptdata['protection'];
10839				}
10840				// get default permissions (reverse byte order)
10841				$pkpermissions = TCPDF_STATIC::getEncPermissionsString($pkprotection);
10842				// envelope data
10843				$envelope = $seed.$pkpermissions;
10844				// write the envelope data to a temporary file
10845				$tempkeyfile = TCPDF_STATIC::getObjFilename('key', $this->file_id);
10846				$f = TCPDF_STATIC::fopenLocal($tempkeyfile, 'wb');
10847				if (!$f) {
10848					$this->Error('Unable to create temporary key file: '.$tempkeyfile);
10849				}
10850				$envelope_length = strlen($envelope);
10851				fwrite($f, $envelope, $envelope_length);
10852				fclose($f);
10853				$tempencfile = TCPDF_STATIC::getObjFilename('enc', $this->file_id);
10854				if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) {
10855					$this->Error('Unable to encrypt the file: '.$tempkeyfile);
10856				}
10857				// read encryption signature
10858				$signature = file_get_contents($tempencfile, false, null, $envelope_length);
10859				// extract signature
10860				$signature = substr($signature, strpos($signature, 'Content-Disposition'));
10861				$tmparr = explode("\n\n", $signature);
10862				$signature = trim($tmparr[1]);
10863				unset($tmparr);
10864				// decode signature
10865				$signature = base64_decode($signature);
10866				// convert signature to hex
10867				$hexsignature = current(unpack('H*', $signature));
10868				// store signature on recipients array
10869				$this->encryptdata['Recipients'][] = $hexsignature;
10870				// The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
10871				$recipient_bytes .= $signature;
10872			}
10873			// calculate encryption key
10874			if ($this->encryptdata['mode'] == 3) { // AES-256
10875				$this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
10876			} else { // RC4-40, RC4-128, AES-128
10877				$this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
10878			}
10879		}
10880	}
10881
10882	/**
10883	 * Set document protection
10884	 * Remark: the protection against modification is for people who have the full Acrobat product.
10885	 * 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.
10886	 * 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.
10887	 * @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>
10888	 * @param $user_pass (String) user password. Empty by default.
10889	 * @param $owner_pass (String) owner password. If not specified, a random value is used.
10890	 * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
10891	 * @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')))
10892	 * @public
10893	 * @since 2.0.000 (2008-01-02)
10894	 * @author Nicola Asuni
10895	 */
10896	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) {
10897		if ($this->pdfa_mode) {
10898			// encryption is not allowed in PDF/A mode
10899			return;
10900		}
10901		$this->encryptdata['protection'] = TCPDF_STATIC::getUserPermissionCode($permissions, $mode);
10902		if (($pubkeys !== null) AND (is_array($pubkeys))) {
10903			// public-key mode
10904			$this->encryptdata['pubkeys'] = $pubkeys;
10905			if ($mode == 0) {
10906				// public-Key Security requires at least 128 bit
10907				$mode = 1;
10908			}
10909			if (!function_exists('openssl_pkcs7_encrypt')) {
10910				$this->Error('Public-Key Security requires openssl library.');
10911			}
10912			// Set Public-Key filter (available are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
10913			$this->encryptdata['pubkey'] = true;
10914			$this->encryptdata['Filter'] = 'Adobe.PubSec';
10915			$this->encryptdata['StmF'] = 'DefaultCryptFilter';
10916			$this->encryptdata['StrF'] = 'DefaultCryptFilter';
10917		} else {
10918			// standard mode (password mode)
10919			$this->encryptdata['pubkey'] = false;
10920			$this->encryptdata['Filter'] = 'Standard';
10921			$this->encryptdata['StmF'] = 'StdCF';
10922			$this->encryptdata['StrF'] = 'StdCF';
10923		}
10924		if ($mode > 1) { // AES
10925			if (!extension_loaded('openssl') && !extension_loaded('mcrypt')) {
10926				$this->Error('AES encryption requires openssl or mcrypt extension (http://www.php.net/manual/en/mcrypt.requirements.php).');
10927			}
10928			if (extension_loaded('openssl') && !in_array('aes-256-cbc', openssl_get_cipher_methods())) {
10929				$this->Error('AES encryption requires openssl/aes-256-cbc cypher.');
10930			}
10931			if (extension_loaded('mcrypt') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
10932				$this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
10933			}
10934			if (($mode == 3) AND !function_exists('hash')) {
10935				// the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
10936				$this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
10937			}
10938		}
10939		if ($owner_pass === null) {
10940			$owner_pass = md5(TCPDF_STATIC::getRandomSeed());
10941		}
10942		$this->encryptdata['user_password'] = $user_pass;
10943		$this->encryptdata['owner_password'] = $owner_pass;
10944		$this->encryptdata['mode'] = $mode;
10945		switch ($mode) {
10946			case 0: { // RC4 40 bit
10947				$this->encryptdata['V'] = 1;
10948				$this->encryptdata['Length'] = 40;
10949				$this->encryptdata['CF']['CFM'] = 'V2';
10950				break;
10951			}
10952			case 1: { // RC4 128 bit
10953				$this->encryptdata['V'] = 2;
10954				$this->encryptdata['Length'] = 128;
10955				$this->encryptdata['CF']['CFM'] = 'V2';
10956				if ($this->encryptdata['pubkey']) {
10957					$this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
10958					$this->encryptdata['Recipients'] = array();
10959				}
10960				break;
10961			}
10962			case 2: { // AES 128 bit
10963				$this->encryptdata['V'] = 4;
10964				$this->encryptdata['Length'] = 128;
10965				$this->encryptdata['CF']['CFM'] = 'AESV2';
10966				$this->encryptdata['CF']['Length'] = 128;
10967				if ($this->encryptdata['pubkey']) {
10968					$this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
10969					$this->encryptdata['Recipients'] = array();
10970				}
10971				break;
10972			}
10973			case 3: { // AES 256 bit
10974				$this->encryptdata['V'] = 5;
10975				$this->encryptdata['Length'] = 256;
10976				$this->encryptdata['CF']['CFM'] = 'AESV3';
10977				$this->encryptdata['CF']['Length'] = 256;
10978				if ($this->encryptdata['pubkey']) {
10979					$this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
10980					$this->encryptdata['Recipients'] = array();
10981				}
10982				break;
10983			}
10984		}
10985		$this->encrypted = true;
10986		$this->encryptdata['fileid'] = TCPDF_STATIC::convertHexStringToString($this->file_id);
10987		$this->_generateencryptionkey();
10988	}
10989
10990	// END OF ENCRYPTION FUNCTIONS -------------------------
10991
10992	// START TRANSFORMATIONS SECTION -----------------------
10993
10994	/**
10995	 * Starts a 2D tranformation saving current graphic state.
10996	 * This function must be called before scaling, mirroring, translation, rotation and skewing.
10997	 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
10998	 * @public
10999	 * @since 2.1.000 (2008-01-07)
11000	 * @see StartTransform(), StopTransform()
11001	 */
11002	public function StartTransform() {
11003		if ($this->state != 2) {
11004			return;
11005		}
11006		$this->_outSaveGraphicsState();
11007		if ($this->inxobj) {
11008			// we are inside an XObject template
11009			$this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
11010		} else {
11011			$this->transfmrk[$this->page][] = $this->pagelen[$this->page];
11012		}
11013		++$this->transfmatrix_key;
11014		$this->transfmatrix[$this->transfmatrix_key] = array();
11015	}
11016
11017	/**
11018	 * Stops a 2D tranformation restoring previous graphic state.
11019	 * This function must be called after scaling, mirroring, translation, rotation and skewing.
11020	 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
11021	 * @public
11022	 * @since 2.1.000 (2008-01-07)
11023	 * @see StartTransform(), StopTransform()
11024	 */
11025	public function StopTransform() {
11026		if ($this->state != 2) {
11027			return;
11028		}
11029		$this->_outRestoreGraphicsState();
11030		if (isset($this->transfmatrix[$this->transfmatrix_key])) {
11031			array_pop($this->transfmatrix[$this->transfmatrix_key]);
11032			--$this->transfmatrix_key;
11033		}
11034		if ($this->inxobj) {
11035			// we are inside an XObject template
11036			array_pop($this->xobjects[$this->xobjid]['transfmrk']);
11037		} else {
11038			array_pop($this->transfmrk[$this->page]);
11039		}
11040	}
11041	/**
11042	 * Horizontal Scaling.
11043	 * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
11044	 * @param $x (int) abscissa of the scaling center. Default is current x position
11045	 * @param $y (int) ordinate of the scaling center. Default is current y position
11046	 * @public
11047	 * @since 2.1.000 (2008-01-07)
11048	 * @see StartTransform(), StopTransform()
11049	 */
11050	public function ScaleX($s_x, $x='', $y='') {
11051		$this->Scale($s_x, 100, $x, $y);
11052	}
11053
11054	/**
11055	 * Vertical Scaling.
11056	 * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
11057	 * @param $x (int) abscissa of the scaling center. Default is current x position
11058	 * @param $y (int) ordinate of the scaling center. Default is current y position
11059	 * @public
11060	 * @since 2.1.000 (2008-01-07)
11061	 * @see StartTransform(), StopTransform()
11062	 */
11063	public function ScaleY($s_y, $x='', $y='') {
11064		$this->Scale(100, $s_y, $x, $y);
11065	}
11066
11067	/**
11068	 * Vertical and horizontal proportional Scaling.
11069	 * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
11070	 * @param $x (int) abscissa of the scaling center. Default is current x position
11071	 * @param $y (int) ordinate of the scaling center. Default is current y position
11072	 * @public
11073	 * @since 2.1.000 (2008-01-07)
11074	 * @see StartTransform(), StopTransform()
11075	 */
11076	public function ScaleXY($s, $x='', $y='') {
11077		$this->Scale($s, $s, $x, $y);
11078	}
11079
11080	/**
11081	 * Vertical and horizontal non-proportional Scaling.
11082	 * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
11083	 * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
11084	 * @param $x (int) abscissa of the scaling center. Default is current x position
11085	 * @param $y (int) ordinate of the scaling center. Default is current y position
11086	 * @public
11087	 * @since 2.1.000 (2008-01-07)
11088	 * @see StartTransform(), StopTransform()
11089	 */
11090	public function Scale($s_x, $s_y, $x='', $y='') {
11091		if ($x === '') {
11092			$x = $this->x;
11093		}
11094		if ($y === '') {
11095			$y = $this->y;
11096		}
11097		if (($s_x == 0) OR ($s_y == 0)) {
11098			$this->Error('Please do not use values equal to zero for scaling');
11099		}
11100		$y = ($this->h - $y) * $this->k;
11101		$x *= $this->k;
11102		//calculate elements of transformation matrix
11103		$s_x /= 100;
11104		$s_y /= 100;
11105		$tm = array();
11106		$tm[0] = $s_x;
11107		$tm[1] = 0;
11108		$tm[2] = 0;
11109		$tm[3] = $s_y;
11110		$tm[4] = $x * (1 - $s_x);
11111		$tm[5] = $y * (1 - $s_y);
11112		//scale the coordinate system
11113		$this->Transform($tm);
11114	}
11115
11116	/**
11117	 * Horizontal Mirroring.
11118	 * @param $x (int) abscissa of the point. Default is current x position
11119	 * @public
11120	 * @since 2.1.000 (2008-01-07)
11121	 * @see StartTransform(), StopTransform()
11122	 */
11123	public function MirrorH($x='') {
11124		$this->Scale(-100, 100, $x);
11125	}
11126
11127	/**
11128	 * Verical Mirroring.
11129	 * @param $y (int) ordinate of the point. Default is current y position
11130	 * @public
11131	 * @since 2.1.000 (2008-01-07)
11132	 * @see StartTransform(), StopTransform()
11133	 */
11134	public function MirrorV($y='') {
11135		$this->Scale(100, -100, '', $y);
11136	}
11137
11138	/**
11139	 * Point reflection mirroring.
11140	 * @param $x (int) abscissa of the point. Default is current x position
11141	 * @param $y (int) ordinate of the point. Default is current y position
11142	 * @public
11143	 * @since 2.1.000 (2008-01-07)
11144	 * @see StartTransform(), StopTransform()
11145	 */
11146	public function MirrorP($x='',$y='') {
11147		$this->Scale(-100, -100, $x, $y);
11148	}
11149
11150	/**
11151	 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
11152	 * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
11153	 * @param $x (int) abscissa of the point. Default is current x position
11154	 * @param $y (int) ordinate of the point. Default is current y position
11155	 * @public
11156	 * @since 2.1.000 (2008-01-07)
11157	 * @see StartTransform(), StopTransform()
11158	 */
11159	public function MirrorL($angle=0, $x='',$y='') {
11160		$this->Scale(-100, 100, $x, $y);
11161		$this->Rotate(-2*($angle-90), $x, $y);
11162	}
11163
11164	/**
11165	 * Translate graphic object horizontally.
11166	 * @param $t_x (int) movement to the right (or left for RTL)
11167	 * @public
11168	 * @since 2.1.000 (2008-01-07)
11169	 * @see StartTransform(), StopTransform()
11170	 */
11171	public function TranslateX($t_x) {
11172		$this->Translate($t_x, 0);
11173	}
11174
11175	/**
11176	 * Translate graphic object vertically.
11177	 * @param $t_y (int) movement to the bottom
11178	 * @public
11179	 * @since 2.1.000 (2008-01-07)
11180	 * @see StartTransform(), StopTransform()
11181	 */
11182	public function TranslateY($t_y) {
11183		$this->Translate(0, $t_y);
11184	}
11185
11186	/**
11187	 * Translate graphic object horizontally and vertically.
11188	 * @param $t_x (int) movement to the right
11189	 * @param $t_y (int) movement to the bottom
11190	 * @public
11191	 * @since 2.1.000 (2008-01-07)
11192	 * @see StartTransform(), StopTransform()
11193	 */
11194	public function Translate($t_x, $t_y) {
11195		//calculate elements of transformation matrix
11196		$tm = array();
11197		$tm[0] = 1;
11198		$tm[1] = 0;
11199		$tm[2] = 0;
11200		$tm[3] = 1;
11201		$tm[4] = $t_x * $this->k;
11202		$tm[5] = -$t_y * $this->k;
11203		//translate the coordinate system
11204		$this->Transform($tm);
11205	}
11206
11207	/**
11208	 * Rotate object.
11209	 * @param $angle (float) angle in degrees for counter-clockwise rotation
11210	 * @param $x (int) abscissa of the rotation center. Default is current x position
11211	 * @param $y (int) ordinate of the rotation center. Default is current y position
11212	 * @public
11213	 * @since 2.1.000 (2008-01-07)
11214	 * @see StartTransform(), StopTransform()
11215	 */
11216	public function Rotate($angle, $x='', $y='') {
11217		if ($x === '') {
11218			$x = $this->x;
11219		}
11220		if ($y === '') {
11221			$y = $this->y;
11222		}
11223		$y = ($this->h - $y) * $this->k;
11224		$x *= $this->k;
11225		//calculate elements of transformation matrix
11226		$tm = array();
11227		$tm[0] = cos(deg2rad($angle));
11228		$tm[1] = sin(deg2rad($angle));
11229		$tm[2] = -$tm[1];
11230		$tm[3] = $tm[0];
11231		$tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
11232		$tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
11233		//rotate the coordinate system around ($x,$y)
11234		$this->Transform($tm);
11235	}
11236
11237	/**
11238	 * Skew horizontally.
11239	 * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
11240	 * @param $x (int) abscissa of the skewing center. default is current x position
11241	 * @param $y (int) ordinate of the skewing center. default is current y position
11242	 * @public
11243	 * @since 2.1.000 (2008-01-07)
11244	 * @see StartTransform(), StopTransform()
11245	 */
11246	public function SkewX($angle_x, $x='', $y='') {
11247		$this->Skew($angle_x, 0, $x, $y);
11248	}
11249
11250	/**
11251	 * Skew vertically.
11252	 * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
11253	 * @param $x (int) abscissa of the skewing center. default is current x position
11254	 * @param $y (int) ordinate of the skewing center. default is current y position
11255	 * @public
11256	 * @since 2.1.000 (2008-01-07)
11257	 * @see StartTransform(), StopTransform()
11258	 */
11259	public function SkewY($angle_y, $x='', $y='') {
11260		$this->Skew(0, $angle_y, $x, $y);
11261	}
11262
11263	/**
11264	 * Skew.
11265	 * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
11266	 * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
11267	 * @param $x (int) abscissa of the skewing center. default is current x position
11268	 * @param $y (int) ordinate of the skewing center. default is current y position
11269	 * @public
11270	 * @since 2.1.000 (2008-01-07)
11271	 * @see StartTransform(), StopTransform()
11272	 */
11273	public function Skew($angle_x, $angle_y, $x='', $y='') {
11274		if ($x === '') {
11275			$x = $this->x;
11276		}
11277		if ($y === '') {
11278			$y = $this->y;
11279		}
11280		if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
11281			$this->Error('Please use values between -90 and +90 degrees for Skewing.');
11282		}
11283		$x *= $this->k;
11284		$y = ($this->h - $y) * $this->k;
11285		//calculate elements of transformation matrix
11286		$tm = array();
11287		$tm[0] = 1;
11288		$tm[1] = tan(deg2rad($angle_y));
11289		$tm[2] = tan(deg2rad($angle_x));
11290		$tm[3] = 1;
11291		$tm[4] = -$tm[2] * $y;
11292		$tm[5] = -$tm[1] * $x;
11293		//skew the coordinate system
11294		$this->Transform($tm);
11295	}
11296
11297	/**
11298	 * Apply graphic transformations.
11299	 * @param $tm (array) transformation matrix
11300	 * @protected
11301	 * @since 2.1.000 (2008-01-07)
11302	 * @see StartTransform(), StopTransform()
11303	 */
11304	protected function Transform($tm) {
11305		if ($this->state != 2) {
11306			return;
11307		}
11308		$this->_out(sprintf('%F %F %F %F %F %F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
11309		// add tranformation matrix
11310		$this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
11311		// update transformation mark
11312		if ($this->inxobj) {
11313			// we are inside an XObject template
11314			if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
11315				$key = key($this->xobjects[$this->xobjid]['transfmrk']);
11316				$this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
11317			}
11318		} elseif (end($this->transfmrk[$this->page]) !== false) {
11319			$key = key($this->transfmrk[$this->page]);
11320			$this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
11321		}
11322	}
11323
11324	// END TRANSFORMATIONS SECTION -------------------------
11325
11326	// START GRAPHIC FUNCTIONS SECTION ---------------------
11327	// The following section is based on the code provided by David Hernandez Sanz
11328
11329	/**
11330	 * 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.
11331	 * @param $width (float) The width.
11332	 * @public
11333	 * @since 1.0
11334	 * @see Line(), Rect(), Cell(), MultiCell()
11335	 */
11336	public function SetLineWidth($width) {
11337		//Set line width
11338		$this->LineWidth = $width;
11339		$this->linestyleWidth = sprintf('%F w', ($width * $this->k));
11340		if ($this->state == 2) {
11341			$this->_out($this->linestyleWidth);
11342		}
11343	}
11344
11345	/**
11346	 * Returns the current the line width.
11347	 * @return int Line width
11348	 * @public
11349	 * @since 2.1.000 (2008-01-07)
11350	 * @see Line(), SetLineWidth()
11351	 */
11352	public function GetLineWidth() {
11353		return $this->LineWidth;
11354	}
11355
11356	/**
11357	 * Set line style.
11358	 * @param $style (array) Line style. Array with keys among the following:
11359	 * <ul>
11360	 *	 <li>width (float): Width of the line in user units.</li>
11361	 *	 <li>cap (string): Type of cap to put on the line. Possible values are:
11362	 * butt, round, square. The difference between "square" and "butt" is that
11363	 * "square" projects a flat end past the end of the line.</li>
11364	 *	 <li>join (string): Type of join. Possible values are: miter, round,
11365	 * bevel.</li>
11366	 *	 <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
11367	 * series of length values, which are the lengths of the on and off dashes.
11368	 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
11369	 * 1 off, 2 on, 1 off, ...</li>
11370	 *	 <li>phase (integer): Modifier on the dash pattern which is used to shift
11371	 * the point at which the pattern starts.</li>
11372	 *	 <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>
11373	 * </ul>
11374	 * @param $ret (boolean) if true do not send the command.
11375	 * @return string the PDF command
11376	 * @public
11377	 * @since 2.1.000 (2008-01-08)
11378	 */
11379	public function SetLineStyle($style, $ret=false) {
11380		$s = ''; // string to be returned
11381		if (!is_array($style)) {
11382			return;
11383		}
11384		if (isset($style['width'])) {
11385			$this->LineWidth = $style['width'];
11386			$this->linestyleWidth = sprintf('%F w', ($style['width'] * $this->k));
11387			$s .= $this->linestyleWidth.' ';
11388		}
11389		if (isset($style['cap'])) {
11390			$ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
11391			if (isset($ca[$style['cap']])) {
11392				$this->linestyleCap = $ca[$style['cap']].' J';
11393				$s .= $this->linestyleCap.' ';
11394			}
11395		}
11396		if (isset($style['join'])) {
11397			$ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
11398			if (isset($ja[$style['join']])) {
11399				$this->linestyleJoin = $ja[$style['join']].' j';
11400				$s .= $this->linestyleJoin.' ';
11401			}
11402		}
11403		if (isset($style['dash'])) {
11404			$dash_string = '';
11405			if ($style['dash']) {
11406				if (preg_match('/^.+,/', $style['dash']) > 0) {
11407					$tab = explode(',', $style['dash']);
11408				} else {
11409					$tab = array($style['dash']);
11410				}
11411				$dash_string = '';
11412				foreach ($tab as $i => $v) {
11413					if ($i) {
11414						$dash_string .= ' ';
11415					}
11416					$dash_string .= sprintf('%F', $v);
11417				}
11418			}
11419			if (!isset($style['phase']) OR !$style['dash']) {
11420				$style['phase'] = 0;
11421			}
11422			$this->linestyleDash = sprintf('[%s] %F d', $dash_string, $style['phase']);
11423			$s .= $this->linestyleDash.' ';
11424		}
11425		if (isset($style['color'])) {
11426			$s .= $this->SetDrawColorArray($style['color'], true).' ';
11427		}
11428		if (!$ret AND ($this->state == 2)) {
11429			$this->_out($s);
11430		}
11431		return $s;
11432	}
11433
11434	/**
11435	 * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
11436	 * @param $x (float) Abscissa of point.
11437	 * @param $y (float) Ordinate of point.
11438	 * @protected
11439	 * @since 2.1.000 (2008-01-08)
11440	 */
11441	protected function _outPoint($x, $y) {
11442		if ($this->state == 2) {
11443			$this->_out(sprintf('%F %F m', ($x * $this->k), (($this->h - $y) * $this->k)));
11444		}
11445	}
11446
11447	/**
11448	 * Append a straight line segment from the current point to the point (x, y).
11449	 * The new current point shall be (x, y).
11450	 * @param $x (float) Abscissa of end point.
11451	 * @param $y (float) Ordinate of end point.
11452	 * @protected
11453	 * @since 2.1.000 (2008-01-08)
11454	 */
11455	protected function _outLine($x, $y) {
11456		if ($this->state == 2) {
11457			$this->_out(sprintf('%F %F l', ($x * $this->k), (($this->h - $y) * $this->k)));
11458		}
11459	}
11460
11461	/**
11462	 * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
11463	 * @param $x (float) Abscissa of upper-left corner.
11464	 * @param $y (float) Ordinate of upper-left corner.
11465	 * @param $w (float) Width.
11466	 * @param $h (float) Height.
11467	 * @param $op (string) options
11468	 * @protected
11469	 * @since 2.1.000 (2008-01-08)
11470	 */
11471	protected function _outRect($x, $y, $w, $h, $op) {
11472		if ($this->state == 2) {
11473			$this->_out(sprintf('%F %F %F %F re %s', ($x * $this->k), (($this->h - $y) * $this->k), ($w * $this->k), (-$h * $this->k), $op));
11474		}
11475	}
11476
11477	/**
11478	 * 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.
11479	 * The new current point shall be (x3, y3).
11480	 * @param $x1 (float) Abscissa of control point 1.
11481	 * @param $y1 (float) Ordinate of control point 1.
11482	 * @param $x2 (float) Abscissa of control point 2.
11483	 * @param $y2 (float) Ordinate of control point 2.
11484	 * @param $x3 (float) Abscissa of end point.
11485	 * @param $y3 (float) Ordinate of end point.
11486	 * @protected
11487	 * @since 2.1.000 (2008-01-08)
11488	 */
11489	protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
11490		if ($this->state == 2) {
11491			$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)));
11492		}
11493	}
11494
11495	/**
11496	 * 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.
11497	 * The new current point shall be (x3, y3).
11498	 * @param $x2 (float) Abscissa of control point 2.
11499	 * @param $y2 (float) Ordinate of control point 2.
11500	 * @param $x3 (float) Abscissa of end point.
11501	 * @param $y3 (float) Ordinate of end point.
11502	 * @protected
11503	 * @since 4.9.019 (2010-04-26)
11504	 */
11505	protected function _outCurveV($x2, $y2, $x3, $y3) {
11506		if ($this->state == 2) {
11507			$this->_out(sprintf('%F %F %F %F v', ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
11508		}
11509	}
11510
11511	/**
11512	 * 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.
11513	 * The new current point shall be (x3, y3).
11514	 * @param $x1 (float) Abscissa of control point 1.
11515	 * @param $y1 (float) Ordinate of control point 1.
11516	 * @param $x3 (float) Abscissa of end point.
11517	 * @param $y3 (float) Ordinate of end point.
11518	 * @protected
11519	 * @since 2.1.000 (2008-01-08)
11520	 */
11521	protected function _outCurveY($x1, $y1, $x3, $y3) {
11522		if ($this->state == 2) {
11523			$this->_out(sprintf('%F %F %F %F y', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
11524		}
11525	}
11526
11527	/**
11528	 * Draws a line between two points.
11529	 * @param $x1 (float) Abscissa of first point.
11530	 * @param $y1 (float) Ordinate of first point.
11531	 * @param $x2 (float) Abscissa of second point.
11532	 * @param $y2 (float) Ordinate of second point.
11533	 * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
11534	 * @public
11535	 * @since 1.0
11536	 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
11537	 */
11538	public function Line($x1, $y1, $x2, $y2, $style=array()) {
11539		if ($this->state != 2) {
11540			return;
11541		}
11542		if (is_array($style)) {
11543			$this->SetLineStyle($style);
11544		}
11545		$this->_outPoint($x1, $y1);
11546		$this->_outLine($x2, $y2);
11547		$this->_out('S');
11548	}
11549
11550	/**
11551	 * Draws a rectangle.
11552	 * @param $x (float) Abscissa of upper-left corner.
11553	 * @param $y (float) Ordinate of upper-left corner.
11554	 * @param $w (float) Width.
11555	 * @param $h (float) Height.
11556	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11557	 * @param $border_style (array) Border style of rectangle. Array with keys among the following:
11558	 * <ul>
11559	 *	 <li>all: Line style of all borders. Array like for SetLineStyle().</li>
11560	 *	 <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
11561	 * </ul>
11562	 * If a key is not present or is null, the correspondent border is not drawn. Default value: default line style (empty array).
11563	 * @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).
11564	 * @public
11565	 * @since 1.0
11566	 * @see SetLineStyle()
11567	 */
11568	public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
11569		if ($this->state != 2) {
11570			return;
11571		}
11572		if (empty($style)) {
11573			$style = 'S';
11574		}
11575		if (!(strpos($style, 'F') === false) AND !empty($fill_color)) {
11576			// set background color
11577			$this->SetFillColorArray($fill_color);
11578		}
11579		if (!empty($border_style)) {
11580			if (isset($border_style['all']) AND !empty($border_style['all'])) {
11581				//set global style for border
11582				$this->SetLineStyle($border_style['all']);
11583				$border_style = array();
11584			} else {
11585				// remove stroke operator from style
11586				$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*' );
11587				if (isset($opnostroke[$style])) {
11588					$style = $opnostroke[$style];
11589				}
11590			}
11591		}
11592		if (!empty($style)) {
11593			$op = TCPDF_STATIC::getPathPaintOperator($style);
11594			$this->_outRect($x, $y, $w, $h, $op);
11595		}
11596		if (!empty($border_style)) {
11597			$border_style2 = array();
11598			foreach ($border_style as $line => $value) {
11599				$length = strlen($line);
11600				for ($i = 0; $i < $length; ++$i) {
11601					$border_style2[$line[$i]] = $value;
11602				}
11603			}
11604			$border_style = $border_style2;
11605			if (isset($border_style['L']) AND $border_style['L']) {
11606				$this->Line($x, $y, $x, $y + $h, $border_style['L']);
11607			}
11608			if (isset($border_style['T']) AND $border_style['T']) {
11609				$this->Line($x, $y, $x + $w, $y, $border_style['T']);
11610			}
11611			if (isset($border_style['R']) AND $border_style['R']) {
11612				$this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
11613			}
11614			if (isset($border_style['B']) AND $border_style['B']) {
11615				$this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
11616			}
11617		}
11618	}
11619
11620	/**
11621	 * Draws a Bezier curve.
11622	 * The Bezier curve is a tangent to the line between the control points at
11623	 * either end of the curve.
11624	 * @param $x0 (float) Abscissa of start point.
11625	 * @param $y0 (float) Ordinate of start point.
11626	 * @param $x1 (float) Abscissa of control point 1.
11627	 * @param $y1 (float) Ordinate of control point 1.
11628	 * @param $x2 (float) Abscissa of control point 2.
11629	 * @param $y2 (float) Ordinate of control point 2.
11630	 * @param $x3 (float) Abscissa of end point.
11631	 * @param $y3 (float) Ordinate of end point.
11632	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11633	 * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
11634	 * @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).
11635	 * @public
11636	 * @see SetLineStyle()
11637	 * @since 2.1.000 (2008-01-08)
11638	 */
11639	public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
11640		if ($this->state != 2) {
11641			return;
11642		}
11643		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
11644			$this->SetFillColorArray($fill_color);
11645		}
11646		$op = TCPDF_STATIC::getPathPaintOperator($style);
11647		if ($line_style) {
11648			$this->SetLineStyle($line_style);
11649		}
11650		$this->_outPoint($x0, $y0);
11651		$this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
11652		$this->_out($op);
11653	}
11654
11655	/**
11656	 * Draws a poly-Bezier curve.
11657	 * Each Bezier curve segment is a tangent to the line between the control points at
11658	 * either end of the curve.
11659	 * @param $x0 (float) Abscissa of start point.
11660	 * @param $y0 (float) Ordinate of start point.
11661	 * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
11662	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11663	 * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
11664	 * @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).
11665	 * @public
11666	 * @see SetLineStyle()
11667	 * @since 3.0008 (2008-05-12)
11668	 */
11669	public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
11670		if ($this->state != 2) {
11671			return;
11672		}
11673		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
11674			$this->SetFillColorArray($fill_color);
11675		}
11676		$op = TCPDF_STATIC::getPathPaintOperator($style);
11677		if ($op == 'f') {
11678			$line_style = array();
11679		}
11680		if ($line_style) {
11681			$this->SetLineStyle($line_style);
11682		}
11683		$this->_outPoint($x0, $y0);
11684		foreach ($segments as $segment) {
11685			list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
11686			$this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
11687		}
11688		$this->_out($op);
11689	}
11690
11691	/**
11692	 * Draws an ellipse.
11693	 * An ellipse is formed from n Bezier curves.
11694	 * @param $x0 (float) Abscissa of center point.
11695	 * @param $y0 (float) Ordinate of center point.
11696	 * @param $rx (float) Horizontal radius.
11697	 * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
11698	 * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
11699	 * @param $astart: (float) Angle start of draw line. Default value: 0.
11700	 * @param $afinish: (float) Angle finish of draw line. Default value: 360.
11701	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11702	 * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
11703	 * @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).
11704	 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
11705	 * @author Nicola Asuni
11706	 * @public
11707	 * @since 2.1.000 (2008-01-08)
11708	 */
11709	public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
11710		if ($this->state != 2) {
11711			return;
11712		}
11713		if (TCPDF_STATIC::empty_string($ry) OR ($ry == 0)) {
11714			$ry = $rx;
11715		}
11716		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
11717			$this->SetFillColorArray($fill_color);
11718		}
11719		$op = TCPDF_STATIC::getPathPaintOperator($style);
11720		if ($op == 'f') {
11721			$line_style = array();
11722		}
11723		if ($line_style) {
11724			$this->SetLineStyle($line_style);
11725		}
11726		$this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
11727		$this->_out($op);
11728	}
11729
11730	/**
11731	 * Append an elliptical arc to the current path.
11732	 * An ellipse is formed from n Bezier curves.
11733	 * @param $xc (float) Abscissa of center point.
11734	 * @param $yc (float) Ordinate of center point.
11735	 * @param $rx (float) Horizontal radius.
11736	 * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
11737	 * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
11738	 * @param $angs: (float) Angle start of draw line. Default value: 0.
11739	 * @param $angf: (float) Angle finish of draw line. Default value: 360.
11740	 * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
11741	 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
11742	 * @param $startpoint (boolean) if true output a starting point.
11743	 * @param $ccw (boolean) if true draws in counter-clockwise.
11744	 * @param $svg (boolean) if true the angles are in svg mode (already calculated).
11745	 * @return array bounding box coordinates (x min, y min, x max, y max)
11746	 * @author Nicola Asuni
11747	 * @protected
11748	 * @since 4.9.019 (2010-04-26)
11749	 */
11750	protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
11751		if (($rx <= 0) OR ($ry < 0)) {
11752			return;
11753		}
11754		$k = $this->k;
11755		if ($nc < 2) {
11756			$nc = 2;
11757		}
11758		$xmin = 2147483647;
11759		$ymin = 2147483647;
11760		$xmax = 0;
11761		$ymax = 0;
11762		if ($pie) {
11763			// center of the arc
11764			$this->_outPoint($xc, $yc);
11765		}
11766		$xang = deg2rad((float) $xang);
11767		$angs = deg2rad((float) $angs);
11768		$angf = deg2rad((float) $angf);
11769		if ($svg) {
11770			$as = $angs;
11771			$af = $angf;
11772		} else {
11773			$as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
11774			$af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
11775		}
11776		if ($as < 0) {
11777			$as += (2 * M_PI);
11778		}
11779		if ($af < 0) {
11780			$af += (2 * M_PI);
11781		}
11782		if ($ccw AND ($as > $af)) {
11783			// reverse rotation
11784			$as -= (2 * M_PI);
11785		} elseif (!$ccw AND ($as < $af)) {
11786			// reverse rotation
11787			$af -= (2 * M_PI);
11788		}
11789		$total_angle = ($af - $as);
11790		if ($nc < 2) {
11791			$nc = 2;
11792		}
11793		// total arcs to draw
11794		$nc *= (2 * abs($total_angle) / M_PI);
11795		$nc = round($nc) + 1;
11796		// angle of each arc
11797		$arcang = ($total_angle / $nc);
11798		// center point in PDF coordinates
11799		$x0 = $xc;
11800		$y0 = ($this->h - $yc);
11801		// starting angle
11802		$ang = $as;
11803		$alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
11804		$cos_xang = cos($xang);
11805		$sin_xang = sin($xang);
11806		$cos_ang = cos($ang);
11807		$sin_ang = sin($ang);
11808		// first arc point
11809		$px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
11810		$py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
11811		// first Bezier control point
11812		$qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
11813		$qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
11814		if ($pie) {
11815			// line from center to arc starting point
11816			$this->_outLine($px1, $this->h - $py1);
11817		} elseif ($startpoint) {
11818			// arc starting point
11819			$this->_outPoint($px1, $this->h - $py1);
11820		}
11821		// draw arcs
11822		for ($i = 1; $i <= $nc; ++$i) {
11823			// starting angle
11824			$ang = $as + ($i * $arcang);
11825			if ($i == $nc) {
11826				$ang = $af;
11827			}
11828			$cos_ang = cos($ang);
11829			$sin_ang = sin($ang);
11830			// second arc point
11831			$px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
11832			$py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
11833			// second Bezier control point
11834			$qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
11835			$qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
11836			// draw arc
11837			$cx1 = ($px1 + $qx1);
11838			$cy1 = ($this->h - ($py1 + $qy1));
11839			$cx2 = ($px2 - $qx2);
11840			$cy2 = ($this->h - ($py2 - $qy2));
11841			$cx3 = $px2;
11842			$cy3 = ($this->h - $py2);
11843			$this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
11844			// get bounding box coordinates
11845			$xmin = min($xmin, $cx1, $cx2, $cx3);
11846			$ymin = min($ymin, $cy1, $cy2, $cy3);
11847			$xmax = max($xmax, $cx1, $cx2, $cx3);
11848			$ymax = max($ymax, $cy1, $cy2, $cy3);
11849			// move to next point
11850			$px1 = $px2;
11851			$py1 = $py2;
11852			$qx1 = $qx2;
11853			$qy1 = $qy2;
11854		}
11855		if ($pie) {
11856			$this->_outLine($xc, $yc);
11857			// get bounding box coordinates
11858			$xmin = min($xmin, $xc);
11859			$ymin = min($ymin, $yc);
11860			$xmax = max($xmax, $xc);
11861			$ymax = max($ymax, $yc);
11862		}
11863		return array($xmin, $ymin, $xmax, $ymax);
11864	}
11865
11866	/**
11867	 * Draws a circle.
11868	 * A circle is formed from n Bezier curves.
11869	 * @param $x0 (float) Abscissa of center point.
11870	 * @param $y0 (float) Ordinate of center point.
11871	 * @param $r (float) Radius.
11872	 * @param $angstr: (float) Angle start of draw line. Default value: 0.
11873	 * @param $angend: (float) Angle finish of draw line. Default value: 360.
11874	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11875	 * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
11876	 * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
11877	 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
11878	 * @public
11879	 * @since 2.1.000 (2008-01-08)
11880	 */
11881	public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
11882		$this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
11883	}
11884
11885	/**
11886	 * Draws a polygonal line
11887	 * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
11888	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11889	 * @param $line_style (array) Line style of polygon. Array with keys among the following:
11890	 * <ul>
11891	 *	 <li>all: Line style of all lines. Array like for SetLineStyle().</li>
11892	 *	 <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
11893	 * </ul>
11894	 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
11895	 * @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).
11896	 * @since 4.8.003 (2009-09-15)
11897	 * @public
11898	 */
11899	public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
11900		$this->Polygon($p, $style, $line_style, $fill_color, false);
11901	}
11902
11903	/**
11904	 * Draws a polygon.
11905	 * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
11906	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11907	 * @param $line_style (array) Line style of polygon. Array with keys among the following:
11908	 * <ul>
11909	 *	 <li>all: Line style of all lines. Array like for SetLineStyle().</li>
11910	 *	 <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
11911	 * </ul>
11912	 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
11913	 * @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).
11914	 * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
11915	 * @public
11916	 * @since 2.1.000 (2008-01-08)
11917	 */
11918	public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
11919		if ($this->state != 2) {
11920			return;
11921		}
11922		$nc = count($p); // number of coordinates
11923		$np = $nc / 2; // number of points
11924		if ($closed) {
11925			// close polygon by adding the first 2 points at the end (one line)
11926			for ($i = 0; $i < 4; ++$i) {
11927				$p[$nc + $i] = $p[$i];
11928			}
11929			// copy style for the last added line
11930			if (isset($line_style[0])) {
11931				$line_style[$np] = $line_style[0];
11932			}
11933			$nc += 4;
11934		}
11935		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
11936			$this->SetFillColorArray($fill_color);
11937		}
11938		$op = TCPDF_STATIC::getPathPaintOperator($style);
11939		if ($op == 'f') {
11940			$line_style = array();
11941		}
11942		$draw = true;
11943		if ($line_style) {
11944			if (isset($line_style['all'])) {
11945				$this->SetLineStyle($line_style['all']);
11946			} else {
11947				$draw = false;
11948				if ($op == 'B') {
11949					// draw fill
11950					$op = 'f';
11951					$this->_outPoint($p[0], $p[1]);
11952					for ($i = 2; $i < $nc; $i = $i + 2) {
11953						$this->_outLine($p[$i], $p[$i + 1]);
11954					}
11955					$this->_out($op);
11956				}
11957				// draw outline
11958				$this->_outPoint($p[0], $p[1]);
11959				for ($i = 2; $i < $nc; $i = $i + 2) {
11960					$line_num = ($i / 2) - 1;
11961					if (isset($line_style[$line_num])) {
11962						if ($line_style[$line_num] != 0) {
11963							if (is_array($line_style[$line_num])) {
11964								$this->_out('S');
11965								$this->SetLineStyle($line_style[$line_num]);
11966								$this->_outPoint($p[$i - 2], $p[$i - 1]);
11967								$this->_outLine($p[$i], $p[$i + 1]);
11968								$this->_out('S');
11969								$this->_outPoint($p[$i], $p[$i + 1]);
11970							} else {
11971								$this->_outLine($p[$i], $p[$i + 1]);
11972							}
11973						}
11974					} else {
11975						$this->_outLine($p[$i], $p[$i + 1]);
11976					}
11977				}
11978				$this->_out($op);
11979			}
11980		}
11981		if ($draw) {
11982			$this->_outPoint($p[0], $p[1]);
11983			for ($i = 2; $i < $nc; $i = $i + 2) {
11984				$this->_outLine($p[$i], $p[$i + 1]);
11985			}
11986			$this->_out($op);
11987		}
11988	}
11989
11990	/**
11991	 * Draws a regular polygon.
11992	 * @param $x0 (float) Abscissa of center point.
11993	 * @param $y0 (float) Ordinate of center point.
11994	 * @param $r: (float) Radius of inscribed circle.
11995	 * @param $ns (integer) Number of sides.
11996	 * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
11997	 * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
11998	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
11999	 * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
12000	 * <ul>
12001	 *	 <li>all: Line style of all sides. Array like for SetLineStyle().</li>
12002	 *	 <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
12003	 * </ul>
12004	 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
12005	 * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
12006	 * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
12007	 * <ul>
12008	 *	 <li>D or empty string: Draw (default).</li>
12009	 *	 <li>F: Fill.</li>
12010	 *	 <li>DF or FD: Draw and fill.</li>
12011	 *	 <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
12012	 *	 <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
12013	 * </ul>
12014	 * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
12015	 * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
12016	 * @public
12017	 * @since 2.1.000 (2008-01-08)
12018	 */
12019	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()) {
12020		if (3 > $ns) {
12021			$ns = 3;
12022		}
12023		if ($draw_circle) {
12024			$this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
12025		}
12026		$p = array();
12027		for ($i = 0; $i < $ns; ++$i) {
12028			$a = $angle + ($i * 360 / $ns);
12029			$a_rad = deg2rad((float) $a);
12030			$p[] = $x0 + ($r * sin($a_rad));
12031			$p[] = $y0 + ($r * cos($a_rad));
12032		}
12033		$this->Polygon($p, $style, $line_style, $fill_color);
12034	}
12035
12036	/**
12037	 * Draws a star polygon
12038	 * @param $x0 (float) Abscissa of center point.
12039	 * @param $y0 (float) Ordinate of center point.
12040	 * @param $r (float) Radius of inscribed circle.
12041	 * @param $nv (integer) Number of vertices.
12042	 * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
12043	 * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
12044	 * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
12045	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
12046	 * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
12047	 * <ul>
12048	 *	 <li>all: Line style of all sides. Array like for
12049	 * SetLineStyle().</li>
12050	 *	 <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
12051	 * </ul>
12052	 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
12053	 * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
12054	 * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
12055	 * <ul>
12056	 *	 <li>D or empty string: Draw (default).</li>
12057	 *	 <li>F: Fill.</li>
12058	 *	 <li>DF or FD: Draw and fill.</li>
12059	 *	 <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
12060	 *	 <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
12061	 * </ul>
12062	 * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
12063	 * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
12064	 * @public
12065	 * @since 2.1.000 (2008-01-08)
12066	 */
12067	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()) {
12068		if ($nv < 2) {
12069			$nv = 2;
12070		}
12071		if ($draw_circle) {
12072			$this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
12073		}
12074		$p2 = array();
12075		$visited = array();
12076		for ($i = 0; $i < $nv; ++$i) {
12077			$a = $angle + ($i * 360 / $nv);
12078			$a_rad = deg2rad((float) $a);
12079			$p2[] = $x0 + ($r * sin($a_rad));
12080			$p2[] = $y0 + ($r * cos($a_rad));
12081			$visited[] = false;
12082		}
12083		$p = array();
12084		$i = 0;
12085		do {
12086			$p[] = $p2[$i * 2];
12087			$p[] = $p2[($i * 2) + 1];
12088			$visited[$i] = true;
12089			$i += $ng;
12090			$i %= $nv;
12091		} while (!$visited[$i]);
12092		$this->Polygon($p, $style, $line_style, $fill_color);
12093	}
12094
12095	/**
12096	 * Draws a rounded rectangle.
12097	 * @param $x (float) Abscissa of upper-left corner.
12098	 * @param $y (float) Ordinate of upper-left corner.
12099	 * @param $w (float) Width.
12100	 * @param $h (float) Height.
12101	 * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
12102	 * @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").
12103	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
12104	 * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
12105	 * @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).
12106	 * @public
12107	 * @since 2.1.000 (2008-01-08)
12108	 */
12109	public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
12110		$this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
12111	}
12112
12113	/**
12114	 * Draws a rounded rectangle.
12115	 * @param $x (float) Abscissa of upper-left corner.
12116	 * @param $y (float) Ordinate of upper-left corner.
12117	 * @param $w (float) Width.
12118	 * @param $h (float) Height.
12119	 * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
12120	 * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
12121	 * @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").
12122	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
12123	 * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
12124	 * @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).
12125	 * @public
12126	 * @since 4.9.019 (2010-04-22)
12127	 */
12128	public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
12129		if ($this->state != 2) {
12130			return;
12131		}
12132		if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
12133			// Not rounded
12134			$this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
12135			return;
12136		}
12137		// Rounded
12138		if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
12139			$this->SetFillColorArray($fill_color);
12140		}
12141		$op = TCPDF_STATIC::getPathPaintOperator($style);
12142		if ($op == 'f') {
12143			$border_style = array();
12144		}
12145		if ($border_style) {
12146			$this->SetLineStyle($border_style);
12147		}
12148		$MyArc = 4 / 3 * (sqrt(2) - 1);
12149		$this->_outPoint($x + $rx, $y);
12150		$xc = $x + $w - $rx;
12151		$yc = $y + $ry;
12152		$this->_outLine($xc, $y);
12153		if ($round_corner[0]) {
12154			$this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
12155		} else {
12156			$this->_outLine($x + $w, $y);
12157		}
12158		$xc = $x + $w - $rx;
12159		$yc = $y + $h - $ry;
12160		$this->_outLine($x + $w, $yc);
12161		if ($round_corner[1]) {
12162			$this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
12163		} else {
12164			$this->_outLine($x + $w, $y + $h);
12165		}
12166		$xc = $x + $rx;
12167		$yc = $y + $h - $ry;
12168		$this->_outLine($xc, $y + $h);
12169		if ($round_corner[2]) {
12170			$this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
12171		} else {
12172			$this->_outLine($x, $y + $h);
12173		}
12174		$xc = $x + $rx;
12175		$yc = $y + $ry;
12176		$this->_outLine($x, $yc);
12177		if ($round_corner[3]) {
12178			$this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
12179		} else {
12180			$this->_outLine($x, $y);
12181			$this->_outLine($x + $rx, $y);
12182		}
12183		$this->_out($op);
12184	}
12185
12186	/**
12187	 * Draws a grahic arrow.
12188	 * @param $x0 (float) Abscissa of first point.
12189	 * @param $y0 (float) Ordinate of first point.
12190	 * @param $x1 (float) Abscissa of second point.
12191	 * @param $y1 (float) Ordinate of second point.
12192	 * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
12193	 * @param $arm_size (float) length of arrowhead arms
12194	 * @param $arm_angle (int) angle between an arm and the shaft
12195	 * @author Piotr Galecki, Nicola Asuni, Andy Meier
12196	 * @since 4.6.018 (2009-07-10)
12197	 */
12198	public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
12199		// getting arrow direction angle
12200		// 0 deg angle is when both arms go along X axis. angle grows clockwise.
12201		$dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
12202		if ($dir_angle < 0) {
12203			$dir_angle += (2 * M_PI);
12204		}
12205		$arm_angle = deg2rad($arm_angle);
12206		$sx1 = $x1;
12207		$sy1 = $y1;
12208		if ($head_style > 0) {
12209			// calculate the stopping point for the arrow shaft
12210			$sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
12211			$sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
12212		}
12213		// main arrow line / shaft
12214		$this->Line($x0, $y0, $sx1, $sy1);
12215		// left arrowhead arm tip
12216		$x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
12217		$y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
12218		// right arrowhead arm tip
12219		$x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
12220		$y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
12221		$mode = 'D';
12222		$style = array();
12223		switch ($head_style) {
12224			case 0: {
12225				// draw only arrowhead arms
12226				$mode = 'D';
12227				$style = array(1, 1, 0);
12228				break;
12229			}
12230			case 1: {
12231				// draw closed arrowhead, but no fill
12232				$mode = 'D';
12233				break;
12234			}
12235			case 2: {
12236				// closed and filled arrowhead
12237				$mode = 'DF';
12238				break;
12239			}
12240			case 3: {
12241				// filled arrowhead
12242				$mode = 'F';
12243				break;
12244			}
12245		}
12246		$this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
12247	}
12248
12249	// END GRAPHIC FUNCTIONS SECTION -----------------------
12250
12251	/**
12252	 * Add a Named Destination.
12253	 * NOTE: destination names are unique, so only last entry will be saved.
12254	 * @param $name (string) Destination name.
12255	 * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
12256	 * @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.
12257	 * @param $x (float) X position in user units of the destiantion on the selected page (default = -1 = current position;).
12258	 * @return (string) Stripped named destination identifier or false in case of error.
12259	 * @public
12260	 * @author Christian Deligant, Nicola Asuni
12261	 * @since 5.9.097 (2011-06-23)
12262	 */
12263	public function setDestination($name, $y=-1, $page='', $x=-1) {
12264		// remove unsupported characters
12265		$name = TCPDF_STATIC::encodeNameObject($name);
12266		if (TCPDF_STATIC::empty_string($name)) {
12267			return false;
12268		}
12269		if ($y == -1) {
12270			$y = $this->GetY();
12271		} elseif ($y < 0) {
12272			$y = 0;
12273		} elseif ($y > $this->h) {
12274			$y = $this->h;
12275		}
12276		if ($x == -1) {
12277			$x = $this->GetX();
12278		} elseif ($x < 0) {
12279			$x = 0;
12280		} elseif ($x > $this->w) {
12281			$x = $this->w;
12282		}
12283		$fixed = false;
12284		if (!empty($page) AND (substr($page, 0, 1) == '*')) {
12285			$page = intval(substr($page, 1));
12286			// this page number will not be changed when moving/add/deleting pages
12287			$fixed = true;
12288		}
12289		if (empty($page)) {
12290			$page = $this->PageNo();
12291			if (empty($page)) {
12292				return;
12293			}
12294		}
12295		$this->dests[$name] = array('x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed);
12296		return $name;
12297	}
12298
12299	/**
12300	 * Return the Named Destination array.
12301	 * @return (array) Named Destination array.
12302	 * @public
12303	 * @author Nicola Asuni
12304	 * @since 5.9.097 (2011-06-23)
12305	 */
12306	public function getDestination() {
12307		return $this->dests;
12308	}
12309
12310	/**
12311	 * Insert Named Destinations.
12312	 * @protected
12313	 * @author Johannes G\FCntert, Nicola Asuni
12314	 * @since 5.9.098 (2011-06-23)
12315	 */
12316	protected function _putdests() {
12317		if (empty($this->dests)) {
12318			return;
12319		}
12320		$this->n_dests = $this->_newobj();
12321		$out = ' <<';
12322		foreach($this->dests as $name => $o) {
12323			$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)));
12324		}
12325		$out .= ' >>';
12326		$out .= "\n".'endobj';
12327		$this->_out($out);
12328	}
12329
12330	/**
12331	 * Adds a bookmark - alias for Bookmark().
12332	 * @param $txt (string) Bookmark description.
12333	 * @param $level (int) Bookmark level (minimum value is 0).
12334	 * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
12335	 * @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.
12336	 * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
12337	 * @param $color (array) RGB color array (values from 0 to 255).
12338	 * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
12339	 * @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).
12340	 * @public
12341	 */
12342	public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
12343		$this->Bookmark($txt, $level, $y, $page, $style, $color, $x, $link);
12344	}
12345
12346	/**
12347	 * Adds a bookmark.
12348	 * @param $txt (string) Bookmark description.
12349	 * @param $level (int) Bookmark level (minimum value is 0).
12350	 * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
12351	 * @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.
12352	 * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
12353	 * @param $color (array) RGB color array (values from 0 to 255).
12354	 * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
12355	 * @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).
12356	 * @public
12357	 * @since 2.1.002 (2008-02-12)
12358	 */
12359	public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
12360		if ($level < 0) {
12361			$level = 0;
12362		}
12363		if (isset($this->outlines[0])) {
12364			$lastoutline = end($this->outlines);
12365			$maxlevel = $lastoutline['l'] + 1;
12366		} else {
12367			$maxlevel = 0;
12368		}
12369		if ($level > $maxlevel) {
12370			$level = $maxlevel;
12371		}
12372		if ($y == -1) {
12373			$y = $this->GetY();
12374		} elseif ($y < 0) {
12375			$y = 0;
12376		} elseif ($y > $this->h) {
12377			$y = $this->h;
12378		}
12379		if ($x == -1) {
12380			$x = $this->GetX();
12381		} elseif ($x < 0) {
12382			$x = 0;
12383		} elseif ($x > $this->w) {
12384			$x = $this->w;
12385		}
12386		$fixed = false;
12387		if ((string)$page && (((string)$page)[0] == '*')) {
12388			$page = intval(substr($page, 1));
12389			// this page number will not be changed when moving/add/deleting pages
12390			$fixed = true;
12391		}
12392		if (empty($page)) {
12393			$page = $this->PageNo();
12394			if (empty($page)) {
12395				return;
12396			}
12397		}
12398		$this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);
12399	}
12400
12401	/**
12402	 * Sort bookmarks for page and key.
12403	 * @protected
12404	 * @since 5.9.119 (2011-09-19)
12405	 */
12406	protected function sortBookmarks() {
12407		// get sorting columns
12408		$outline_p = array();
12409		$outline_y = array();
12410		foreach ($this->outlines as $key => $row) {
12411			$outline_p[$key] = $row['p'];
12412			$outline_k[$key] = $key;
12413		}
12414		// sort outlines by page and original position
12415		array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
12416	}
12417
12418	/**
12419	 * Create a bookmark PDF string.
12420	 * @protected
12421	 * @author Olivier Plathey, Nicola Asuni
12422	 * @since 2.1.002 (2008-02-12)
12423	 */
12424	protected function _putbookmarks() {
12425		$nb = count($this->outlines);
12426		if ($nb == 0) {
12427			return;
12428		}
12429		// sort bookmarks
12430		$this->sortBookmarks();
12431		$lru = array();
12432		$level = 0;
12433		foreach ($this->outlines as $i => $o) {
12434			if ($o['l'] > 0) {
12435				$parent = $lru[($o['l'] - 1)];
12436				//Set parent and last pointers
12437				$this->outlines[$i]['parent'] = $parent;
12438				$this->outlines[$parent]['last'] = $i;
12439				if ($o['l'] > $level) {
12440					//Level increasing: set first pointer
12441					$this->outlines[$parent]['first'] = $i;
12442				}
12443			} else {
12444				$this->outlines[$i]['parent'] = $nb;
12445			}
12446			if (($o['l'] <= $level) AND ($i > 0)) {
12447				//Set prev and next pointers
12448				$prev = $lru[$o['l']];
12449				$this->outlines[$prev]['next'] = $i;
12450				$this->outlines[$i]['prev'] = $prev;
12451			}
12452			$lru[$o['l']] = $i;
12453			$level = $o['l'];
12454		}
12455		//Outline items
12456		$n = $this->n + 1;
12457		$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';
12458		foreach ($this->outlines as $i => $o) {
12459			$oid = $this->_newobj();
12460			// covert HTML title to string
12461			$title = preg_replace($nltags, "\n", $o['t']);
12462			$title = preg_replace("/[\r]+/si", '', $title);
12463			$title = preg_replace("/[\n]+/si", "\n", $title);
12464			$title = strip_tags($title);
12465			$title = $this->stringTrim($title);
12466			$out = '<</Title '.$this->_textstring($title, $oid);
12467			$out .= ' /Parent '.($n + $o['parent']).' 0 R';
12468			if (isset($o['prev'])) {
12469				$out .= ' /Prev '.($n + $o['prev']).' 0 R';
12470			}
12471			if (isset($o['next'])) {
12472				$out .= ' /Next '.($n + $o['next']).' 0 R';
12473			}
12474			if (isset($o['first'])) {
12475				$out .= ' /First '.($n + $o['first']).' 0 R';
12476			}
12477			if (isset($o['last'])) {
12478				$out .= ' /Last '.($n + $o['last']).' 0 R';
12479			}
12480			if (isset($o['u']) AND !empty($o['u'])) {
12481				// link
12482				if (is_string($o['u'])) {
12483					if ($o['u'][0] == '#') {
12484						// internal destination
12485						$out .= ' /Dest /'.TCPDF_STATIC::encodeNameObject(substr($o['u'], 1));
12486					} elseif ($o['u'][0] == '%') {
12487						// embedded PDF file
12488						$filename = basename(substr($o['u'], 1));
12489						$out .= ' /A <</S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($o['p'] - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
12490					} elseif ($o['u'][0] == '*') {
12491						// embedded generic file
12492						$filename = basename(substr($o['u'], 1));
12493						$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});';
12494						$out .= ' /A <</S /JavaScript /JS '.$this->_textstring($jsa, $oid).'>>';
12495					} else {
12496						// external URI link
12497						$out .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($o['u']), $oid).'>>';
12498					}
12499				} elseif (isset($this->links[$o['u']])) {
12500					// internal link ID
12501					$l = $this->links[$o['u']];
12502					if (isset($this->page_obj_id[($l['p'])])) {
12503						$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)));
12504					}
12505				}
12506			} elseif (isset($this->page_obj_id[($o['p'])])) {
12507				// link to a page
12508				$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)));
12509			}
12510			// set font style
12511			$style = 0;
12512			if (!empty($o['s'])) {
12513				// bold
12514				if (strpos($o['s'], 'B') !== false) {
12515					$style |= 2;
12516				}
12517				// oblique
12518				if (strpos($o['s'], 'I') !== false) {
12519					$style |= 1;
12520				}
12521			}
12522			$out .= sprintf(' /F %d', $style);
12523			// set bookmark color
12524			if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
12525				$color = array_values($o['c']);
12526				$out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
12527			} else {
12528				// black
12529				$out .= ' /C [0.0 0.0 0.0]';
12530			}
12531			$out .= ' /Count 0'; // normally closed item
12532			$out .= ' >>';
12533			$out .= "\n".'endobj';
12534			$this->_out($out);
12535		}
12536		//Outline root
12537		$this->OutlineRoot = $this->_newobj();
12538		$this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
12539	}
12540
12541	// --- JAVASCRIPT ------------------------------------------------------
12542
12543	/**
12544	 * Adds a javascript
12545	 * @param $script (string) Javascript code
12546	 * @public
12547	 * @author Johannes G\FCntert, Nicola Asuni
12548	 * @since 2.1.002 (2008-02-12)
12549	 */
12550	public function IncludeJS($script) {
12551		$this->javascript .= $script;
12552	}
12553
12554	/**
12555	 * Adds a javascript object and return object ID
12556	 * @param $script (string) Javascript code
12557	 * @param $onload (boolean) if true executes this object when opening the document
12558	 * @return int internal object ID
12559	 * @public
12560	 * @author Nicola Asuni
12561	 * @since 4.8.000 (2009-09-07)
12562	 */
12563	public function addJavascriptObject($script, $onload=false) {
12564		if ($this->pdfa_mode) {
12565			// javascript is not allowed in PDF/A mode
12566			return false;
12567		}
12568		++$this->n;
12569		$this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
12570		return $this->n;
12571	}
12572
12573	/**
12574	 * Create a javascript PDF string.
12575	 * @protected
12576	 * @author Johannes G\FCntert, Nicola Asuni
12577	 * @since 2.1.002 (2008-02-12)
12578	 */
12579	protected function _putjavascript() {
12580		if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
12581			return;
12582		}
12583		if (strpos($this->javascript, 'this.addField') > 0) {
12584			if (!$this->ur['enabled']) {
12585				//$this->setUserRights();
12586			}
12587			// the following two lines are used to avoid form fields duplication after saving
12588			// The addField method only works when releasing user rights (UR3)
12589			$jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
12590			$jsb = "getField('tcpdfdocsaved').value='saved';";
12591			$this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
12592		}
12593		// name tree for javascript
12594		$this->n_js = '<< /Names [';
12595		if (!empty($this->javascript)) {
12596			$this->n_js .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
12597		}
12598		if (!empty($this->js_objects)) {
12599			foreach ($this->js_objects as $key => $val) {
12600				if ($val['onload']) {
12601					$this->n_js .= ' (JS'.$key.') '.$key.' 0 R';
12602				}
12603			}
12604		}
12605		$this->n_js .= ' ] >>';
12606		// default Javascript object
12607		if (!empty($this->javascript)) {
12608			$obj_id = $this->_newobj();
12609			$out = '<< /S /JavaScript';
12610			$out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
12611			$out .= ' >>';
12612			$out .= "\n".'endobj';
12613			$this->_out($out);
12614		}
12615		// additional Javascript objects
12616		if (!empty($this->js_objects)) {
12617			foreach ($this->js_objects as $key => $val) {
12618				$out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
12619				$this->_out($out);
12620			}
12621		}
12622	}
12623
12624	/**
12625	 * Adds a javascript form field.
12626	 * @param $type (string) field type
12627	 * @param $name (string) field name
12628	 * @param $x (int) horizontal position
12629	 * @param $y (int) vertical position
12630	 * @param $w (int) width
12631	 * @param $h (int) height
12632	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12633	 * @protected
12634	 * @author Denis Van Nuffelen, Nicola Asuni
12635	 * @since 2.1.002 (2008-02-12)
12636	 */
12637	protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
12638		if ($this->rtl) {
12639			$x = $x - $w;
12640		}
12641		// the followind avoid fields duplication after saving the document
12642		$this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
12643		$k = $this->k;
12644		$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";
12645		$this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
12646		foreach($prop as $key => $val) {
12647			if (strcmp(substr($key, -5), 'Color') == 0) {
12648				$val = TCPDF_COLORS::_JScolor($val);
12649			} else {
12650				$val = "'".$val."'";
12651			}
12652			$this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
12653		}
12654		if ($this->rtl) {
12655			$this->x -= $w;
12656		} else {
12657			$this->x += $w;
12658		}
12659		$this->javascript .= '}';
12660	}
12661
12662	// --- FORM FIELDS -----------------------------------------------------
12663
12664
12665
12666	/**
12667	 * Set default properties for form fields.
12668	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12669	 * @public
12670	 * @author Nicola Asuni
12671	 * @since 4.8.000 (2009-09-06)
12672	 */
12673	public function setFormDefaultProp($prop=array()) {
12674		$this->default_form_prop = $prop;
12675	}
12676
12677	/**
12678	 * Return the default properties for form fields.
12679	 * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12680	 * @public
12681	 * @author Nicola Asuni
12682	 * @since 4.8.000 (2009-09-06)
12683	 */
12684	public function getFormDefaultProp() {
12685		return $this->default_form_prop;
12686	}
12687
12688	/**
12689	 * Creates a text field
12690	 * @param $name (string) field name
12691	 * @param $w (float) Width of the rectangle
12692	 * @param $h (float) Height of the rectangle
12693	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12694	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
12695	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
12696	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
12697	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
12698	 * @public
12699	 * @author Nicola Asuni
12700	 * @since 4.8.000 (2009-09-07)
12701	 */
12702	public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
12703		if ($x === '') {
12704			$x = $this->x;
12705		}
12706		if ($y === '') {
12707			$y = $this->y;
12708		}
12709		// check page for no-write regions and adapt page margins if necessary
12710		list($x, $y) = $this->checkPageRegions($h, $x, $y);
12711		if ($js) {
12712			$this->_addfield('text', $name, $x, $y, $w, $h, $prop);
12713			return;
12714		}
12715		// get default style
12716		$prop = array_merge($this->getFormDefaultProp(), $prop);
12717		// get annotation data
12718		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
12719		// set default appearance stream
12720		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
12721		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
12722		$popt['da'] = $fontstyle;
12723		// build appearance stream
12724		$popt['ap'] = array();
12725		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
12726		$text = '';
12727		if (isset($prop['value']) AND !empty($prop['value'])) {
12728			$text = $prop['value'];
12729		} elseif (isset($opt['v']) AND !empty($opt['v'])) {
12730			$text = $opt['v'];
12731		}
12732		$tmpid = $this->startTemplate($w, $h, false);
12733		$align = '';
12734		if (isset($popt['q'])) {
12735			switch ($popt['q']) {
12736				case 0: {
12737					$align = 'L';
12738					break;
12739				}
12740				case 1: {
12741					$align = 'C';
12742					break;
12743				}
12744				case 2: {
12745					$align = 'R';
12746					break;
12747				}
12748				default: {
12749					$align = '';
12750					break;
12751				}
12752			}
12753		}
12754		$this->MultiCell($w, $h, $text, 0, $align, false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
12755		$this->endTemplate();
12756		--$this->n;
12757		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
12758		unset($this->xobjects[$tmpid]);
12759		$popt['ap']['n'] .= 'Q EMC';
12760		// merge options
12761		$opt = array_merge($popt, $opt);
12762		// remove some conflicting options
12763		unset($opt['bs']);
12764		// set remaining annotation data
12765		$opt['Subtype'] = 'Widget';
12766		$opt['ft'] = 'Tx';
12767		$opt['t'] = $name;
12768		// Additional annotation's parameters (check _putannotsobj() method):
12769		//$opt['f']
12770		//$opt['as']
12771		//$opt['bs']
12772		//$opt['be']
12773		//$opt['c']
12774		//$opt['border']
12775		//$opt['h']
12776		//$opt['mk'];
12777		//$opt['mk']['r']
12778		//$opt['mk']['bc'];
12779		//$opt['mk']['bg'];
12780		unset($opt['mk']['ca']);
12781		unset($opt['mk']['rc']);
12782		unset($opt['mk']['ac']);
12783		unset($opt['mk']['i']);
12784		unset($opt['mk']['ri']);
12785		unset($opt['mk']['ix']);
12786		unset($opt['mk']['if']);
12787		//$opt['mk']['if']['sw'];
12788		//$opt['mk']['if']['s'];
12789		//$opt['mk']['if']['a'];
12790		//$opt['mk']['if']['fb'];
12791		unset($opt['mk']['tp']);
12792		//$opt['tu']
12793		//$opt['tm']
12794		//$opt['ff']
12795		//$opt['v']
12796		//$opt['dv']
12797		//$opt['a']
12798		//$opt['aa']
12799		//$opt['q']
12800		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
12801		if ($this->rtl) {
12802			$this->x -= $w;
12803		} else {
12804			$this->x += $w;
12805		}
12806	}
12807
12808	/**
12809	 * Creates a RadioButton field.
12810	 * @param $name (string) Field name.
12811	 * @param $w (int) Width of the radio button.
12812	 * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12813	 * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
12814	 * @param $onvalue (string) Value to be returned if selected.
12815	 * @param $checked (boolean) Define the initial state.
12816	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
12817	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
12818	 * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
12819	 * @public
12820	 * @author Nicola Asuni
12821	 * @since 4.8.000 (2009-09-07)
12822	 */
12823	public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
12824		if ($x === '') {
12825			$x = $this->x;
12826		}
12827		if ($y === '') {
12828			$y = $this->y;
12829		}
12830		// check page for no-write regions and adapt page margins if necessary
12831		list($x, $y) = $this->checkPageRegions($w, $x, $y);
12832		if ($js) {
12833			$this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
12834			return;
12835		}
12836		if (TCPDF_STATIC::empty_string($onvalue)) {
12837			$onvalue = 'On';
12838		}
12839		if ($checked) {
12840			$defval = $onvalue;
12841		} else {
12842			$defval = 'Off';
12843		}
12844		// set font
12845		$font = 'zapfdingbats';
12846		if ($this->pdfa_mode) {
12847			// all fonts must be embedded
12848			$font = 'pdfa'.$font;
12849		}
12850		$this->AddFont($font);
12851		$tmpfont = $this->getFontBuffer($font);
12852		// set data for parent group
12853		if (!isset($this->radiobutton_groups[$this->page])) {
12854			$this->radiobutton_groups[$this->page] = array();
12855		}
12856		if (!isset($this->radiobutton_groups[$this->page][$name])) {
12857			$this->radiobutton_groups[$this->page][$name] = array();
12858			++$this->n;
12859			$this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
12860			$this->radio_groups[] = $this->n;
12861		}
12862		$kid = ($this->n + 1);
12863		// save object ID to be added on Kids entry on parent object
12864		$this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
12865		// get default style
12866		$prop = array_merge($this->getFormDefaultProp(), $prop);
12867		$prop['NoToggleToOff'] = 'true';
12868		$prop['Radio'] = 'true';
12869		$prop['borderStyle'] = 'inset';
12870		// get annotation data
12871		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
12872		// set additional default options
12873		$this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
12874		$fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
12875		$popt['da'] = $fontstyle;
12876		// build appearance stream
12877		$popt['ap'] = array();
12878		$popt['ap']['n'] = array();
12879		$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][108])) / 2) * $this->k);
12880		$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
12881		$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);
12882		$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);
12883		if (!isset($popt['mk'])) {
12884			$popt['mk'] = array();
12885		}
12886		$popt['mk']['ca'] = '(l)';
12887		// merge options
12888		$opt = array_merge($popt, $opt);
12889		// set remaining annotation data
12890		$opt['Subtype'] = 'Widget';
12891		$opt['ft'] = 'Btn';
12892		if ($checked) {
12893			$opt['v'] = array('/'.$onvalue);
12894			$opt['as'] = $onvalue;
12895		} else {
12896			$opt['as'] = 'Off';
12897		}
12898		// store readonly flag
12899		if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
12900			$this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
12901		}
12902		$this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
12903		$this->Annotation($x, $y, $w, $w, $name, $opt, 0);
12904		if ($this->rtl) {
12905			$this->x -= $w;
12906		} else {
12907			$this->x += $w;
12908		}
12909	}
12910
12911	/**
12912	 * Creates a List-box field
12913	 * @param $name (string) field name
12914	 * @param $w (int) width
12915	 * @param $h (int) height
12916	 * @param $values (array) array containing the list of values.
12917	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12918	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
12919	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
12920	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
12921	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
12922	 * @public
12923	 * @author Nicola Asuni
12924	 * @since 4.8.000 (2009-09-07)
12925	 */
12926	public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
12927		if ($x === '') {
12928			$x = $this->x;
12929		}
12930		if ($y === '') {
12931			$y = $this->y;
12932		}
12933		// check page for no-write regions and adapt page margins if necessary
12934		list($x, $y) = $this->checkPageRegions($h, $x, $y);
12935		if ($js) {
12936			$this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
12937			$s = '';
12938			foreach ($values as $value) {
12939				if (is_array($value)) {
12940					$s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
12941				} else {
12942					$s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
12943				}
12944			}
12945			$this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
12946			return;
12947		}
12948		// get default style
12949		$prop = array_merge($this->getFormDefaultProp(), $prop);
12950		// get annotation data
12951		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
12952		// set additional default values
12953		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
12954		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
12955		$popt['da'] = $fontstyle;
12956		// build appearance stream
12957		$popt['ap'] = array();
12958		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
12959		$text = '';
12960		foreach($values as $item) {
12961			if (is_array($item)) {
12962				$text .= $item[1]."\n";
12963			} else {
12964				$text .= $item."\n";
12965			}
12966		}
12967		$tmpid = $this->startTemplate($w, $h, false);
12968		$this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
12969		$this->endTemplate();
12970		--$this->n;
12971		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
12972		unset($this->xobjects[$tmpid]);
12973		$popt['ap']['n'] .= 'Q EMC';
12974		// merge options
12975		$opt = array_merge($popt, $opt);
12976		// set remaining annotation data
12977		$opt['Subtype'] = 'Widget';
12978		$opt['ft'] = 'Ch';
12979		$opt['t'] = $name;
12980		$opt['opt'] = $values;
12981		unset($opt['mk']['ca']);
12982		unset($opt['mk']['rc']);
12983		unset($opt['mk']['ac']);
12984		unset($opt['mk']['i']);
12985		unset($opt['mk']['ri']);
12986		unset($opt['mk']['ix']);
12987		unset($opt['mk']['if']);
12988		unset($opt['mk']['tp']);
12989		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
12990		if ($this->rtl) {
12991			$this->x -= $w;
12992		} else {
12993			$this->x += $w;
12994		}
12995	}
12996
12997	/**
12998	 * Creates a Combo-box field
12999	 * @param $name (string) field name
13000	 * @param $w (int) width
13001	 * @param $h (int) height
13002	 * @param $values (array) array containing the list of values.
13003	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13004	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
13005	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
13006	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
13007	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13008	 * @public
13009	 * @author Nicola Asuni
13010	 * @since 4.8.000 (2009-09-07)
13011	 */
13012	public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
13013		if ($x === '') {
13014			$x = $this->x;
13015		}
13016		if ($y === '') {
13017			$y = $this->y;
13018		}
13019		// check page for no-write regions and adapt page margins if necessary
13020		list($x, $y) = $this->checkPageRegions($h, $x, $y);
13021		if ($js) {
13022			$this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
13023			$s = '';
13024			foreach ($values as $value) {
13025				if (is_array($value)) {
13026					$s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
13027				} else {
13028					$s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
13029				}
13030			}
13031			$this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
13032			return;
13033		}
13034		// get default style
13035		$prop = array_merge($this->getFormDefaultProp(), $prop);
13036		$prop['Combo'] = true;
13037		// get annotation data
13038		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
13039		// set additional default options
13040		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
13041		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
13042		$popt['da'] = $fontstyle;
13043		// build appearance stream
13044		$popt['ap'] = array();
13045		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
13046		$text = '';
13047		foreach($values as $item) {
13048			if (is_array($item)) {
13049				$text .= $item[1]."\n";
13050			} else {
13051				$text .= $item."\n";
13052			}
13053		}
13054		$tmpid = $this->startTemplate($w, $h, false);
13055		$this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
13056		$this->endTemplate();
13057		--$this->n;
13058		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
13059		unset($this->xobjects[$tmpid]);
13060		$popt['ap']['n'] .= 'Q EMC';
13061		// merge options
13062		$opt = array_merge($popt, $opt);
13063		// set remaining annotation data
13064		$opt['Subtype'] = 'Widget';
13065		$opt['ft'] = 'Ch';
13066		$opt['t'] = $name;
13067		$opt['opt'] = $values;
13068		unset($opt['mk']['ca']);
13069		unset($opt['mk']['rc']);
13070		unset($opt['mk']['ac']);
13071		unset($opt['mk']['i']);
13072		unset($opt['mk']['ri']);
13073		unset($opt['mk']['ix']);
13074		unset($opt['mk']['if']);
13075		unset($opt['mk']['tp']);
13076		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
13077		if ($this->rtl) {
13078			$this->x -= $w;
13079		} else {
13080			$this->x += $w;
13081		}
13082	}
13083
13084	/**
13085	 * Creates a CheckBox field
13086	 * @param $name (string) field name
13087	 * @param $w (int) width
13088	 * @param $checked (boolean) define the initial state.
13089	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13090	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
13091	 * @param $onvalue (string) value to be returned if selected.
13092	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
13093	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
13094	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13095	 * @public
13096	 * @author Nicola Asuni
13097	 * @since 4.8.000 (2009-09-07)
13098	 */
13099	public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
13100		if ($x === '') {
13101			$x = $this->x;
13102		}
13103		if ($y === '') {
13104			$y = $this->y;
13105		}
13106		// check page for no-write regions and adapt page margins if necessary
13107		list($x, $y) = $this->checkPageRegions($w, $x, $y);
13108		if ($js) {
13109			$this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
13110			return;
13111		}
13112		if (!isset($prop['value'])) {
13113			$prop['value'] = array('Yes');
13114		}
13115		// get default style
13116		$prop = array_merge($this->getFormDefaultProp(), $prop);
13117		$prop['borderStyle'] = 'inset';
13118		// get annotation data
13119		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
13120		// set additional default options
13121		$font = 'zapfdingbats';
13122		if ($this->pdfa_mode) {
13123			// all fonts must be embedded
13124			$font = 'pdfa'.$font;
13125		}
13126		$this->AddFont($font);
13127		$tmpfont = $this->getFontBuffer($font);
13128		$this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
13129		$fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
13130		$popt['da'] = $fontstyle;
13131		// build appearance stream
13132		$popt['ap'] = array();
13133		$popt['ap']['n'] = array();
13134		$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][110])) / 2) * $this->k);
13135		$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
13136		$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);
13137		$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);
13138		// merge options
13139		$opt = array_merge($popt, $opt);
13140		// set remaining annotation data
13141		$opt['Subtype'] = 'Widget';
13142		$opt['ft'] = 'Btn';
13143		$opt['t'] = $name;
13144		if (TCPDF_STATIC::empty_string($onvalue)) {
13145			$onvalue = 'Yes';
13146		}
13147		$opt['opt'] = array($onvalue);
13148		if ($checked) {
13149			$opt['v'] = array('/Yes');
13150			$opt['as'] = 'Yes';
13151		} else {
13152			$opt['v'] = array('/Off');
13153			$opt['as'] = 'Off';
13154		}
13155		$this->Annotation($x, $y, $w, $w, $name, $opt, 0);
13156		if ($this->rtl) {
13157			$this->x -= $w;
13158		} else {
13159			$this->x += $w;
13160		}
13161	}
13162
13163	/**
13164	 * Creates a button field
13165	 * @param $name (string) field name
13166	 * @param $w (int) width
13167	 * @param $h (int) height
13168	 * @param $caption (string) caption.
13169	 * @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.
13170	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13171	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
13172	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
13173	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
13174	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13175	 * @public
13176	 * @author Nicola Asuni
13177	 * @since 4.8.000 (2009-09-07)
13178	 */
13179	public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
13180		if ($x === '') {
13181			$x = $this->x;
13182		}
13183		if ($y === '') {
13184			$y = $this->y;
13185		}
13186		// check page for no-write regions and adapt page margins if necessary
13187		list($x, $y) = $this->checkPageRegions($h, $x, $y);
13188		if ($js) {
13189			$this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
13190			$this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
13191			$this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
13192			$this->javascript .= 'f'.$name.".highlight='push';\n";
13193			$this->javascript .= 'f'.$name.".print=false;\n";
13194			return;
13195		}
13196		// get default style
13197		$prop = array_merge($this->getFormDefaultProp(), $prop);
13198		$prop['Pushbutton'] = 'true';
13199		$prop['highlight'] = 'push';
13200		$prop['display'] = 'display.noPrint';
13201		// get annotation data
13202		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
13203		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
13204		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
13205		$popt['da'] = $fontstyle;
13206		// build appearance stream
13207		$popt['ap'] = array();
13208		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
13209		$tmpid = $this->startTemplate($w, $h, false);
13210		$bw = (2 / $this->k); // border width
13211		$border = array(
13212			'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
13213			'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
13214			'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
13215			'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
13216		$this->SetFillColor(204);
13217		$this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
13218		$this->endTemplate();
13219		--$this->n;
13220		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
13221		unset($this->xobjects[$tmpid]);
13222		$popt['ap']['n'] .= 'Q EMC';
13223		// set additional default options
13224		if (!isset($popt['mk'])) {
13225			$popt['mk'] = array();
13226		}
13227		$ann_obj_id = ($this->n + 1);
13228		if (!empty($action) AND !is_array($action)) {
13229			$ann_obj_id = ($this->n + 2);
13230		}
13231		$popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
13232		$popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
13233		$popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
13234		// merge options
13235		$opt = array_merge($popt, $opt);
13236		// set remaining annotation data
13237		$opt['Subtype'] = 'Widget';
13238		$opt['ft'] = 'Btn';
13239		$opt['t'] = $caption;
13240		$opt['v'] = $name;
13241		if (!empty($action)) {
13242			if (is_array($action)) {
13243				// form action options as on section 12.7.5 of PDF32000_2008.
13244				$opt['aa'] = '/D <<';
13245				$bmode = array('SubmitForm', 'ResetForm', 'ImportData');
13246				foreach ($action AS $key => $val) {
13247					if (($key == 'S') AND in_array($val, $bmode)) {
13248						$opt['aa'] .= ' /S /'.$val;
13249					} elseif (($key == 'F') AND (!empty($val))) {
13250						$opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
13251					} elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
13252						$opt['aa'] .= ' /Fields [';
13253						foreach ($val AS $field) {
13254							$opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
13255						}
13256						$opt['aa'] .= ']';
13257					} elseif (($key == 'Flags')) {
13258						$ff = 0;
13259						if (is_array($val)) {
13260							foreach ($val AS $flag) {
13261								switch ($flag) {
13262									case 'Include/Exclude': {
13263										$ff += 1 << 0;
13264										break;
13265									}
13266									case 'IncludeNoValueFields': {
13267										$ff += 1 << 1;
13268										break;
13269									}
13270									case 'ExportFormat': {
13271										$ff += 1 << 2;
13272										break;
13273									}
13274									case 'GetMethod': {
13275										$ff += 1 << 3;
13276										break;
13277									}
13278									case 'SubmitCoordinates': {
13279										$ff += 1 << 4;
13280										break;
13281									}
13282									case 'XFDF': {
13283										$ff += 1 << 5;
13284										break;
13285									}
13286									case 'IncludeAppendSaves': {
13287										$ff += 1 << 6;
13288										break;
13289									}
13290									case 'IncludeAnnotations': {
13291										$ff += 1 << 7;
13292										break;
13293									}
13294									case 'SubmitPDF': {
13295										$ff += 1 << 8;
13296										break;
13297									}
13298									case 'CanonicalFormat': {
13299										$ff += 1 << 9;
13300										break;
13301									}
13302									case 'ExclNonUserAnnots': {
13303										$ff += 1 << 10;
13304										break;
13305									}
13306									case 'ExclFKey': {
13307										$ff += 1 << 11;
13308										break;
13309									}
13310									case 'EmbedForm': {
13311										$ff += 1 << 13;
13312										break;
13313									}
13314								}
13315							}
13316						} else {
13317							$ff = intval($val);
13318						}
13319						$opt['aa'] .= ' /Flags '.$ff;
13320					}
13321				}
13322				$opt['aa'] .= ' >>';
13323			} else {
13324				// Javascript action or raw action command
13325				$js_obj_id = $this->addJavascriptObject($action);
13326				$opt['aa'] = '/D '.$js_obj_id.' 0 R';
13327			}
13328		}
13329		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
13330		if ($this->rtl) {
13331			$this->x -= $w;
13332		} else {
13333			$this->x += $w;
13334		}
13335	}
13336
13337	// --- END FORMS FIELDS ------------------------------------------------
13338
13339	/**
13340	 * Add certification signature (DocMDP or UR3)
13341	 * You can set only one signature type
13342	 * @protected
13343	 * @author Nicola Asuni
13344	 * @since 4.6.008 (2009-05-07)
13345	 */
13346	protected function _putsignature() {
13347		if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
13348			return;
13349		}
13350		$sigobjid = ($this->sig_obj_id + 1);
13351		$out = $this->_getobj($sigobjid)."\n";
13352		$out .= '<< /Type /Sig';
13353		$out .= ' /Filter /Adobe.PPKLite';
13354		$out .= ' /SubFilter /adbe.pkcs7.detached';
13355		$out .= ' '.TCPDF_STATIC::$byterange_string;
13356		$out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
13357		if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
13358			$out .= ' /Reference ['; // array of signature reference dictionaries
13359			$out .= ' << /Type /SigRef';
13360			if ($this->signature_data['cert_type'] > 0) {
13361				$out .= ' /TransformMethod /DocMDP';
13362				$out .= ' /TransformParams <<';
13363				$out .= ' /Type /TransformParams';
13364				$out .= ' /P '.$this->signature_data['cert_type'];
13365				$out .= ' /V /1.2';
13366			} else {
13367				$out .= ' /TransformMethod /UR3';
13368				$out .= ' /TransformParams <<';
13369				$out .= ' /Type /TransformParams';
13370				$out .= ' /V /2.2';
13371				if (!TCPDF_STATIC::empty_string($this->ur['document'])) {
13372					$out .= ' /Document['.$this->ur['document'].']';
13373				}
13374				if (!TCPDF_STATIC::empty_string($this->ur['form'])) {
13375					$out .= ' /Form['.$this->ur['form'].']';
13376				}
13377				if (!TCPDF_STATIC::empty_string($this->ur['signature'])) {
13378					$out .= ' /Signature['.$this->ur['signature'].']';
13379				}
13380				if (!TCPDF_STATIC::empty_string($this->ur['annots'])) {
13381					$out .= ' /Annots['.$this->ur['annots'].']';
13382				}
13383				if (!TCPDF_STATIC::empty_string($this->ur['ef'])) {
13384					$out .= ' /EF['.$this->ur['ef'].']';
13385				}
13386				if (!TCPDF_STATIC::empty_string($this->ur['formex'])) {
13387					$out .= ' /FormEX['.$this->ur['formex'].']';
13388				}
13389			}
13390			$out .= ' >>'; // close TransformParams
13391			// optional digest data (values must be calculated and replaced later)
13392			//$out .= ' /Data ********** 0 R';
13393			//$out .= ' /DigestMethod/MD5';
13394			//$out .= ' /DigestLocation[********** 34]';
13395			//$out .= ' /DigestValue<********************************>';
13396			$out .= ' >>';
13397			$out .= ' ]'; // end of reference
13398		}
13399		if (isset($this->signature_data['info']['Name']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Name'])) {
13400			$out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
13401		}
13402		if (isset($this->signature_data['info']['Location']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Location'])) {
13403			$out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
13404		}
13405		if (isset($this->signature_data['info']['Reason']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Reason'])) {
13406			$out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
13407		}
13408		if (isset($this->signature_data['info']['ContactInfo']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['ContactInfo'])) {
13409			$out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
13410		}
13411		$out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp);
13412		$out .= ' >>';
13413		$out .= "\n".'endobj';
13414		$this->_out($out);
13415	}
13416
13417	/**
13418	 * Set User's Rights for PDF Reader
13419	 * WARNING: This is experimental and currently do not work.
13420	 * Check the PDF Reference 8.7.1 Transform Methods,
13421	 * Table 8.105 Entries in the UR transform parameters dictionary
13422	 * @param $enable (boolean) if true enable user's rights on PDF reader
13423	 * @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.
13424	 * @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.
13425	 * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
13426	 * @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.
13427	 * @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
13428	 Names specifying additional embedded-files-related usage rights for the document.
13429	 * @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.
13430	 * @public
13431	 * @author Nicola Asuni
13432	 * @since 2.9.000 (2008-03-26)
13433	 */
13434	public function setUserRights(
13435			$enable=true,
13436			$document='/FullSave',
13437			$annots='/Create/Delete/Modify/Copy/Import/Export',
13438			$form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
13439			$signature='/Modify',
13440			$ef='/Create/Delete/Modify/Import',
13441			$formex='') {
13442		$this->ur['enabled'] = $enable;
13443		$this->ur['document'] = $document;
13444		$this->ur['annots'] = $annots;
13445		$this->ur['form'] = $form;
13446		$this->ur['signature'] = $signature;
13447		$this->ur['ef'] = $ef;
13448		$this->ur['formex'] = $formex;
13449		if (!$this->sign) {
13450			$this->setSignature('', '', '', '', 0, array());
13451		}
13452	}
13453
13454	/**
13455	 * Enable document signature (requires the OpenSSL Library).
13456	 * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
13457	 * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
13458	 * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
13459	 * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
13460	 * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
13461	 * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
13462	 * @param $private_key_password (string) password
13463	 * @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.
13464	 * @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.
13465	 * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
13466	 * @param $approval (string) Enable approval signature eg. for PDF incremental update
13467	 * @public
13468	 * @author Nicola Asuni
13469	 * @since 4.6.005 (2009-04-24)
13470	 */
13471	public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array(), $approval='') {
13472		// to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
13473		// to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
13474		// to convert pfx certificate to pem: openssl
13475		//     OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
13476		$this->sign = true;
13477		++$this->n;
13478		$this->sig_obj_id = $this->n; // signature widget
13479		++$this->n; // signature object ($this->sig_obj_id + 1)
13480		$this->signature_data = array();
13481		if (strlen($signing_cert) == 0) {
13482			$this->Error('Please provide a certificate file and password!');
13483		}
13484		if (strlen($private_key) == 0) {
13485			$private_key = $signing_cert;
13486		}
13487		$this->signature_data['signcert'] = $signing_cert;
13488		$this->signature_data['privkey'] = $private_key;
13489		$this->signature_data['password'] = $private_key_password;
13490		$this->signature_data['extracerts'] = $extracerts;
13491		$this->signature_data['cert_type'] = $cert_type;
13492		$this->signature_data['info'] = $info;
13493		$this->signature_data['approval'] = $approval;
13494	}
13495
13496	/**
13497	 * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
13498	 * @param $x (float) Abscissa of the upper-left corner.
13499	 * @param $y (float) Ordinate of the upper-left corner.
13500	 * @param $w (float) Width of the signature area.
13501	 * @param $h (float) Height of the signature area.
13502	 * @param $page (int) option page number (if < 0 the current page is used).
13503	 * @param $name (string) Name of the signature.
13504	 * @public
13505	 * @author Nicola Asuni
13506	 * @since 5.3.011 (2010-06-17)
13507	 */
13508	public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13509		$this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
13510	}
13511
13512	/**
13513	 * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
13514	 * @param $x (float) Abscissa of the upper-left corner.
13515	 * @param $y (float) Ordinate of the upper-left corner.
13516	 * @param $w (float) Width of the signature area.
13517	 * @param $h (float) Height of the signature area.
13518	 * @param $page (int) option page number (if < 0 the current page is used).
13519	 * @param $name (string) Name of the signature.
13520	 * @public
13521	 * @author Nicola Asuni
13522	 * @since 5.9.101 (2011-07-06)
13523	 */
13524	public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13525		++$this->n;
13526		$this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
13527	}
13528
13529	/**
13530	 * Get the array that defines the signature appearance (page and rectangle coordinates).
13531	 * @param $x (float) Abscissa of the upper-left corner.
13532	 * @param $y (float) Ordinate of the upper-left corner.
13533	 * @param $w (float) Width of the signature area.
13534	 * @param $h (float) Height of the signature area.
13535	 * @param $page (int) option page number (if < 0 the current page is used).
13536	 * @param $name (string) Name of the signature.
13537	 * @return (array) Array defining page and rectangle coordinates of signature appearance.
13538	 * @protected
13539	 * @author Nicola Asuni
13540	 * @since 5.9.101 (2011-07-06)
13541	 */
13542	protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13543		$sigapp = array();
13544		if (($page < 1) OR ($page > $this->numpages)) {
13545			$sigapp['page'] = $this->page;
13546		} else {
13547			$sigapp['page'] = intval($page);
13548		}
13549		if (empty($name)) {
13550			$sigapp['name'] = 'Signature';
13551		} else {
13552			$sigapp['name'] = $name;
13553		}
13554		$a = $x * $this->k;
13555		$b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
13556		$c = $w * $this->k;
13557		$d = $h * $this->k;
13558		$sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a + $c), ($b + $d));
13559		return $sigapp;
13560	}
13561
13562	/**
13563	 * Enable document timestamping (requires the OpenSSL Library).
13564	 * The trusted timestamping improve document security that means that no one should be able to change the document once it has been recorded.
13565	 * Use with digital signature only!
13566	 * @param $tsa_host (string) Time Stamping Authority (TSA) server (prefixed with 'https://')
13567	 * @param $tsa_username (string) Specifies the username for TSA authorization (optional) OR specifies the TSA authorization PEM file (see: example_66.php, optional)
13568	 * @param $tsa_password (string) Specifies the password for TSA authorization (optional)
13569	 * @param $tsa_cert (string) Specifies the location of TSA certificate for authorization (optional for cURL)
13570	 * @public
13571	 * @author Richard Stockinger
13572	 * @since 6.0.090 (2014-06-16)
13573	 */
13574	public function setTimeStamp($tsa_host='', $tsa_username='', $tsa_password='', $tsa_cert='') {
13575		$this->tsa_data = array();
13576		if (!function_exists('curl_init')) {
13577			$this->Error('Please enable cURL PHP extension!');
13578		}
13579		if (strlen($tsa_host) == 0) {
13580			$this->Error('Please specify the host of Time Stamping Authority (TSA)!');
13581		}
13582		$this->tsa_data['tsa_host'] = $tsa_host;
13583		if (is_file($tsa_username)) {
13584			$this->tsa_data['tsa_auth'] = $tsa_username;
13585		} else {
13586			$this->tsa_data['tsa_username'] = $tsa_username;
13587		}
13588		$this->tsa_data['tsa_password'] = $tsa_password;
13589		$this->tsa_data['tsa_cert'] = $tsa_cert;
13590		$this->tsa_timestamp = true;
13591	}
13592
13593	/**
13594	 * NOT YET IMPLEMENTED
13595	 * Request TSA for a timestamp
13596	 * @param $signature (string) Digital signature as binary string
13597	 * @return (string) Timestamped digital signature
13598	 * @protected
13599	 * @author Richard Stockinger
13600	 * @since 6.0.090 (2014-06-16)
13601	 */
13602	protected function applyTSA($signature) {
13603		if (!$this->tsa_timestamp) {
13604			return $signature;
13605		}
13606		//@TODO: implement this feature
13607		return $signature;
13608	}
13609
13610	/**
13611	 * Create a new page group.
13612	 * NOTE: call this function before calling AddPage()
13613	 * @param $page (int) starting group page (leave empty for next page).
13614	 * @public
13615	 * @since 3.0.000 (2008-03-27)
13616	 */
13617	public function startPageGroup($page='') {
13618		if (empty($page)) {
13619			$page = $this->page + 1;
13620		}
13621		$this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
13622	}
13623
13624	/**
13625	 * Set the starting page number.
13626	 * @param $num (int) Starting page number.
13627	 * @since 5.9.093 (2011-06-16)
13628	 * @public
13629	 */
13630	public function setStartingPageNumber($num=1) {
13631		$this->starting_page_number = max(0, intval($num));
13632	}
13633
13634	/**
13635	 * Returns the string alias used right align page numbers.
13636	 * If the current font is unicode type, the returned string wil contain an additional open curly brace.
13637	 * @return string
13638	 * @since 5.9.099 (2011-06-27)
13639	 * @public
13640	 */
13641	public function getAliasRightShift() {
13642		// calculate aproximatively the ratio between widths of aliases and replacements.
13643		$ref = '{'.TCPDF_STATIC::$alias_right_shift.'}{'.TCPDF_STATIC::$alias_tot_pages.'}{'.TCPDF_STATIC::$alias_num_page.'}';
13644		$rep = str_repeat(' ', $this->GetNumChars($ref));
13645		$wrep = $this->GetStringWidth($rep);
13646		if ($wrep > 0) {
13647			$wdiff = max(1, ($this->GetStringWidth($ref) / $wrep));
13648		} else {
13649			$wdiff = 1;
13650		}
13651		$sdiff = sprintf('%F', $wdiff);
13652		$alias = TCPDF_STATIC::$alias_right_shift.$sdiff.'}';
13653		if ($this->isUnicodeFont()) {
13654			$alias = '{'.$alias;
13655		}
13656		return $alias;
13657	}
13658
13659	/**
13660	 * Returns the string alias used for the total number of pages.
13661	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13662	 * This alias will be replaced by the total number of pages in the document.
13663	 * @return string
13664	 * @since 4.0.018 (2008-08-08)
13665	 * @public
13666	 */
13667	public function getAliasNbPages() {
13668		if ($this->isUnicodeFont()) {
13669			return '{'.TCPDF_STATIC::$alias_tot_pages.'}';
13670		}
13671		return TCPDF_STATIC::$alias_tot_pages;
13672	}
13673
13674	/**
13675	 * Returns the string alias used for the page number.
13676	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13677	 * This alias will be replaced by the page number.
13678	 * @return string
13679	 * @since 4.5.000 (2009-01-02)
13680	 * @public
13681	 */
13682	public function getAliasNumPage() {
13683		if ($this->isUnicodeFont()) {
13684			return '{'.TCPDF_STATIC::$alias_num_page.'}';
13685		}
13686		return TCPDF_STATIC::$alias_num_page;
13687	}
13688
13689	/**
13690	 * Return the alias for the total number of pages in the current page group.
13691	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13692	 * This alias will be replaced by the total number of pages in this group.
13693	 * @return alias of the current page group
13694	 * @public
13695	 * @since 3.0.000 (2008-03-27)
13696	 */
13697	public function getPageGroupAlias() {
13698		if ($this->isUnicodeFont()) {
13699			return '{'.TCPDF_STATIC::$alias_group_tot_pages.'}';
13700		}
13701		return TCPDF_STATIC::$alias_group_tot_pages;
13702	}
13703
13704	/**
13705	 * Return the alias for the page number on the current page group.
13706	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13707	 * This alias will be replaced by the page number (relative to the belonging group).
13708	 * @return alias of the current page group
13709	 * @public
13710	 * @since 4.5.000 (2009-01-02)
13711	 */
13712	public function getPageNumGroupAlias() {
13713		if ($this->isUnicodeFont()) {
13714			return '{'.TCPDF_STATIC::$alias_group_num_page.'}';
13715		}
13716		return TCPDF_STATIC::$alias_group_num_page;
13717	}
13718
13719	/**
13720	 * Return the current page in the group.
13721	 * @return current page in the group
13722	 * @public
13723	 * @since 3.0.000 (2008-03-27)
13724	 */
13725	public function getGroupPageNo() {
13726		return $this->pagegroups[$this->currpagegroup];
13727	}
13728
13729	/**
13730	 * Returns the current group page number formatted as a string.
13731	 * @public
13732	 * @since 4.3.003 (2008-11-18)
13733	 * @see PaneNo(), formatPageNumber()
13734	 */
13735	public function getGroupPageNoFormatted() {
13736		return TCPDF_STATIC::formatPageNumber($this->getGroupPageNo());
13737	}
13738
13739	/**
13740	 * Returns the current page number formatted as a string.
13741	 * @public
13742	 * @since 4.2.005 (2008-11-06)
13743	 * @see PaneNo(), formatPageNumber()
13744	 */
13745	public function PageNoFormatted() {
13746		return TCPDF_STATIC::formatPageNumber($this->PageNo());
13747	}
13748
13749	/**
13750	 * Put pdf layers.
13751	 * @protected
13752	 * @since 3.0.000 (2008-03-27)
13753	 */
13754	protected function _putocg() {
13755		if (empty($this->pdflayers)) {
13756			return;
13757		}
13758		foreach ($this->pdflayers as $key => $layer) {
13759			 $this->pdflayers[$key]['objid'] = $this->_newobj();
13760			 $out = '<< /Type /OCG';
13761			 $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
13762			 $out .= ' /Usage <<';
13763			 if (isset($layer['print']) AND ($layer['print'] !== NULL)) {
13764				$out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
13765			 }
13766			 $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
13767			 $out .= ' >> >>';
13768			 $out .= "\n".'endobj';
13769			 $this->_out($out);
13770		}
13771	}
13772
13773	/**
13774	 * Start a new pdf layer.
13775	 * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
13776	 * @param $print (boolean|null) Set to TRUE to print this layer, FALSE to not print and NULL to not set this option
13777	 * @param $view (boolean) Set to true to view this layer.
13778	 * @param $lock (boolean) If true lock the layer
13779	 * @public
13780	 * @since 5.9.102 (2011-07-13)
13781	 */
13782	public function startLayer($name='', $print=true, $view=true, $lock=true) {
13783		if ($this->state != 2) {
13784			return;
13785		}
13786		$layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
13787		if (empty($name)) {
13788			$name = $layer;
13789		} else {
13790			$name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
13791		}
13792		$this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view, 'lock' => $lock);
13793		$this->openMarkedContent = true;
13794		$this->_out('/OC /'.$layer.' BDC');
13795	}
13796
13797	/**
13798	 * End the current PDF layer.
13799	 * @public
13800	 * @since 5.9.102 (2011-07-13)
13801	 */
13802	public function endLayer() {
13803		if ($this->state != 2) {
13804			return;
13805		}
13806		if ($this->openMarkedContent) {
13807			// close existing open marked-content layer
13808			$this->_out('EMC');
13809			$this->openMarkedContent = false;
13810		}
13811	}
13812
13813	/**
13814	 * Set the visibility of the successive elements.
13815	 * This can be useful, for instance, to put a background
13816	 * image or color that will show on screen but won't print.
13817	 * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
13818	 * @public
13819	 * @since 3.0.000 (2008-03-27)
13820	 */
13821	public function setVisibility($v) {
13822		if ($this->state != 2) {
13823			return;
13824		}
13825		$this->endLayer();
13826		switch($v) {
13827			case 'print': {
13828				$this->startLayer('Print', true, false);
13829				break;
13830			}
13831			case 'view':
13832			case 'screen': {
13833				$this->startLayer('View', false, true);
13834				break;
13835			}
13836			case 'all': {
13837				$this->_out('');
13838				break;
13839			}
13840			default: {
13841				$this->Error('Incorrect visibility: '.$v);
13842				break;
13843			}
13844		}
13845	}
13846
13847	/**
13848	 * Add transparency parameters to the current extgstate
13849	 * @param $parms (array) parameters
13850	 * @return the number of extgstates
13851	 * @protected
13852	 * @since 3.0.000 (2008-03-27)
13853	 */
13854	protected function addExtGState($parms) {
13855		if ($this->pdfa_mode) {
13856			// transparencies are not allowed in PDF/A mode
13857			return;
13858		}
13859		// check if this ExtGState already exist
13860		foreach ($this->extgstates as $i => $ext) {
13861			if ($ext['parms'] == $parms) {
13862				if ($this->inxobj) {
13863					// we are inside an XObject template
13864					$this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
13865				}
13866				// return reference to existing ExtGState
13867				return $i;
13868			}
13869		}
13870		$n = (count($this->extgstates) + 1);
13871		$this->extgstates[$n] = array('parms' => $parms);
13872		if ($this->inxobj) {
13873			// we are inside an XObject template
13874			$this->xobjects[$this->xobjid]['extgstates'][$n] = $this->extgstates[$n];
13875		}
13876		return $n;
13877	}
13878
13879	/**
13880	 * Add an extgstate
13881	 * @param $gs (array) extgstate
13882	 * @protected
13883	 * @since 3.0.000 (2008-03-27)
13884	 */
13885	protected function setExtGState($gs) {
13886		if ($this->pdfa_mode OR ($this->state != 2)) {
13887			// transparency is not allowed in PDF/A mode
13888			return;
13889		}
13890		$this->_out(sprintf('/GS%d gs', $gs));
13891	}
13892
13893	/**
13894	 * Put extgstates for object transparency
13895	 * @protected
13896	 * @since 3.0.000 (2008-03-27)
13897	 */
13898	protected function _putextgstates() {
13899		foreach ($this->extgstates as $i => $ext) {
13900			$this->extgstates[$i]['n'] = $this->_newobj();
13901			$out = '<< /Type /ExtGState';
13902			foreach ($ext['parms'] as $k => $v) {
13903				if (is_float($v)) {
13904					$v = sprintf('%F', $v);
13905				} elseif ($v === true) {
13906					$v = 'true';
13907				} elseif ($v === false) {
13908					$v = 'false';
13909				}
13910				$out .= ' /'.$k.' '.$v;
13911			}
13912			$out .= ' >>';
13913			$out .= "\n".'endobj';
13914			$this->_out($out);
13915		}
13916	}
13917
13918	/**
13919	 * Set overprint mode for stroking (OP) and non-stroking (op) painting operations.
13920	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13921	 * @param $stroking (boolean) If true apply overprint for stroking operations.
13922	 * @param $nonstroking (boolean) If true apply overprint for painting operations other than stroking.
13923	 * @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).
13924	 * @public
13925	 * @since 5.9.152 (2012-03-23)
13926	 */
13927	public function setOverprint($stroking=true, $nonstroking='', $mode=0) {
13928		if ($this->state != 2) {
13929			return;
13930		}
13931		$stroking = $stroking ? true : false;
13932		if (TCPDF_STATIC::empty_string($nonstroking)) {
13933			// default value if not set
13934			$nonstroking = $stroking;
13935		} else {
13936			$nonstroking = $nonstroking ? true : false;
13937		}
13938		if (($mode != 0) AND ($mode != 1)) {
13939			$mode = 0;
13940		}
13941		$this->overprint = array('OP' => $stroking, 'op' => $nonstroking, 'OPM' => $mode);
13942		$gs = $this->addExtGState($this->overprint);
13943		$this->setExtGState($gs);
13944	}
13945
13946	/**
13947	 * Get the overprint mode array (OP, op, OPM).
13948	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13949	 * @return array.
13950	 * @public
13951	 * @since 5.9.152 (2012-03-23)
13952	 */
13953	public function getOverprint() {
13954		return $this->overprint;
13955	}
13956
13957	/**
13958	 * Set alpha for stroking (CA) and non-stroking (ca) operations.
13959	 * @param $stroking (float) Alpha value for stroking operations: real value from 0 (transparent) to 1 (opaque).
13960	 * @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
13961	 * @param $nonstroking (float) Alpha value for non-stroking operations: real value from 0 (transparent) to 1 (opaque).
13962	 * @param $ais (boolean)
13963	 * @public
13964	 * @since 3.0.000 (2008-03-27)
13965	 */
13966	public function setAlpha($stroking=1, $bm='Normal', $nonstroking='', $ais=false) {
13967		if ($this->pdfa_mode) {
13968			// transparency is not allowed in PDF/A mode
13969			return;
13970		}
13971		$stroking = floatval($stroking);
13972		if (TCPDF_STATIC::empty_string($nonstroking)) {
13973			// default value if not set
13974			$nonstroking = $stroking;
13975		} else {
13976			$nonstroking = floatval($nonstroking);
13977		}
13978		if ($bm[0] == '/') {
13979			// remove trailing slash
13980			$bm = substr($bm, 1);
13981		}
13982		if (!in_array($bm, array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
13983			$bm = 'Normal';
13984		}
13985		$ais = $ais ? true : false;
13986		$this->alpha = array('CA' => $stroking, 'ca' => $nonstroking, 'BM' => '/'.$bm, 'AIS' => $ais);
13987		$gs = $this->addExtGState($this->alpha);
13988		$this->setExtGState($gs);
13989	}
13990
13991	/**
13992	 * Get the alpha mode array (CA, ca, BM, AIS).
13993	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13994	 * @return array.
13995	 * @public
13996	 * @since 5.9.152 (2012-03-23)
13997	 */
13998	public function getAlpha() {
13999		return $this->alpha;
14000	}
14001
14002	/**
14003	 * Set the default JPEG compression quality (1-100)
14004	 * @param $quality (int) JPEG quality, integer between 1 and 100
14005	 * @public
14006	 * @since 3.0.000 (2008-03-27)
14007	 */
14008	public function setJPEGQuality($quality) {
14009		if (($quality < 1) OR ($quality > 100)) {
14010			$quality = 75;
14011		}
14012		$this->jpeg_quality = intval($quality);
14013	}
14014
14015	/**
14016	 * Set the default number of columns in a row for HTML tables.
14017	 * @param $cols (int) number of columns
14018	 * @public
14019	 * @since 3.0.014 (2008-06-04)
14020	 */
14021	public function setDefaultTableColumns($cols=4) {
14022		$this->default_table_columns = intval($cols);
14023	}
14024
14025	/**
14026	 * Set the height of the cell (line height) respect the font height.
14027	 * @param $h (int) cell proportion respect font height (typical value = 1.25).
14028	 * @public
14029	 * @since 3.0.014 (2008-06-04)
14030	 */
14031	public function setCellHeightRatio($h) {
14032		$this->cell_height_ratio = $h;
14033	}
14034
14035	/**
14036	 * return the height of cell repect font height.
14037	 * @public
14038	 * @since 4.0.012 (2008-07-24)
14039	 */
14040	public function getCellHeightRatio() {
14041		return $this->cell_height_ratio;
14042	}
14043
14044	/**
14045	 * Set the PDF version (check PDF reference for valid values).
14046	 * @param $version (string) PDF document version.
14047	 * @public
14048	 * @since 3.1.000 (2008-06-09)
14049	 */
14050	public function setPDFVersion($version='1.7') {
14051		if ($this->pdfa_mode && $this->pdfa_version == 1 ) {
14052			// PDF/A mode
14053			$this->PDFVersion = '1.4';
14054		} else {
14055			$this->PDFVersion = $version;
14056		}
14057	}
14058
14059	/**
14060	 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
14061	 * (see Section 8.1 of PDF reference, "Viewer Preferences").
14062	 * <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>
14063	 * @param $preferences (array) array of options.
14064	 * @author Nicola Asuni
14065	 * @public
14066	 * @since 3.1.000 (2008-06-09)
14067	 */
14068	public function setViewerPreferences($preferences) {
14069		$this->viewer_preferences = $preferences;
14070	}
14071
14072	/**
14073	 * Paints color transition registration bars
14074	 * @param $x (float) abscissa of the top left corner of the rectangle.
14075	 * @param $y (float) ordinate of the top left corner of the rectangle.
14076	 * @param $w (float) width of the rectangle.
14077	 * @param $h (float) height of the rectangle.
14078	 * @param $transition (boolean) if true prints tcolor transitions to white.
14079	 * @param $vertical (boolean) if true prints bar vertically.
14080	 * @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.
14081	 * @author Nicola Asuni
14082	 * @since 4.9.000 (2010-03-26)
14083	 * @public
14084	 */
14085	public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
14086		if (strpos($colors, 'ALLSPOT') !== false) {
14087			// expand spot colors
14088			$spot_colors = '';
14089			foreach ($this->spot_colors as $spot_color_name => $v) {
14090				$spot_colors .= ','.$spot_color_name;
14091			}
14092			if (!empty($spot_colors)) {
14093				$spot_colors = substr($spot_colors, 1);
14094				$colors = str_replace('ALLSPOT', $spot_colors, $colors);
14095			} else {
14096				$colors = str_replace('ALLSPOT', 'NONE', $colors);
14097			}
14098		}
14099		$bars = explode(',', $colors);
14100		$numbars = count($bars); // number of bars to print
14101		if ($numbars <= 0) {
14102			return;
14103		}
14104		// set bar measures
14105		if ($vertical) {
14106			$coords = array(0, 0, 0, 1);
14107			$wb = $w / $numbars; // bar width
14108			$hb = $h; // bar height
14109			$xd = $wb; // delta x
14110			$yd = 0; // delta y
14111		} else {
14112			$coords = array(1, 0, 0, 0);
14113			$wb = $w; // bar width
14114			$hb = $h / $numbars; // bar height
14115			$xd = 0; // delta x
14116			$yd = $hb; // delta y
14117		}
14118		$xb = $x;
14119		$yb = $y;
14120		foreach ($bars as $col) {
14121			switch ($col) {
14122				// set transition colors
14123				case 'A': { // BLACK (GRAYSCALE)
14124					$col_a = array(255);
14125					$col_b = array(0);
14126					break;
14127				}
14128				case 'W': { // WHITE (GRAYSCALE)
14129					$col_a = array(0);
14130					$col_b = array(255);
14131					break;
14132				}
14133				case 'R': { // RED (RGB)
14134					$col_a = array(255,255,255);
14135					$col_b = array(255,0,0);
14136					break;
14137				}
14138				case 'G': { // GREEN (RGB)
14139					$col_a = array(255,255,255);
14140					$col_b = array(0,255,0);
14141					break;
14142				}
14143				case 'B': { // BLUE (RGB)
14144					$col_a = array(255,255,255);
14145					$col_b = array(0,0,255);
14146					break;
14147				}
14148				case 'C': { // CYAN (CMYK)
14149					$col_a = array(0,0,0,0);
14150					$col_b = array(100,0,0,0);
14151					break;
14152				}
14153				case 'M': { // MAGENTA (CMYK)
14154					$col_a = array(0,0,0,0);
14155					$col_b = array(0,100,0,0);
14156					break;
14157				}
14158				case 'Y': { // YELLOW (CMYK)
14159					$col_a = array(0,0,0,0);
14160					$col_b = array(0,0,100,0);
14161					break;
14162				}
14163				case 'K': { // KEY - BLACK (CMYK)
14164					$col_a = array(0,0,0,0);
14165					$col_b = array(0,0,0,100);
14166					break;
14167				}
14168				case 'RGB': { // BLACK REGISTRATION (RGB)
14169					$col_a = array(255,255,255);
14170					$col_b = array(0,0,0);
14171					break;
14172				}
14173				case 'CMYK': { // BLACK REGISTRATION (CMYK)
14174					$col_a = array(0,0,0,0);
14175					$col_b = array(100,100,100,100);
14176					break;
14177				}
14178				case 'ALL': { // SPOT COLOR REGISTRATION
14179					$col_a = array(0,0,0,0,'None');
14180					$col_b = array(100,100,100,100,'All');
14181					break;
14182				}
14183				case 'NONE': { // SKIP THIS COLOR
14184					$col_a = array(0,0,0,0,'None');
14185					$col_b = array(0,0,0,0,'None');
14186					break;
14187				}
14188				default: { // SPECIFIC SPOT COLOR NAME
14189					$col_a = array(0,0,0,0,'None');
14190					$col_b = TCPDF_COLORS::getSpotColor($col, $this->spot_colors);
14191					if ($col_b === false) {
14192						// in case of error defaults to the registration color
14193						$col_b = array(100,100,100,100,'All');
14194					}
14195					break;
14196				}
14197			}
14198			if ($col != 'NONE') {
14199				if ($transition) {
14200					// color gradient
14201					$this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
14202				} else {
14203					$this->SetFillColorArray($col_b);
14204					// colored rectangle
14205					$this->Rect($xb, $yb, $wb, $hb, 'F', array());
14206				}
14207				$xb += $xd;
14208				$yb += $yd;
14209			}
14210		}
14211	}
14212
14213	/**
14214	 * Paints crop marks.
14215	 * @param $x (float) abscissa of the crop mark center.
14216	 * @param $y (float) ordinate of the crop mark center.
14217	 * @param $w (float) width of the crop mark.
14218	 * @param $h (float) height of the crop mark.
14219	 * @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.
14220	 * @param $color (array) crop mark color (default spot registration color).
14221	 * @author Nicola Asuni
14222	 * @since 4.9.000 (2010-03-26)
14223	 * @public
14224	 */
14225	public function cropMark($x, $y, $w, $h, $type='T,R,B,L', $color=array(100,100,100,100,'All')) {
14226		$this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
14227		$type = strtoupper($type);
14228		$type = preg_replace('/[^A-Z\-\,]*/', '', $type);
14229		// split type in single components
14230		$type = str_replace('-', ',', $type);
14231		$type = str_replace('TL', 'T,L', $type);
14232		$type = str_replace('TR', 'T,R', $type);
14233		$type = str_replace('BL', 'F,L', $type);
14234		$type = str_replace('BR', 'F,R', $type);
14235		$type = str_replace('A', 'T,L', $type);
14236		$type = str_replace('B', 'T,R', $type);
14237		$type = str_replace('T,RO', 'BO', $type);
14238		$type = str_replace('C', 'F,L', $type);
14239		$type = str_replace('D', 'F,R', $type);
14240		$crops = explode(',', strtoupper($type));
14241		// remove duplicates
14242		$crops = array_unique($crops);
14243		$dw = ($w / 4); // horizontal space to leave before the intersection point
14244		$dh = ($h / 4); // vertical space to leave before the intersection point
14245		foreach ($crops as $crop) {
14246			switch ($crop) {
14247				case 'T':
14248				case 'TOP': {
14249					$x1 = $x;
14250					$y1 = ($y - $h);
14251					$x2 = $x;
14252					$y2 = ($y - $dh);
14253					break;
14254				}
14255				case 'F':
14256				case 'BOTTOM': {
14257					$x1 = $x;
14258					$y1 = ($y + $dh);
14259					$x2 = $x;
14260					$y2 = ($y + $h);
14261					break;
14262				}
14263				case 'L':
14264				case 'LEFT': {
14265					$x1 = ($x - $w);
14266					$y1 = $y;
14267					$x2 = ($x - $dw);
14268					$y2 = $y;
14269					break;
14270				}
14271				case 'R':
14272				case 'RIGHT': {
14273					$x1 = ($x + $dw);
14274					$y1 = $y;
14275					$x2 = ($x + $w);
14276					$y2 = $y;
14277					break;
14278				}
14279			}
14280			$this->Line($x1, $y1, $x2, $y2);
14281		}
14282	}
14283
14284	/**
14285	 * Paints a registration mark
14286	 * @param $x (float) abscissa of the registration mark center.
14287	 * @param $y (float) ordinate of the registration mark center.
14288	 * @param $r (float) radius of the crop mark.
14289	 * @param $double (boolean) if true print two concentric crop marks.
14290	 * @param $cola (array) crop mark color (default spot registration color 'All').
14291	 * @param $colb (array) second crop mark color (default spot registration color 'None').
14292	 * @author Nicola Asuni
14293	 * @since 4.9.000 (2010-03-26)
14294	 * @public
14295	 */
14296	public function registrationMark($x, $y, $r, $double=false, $cola=array(100,100,100,100,'All'), $colb=array(0,0,0,0,'None')) {
14297		$line_style = array('width' => max((0.5 / $this->k),($r / 30)), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
14298		$this->SetFillColorArray($cola);
14299		$this->PieSector($x, $y, $r, 90, 180, 'F');
14300		$this->PieSector($x, $y, $r, 270, 360, 'F');
14301		$this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
14302		if ($double) {
14303			$ri = $r * 0.5;
14304			$this->SetFillColorArray($colb);
14305			$this->PieSector($x, $y, $ri, 90, 180, 'F');
14306			$this->PieSector($x, $y, $ri, 270, 360, 'F');
14307			$this->SetFillColorArray($cola);
14308			$this->PieSector($x, $y, $ri, 0, 90, 'F');
14309			$this->PieSector($x, $y, $ri, 180, 270, 'F');
14310			$this->Circle($x, $y, $ri, 0, 360, 'C', $line_style, array(), 8);
14311		}
14312	}
14313
14314	/**
14315	 * Paints a CMYK registration mark
14316	 * @param $x (float) abscissa of the registration mark center.
14317	 * @param $y (float) ordinate of the registration mark center.
14318	 * @param $r (float) radius of the crop mark.
14319	 * @author Nicola Asuni
14320	 * @since 6.0.038 (2013-09-30)
14321	 * @public
14322	 */
14323	public function registrationMarkCMYK($x, $y, $r) {
14324		// line width
14325		$lw = max((0.5 / $this->k),($r / 8));
14326		// internal radius
14327		$ri = ($r * 0.6);
14328		// external radius
14329		$re = ($r * 1.3);
14330		// Cyan
14331		$this->SetFillColorArray(array(100,0,0,0));
14332		$this->PieSector($x, $y, $ri, 270, 360, 'F');
14333		// Magenta
14334		$this->SetFillColorArray(array(0,100,0,0));
14335		$this->PieSector($x, $y, $ri, 0, 90, 'F');
14336		// Yellow
14337		$this->SetFillColorArray(array(0,0,100,0));
14338		$this->PieSector($x, $y, $ri, 90, 180, 'F');
14339		// Key - black
14340		$this->SetFillColorArray(array(0,0,0,100));
14341		$this->PieSector($x, $y, $ri, 180, 270, 'F');
14342		// registration color
14343		$line_style = array('width' => $lw, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(100,100,100,100,'All'));
14344		$this->SetFillColorArray(array(100,100,100,100,'All'));
14345		// external circle
14346		$this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
14347		// cross lines
14348		$this->Line($x, ($y - $re), $x, ($y - $ri));
14349		$this->Line($x, ($y + $ri), $x, ($y + $re));
14350		$this->Line(($x - $re), $y, ($x - $ri), $y);
14351		$this->Line(($x + $ri), $y, ($x + $re), $y);
14352	}
14353
14354	/**
14355	 * Paints a linear colour gradient.
14356	 * @param $x (float) abscissa of the top left corner of the rectangle.
14357	 * @param $y (float) ordinate of the top left corner of the rectangle.
14358	 * @param $w (float) width of the rectangle.
14359	 * @param $h (float) height of the rectangle.
14360	 * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
14361	 * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
14362	 * @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).
14363	 * @author Andreas W\FCrmser, Nicola Asuni
14364	 * @since 3.1.000 (2008-06-09)
14365	 * @public
14366	 */
14367	public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
14368		$this->Clip($x, $y, $w, $h);
14369		$this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
14370	}
14371
14372	/**
14373	 * Paints a radial colour gradient.
14374	 * @param $x (float) abscissa of the top left corner of the rectangle.
14375	 * @param $y (float) ordinate of the top left corner of the rectangle.
14376	 * @param $w (float) width of the rectangle.
14377	 * @param $h (float) height of the rectangle.
14378	 * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
14379	 * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
14380	 * @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.
14381	 * @author Andreas W\FCrmser, Nicola Asuni
14382	 * @since 3.1.000 (2008-06-09)
14383	 * @public
14384	 */
14385	public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
14386		$this->Clip($x, $y, $w, $h);
14387		$this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
14388	}
14389
14390	/**
14391	 * Paints a coons patch mesh.
14392	 * @param $x (float) abscissa of the top left corner of the rectangle.
14393	 * @param $y (float) ordinate of the top left corner of the rectangle.
14394	 * @param $w (float) width of the rectangle.
14395	 * @param $h (float) height of the rectangle.
14396	 * @param $col1 (array) first color (lower left corner) (RGB components).
14397	 * @param $col2 (array) second color (lower right corner) (RGB components).
14398	 * @param $col3 (array) third color (upper right corner) (RGB components).
14399	 * @param $col4 (array) fourth color (upper left corner) (RGB components).
14400	 * @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>
14401	 * @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
14402	 * @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
14403	 * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
14404	 * @author Andreas W\FCrmser, Nicola Asuni
14405	 * @since 3.1.000 (2008-06-09)
14406	 * @public
14407	 */
14408	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) {
14409		if ($this->pdfa_mode OR ($this->state != 2)) {
14410			return;
14411		}
14412		$this->Clip($x, $y, $w, $h);
14413		$n = count($this->gradients) + 1;
14414		$this->gradients[$n] = array();
14415		$this->gradients[$n]['type'] = 6; //coons patch mesh
14416		$this->gradients[$n]['coords'] = array();
14417		$this->gradients[$n]['antialias'] = $antialias;
14418		$this->gradients[$n]['colors'] = array();
14419		$this->gradients[$n]['transparency'] = false;
14420		//check the coords array if it is the simple array or the multi patch array
14421		if (!isset($coords[0]['f'])) {
14422			//simple array -> convert to multi patch array
14423			if (!isset($col1[1])) {
14424				$col1[1] = $col1[2] = $col1[0];
14425			}
14426			if (!isset($col2[1])) {
14427				$col2[1] = $col2[2] = $col2[0];
14428			}
14429			if (!isset($col3[1])) {
14430				$col3[1] = $col3[2] = $col3[0];
14431			}
14432			if (!isset($col4[1])) {
14433				$col4[1] = $col4[2] = $col4[0];
14434			}
14435			$patch_array[0]['f'] = 0;
14436			$patch_array[0]['points'] = $coords;
14437			$patch_array[0]['colors'][0]['r'] = $col1[0];
14438			$patch_array[0]['colors'][0]['g'] = $col1[1];
14439			$patch_array[0]['colors'][0]['b'] = $col1[2];
14440			$patch_array[0]['colors'][1]['r'] = $col2[0];
14441			$patch_array[0]['colors'][1]['g'] = $col2[1];
14442			$patch_array[0]['colors'][1]['b'] = $col2[2];
14443			$patch_array[0]['colors'][2]['r'] = $col3[0];
14444			$patch_array[0]['colors'][2]['g'] = $col3[1];
14445			$patch_array[0]['colors'][2]['b'] = $col3[2];
14446			$patch_array[0]['colors'][3]['r'] = $col4[0];
14447			$patch_array[0]['colors'][3]['g'] = $col4[1];
14448			$patch_array[0]['colors'][3]['b'] = $col4[2];
14449		} else {
14450			//multi patch array
14451			$patch_array = $coords;
14452		}
14453		$bpcd = 65535; //16 bits per coordinate
14454		//build the data stream
14455		$this->gradients[$n]['stream'] = '';
14456		$count_patch = count($patch_array);
14457		for ($i=0; $i < $count_patch; ++$i) {
14458			$this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
14459			$count_points = count($patch_array[$i]['points']);
14460			for ($j=0; $j < $count_points; ++$j) {
14461				//each point as 16 bit
14462				$patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
14463				if ($patch_array[$i]['points'][$j] < 0) {
14464					$patch_array[$i]['points'][$j] = 0;
14465				}
14466				if ($patch_array[$i]['points'][$j] > $bpcd) {
14467					$patch_array[$i]['points'][$j] = $bpcd;
14468				}
14469				$this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
14470				$this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
14471			}
14472			$count_cols = count($patch_array[$i]['colors']);
14473			for ($j=0; $j < $count_cols; ++$j) {
14474				//each color component as 8 bit
14475				$this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
14476				$this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
14477				$this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
14478			}
14479		}
14480		//paint the gradient
14481		$this->_out('/Sh'.$n.' sh');
14482		//restore previous Graphic State
14483		$this->_outRestoreGraphicsState();
14484		if ($this->inxobj) {
14485			// we are inside an XObject template
14486			$this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
14487		}
14488	}
14489
14490	/**
14491	 * Set a rectangular clipping area.
14492	 * @param $x (float) abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
14493	 * @param $y (float) ordinate of the top left corner of the rectangle.
14494	 * @param $w (float) width of the rectangle.
14495	 * @param $h (float) height of the rectangle.
14496	 * @author Andreas W\FCrmser, Nicola Asuni
14497	 * @since 3.1.000 (2008-06-09)
14498	 * @protected
14499	 */
14500	protected function Clip($x, $y, $w, $h) {
14501		if ($this->state != 2) {
14502			 return;
14503		}
14504		if ($this->rtl) {
14505			$x = $this->w - $x - $w;
14506		}
14507		//save current Graphic State
14508		$s = 'q';
14509		//set clipping area
14510		$s .= sprintf(' %F %F %F %F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
14511		//set up transformation matrix for gradient
14512		$s .= sprintf(' %F 0 0 %F %F %F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
14513		$this->_out($s);
14514	}
14515
14516	/**
14517	 * Output gradient.
14518	 * @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)
14519	 * @param $coords (array) array of coordinates.
14520	 * @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).
14521	 * @param $background (array) An array of colour components appropriate to the colour space, specifying a single background colour value.
14522	 * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
14523	 * @author Nicola Asuni
14524	 * @since 3.1.000 (2008-06-09)
14525	 * @public
14526	 */
14527	public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
14528		if ($this->pdfa_mode OR ($this->state != 2)) {
14529			return;
14530		}
14531		$n = count($this->gradients) + 1;
14532		$this->gradients[$n] = array();
14533		$this->gradients[$n]['type'] = $type;
14534		$this->gradients[$n]['coords'] = $coords;
14535		$this->gradients[$n]['antialias'] = $antialias;
14536		$this->gradients[$n]['colors'] = array();
14537		$this->gradients[$n]['transparency'] = false;
14538		// color space
14539		$numcolspace = count($stops[0]['color']);
14540		$bcolor = array_values($background);
14541		switch($numcolspace) {
14542			case 5:   // SPOT
14543			case 4: { // CMYK
14544				$this->gradients[$n]['colspace'] = 'DeviceCMYK';
14545				if (!empty($background)) {
14546					$this->gradients[$n]['background'] = sprintf('%F %F %F %F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
14547				}
14548				break;
14549			}
14550			case 3: { // RGB
14551				$this->gradients[$n]['colspace'] = 'DeviceRGB';
14552				if (!empty($background)) {
14553					$this->gradients[$n]['background'] = sprintf('%F %F %F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
14554				}
14555				break;
14556			}
14557			case 1: { // GRAY SCALE
14558				$this->gradients[$n]['colspace'] = 'DeviceGray';
14559				if (!empty($background)) {
14560					$this->gradients[$n]['background'] = sprintf('%F', $bcolor[0]/255);
14561				}
14562				break;
14563			}
14564		}
14565		$num_stops = count($stops);
14566		$last_stop_id = $num_stops - 1;
14567		foreach ($stops as $key => $stop) {
14568			$this->gradients[$n]['colors'][$key] = array();
14569			// offset represents a location along the gradient vector
14570			if (isset($stop['offset'])) {
14571				$this->gradients[$n]['colors'][$key]['offset'] = $stop['offset'];
14572			} else {
14573				if ($key == 0) {
14574					$this->gradients[$n]['colors'][$key]['offset'] = 0;
14575				} elseif ($key == $last_stop_id) {
14576					$this->gradients[$n]['colors'][$key]['offset'] = 1;
14577				} else {
14578					$offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
14579					$this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep;
14580				}
14581			}
14582			if (isset($stop['opacity'])) {
14583				$this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity'];
14584				if ((!$this->pdfa_mode) AND ($stop['opacity'] < 1)) {
14585					$this->gradients[$n]['transparency'] = true;
14586				}
14587			} else {
14588				$this->gradients[$n]['colors'][$key]['opacity'] = 1;
14589			}
14590			// exponent for the exponential interpolation function
14591			if (isset($stop['exponent'])) {
14592				$this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent'];
14593			} else {
14594				$this->gradients[$n]['colors'][$key]['exponent'] = 1;
14595			}
14596			// set colors
14597			$color = array_values($stop['color']);
14598			switch($numcolspace) {
14599				case 5:   // SPOT
14600				case 4: { // CMYK
14601					$this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F %F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
14602					break;
14603				}
14604				case 3: { // RGB
14605					$this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F', $color[0]/255, $color[1]/255, $color[2]/255);
14606					break;
14607				}
14608				case 1: { // GRAY SCALE
14609					$this->gradients[$n]['colors'][$key]['color'] = sprintf('%F', $color[0]/255);
14610					break;
14611				}
14612			}
14613		}
14614		if ($this->gradients[$n]['transparency']) {
14615			// paint luminosity gradient
14616			$this->_out('/TGS'.$n.' gs');
14617		}
14618		//paint the gradient
14619		$this->_out('/Sh'.$n.' sh');
14620		//restore previous Graphic State
14621		$this->_outRestoreGraphicsState();
14622		if ($this->inxobj) {
14623			// we are inside an XObject template
14624			$this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
14625		}
14626	}
14627
14628	/**
14629	 * Output gradient shaders.
14630	 * @author Nicola Asuni
14631	 * @since 3.1.000 (2008-06-09)
14632	 * @protected
14633	 */
14634	function _putshaders() {
14635		if ($this->pdfa_mode) {
14636			return;
14637		}
14638		$idt = count($this->gradients); //index for transparency gradients
14639		foreach ($this->gradients as $id => $grad) {
14640			if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
14641				$fc = $this->_newobj();
14642				$out = '<<';
14643				$out .= ' /FunctionType 3';
14644				$out .= ' /Domain [0 1]';
14645				$functions = '';
14646				$bounds = '';
14647				$encode = '';
14648				$i = 1;
14649				$num_cols = count($grad['colors']);
14650				$lastcols = $num_cols - 1;
14651				for ($i = 1; $i < $num_cols; ++$i) {
14652					$functions .= ($fc + $i).' 0 R ';
14653					if ($i < $lastcols) {
14654						$bounds .= sprintf('%F ', $grad['colors'][$i]['offset']);
14655					}
14656					$encode .= '0 1 ';
14657				}
14658				$out .= ' /Functions ['.trim($functions).']';
14659				$out .= ' /Bounds ['.trim($bounds).']';
14660				$out .= ' /Encode ['.trim($encode).']';
14661				$out .= ' >>';
14662				$out .= "\n".'endobj';
14663				$this->_out($out);
14664				for ($i = 1; $i < $num_cols; ++$i) {
14665					$this->_newobj();
14666					$out = '<<';
14667					$out .= ' /FunctionType 2';
14668					$out .= ' /Domain [0 1]';
14669					$out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
14670					$out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
14671					$out .= ' /N '.$grad['colors'][$i]['exponent'];
14672					$out .= ' >>';
14673					$out .= "\n".'endobj';
14674					$this->_out($out);
14675				}
14676				// set transparency functions
14677				if ($grad['transparency']) {
14678					$ft = $this->_newobj();
14679					$out = '<<';
14680					$out .= ' /FunctionType 3';
14681					$out .= ' /Domain [0 1]';
14682					$functions = '';
14683					$i = 1;
14684					$num_cols = count($grad['colors']);
14685					for ($i = 1; $i < $num_cols; ++$i) {
14686						$functions .= ($ft + $i).' 0 R ';
14687					}
14688					$out .= ' /Functions ['.trim($functions).']';
14689					$out .= ' /Bounds ['.trim($bounds).']';
14690					$out .= ' /Encode ['.trim($encode).']';
14691					$out .= ' >>';
14692					$out .= "\n".'endobj';
14693					$this->_out($out);
14694					for ($i = 1; $i < $num_cols; ++$i) {
14695						$this->_newobj();
14696						$out = '<<';
14697						$out .= ' /FunctionType 2';
14698						$out .= ' /Domain [0 1]';
14699						$out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
14700						$out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
14701						$out .= ' /N '.$grad['colors'][$i]['exponent'];
14702						$out .= ' >>';
14703						$out .= "\n".'endobj';
14704						$this->_out($out);
14705					}
14706				}
14707			}
14708			// set shading object
14709			$this->_newobj();
14710			$out = '<< /ShadingType '.$grad['type'];
14711			if (isset($grad['colspace'])) {
14712				$out .= ' /ColorSpace /'.$grad['colspace'];
14713			} else {
14714				$out .= ' /ColorSpace /DeviceRGB';
14715			}
14716			if (isset($grad['background']) AND !empty($grad['background'])) {
14717				$out .= ' /Background ['.$grad['background'].']';
14718			}
14719			if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
14720				$out .= ' /AntiAlias true';
14721			}
14722			if ($grad['type'] == 2) {
14723				$out .= ' '.sprintf('/Coords [%F %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
14724				$out .= ' /Domain [0 1]';
14725				$out .= ' /Function '.$fc.' 0 R';
14726				$out .= ' /Extend [true true]';
14727				$out .= ' >>';
14728			} elseif ($grad['type'] == 3) {
14729				//x0, y0, r0, x1, y1, r1
14730				//at this this time radius of inner circle is 0
14731				$out .= ' '.sprintf('/Coords [%F %F 0 %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
14732				$out .= ' /Domain [0 1]';
14733				$out .= ' /Function '.$fc.' 0 R';
14734				$out .= ' /Extend [true true]';
14735				$out .= ' >>';
14736			} elseif ($grad['type'] == 6) {
14737				$out .= ' /BitsPerCoordinate 16';
14738				$out .= ' /BitsPerComponent 8';
14739				$out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
14740				$out .= ' /BitsPerFlag 8';
14741				$stream = $this->_getrawstream($grad['stream']);
14742				$out .= ' /Length '.strlen($stream);
14743				$out .= ' >>';
14744				$out .= ' stream'."\n".$stream."\n".'endstream';
14745			}
14746			$out .= "\n".'endobj';
14747			$this->_out($out);
14748			if ($grad['transparency']) {
14749				$shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
14750				$shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
14751			}
14752			$this->gradients[$id]['id'] = $this->n;
14753			// set pattern object
14754			$this->_newobj();
14755			$out = '<< /Type /Pattern /PatternType 2';
14756			$out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R';
14757			$out .= ' >>';
14758			$out .= "\n".'endobj';
14759			$this->_out($out);
14760			$this->gradients[$id]['pattern'] = $this->n;
14761			// set shading and pattern for transparency mask
14762			if ($grad['transparency']) {
14763				// luminosity pattern
14764				$idgs = $id + $idt;
14765				$this->_newobj();
14766				$this->_out($shading_transparency);
14767				$this->gradients[$idgs]['id'] = $this->n;
14768				$this->_newobj();
14769				$out = '<< /Type /Pattern /PatternType 2';
14770				$out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R';
14771				$out .= ' >>';
14772				$out .= "\n".'endobj';
14773				$this->_out($out);
14774				$this->gradients[$idgs]['pattern'] = $this->n;
14775				// luminosity XObject
14776				$oid = $this->_newobj();
14777				$this->xobjects['LX'.$oid] = array('n' => $oid);
14778				$filter = '';
14779				$stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q';
14780				if ($this->compress) {
14781					$filter = ' /Filter /FlateDecode';
14782					$stream = gzcompress($stream);
14783				}
14784				$stream = $this->_getrawstream($stream);
14785				$out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
14786				$out .= ' /Length '.strlen($stream);
14787				$rect = sprintf('%F %F', $this->wPt, $this->hPt);
14788				$out .= ' /BBox [0 0 '.$rect.']';
14789				$out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
14790				$out .= ' /Resources <<';
14791				$out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
14792				$out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>';
14793				$out .= ' >>';
14794				$out .= ' >> ';
14795				$out .= ' stream'."\n".$stream."\n".'endstream';
14796				$out .= "\n".'endobj';
14797				$this->_out($out);
14798				// SMask
14799				$this->_newobj();
14800				$out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj';
14801				$this->_out($out);
14802				// ExtGState
14803				$this->_newobj();
14804				$out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj';
14805				$this->_out($out);
14806				$this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id);
14807			}
14808		}
14809	}
14810
14811	/**
14812	 * Draw the sector of a circle.
14813	 * It can be used for instance to render pie charts.
14814	 * @param $xc (float) abscissa of the center.
14815	 * @param $yc (float) ordinate of the center.
14816	 * @param $r (float) radius.
14817	 * @param $a (float) start angle (in degrees).
14818	 * @param $b (float) end angle (in degrees).
14819	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
14820	 * @param $cw: (float) indicates whether to go clockwise (default: true).
14821	 * @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.
14822	 * @author Maxime Delorme, Nicola Asuni
14823	 * @since 3.1.000 (2008-06-09)
14824	 * @public
14825	 */
14826	public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
14827		$this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
14828	}
14829
14830	/**
14831	 * Draw the sector of an ellipse.
14832	 * It can be used for instance to render pie charts.
14833	 * @param $xc (float) abscissa of the center.
14834	 * @param $yc (float) ordinate of the center.
14835	 * @param $rx (float) the x-axis radius.
14836	 * @param $ry (float) the y-axis radius.
14837	 * @param $a (float) start angle (in degrees).
14838	 * @param $b (float) end angle (in degrees).
14839	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
14840	 * @param $cw: (float) indicates whether to go clockwise.
14841	 * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
14842	 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of arc.
14843	 * @author Maxime Delorme, Nicola Asuni
14844	 * @since 3.1.000 (2008-06-09)
14845	 * @public
14846	 */
14847	public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
14848		if ($this->state != 2) {
14849			 return;
14850		}
14851		if ($this->rtl) {
14852			$xc = ($this->w - $xc);
14853		}
14854		$op = TCPDF_STATIC::getPathPaintOperator($style);
14855		if ($op == 'f') {
14856			$line_style = array();
14857		}
14858		if ($cw) {
14859			$d = $b;
14860			$b = (360 - $a + $o);
14861			$a = (360 - $d + $o);
14862		} else {
14863			$b += $o;
14864			$a += $o;
14865		}
14866		$this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
14867		$this->_out($op);
14868	}
14869
14870	/**
14871	 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
14872	 * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
14873	 * Only vector drawing is supported, not text or bitmap.
14874	 * 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).
14875	 * @param $file (string) Name of the file containing the image or a '@' character followed by the EPS/AI data string.
14876	 * @param $x (float) Abscissa of the upper-left corner.
14877	 * @param $y (float) Ordinate of the upper-left corner.
14878	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
14879	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
14880	 * @param $link (mixed) URL or identifier returned by AddLink().
14881	 * @param $useBoundingBox (boolean) specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
14882	 * @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>
14883	 * @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>
14884	 * @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)))
14885	 * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
14886	 * @param $fixoutvals (boolean) if true remove values outside the bounding box.
14887	 * @author Valentin Schmidt, Nicola Asuni
14888	 * @since 3.1.000 (2008-06-09)
14889	 * @public
14890	 */
14891	public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
14892		if ($this->state != 2) {
14893			 return;
14894		}
14895		if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
14896			// convert EPS to raster image using GD or ImageMagick libraries
14897			return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
14898		}
14899		if ($x === '') {
14900			$x = $this->x;
14901		}
14902		if ($y === '') {
14903			$y = $this->y;
14904		}
14905		// check page for no-write regions and adapt page margins if necessary
14906		list($x, $y) = $this->checkPageRegions($h, $x, $y);
14907		$k = $this->k;
14908		if ($file[0] === '@') { // image from string
14909			$data = substr($file, 1);
14910		} else { // EPS/AI file
14911			$data = TCPDF_STATIC::fileGetContents($file);
14912		}
14913		if ($data === FALSE) {
14914			$this->Error('EPS file not found: '.$file);
14915		}
14916		$regs = array();
14917		// EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
14918		preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
14919		if (count($regs) > 1) {
14920			$version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
14921			if (strpos($version_str, 'Adobe Illustrator') !== false) {
14922				$versexp = explode(' ', $version_str);
14923				$version = (float)array_pop($versexp);
14924				if ($version >= 9) {
14925					$this->Error('This version of Adobe Illustrator file is not supported: '.$file);
14926				}
14927			}
14928		}
14929		// strip binary bytes in front of PS-header
14930		$start = strpos($data, '%!PS-Adobe');
14931		if ($start > 0) {
14932			$data = substr($data, $start);
14933		}
14934		// find BoundingBox params
14935		preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
14936		if (count($regs) > 1) {
14937			list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
14938		} else {
14939			$this->Error('No BoundingBox found in EPS/AI file: '.$file);
14940		}
14941		$start = strpos($data, '%%EndSetup');
14942		if ($start === false) {
14943			$start = strpos($data, '%%EndProlog');
14944		}
14945		if ($start === false) {
14946			$start = strpos($data, '%%BoundingBox');
14947		}
14948		$data = substr($data, $start);
14949		$end = strpos($data, '%%PageTrailer');
14950		if ($end===false) {
14951			$end = strpos($data, 'showpage');
14952		}
14953		if ($end) {
14954			$data = substr($data, 0, $end);
14955		}
14956		// calculate image width and height on document
14957		if (($w <= 0) AND ($h <= 0)) {
14958			$w = ($x2 - $x1) / $k;
14959			$h = ($y2 - $y1) / $k;
14960		} elseif ($w <= 0) {
14961			$w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
14962		} elseif ($h <= 0) {
14963			$h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
14964		}
14965		// fit the image on available space
14966		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
14967		if ($this->rasterize_vector_images) {
14968			// convert EPS to raster image using GD or ImageMagick libraries
14969			return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
14970		}
14971		// set scaling factors
14972		$scale_x = $w / (($x2 - $x1) / $k);
14973		$scale_y = $h / (($y2 - $y1) / $k);
14974		// set alignment
14975		$this->img_rb_y = $y + $h;
14976		// set alignment
14977		if ($this->rtl) {
14978			if ($palign == 'L') {
14979				$ximg = $this->lMargin;
14980			} elseif ($palign == 'C') {
14981				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
14982			} elseif ($palign == 'R') {
14983				$ximg = $this->w - $this->rMargin - $w;
14984			} else {
14985				$ximg = $x - $w;
14986			}
14987			$this->img_rb_x = $ximg;
14988		} else {
14989			if ($palign == 'L') {
14990				$ximg = $this->lMargin;
14991			} elseif ($palign == 'C') {
14992				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
14993			} elseif ($palign == 'R') {
14994				$ximg = $this->w - $this->rMargin - $w;
14995			} else {
14996				$ximg = $x;
14997			}
14998			$this->img_rb_x = $ximg + $w;
14999		}
15000		if ($useBoundingBox) {
15001			$dx = $ximg * $k - $x1;
15002			$dy = $y * $k - $y1;
15003		} else {
15004			$dx = $ximg * $k;
15005			$dy = $y * $k;
15006		}
15007		// save the current graphic state
15008		$this->_out('q'.$this->epsmarker);
15009		// translate
15010		$this->_out(sprintf('%F %F %F %F %F %F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
15011		// scale
15012		if (isset($scale_x)) {
15013			$this->_out(sprintf('%F %F %F %F %F %F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
15014		}
15015		// handle pc/unix/mac line endings
15016		$lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY);
15017		$u=0;
15018		$cnt = count($lines);
15019		for ($i=0; $i < $cnt; ++$i) {
15020			$line = $lines[$i];
15021			if (($line == '') OR ($line[0] == '%')) {
15022				continue;
15023			}
15024			$len = strlen($line);
15025			// check for spot color names
15026			$color_name = '';
15027			if (strcasecmp('x', substr(trim($line), -1)) == 0) {
15028				if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
15029					// extract spot color name
15030					$color_name = $matches[0];
15031					// remove color name from string
15032					$line = str_replace(' '.$color_name, '', $line);
15033					// remove pharentesis from color name
15034					$color_name = substr($color_name, 1, -1);
15035				}
15036			}
15037			$chunks = explode(' ', $line);
15038			$cmd = trim(array_pop($chunks));
15039			// RGB
15040			if (($cmd == 'Xa') OR ($cmd == 'XA')) {
15041				$b = array_pop($chunks);
15042				$g = array_pop($chunks);
15043				$r = array_pop($chunks);
15044				$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!
15045				continue;
15046			}
15047			$skip = false;
15048			if ($fixoutvals) {
15049				// check for values outside the bounding box
15050				switch ($cmd) {
15051					case 'm':
15052					case 'l':
15053					case 'L': {
15054						// skip values outside bounding box
15055						foreach ($chunks as $key => $val) {
15056							if ((($key % 2) == 0) AND (($val < $x1) OR ($val > $x2))) {
15057								$skip = true;
15058							} elseif ((($key % 2) != 0) AND (($val < $y1) OR ($val > $y2))) {
15059								$skip = true;
15060							}
15061						}
15062					}
15063				}
15064			}
15065			switch ($cmd) {
15066				case 'm':
15067				case 'l':
15068				case 'v':
15069				case 'y':
15070				case 'c':
15071				case 'k':
15072				case 'K':
15073				case 'g':
15074				case 'G':
15075				case 's':
15076				case 'S':
15077				case 'J':
15078				case 'j':
15079				case 'w':
15080				case 'M':
15081				case 'd':
15082				case 'n': {
15083					if ($skip) {
15084						break;
15085					}
15086					$this->_out($line);
15087					break;
15088				}
15089				case 'x': {// custom fill color
15090					if (empty($color_name)) {
15091						// CMYK color
15092						list($col_c, $col_m, $col_y, $col_k) = $chunks;
15093						$this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
15094					} else {
15095						// Spot Color (CMYK + tint)
15096						list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
15097						$this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
15098						$color_cmd = sprintf('/CS%d cs %F scn', $this->spot_colors[$color_name]['i'], (1 - $col_t));
15099						$this->_out($color_cmd);
15100					}
15101					break;
15102				}
15103				case 'X': { // custom stroke color
15104					if (empty($color_name)) {
15105						// CMYK color
15106						list($col_c, $col_m, $col_y, $col_k) = $chunks;
15107						$this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
15108					} else {
15109						// Spot Color (CMYK + tint)
15110						list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
15111						$this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
15112						$color_cmd = sprintf('/CS%d CS %F SCN', $this->spot_colors[$color_name]['i'], (1 - $col_t));
15113						$this->_out($color_cmd);
15114					}
15115					break;
15116				}
15117				case 'Y':
15118				case 'N':
15119				case 'V':
15120				case 'L':
15121				case 'C': {
15122					if ($skip) {
15123						break;
15124					}
15125					$line[($len - 1)] = strtolower($cmd);
15126					$this->_out($line);
15127					break;
15128				}
15129				case 'b':
15130				case 'B': {
15131					$this->_out($cmd . '*');
15132					break;
15133				}
15134				case 'f':
15135				case 'F': {
15136					if ($u > 0) {
15137						$isU = false;
15138						$max = min(($i + 5), $cnt);
15139						for ($j = ($i + 1); $j < $max; ++$j) {
15140							$isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
15141						}
15142						if ($isU) {
15143							$this->_out('f*');
15144						}
15145					} else {
15146						$this->_out('f*');
15147					}
15148					break;
15149				}
15150				case '*u': {
15151					++$u;
15152					break;
15153				}
15154				case '*U': {
15155					--$u;
15156					break;
15157				}
15158			}
15159		}
15160		// restore previous graphic state
15161		$this->_out($this->epsmarker.'Q');
15162		if (!empty($border)) {
15163			$bx = $this->x;
15164			$by = $this->y;
15165			$this->x = $ximg;
15166			if ($this->rtl) {
15167				$this->x += $w;
15168			}
15169			$this->y = $y;
15170			$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
15171			$this->x = $bx;
15172			$this->y = $by;
15173		}
15174		if ($link) {
15175			$this->Link($ximg, $y, $w, $h, $link, 0);
15176		}
15177		// set pointer to align the next text/objects
15178		switch($align) {
15179			case 'T':{
15180				$this->y = $y;
15181				$this->x = $this->img_rb_x;
15182				break;
15183			}
15184			case 'M':{
15185				$this->y = $y + round($h/2);
15186				$this->x = $this->img_rb_x;
15187				break;
15188			}
15189			case 'B':{
15190				$this->y = $this->img_rb_y;
15191				$this->x = $this->img_rb_x;
15192				break;
15193			}
15194			case 'N':{
15195				$this->SetY($this->img_rb_y);
15196				break;
15197			}
15198			default:{
15199				break;
15200			}
15201		}
15202		$this->endlinex = $this->img_rb_x;
15203	}
15204
15205	/**
15206	 * Set document barcode.
15207	 * @param $bc (string) barcode
15208	 * @public
15209	 */
15210	public function setBarcode($bc='') {
15211		$this->barcode = $bc;
15212	}
15213
15214	/**
15215	 * Get current barcode.
15216	 * @return string
15217	 * @public
15218	 * @since 4.0.012 (2008-07-24)
15219	 */
15220	public function getBarcode() {
15221		return $this->barcode;
15222	}
15223
15224	/**
15225	 * Print a Linear Barcode.
15226	 * @param $code (string) code to print
15227	 * @param $type (string) type of barcode (see tcpdf_barcodes_1d.php for supported formats).
15228	 * @param $x (int) x position in user units (empty string = current x position)
15229	 * @param $y (int) y position in user units (empty string = current y position)
15230	 * @param $w (int) width in user units (empty string = remaining page width)
15231	 * @param $h (int) height in user units (empty string = remaining page height)
15232	 * @param $xres (float) width of the smallest bar in user units (empty string = default value = 0.4mm)
15233	 * @param $style (array) array of options:<ul>
15234	 * <li>boolean $style['border'] if true prints a border</li>
15235	 * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
15236	 * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
15237	 * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
15238	 * <li>array $style['fgcolor'] color array for bars and text</li>
15239	 * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
15240	 * <li>boolean $style['text'] if true prints text below the barcode</li>
15241	 * <li>string $style['label'] override default label</li>
15242	 * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
15243	 * <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>
15244	 * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
15245	 * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
15246	 * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
15247	 * <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>
15248	 * <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>
15249	 * @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>
15250	 * @author Nicola Asuni
15251	 * @since 3.1.000 (2008-06-09)
15252	 * @public
15253	 */
15254	public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style=array(), $align='') {
15255		if (TCPDF_STATIC::empty_string(trim($code))) {
15256			return;
15257		}
15258		require_once(dirname(__FILE__).'/tcpdf_barcodes_1d.php');
15259		// save current graphic settings
15260		$gvars = $this->getGraphicVars();
15261		// create new barcode object
15262		$barcodeobj = new TCPDFBarcode($code, $type);
15263		$arrcode = $barcodeobj->getBarcodeArray();
15264		if (($arrcode === false) OR empty($arrcode) OR ($arrcode['maxw'] <= 0)) {
15265			$this->Error('Error in 1D barcode string');
15266		}
15267		if ($arrcode['maxh'] <= 0) {
15268			$arrcode['maxh'] = 1;
15269		}
15270		// set default values
15271		if (!isset($style['position'])) {
15272			$style['position'] = '';
15273		} elseif ($style['position'] == 'S') {
15274			// keep this for backward compatibility
15275			$style['position'] = '';
15276			$style['stretch'] = true;
15277		}
15278		if (!isset($style['fitwidth'])) {
15279			if (!isset($style['stretch'])) {
15280				$style['fitwidth'] = true;
15281			} else {
15282				$style['fitwidth'] = false;
15283			}
15284		}
15285		if ($style['fitwidth']) {
15286			// disable stretch
15287			$style['stretch'] = false;
15288		}
15289		if (!isset($style['stretch'])) {
15290			if (($w === '') OR ($w <= 0)) {
15291				$style['stretch'] = false;
15292			} else {
15293				$style['stretch'] = true;
15294			}
15295		}
15296		if (!isset($style['fgcolor'])) {
15297			$style['fgcolor'] = array(0,0,0); // default black
15298		}
15299		if (!isset($style['bgcolor'])) {
15300			$style['bgcolor'] = false; // default transparent
15301		}
15302		if (!isset($style['border'])) {
15303			$style['border'] = false;
15304		}
15305		$fontsize = 0;
15306		if (!isset($style['text'])) {
15307			$style['text'] = false;
15308		}
15309		if ($style['text'] AND isset($style['font'])) {
15310			if (isset($style['fontsize'])) {
15311				$fontsize = $style['fontsize'];
15312			}
15313			$this->SetFont($style['font'], '', $fontsize);
15314		}
15315		if (!isset($style['stretchtext'])) {
15316			$style['stretchtext'] = 4;
15317		}
15318		if ($x === '') {
15319			$x = $this->x;
15320		}
15321		if ($y === '') {
15322			$y = $this->y;
15323		}
15324		// check page for no-write regions and adapt page margins if necessary
15325		list($x, $y) = $this->checkPageRegions($h, $x, $y);
15326		if (($w === '') OR ($w <= 0)) {
15327			if ($this->rtl) {
15328				$w = $x - $this->lMargin;
15329			} else {
15330				$w = $this->w - $this->rMargin - $x;
15331			}
15332		}
15333		// padding
15334		if (!isset($style['padding'])) {
15335			$padding = 0;
15336		} elseif ($style['padding'] === 'auto') {
15337			$padding = 10 * ($w / ($arrcode['maxw'] + 20));
15338		} else {
15339			$padding = floatval($style['padding']);
15340		}
15341		// horizontal padding
15342		if (!isset($style['hpadding'])) {
15343			$hpadding = $padding;
15344		} elseif ($style['hpadding'] === 'auto') {
15345			$hpadding = 10 * ($w / ($arrcode['maxw'] + 20));
15346		} else {
15347			$hpadding = floatval($style['hpadding']);
15348		}
15349		// vertical padding
15350		if (!isset($style['vpadding'])) {
15351			$vpadding = $padding;
15352		} elseif ($style['vpadding'] === 'auto') {
15353			$vpadding = ($hpadding / 2);
15354		} else {
15355			$vpadding = floatval($style['vpadding']);
15356		}
15357		// calculate xres (single bar width)
15358		$max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
15359		if ($style['stretch']) {
15360			$xres = $max_xres;
15361		} else {
15362			if (TCPDF_STATIC::empty_string($xres)) {
15363				$xres = (0.141 * $this->k); // default bar width = 0.4 mm
15364			}
15365			if ($xres > $max_xres) {
15366				// correct xres to fit on $w
15367				$xres = $max_xres;
15368			}
15369			if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
15370				OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
15371				$hpadding = 10 * $xres;
15372				if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
15373					$vpadding = ($hpadding / 2);
15374				}
15375			}
15376		}
15377		if ($style['fitwidth']) {
15378			$wold = $w;
15379			$w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));
15380			if (isset($style['cellfitalign'])) {
15381				switch ($style['cellfitalign']) {
15382					case 'L': {
15383						if ($this->rtl) {
15384							$x -= ($wold - $w);
15385						}
15386						break;
15387					}
15388					case 'R': {
15389						if (!$this->rtl) {
15390							$x += ($wold - $w);
15391						}
15392						break;
15393					}
15394					case 'C': {
15395						if ($this->rtl) {
15396							$x -= (($wold - $w) / 2);
15397						} else {
15398							$x += (($wold - $w) / 2);
15399						}
15400						break;
15401					}
15402					default : {
15403						break;
15404					}
15405				}
15406			}
15407		}
15408		$text_height = $this->getCellHeight($fontsize / $this->k);
15409		// height
15410		if (($h === '') OR ($h <= 0)) {
15411			// set default height
15412			$h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;
15413		}
15414		$barh = $h - $text_height - (2 * $vpadding);
15415		if ($barh <=0) {
15416			// try to reduce font or padding to fit barcode on available height
15417			if ($text_height > $h) {
15418				$fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));
15419				$text_height = $this->getCellHeight($fontsize / $this->k);
15420				$this->SetFont($style['font'], '', $fontsize);
15421			}
15422			if ($vpadding > 0) {
15423				$vpadding = (($h - $text_height) / 4);
15424			}
15425			$barh = $h - $text_height - (2 * $vpadding);
15426		}
15427		// fit the barcode on available space
15428		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
15429		// set alignment
15430		$this->img_rb_y = $y + $h;
15431		// set alignment
15432		if ($this->rtl) {
15433			if ($style['position'] == 'L') {
15434				$xpos = $this->lMargin;
15435			} elseif ($style['position'] == 'C') {
15436				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15437			} elseif ($style['position'] == 'R') {
15438				$xpos = $this->w - $this->rMargin - $w;
15439			} else {
15440				$xpos = $x - $w;
15441			}
15442			$this->img_rb_x = $xpos;
15443		} else {
15444			if ($style['position'] == 'L') {
15445				$xpos = $this->lMargin;
15446			} elseif ($style['position'] == 'C') {
15447				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15448			} elseif ($style['position'] == 'R') {
15449				$xpos = $this->w - $this->rMargin - $w;
15450			} else {
15451				$xpos = $x;
15452			}
15453			$this->img_rb_x = $xpos + $w;
15454		}
15455		$xpos_rect = $xpos;
15456		if (!isset($style['align'])) {
15457			$style['align'] = 'C';
15458		}
15459		switch ($style['align']) {
15460			case 'L': {
15461				$xpos = $xpos_rect + $hpadding;
15462				break;
15463			}
15464			case 'R': {
15465				$xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;
15466				break;
15467			}
15468			case 'C':
15469			default : {
15470				$xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);
15471				break;
15472			}
15473		}
15474		$xpos_text = $xpos;
15475		// barcode is always printed in LTR direction
15476		$tempRTL = $this->rtl;
15477		$this->rtl = false;
15478		// print background color
15479		if ($style['bgcolor']) {
15480			$this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
15481		} elseif ($style['border']) {
15482			$this->Rect($xpos_rect, $y, $w, $h, 'D');
15483		}
15484		// set foreground color
15485		$this->SetDrawColorArray($style['fgcolor']);
15486		$this->SetTextColorArray($style['fgcolor']);
15487		// print bars
15488		foreach ($arrcode['bcode'] as $k => $v) {
15489			$bw = ($v['w'] * $xres);
15490			if ($v['t']) {
15491				// draw a vertical bar
15492				$ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);
15493				$this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
15494			}
15495			$xpos += $bw;
15496		}
15497		// print text
15498		if ($style['text']) {
15499			if (isset($style['label']) AND !TCPDF_STATIC::empty_string($style['label'])) {
15500				$label = $style['label'];
15501			} else {
15502				$label = $code;
15503			}
15504			$txtwidth = ($arrcode['maxw'] * $xres);
15505			if ($this->GetStringWidth($label) > $txtwidth) {
15506				$style['stretchtext'] = 2;
15507			}
15508			// print text
15509			$this->x = $xpos_text;
15510			$this->y = $y + $vpadding + $barh;
15511			$cellpadding = $this->cell_padding;
15512			$this->SetCellPadding(0);
15513			$this->Cell($txtwidth, '', $label, 0, 0, 'C', false, '', $style['stretchtext'], false, 'T', 'T');
15514			$this->cell_padding = $cellpadding;
15515		}
15516		// restore original direction
15517		$this->rtl = $tempRTL;
15518		// restore previous settings
15519		$this->setGraphicVars($gvars);
15520		// set pointer to align the next text/objects
15521		switch($align) {
15522			case 'T':{
15523				$this->y = $y;
15524				$this->x = $this->img_rb_x;
15525				break;
15526			}
15527			case 'M':{
15528				$this->y = $y + round($h / 2);
15529				$this->x = $this->img_rb_x;
15530				break;
15531			}
15532			case 'B':{
15533				$this->y = $this->img_rb_y;
15534				$this->x = $this->img_rb_x;
15535				break;
15536			}
15537			case 'N':{
15538				$this->SetY($this->img_rb_y);
15539				break;
15540			}
15541			default:{
15542				break;
15543			}
15544		}
15545		$this->endlinex = $this->img_rb_x;
15546	}
15547
15548	/**
15549	 * Print 2D Barcode.
15550	 * @param $code (string) code to print
15551	 * @param $type (string) type of barcode (see tcpdf_barcodes_2d.php for supported formats).
15552	 * @param $x (int) x position in user units
15553	 * @param $y (int) y position in user units
15554	 * @param $w (int) width in user units
15555	 * @param $h (int) height in user units
15556	 * @param $style (array) array of options:<ul>
15557	 * <li>boolean $style['border'] if true prints a border around the barcode</li>
15558	 * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
15559	 * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
15560	 * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
15561	 * <li>int $style['module_width'] width of a single module in points</li>
15562	 * <li>int $style['module_height'] height of a single module in points</li>
15563	 * <li>array $style['fgcolor'] color array for bars and text</li>
15564	 * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
15565	 * <li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li>
15566	 * @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>
15567	 * @param $distort (boolean) if true distort the barcode to fit width and height, otherwise preserve aspect ratio
15568	 * @author Nicola Asuni
15569	 * @since 4.5.037 (2009-04-07)
15570	 * @public
15571	 */
15572	public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style=array(), $align='', $distort=false) {
15573		if (TCPDF_STATIC::empty_string(trim($code))) {
15574			return;
15575		}
15576		require_once(dirname(__FILE__).'/tcpdf_barcodes_2d.php');
15577		// save current graphic settings
15578		$gvars = $this->getGraphicVars();
15579		// create new barcode object
15580		$barcodeobj = new TCPDF2DBarcode($code, $type);
15581		$arrcode = $barcodeobj->getBarcodeArray();
15582		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)) {
15583			$this->Error('Error in 2D barcode string');
15584		}
15585		// set default values
15586		if (!isset($style['position'])) {
15587			$style['position'] = '';
15588		}
15589		if (!isset($style['fgcolor'])) {
15590			$style['fgcolor'] = array(0,0,0); // default black
15591		}
15592		if (!isset($style['bgcolor'])) {
15593			$style['bgcolor'] = false; // default transparent
15594		}
15595		if (!isset($style['border'])) {
15596			$style['border'] = false;
15597		}
15598		// padding
15599		if (!isset($style['padding'])) {
15600			$style['padding'] = 0;
15601		} elseif ($style['padding'] === 'auto') {
15602			$style['padding'] = 4;
15603		}
15604		if (!isset($style['hpadding'])) {
15605			$style['hpadding'] = $style['padding'];
15606		} elseif ($style['hpadding'] === 'auto') {
15607			$style['hpadding'] = 4;
15608		}
15609		if (!isset($style['vpadding'])) {
15610			$style['vpadding'] = $style['padding'];
15611		} elseif ($style['vpadding'] === 'auto') {
15612			$style['vpadding'] = 4;
15613		}
15614		$hpad = (2 * $style['hpadding']);
15615		$vpad = (2 * $style['vpadding']);
15616		// cell (module) dimension
15617		if (!isset($style['module_width'])) {
15618			$style['module_width'] = 1; // width of a single module in points
15619		}
15620		if (!isset($style['module_height'])) {
15621			$style['module_height'] = 1; // height of a single module in points
15622		}
15623		if ($x === '') {
15624			$x = $this->x;
15625		}
15626		if ($y === '') {
15627			$y = $this->y;
15628		}
15629		// check page for no-write regions and adapt page margins if necessary
15630		list($x, $y) = $this->checkPageRegions($h, $x, $y);
15631		// number of barcode columns and rows
15632		$rows = $arrcode['num_rows'];
15633		$cols = $arrcode['num_cols'];
15634		if (($rows <= 0) || ($cols <= 0)){
15635			$this->Error('Error in 2D barcode string');
15636		}
15637		// module width and height
15638		$mw = $style['module_width'];
15639		$mh = $style['module_height'];
15640		if (($mw <= 0) OR ($mh <= 0)) {
15641			$this->Error('Error in 2D barcode string');
15642		}
15643		// get max dimensions
15644		if ($this->rtl) {
15645			$maxw = $x - $this->lMargin;
15646		} else {
15647			$maxw = $this->w - $this->rMargin - $x;
15648		}
15649		$maxh = ($this->h - $this->tMargin - $this->bMargin);
15650		$ratioHW = ((($rows * $mh) + $hpad) / (($cols * $mw) + $vpad));
15651		$ratioWH = ((($cols * $mw) + $vpad) / (($rows * $mh) + $hpad));
15652		if (!$distort) {
15653			if (($maxw * $ratioHW) > $maxh) {
15654				$maxw = $maxh * $ratioWH;
15655			}
15656			if (($maxh * $ratioWH) > $maxw) {
15657				$maxh = $maxw * $ratioHW;
15658			}
15659		}
15660		// set maximum dimensions
15661		if ($w > $maxw) {
15662			$w = $maxw;
15663		}
15664		if ($h > $maxh) {
15665			$h = $maxh;
15666		}
15667		// set dimensions
15668		if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {
15669			$w = ($cols + $hpad) * ($mw / $this->k);
15670			$h = ($rows + $vpad) * ($mh / $this->k);
15671		} elseif (($w === '') OR ($w <= 0)) {
15672			$w = $h * $ratioWH;
15673		} elseif (($h === '') OR ($h <= 0)) {
15674			$h = $w * $ratioHW;
15675		}
15676		// barcode size (excluding padding)
15677		$bw = ($w * $cols) / ($cols + $hpad);
15678		$bh = ($h * $rows) / ($rows + $vpad);
15679		// dimension of single barcode cell unit
15680		$cw = $bw / $cols;
15681		$ch = $bh / $rows;
15682		if (!$distort) {
15683			if (($cw / $ch) > ($mw / $mh)) {
15684				// correct horizontal distortion
15685				$cw = $ch * $mw / $mh;
15686				$bw = $cw * $cols;
15687				$style['hpadding'] = ($w - $bw) / (2 * $cw);
15688			} else {
15689				// correct vertical distortion
15690				$ch = $cw * $mh / $mw;
15691				$bh = $ch * $rows;
15692				$style['vpadding'] = ($h - $bh) / (2 * $ch);
15693			}
15694		}
15695		// fit the barcode on available space
15696		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
15697		// set alignment
15698		$this->img_rb_y = $y + $h;
15699		// set alignment
15700		if ($this->rtl) {
15701			if ($style['position'] == 'L') {
15702				$xpos = $this->lMargin;
15703			} elseif ($style['position'] == 'C') {
15704				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15705			} elseif ($style['position'] == 'R') {
15706				$xpos = $this->w - $this->rMargin - $w;
15707			} else {
15708				$xpos = $x - $w;
15709			}
15710			$this->img_rb_x = $xpos;
15711		} else {
15712			if ($style['position'] == 'L') {
15713				$xpos = $this->lMargin;
15714			} elseif ($style['position'] == 'C') {
15715				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15716			} elseif ($style['position'] == 'R') {
15717				$xpos = $this->w - $this->rMargin - $w;
15718			} else {
15719				$xpos = $x;
15720			}
15721			$this->img_rb_x = $xpos + $w;
15722		}
15723		$xstart = $xpos + ($style['hpadding'] * $cw);
15724		$ystart = $y + ($style['vpadding'] * $ch);
15725		// barcode is always printed in LTR direction
15726		$tempRTL = $this->rtl;
15727		$this->rtl = false;
15728		// print background color
15729		if ($style['bgcolor']) {
15730			$this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
15731		} elseif ($style['border']) {
15732			$this->Rect($xpos, $y, $w, $h, 'D');
15733		}
15734		// set foreground color
15735		$this->SetDrawColorArray($style['fgcolor']);
15736		// print barcode cells
15737		// for each row
15738		for ($r = 0; $r < $rows; ++$r) {
15739			$xr = $xstart;
15740			// for each column
15741			for ($c = 0; $c < $cols; ++$c) {
15742				if ($arrcode['bcode'][$r][$c] == 1) {
15743					// draw a single barcode cell
15744					$this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
15745				}
15746				$xr += $cw;
15747			}
15748			$ystart += $ch;
15749		}
15750		// restore original direction
15751		$this->rtl = $tempRTL;
15752		// restore previous settings
15753		$this->setGraphicVars($gvars);
15754		// set pointer to align the next text/objects
15755		switch($align) {
15756			case 'T':{
15757				$this->y = $y;
15758				$this->x = $this->img_rb_x;
15759				break;
15760			}
15761			case 'M':{
15762				$this->y = $y + round($h/2);
15763				$this->x = $this->img_rb_x;
15764				break;
15765			}
15766			case 'B':{
15767				$this->y = $this->img_rb_y;
15768				$this->x = $this->img_rb_x;
15769				break;
15770			}
15771			case 'N':{
15772				$this->SetY($this->img_rb_y);
15773				break;
15774			}
15775			default:{
15776				break;
15777			}
15778		}
15779		$this->endlinex = $this->img_rb_x;
15780	}
15781
15782	/**
15783	 * Returns an array containing current margins:
15784	 * <ul>
15785			<li>$ret['left'] = left margin</li>
15786			<li>$ret['right'] = right margin</li>
15787			<li>$ret['top'] = top margin</li>
15788			<li>$ret['bottom'] = bottom margin</li>
15789			<li>$ret['header'] = header margin</li>
15790			<li>$ret['footer'] = footer margin</li>
15791			<li>$ret['cell'] = cell padding array</li>
15792			<li>$ret['padding_left'] = cell left padding</li>
15793			<li>$ret['padding_top'] = cell top padding</li>
15794			<li>$ret['padding_right'] = cell right padding</li>
15795			<li>$ret['padding_bottom'] = cell bottom padding</li>
15796	 * </ul>
15797	 * @return array containing all margins measures
15798	 * @public
15799	 * @since 3.2.000 (2008-06-23)
15800	 */
15801	public function getMargins() {
15802		$ret = array(
15803			'left' => $this->lMargin,
15804			'right' => $this->rMargin,
15805			'top' => $this->tMargin,
15806			'bottom' => $this->bMargin,
15807			'header' => $this->header_margin,
15808			'footer' => $this->footer_margin,
15809			'cell' => $this->cell_padding,
15810			'padding_left' => $this->cell_padding['L'],
15811			'padding_top' => $this->cell_padding['T'],
15812			'padding_right' => $this->cell_padding['R'],
15813			'padding_bottom' => $this->cell_padding['B']
15814		);
15815		return $ret;
15816	}
15817
15818	/**
15819	 * Returns an array containing original margins:
15820	 * <ul>
15821			<li>$ret['left'] = left margin</li>
15822			<li>$ret['right'] = right margin</li>
15823	 * </ul>
15824	 * @return array containing all margins measures
15825	 * @public
15826	 * @since 4.0.012 (2008-07-24)
15827	 */
15828	public function getOriginalMargins() {
15829		$ret = array(
15830			'left' => $this->original_lMargin,
15831			'right' => $this->original_rMargin
15832		);
15833		return $ret;
15834	}
15835
15836	/**
15837	 * Returns the current font size.
15838	 * @return current font size
15839	 * @public
15840	 * @since 3.2.000 (2008-06-23)
15841	 */
15842	public function getFontSize() {
15843		return $this->FontSize;
15844	}
15845
15846	/**
15847	 * Returns the current font size in points unit.
15848	 * @return current font size in points unit
15849	 * @public
15850	 * @since 3.2.000 (2008-06-23)
15851	 */
15852	public function getFontSizePt() {
15853		return $this->FontSizePt;
15854	}
15855
15856	/**
15857	 * Returns the current font family name.
15858	 * @return string current font family name
15859	 * @public
15860	 * @since 4.3.008 (2008-12-05)
15861	 */
15862	public function getFontFamily() {
15863		return $this->FontFamily;
15864	}
15865
15866	/**
15867	 * Returns the current font style.
15868	 * @return string current font style
15869	 * @public
15870	 * @since 4.3.008 (2008-12-05)
15871	 */
15872	public function getFontStyle() {
15873		return $this->FontStyle;
15874	}
15875
15876	/**
15877	 * Cleanup HTML code (requires HTML Tidy library).
15878	 * @param $html (string) htmlcode to fix
15879	 * @param $default_css (string) CSS commands to add
15880	 * @param $tagvs (array) parameters for setHtmlVSpace method
15881	 * @param $tidy_options (array) options for tidy_parse_string function
15882	 * @return string XHTML code cleaned up
15883	 * @author Nicola Asuni
15884	 * @public
15885	 * @since 5.9.017 (2010-11-16)
15886	 * @see setHtmlVSpace()
15887	 */
15888	public function fixHTMLCode($html, $default_css='', $tagvs='', $tidy_options='') {
15889		return TCPDF_STATIC::fixHTMLCode($html, $default_css, $tagvs, $tidy_options, $this->tagvspaces);
15890	}
15891
15892	/**
15893	 * Returns the border width from CSS property
15894	 * @param $width (string) border width
15895	 * @return int with in user units
15896	 * @protected
15897	 * @since 5.7.000 (2010-08-02)
15898	 */
15899	protected function getCSSBorderWidth($width) {
15900		if ($width == 'thin') {
15901			$width = (2 / $this->k);
15902		} elseif ($width == 'medium') {
15903			$width = (4 / $this->k);
15904		} elseif ($width == 'thick') {
15905			$width = (6 / $this->k);
15906		} else {
15907			$width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
15908		}
15909		return $width;
15910	}
15911
15912	/**
15913	 * Returns the border dash style from CSS property
15914	 * @param $style (string) border style to convert
15915	 * @return int sash style (return -1 in case of none or hidden border)
15916	 * @protected
15917	 * @since 5.7.000 (2010-08-02)
15918	 */
15919	protected function getCSSBorderDashStyle($style) {
15920		switch (strtolower($style)) {
15921			case 'none':
15922			case 'hidden': {
15923				$dash = -1;
15924				break;
15925			}
15926			case 'dotted': {
15927				$dash = 1;
15928				break;
15929			}
15930			case 'dashed': {
15931				$dash = 3;
15932				break;
15933			}
15934			case 'double':
15935			case 'groove':
15936			case 'ridge':
15937			case 'inset':
15938			case 'outset':
15939			case 'solid':
15940			default: {
15941				$dash = 0;
15942				break;
15943			}
15944		}
15945		return $dash;
15946	}
15947
15948	/**
15949	 * Returns the border style array from CSS border properties
15950	 * @param $cssborder (string) border properties
15951	 * @return array containing border properties
15952	 * @protected
15953	 * @since 5.7.000 (2010-08-02)
15954	 */
15955	protected function getCSSBorderStyle($cssborder) {
15956		$bprop = preg_split('/[\s]+/', trim($cssborder));
15957		$border = array(); // value to be returned
15958		switch (count($bprop)) {
15959			case 3: {
15960				$width = $bprop[0];
15961				$style = $bprop[1];
15962				$color = $bprop[2];
15963				break;
15964			}
15965			case 2: {
15966				$width = 'medium';
15967				$style = $bprop[0];
15968				$color = $bprop[1];
15969				break;
15970			}
15971			case 1: {
15972				$width = 'medium';
15973				$style = $bprop[0];
15974				$color = 'black';
15975				break;
15976			}
15977			default: {
15978				$width = 'medium';
15979				$style = 'solid';
15980				$color = 'black';
15981				break;
15982			}
15983		}
15984		if ($style == 'none') {
15985			return array();
15986		}
15987		$border['cap'] = 'square';
15988		$border['join'] = 'miter';
15989		$border['dash'] = $this->getCSSBorderDashStyle($style);
15990		if ($border['dash'] < 0) {
15991			return array();
15992		}
15993		$border['width'] = $this->getCSSBorderWidth($width);
15994		$border['color'] = TCPDF_COLORS::convertHTMLColorToDec($color, $this->spot_colors);
15995		return $border;
15996	}
15997
15998	/**
15999	 * Get the internal Cell padding from CSS attribute.
16000	 * @param $csspadding (string) padding properties
16001	 * @param $width (float) width of the containing element
16002	 * @return array of cell paddings
16003	 * @public
16004	 * @since 5.9.000 (2010-10-04)
16005	 */
16006	public function getCSSPadding($csspadding, $width=0) {
16007		$padding = preg_split('/[\s]+/', trim($csspadding));
16008		$cell_padding = array(); // value to be returned
16009		switch (count($padding)) {
16010			case 4: {
16011				$cell_padding['T'] = $padding[0];
16012				$cell_padding['R'] = $padding[1];
16013				$cell_padding['B'] = $padding[2];
16014				$cell_padding['L'] = $padding[3];
16015				break;
16016			}
16017			case 3: {
16018				$cell_padding['T'] = $padding[0];
16019				$cell_padding['R'] = $padding[1];
16020				$cell_padding['B'] = $padding[2];
16021				$cell_padding['L'] = $padding[1];
16022				break;
16023			}
16024			case 2: {
16025				$cell_padding['T'] = $padding[0];
16026				$cell_padding['R'] = $padding[1];
16027				$cell_padding['B'] = $padding[0];
16028				$cell_padding['L'] = $padding[1];
16029				break;
16030			}
16031			case 1: {
16032				$cell_padding['T'] = $padding[0];
16033				$cell_padding['R'] = $padding[0];
16034				$cell_padding['B'] = $padding[0];
16035				$cell_padding['L'] = $padding[0];
16036				break;
16037			}
16038			default: {
16039				return $this->cell_padding;
16040			}
16041		}
16042		if ($width == 0) {
16043			$width = $this->w - $this->lMargin - $this->rMargin;
16044		}
16045		$cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
16046		$cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
16047		$cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
16048		$cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
16049		return $cell_padding;
16050	}
16051
16052	/**
16053	 * Get the internal Cell margin from CSS attribute.
16054	 * @param $cssmargin (string) margin properties
16055	 * @param $width (float) width of the containing element
16056	 * @return array of cell margins
16057	 * @public
16058	 * @since 5.9.000 (2010-10-04)
16059	 */
16060	public function getCSSMargin($cssmargin, $width=0) {
16061		$margin = preg_split('/[\s]+/', trim($cssmargin));
16062		$cell_margin = array(); // value to be returned
16063		switch (count($margin)) {
16064			case 4: {
16065				$cell_margin['T'] = $margin[0];
16066				$cell_margin['R'] = $margin[1];
16067				$cell_margin['B'] = $margin[2];
16068				$cell_margin['L'] = $margin[3];
16069				break;
16070			}
16071			case 3: {
16072				$cell_margin['T'] = $margin[0];
16073				$cell_margin['R'] = $margin[1];
16074				$cell_margin['B'] = $margin[2];
16075				$cell_margin['L'] = $margin[1];
16076				break;
16077			}
16078			case 2: {
16079				$cell_margin['T'] = $margin[0];
16080				$cell_margin['R'] = $margin[1];
16081				$cell_margin['B'] = $margin[0];
16082				$cell_margin['L'] = $margin[1];
16083				break;
16084			}
16085			case 1: {
16086				$cell_margin['T'] = $margin[0];
16087				$cell_margin['R'] = $margin[0];
16088				$cell_margin['B'] = $margin[0];
16089				$cell_margin['L'] = $margin[0];
16090				break;
16091			}
16092			default: {
16093				return $this->cell_margin;
16094			}
16095		}
16096		if ($width == 0) {
16097			$width = $this->w - $this->lMargin - $this->rMargin;
16098		}
16099		$cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
16100		$cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
16101		$cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
16102		$cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
16103		return $cell_margin;
16104	}
16105
16106	/**
16107	 * Get the border-spacing from CSS attribute.
16108	 * @param $cssbspace (string) border-spacing CSS properties
16109	 * @param $width (float) width of the containing element
16110	 * @return array of border spacings
16111	 * @public
16112	 * @since 5.9.010 (2010-10-27)
16113	 */
16114	public function getCSSBorderMargin($cssbspace, $width=0) {
16115		$space = preg_split('/[\s]+/', trim($cssbspace));
16116		$border_spacing = array(); // value to be returned
16117		switch (count($space)) {
16118			case 2: {
16119				$border_spacing['H'] = $space[0];
16120				$border_spacing['V'] = $space[1];
16121				break;
16122			}
16123			case 1: {
16124				$border_spacing['H'] = $space[0];
16125				$border_spacing['V'] = $space[0];
16126				break;
16127			}
16128			default: {
16129				return array('H' => 0, 'V' => 0);
16130			}
16131		}
16132		if ($width == 0) {
16133			$width = $this->w - $this->lMargin - $this->rMargin;
16134		}
16135		$border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
16136		$border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
16137		return $border_spacing;
16138	}
16139
16140	/**
16141	 * Returns the letter-spacing value from CSS value
16142	 * @param $spacing (string) letter-spacing value
16143	 * @param $parent (float) font spacing (tracking) value of the parent element
16144	 * @return float quantity to increases or decreases the space between characters in a text.
16145	 * @protected
16146	 * @since 5.9.000 (2010-10-02)
16147	 */
16148	protected function getCSSFontSpacing($spacing, $parent=0) {
16149		$val = 0; // value to be returned
16150		$spacing = trim($spacing);
16151		switch ($spacing) {
16152			case 'normal': {
16153				$val = 0;
16154				break;
16155			}
16156			case 'inherit': {
16157				if ($parent == 'normal') {
16158					$val = 0;
16159				} else {
16160					$val = $parent;
16161				}
16162				break;
16163			}
16164			default: {
16165				$val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
16166			}
16167		}
16168		return $val;
16169	}
16170
16171	/**
16172	 * Returns the percentage of font stretching from CSS value
16173	 * @param $stretch (string) stretch mode
16174	 * @param $parent (float) stretch value of the parent element
16175	 * @return float font stretching percentage
16176	 * @protected
16177	 * @since 5.9.000 (2010-10-02)
16178	 */
16179	protected function getCSSFontStretching($stretch, $parent=100) {
16180		$val = 100; // value to be returned
16181		$stretch = trim($stretch);
16182		switch ($stretch) {
16183			case 'ultra-condensed': {
16184				$val = 40;
16185				break;
16186			}
16187			case 'extra-condensed': {
16188				$val = 55;
16189				break;
16190			}
16191			case 'condensed': {
16192				$val = 70;
16193				break;
16194			}
16195			case 'semi-condensed': {
16196				$val = 85;
16197				break;
16198			}
16199			case 'normal': {
16200				$val = 100;
16201				break;
16202			}
16203			case 'semi-expanded': {
16204				$val = 115;
16205				break;
16206			}
16207			case 'expanded': {
16208				$val = 130;
16209				break;
16210			}
16211			case 'extra-expanded': {
16212				$val = 145;
16213				break;
16214			}
16215			case 'ultra-expanded': {
16216				$val = 160;
16217				break;
16218			}
16219			case 'wider': {
16220				$val = ($parent + 10);
16221				break;
16222			}
16223			case 'narrower': {
16224				$val = ($parent - 10);
16225				break;
16226			}
16227			case 'inherit': {
16228				if ($parent == 'normal') {
16229					$val = 100;
16230				} else {
16231					$val = $parent;
16232				}
16233				break;
16234			}
16235			default: {
16236				$val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
16237			}
16238		}
16239		return $val;
16240	}
16241
16242	/**
16243	 * Convert HTML string containing font size value to points
16244	 * @param $val (string) String containing font size value and unit.
16245	 * @param $refsize (float) Reference font size in points.
16246	 * @param $parent_size (float) Parent font size in points.
16247	 * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
16248	 * @return float value in points
16249	 * @public
16250	 */
16251	public function getHTMLFontUnits($val, $refsize=12, $parent_size=12, $defaultunit='pt') {
16252		$refsize = TCPDF_FONTS::getFontRefSize($refsize);
16253		$parent_size = TCPDF_FONTS::getFontRefSize($parent_size, $refsize);
16254		switch ($val) {
16255			case 'xx-small': {
16256				$size = ($refsize - 4);
16257				break;
16258			}
16259			case 'x-small': {
16260				$size = ($refsize - 3);
16261				break;
16262			}
16263			case 'small': {
16264				$size = ($refsize - 2);
16265				break;
16266			}
16267			case 'medium': {
16268				$size = $refsize;
16269				break;
16270			}
16271			case 'large': {
16272				$size = ($refsize + 2);
16273				break;
16274			}
16275			case 'x-large': {
16276				$size = ($refsize + 4);
16277				break;
16278			}
16279			case 'xx-large': {
16280				$size = ($refsize + 6);
16281				break;
16282			}
16283			case 'smaller': {
16284				$size = ($parent_size - 3);
16285				break;
16286			}
16287			case 'larger': {
16288				$size = ($parent_size + 3);
16289				break;
16290			}
16291			default: {
16292				$size = $this->getHTMLUnitToUnits($val, $parent_size, $defaultunit, true);
16293			}
16294		}
16295		return $size;
16296	}
16297
16298	/**
16299	 * Returns the HTML DOM array.
16300	 * @param $html (string) html code
16301	 * @return array
16302	 * @protected
16303	 * @since 3.2.000 (2008-06-20)
16304	 */
16305	protected function getHtmlDomArray($html) {
16306		// array of CSS styles ( selector => properties).
16307		$css = array();
16308		// get CSS array defined at previous call
16309		$matches = array();
16310		if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) {
16311			if (isset($matches[1][0])) {
16312				$css = array_merge($css, json_decode($this->unhtmlentities($matches[1][0]), true));
16313			}
16314			$html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html);
16315		}
16316		// extract external CSS files
16317		$matches = array();
16318		if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) {
16319			foreach ($matches[1] as $key => $link) {
16320				$type = array();
16321				if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
16322					$type = array();
16323					preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
16324					// get 'all' and 'print' media, other media types are discarded
16325					// (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
16326					if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
16327						$type = array();
16328						if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
16329							// read CSS data file
16330							$cssdata = TCPDF_STATIC::fileGetContents(trim($type[1]));
16331							if (($cssdata !== FALSE) AND (strlen($cssdata) > 0)) {
16332								$css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
16333							}
16334						}
16335					}
16336				}
16337			}
16338		}
16339		// extract style tags
16340		$matches = array();
16341		if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) {
16342			foreach ($matches[1] as $key => $media) {
16343				$type = array();
16344				preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
16345				// get 'all' and 'print' media, other media types are discarded
16346				// (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
16347				if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
16348					$cssdata = $matches[2][$key];
16349					$css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
16350				}
16351			}
16352		}
16353		// create a special tag to contain the CSS array (used for table content)
16354		$csstagarray = '<cssarray>'.htmlentities(json_encode($css)).'</cssarray>';
16355		// remove head and style blocks
16356		$html = preg_replace('/<head([^\>]*)>(.*?)<\/head>/siU', '', $html);
16357		$html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html);
16358		// define block tags
16359		$blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
16360		// define self-closing tags
16361		$selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
16362		// remove all unsupported tags (the line below lists all supported tags)
16363		$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>');
16364		//replace some blank characters
16365		$html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
16366		$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);
16367		$html = preg_replace('@(\r\n|\r)@', "\n", $html);
16368		$repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
16369		$html = strtr($html, $repTable);
16370		$offset = 0;
16371		while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
16372			$html_a = substr($html, 0, $offset);
16373			$html_b = substr($html, $offset, ($pos - $offset + 6));
16374			while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
16375				// preserve newlines on <pre> tag
16376				$html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
16377			}
16378			while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) {
16379				// preserve spaces on <pre> tag
16380				$html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b);
16381			}
16382			$html = $html_a.$html_b.substr($html, $pos + 6);
16383			$offset = strlen($html_a.$html_b);
16384		}
16385		$offset = 0;
16386		while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
16387			$html_a = substr($html, 0, $offset);
16388			$html_b = substr($html, $offset, ($pos - $offset + 11));
16389			while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
16390				// preserve newlines on <textarea> tag
16391				$html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
16392				$html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
16393			}
16394			$html = $html_a.$html_b.substr($html, $pos + 11);
16395			$offset = strlen($html_a.$html_b);
16396		}
16397		$html = preg_replace('/([\s]*)<option/si', '<option', $html);
16398		$html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
16399		$offset = 0;
16400		while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
16401			$html_a = substr($html, 0, $offset);
16402			$html_b = substr($html, $offset, ($pos - $offset + 9));
16403			while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
16404				$html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
16405				$html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
16406			}
16407			$html = $html_a.$html_b.substr($html, $pos + 9);
16408			$offset = strlen($html_a.$html_b);
16409		}
16410		if (preg_match("'</select'si", $html)) {
16411			$html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
16412			$html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
16413		}
16414		$html = str_replace("\n", ' ', $html);
16415		// restore textarea newlines
16416		$html = str_replace('<TBR>', "\n", $html);
16417		// remove extra spaces from code
16418		$html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
16419		$html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html);
16420		$html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
16421		$html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html);
16422		$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);
16423		$html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
16424		$html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
16425		$html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html);
16426		$html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1>&nbsp;\\2', $html);
16427		$html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
16428		$html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
16429		$html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
16430		$html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html);
16431		$html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html);
16432		$html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces
16433		$html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces
16434		$html = preg_replace('/<su([bp])/', '<zws/><su\\1', $html); // fix sub/sup alignment
16435		$html = preg_replace('/<\/su([bp])>/', '</su\\1><zws/>', $html); // fix sub/sup alignment
16436		$html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space
16437		// trim string
16438		$html = $this->stringTrim($html);
16439		// fix br tag after li
16440		$html = preg_replace('/<li><br([^\>]*)>/', '<li> <br\\1>', $html);
16441		// fix first image tag alignment
16442		$html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
16443		// pattern for generic tag
16444		$tagpattern = '/(<[^>]+>)/';
16445		// explodes the string
16446		$a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
16447		// count elements
16448		$maxel = count($a);
16449		$elkey = 0;
16450		$key = 0;
16451		// create an array of elements
16452		$dom = array();
16453		$dom[$key] = array();
16454		// set inheritable properties fot the first void element
16455		// 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
16456		$dom[$key]['tag'] = false;
16457		$dom[$key]['block'] = false;
16458		$dom[$key]['value'] = '';
16459		$dom[$key]['parent'] = 0;
16460		$dom[$key]['hide'] = false;
16461		$dom[$key]['fontname'] = $this->FontFamily;
16462		$dom[$key]['fontstyle'] = $this->FontStyle;
16463		$dom[$key]['fontsize'] = $this->FontSizePt;
16464		$dom[$key]['font-stretch'] = $this->font_stretching;
16465		$dom[$key]['letter-spacing'] = $this->font_spacing;
16466		$dom[$key]['stroke'] = $this->textstrokewidth;
16467		$dom[$key]['fill'] = (($this->textrendermode % 2) == 0);
16468		$dom[$key]['clip'] = ($this->textrendermode > 3);
16469		$dom[$key]['line-height'] = $this->cell_height_ratio;
16470		$dom[$key]['bgcolor'] = false;
16471		$dom[$key]['fgcolor'] = $this->fgcolor; // color
16472		$dom[$key]['strokecolor'] = $this->strokecolor;
16473		$dom[$key]['align'] = '';
16474		$dom[$key]['listtype'] = '';
16475		$dom[$key]['text-indent'] = 0;
16476		$dom[$key]['text-transform'] = '';
16477		$dom[$key]['border'] = array();
16478		$dom[$key]['dir'] = $this->rtl?'rtl':'ltr';
16479		$thead = false; // true when we are inside the THEAD tag
16480		++$key;
16481		$level = array();
16482		array_push($level, 0); // root
16483		while ($elkey < $maxel) {
16484			$dom[$key] = array();
16485			$element = $a[$elkey];
16486			$dom[$key]['elkey'] = $elkey;
16487			if (preg_match($tagpattern, $element)) {
16488				// html tag
16489				$element = substr($element, 1, -1);
16490				// get tag name
16491				preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
16492				$tagname = strtolower($tag[1]);
16493				// check if we are inside a table header
16494				if ($tagname == 'thead') {
16495					if ($element[0] == '/') {
16496						$thead = false;
16497					} else {
16498						$thead = true;
16499					}
16500					++$elkey;
16501					continue;
16502				}
16503				$dom[$key]['tag'] = true;
16504				$dom[$key]['value'] = $tagname;
16505				if (in_array($dom[$key]['value'], $blocktags)) {
16506					$dom[$key]['block'] = true;
16507				} else {
16508					$dom[$key]['block'] = false;
16509				}
16510				if ($element[0] == '/') {
16511					// *** closing html tag
16512					$dom[$key]['opening'] = false;
16513					$dom[$key]['parent'] = end($level);
16514					array_pop($level);
16515					$dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
16516					$dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
16517					$dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
16518					$dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
16519					$dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
16520					$dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
16521					$dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
16522					$dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
16523					$dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
16524					$dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
16525					$dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
16526					$dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
16527					$dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
16528					$dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
16529					$dom[$key]['text-transform'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['text-transform'];
16530					$dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
16531					if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
16532						$dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
16533					}
16534					// set the number of columns in table tag
16535					if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
16536						$dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
16537					}
16538					if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
16539						$dom[($dom[$key]['parent'])]['content'] = $csstagarray;
16540						for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
16541							$dom[($dom[$key]['parent'])]['content'] .= stripslashes($a[$dom[$i]['elkey']]);
16542						}
16543						$key = $i;
16544						// mark nested tables
16545						$dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
16546						// remove thead sections from nested tables
16547						$dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
16548						$dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
16549					}
16550					// store header rows on a new table
16551					if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] === true)) {
16552						if (TCPDF_STATIC::empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
16553							$dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
16554						}
16555						for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
16556							$dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
16557						}
16558						if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
16559							$dom[($dom[$key]['parent'])]['attribute'] = array();
16560						}
16561						// header elements must be always contained in a single page
16562						$dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
16563					}
16564					if (($dom[$key]['value'] == 'table') AND (!TCPDF_STATIC::empty_string($dom[($dom[$key]['parent'])]['thead']))) {
16565						// remove the nobr attributes from the table header
16566						$dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
16567						$dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
16568					}
16569				} else {
16570					// *** opening or self-closing html tag
16571					$dom[$key]['opening'] = true;
16572					$dom[$key]['parent'] = end($level);
16573					if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
16574						// self-closing tag
16575						$dom[$key]['self'] = true;
16576					} else {
16577						// opening tag
16578						array_push($level, $key);
16579						$dom[$key]['self'] = false;
16580					}
16581					// copy some values from parent
16582					$parentkey = 0;
16583					if ($key > 0) {
16584						$parentkey = $dom[$key]['parent'];
16585						$dom[$key]['hide'] = $dom[$parentkey]['hide'];
16586						$dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
16587						$dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
16588						$dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
16589						$dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
16590						$dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
16591						$dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
16592						$dom[$key]['fill'] = $dom[$parentkey]['fill'];
16593						$dom[$key]['clip'] = $dom[$parentkey]['clip'];
16594						$dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
16595						$dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
16596						$dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
16597						$dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
16598						$dom[$key]['align'] = $dom[$parentkey]['align'];
16599						$dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
16600						$dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
16601						$dom[$key]['text-transform'] = $dom[$parentkey]['text-transform'];
16602						$dom[$key]['border'] = array();
16603						$dom[$key]['dir'] = $dom[$parentkey]['dir'];
16604					}
16605					// get attributes
16606					preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER);
16607					$dom[$key]['attribute'] = array(); // reset attribute array
16608                    foreach($attr_array[1] as $id => $name) {
16609                        $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
16610                    }
16611					if (!empty($css)) {
16612						// merge CSS style to current style
16613						list($dom[$key]['csssel'], $dom[$key]['cssdata']) = TCPDF_STATIC::getCSSdataArray($dom, $key, $css);
16614						$dom[$key]['attribute']['style'] = TCPDF_STATIC::getTagStyleFromCSSarray($dom[$key]['cssdata']);
16615					}
16616					// split style attributes
16617					if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
16618						// get style attributes
16619						preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
16620						$dom[$key]['style'] = array(); // reset style attribute array
16621                        foreach($style_array[1] as $id => $name) {
16622                            // in case of duplicate attribute the last replace the previous
16623                            $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
16624                        }
16625						// --- get some style attributes ---
16626						// text direction
16627						if (isset($dom[$key]['style']['direction'])) {
16628							$dom[$key]['dir'] = $dom[$key]['style']['direction'];
16629						}
16630						// display
16631						if (isset($dom[$key]['style']['display'])) {
16632							$dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
16633						}
16634						// font family
16635						if (isset($dom[$key]['style']['font-family'])) {
16636							$dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
16637						}
16638						// list-style-type
16639						if (isset($dom[$key]['style']['list-style-type'])) {
16640							$dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
16641							if ($dom[$key]['listtype'] == 'inherit') {
16642								$dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
16643							}
16644						}
16645						// text-indent
16646						if (isset($dom[$key]['style']['text-indent'])) {
16647							$dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
16648							if ($dom[$key]['text-indent'] == 'inherit') {
16649								$dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
16650							}
16651						}
16652						// text-transform
16653						if (isset($dom[$key]['style']['text-transform'])) {
16654							$dom[$key]['text-transform'] = $dom[$key]['style']['text-transform'];
16655						}
16656						// font size
16657						if (isset($dom[$key]['style']['font-size'])) {
16658							$fsize = trim($dom[$key]['style']['font-size']);
16659							$dom[$key]['fontsize'] = $this->getHTMLFontUnits($fsize, $dom[0]['fontsize'], $dom[$parentkey]['fontsize'], 'pt');
16660						}
16661						// font-stretch
16662						if (isset($dom[$key]['style']['font-stretch'])) {
16663							$dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
16664						}
16665						// letter-spacing
16666						if (isset($dom[$key]['style']['letter-spacing'])) {
16667							$dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
16668						}
16669						// line-height (internally is the cell height ratio)
16670						if (isset($dom[$key]['style']['line-height'])) {
16671							$lineheight = trim($dom[$key]['style']['line-height']);
16672							switch ($lineheight) {
16673								// A normal line height. This is default
16674								case 'normal': {
16675									$dom[$key]['line-height'] = $dom[0]['line-height'];
16676									break;
16677								}
16678								case 'inherit': {
16679									$dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
16680								}
16681								default: {
16682									if (is_numeric($lineheight)) {
16683										// convert to percentage of font height
16684										$lineheight = ($lineheight * 100).'%';
16685									}
16686									$dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
16687									if (substr($lineheight, -1) !== '%') {
16688										if ($dom[$key]['fontsize'] <= 0) {
16689											$dom[$key]['line-height'] = 1;
16690										} else {
16691											$dom[$key]['line-height'] = (($dom[$key]['line-height'] - $this->cell_padding['T'] - $this->cell_padding['B']) / $dom[$key]['fontsize']);
16692										}
16693									}
16694								}
16695							}
16696						}
16697						// font style
16698						if (isset($dom[$key]['style']['font-weight'])) {
16699							if (strtolower($dom[$key]['style']['font-weight'][0]) == 'n') {
16700								if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
16701									$dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
16702								}
16703							} elseif (strtolower($dom[$key]['style']['font-weight'][0]) == 'b') {
16704								$dom[$key]['fontstyle'] .= 'B';
16705							}
16706						}
16707						if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style'][0]) == 'i')) {
16708							$dom[$key]['fontstyle'] .= 'I';
16709						}
16710						// font color
16711						if (isset($dom[$key]['style']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['color']))) {
16712							$dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['color'], $this->spot_colors);
16713						} elseif ($dom[$key]['value'] == 'a') {
16714							$dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
16715						}
16716						// background color
16717						if (isset($dom[$key]['style']['background-color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['background-color']))) {
16718							$dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['background-color'], $this->spot_colors);
16719						}
16720						// text-decoration
16721						if (isset($dom[$key]['style']['text-decoration'])) {
16722							$decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
16723							foreach ($decors as $dec) {
16724								$dec = trim($dec);
16725								if (!TCPDF_STATIC::empty_string($dec)) {
16726									if ($dec[0] == 'u') {
16727										// underline
16728										$dom[$key]['fontstyle'] .= 'U';
16729									} elseif ($dec[0] == 'l') {
16730										// line-through
16731										$dom[$key]['fontstyle'] .= 'D';
16732									} elseif ($dec[0] == 'o') {
16733										// overline
16734										$dom[$key]['fontstyle'] .= 'O';
16735									}
16736								}
16737							}
16738						} elseif ($dom[$key]['value'] == 'a') {
16739							$dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
16740						}
16741						// check for width attribute
16742						if (isset($dom[$key]['style']['width'])) {
16743							$dom[$key]['width'] = $dom[$key]['style']['width'];
16744						}
16745						// check for height attribute
16746						if (isset($dom[$key]['style']['height'])) {
16747							$dom[$key]['height'] = $dom[$key]['style']['height'];
16748						}
16749						// check for text alignment
16750						if (isset($dom[$key]['style']['text-align'])) {
16751							$dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align'][0]);
16752						}
16753						// check for CSS border properties
16754						if (isset($dom[$key]['style']['border'])) {
16755							$borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
16756							if (!empty($borderstyle)) {
16757								$dom[$key]['border']['LTRB'] = $borderstyle;
16758							}
16759						}
16760						if (isset($dom[$key]['style']['border-color'])) {
16761							$brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
16762							if (isset($brd_colors[3])) {
16763								$dom[$key]['border']['L']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[3], $this->spot_colors);
16764							}
16765							if (isset($brd_colors[1])) {
16766								$dom[$key]['border']['R']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[1], $this->spot_colors);
16767							}
16768							if (isset($brd_colors[0])) {
16769								$dom[$key]['border']['T']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[0], $this->spot_colors);
16770							}
16771							if (isset($brd_colors[2])) {
16772								$dom[$key]['border']['B']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[2], $this->spot_colors);
16773							}
16774						}
16775						if (isset($dom[$key]['style']['border-width'])) {
16776							$brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
16777							if (isset($brd_widths[3])) {
16778								$dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
16779							}
16780							if (isset($brd_widths[1])) {
16781								$dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
16782							}
16783							if (isset($brd_widths[0])) {
16784								$dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
16785							}
16786							if (isset($brd_widths[2])) {
16787								$dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
16788							}
16789						}
16790						if (isset($dom[$key]['style']['border-style'])) {
16791							$brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
16792							if (isset($brd_styles[3]) AND ($brd_styles[3]!='none')) {
16793								$dom[$key]['border']['L']['cap'] = 'square';
16794								$dom[$key]['border']['L']['join'] = 'miter';
16795								$dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
16796								if ($dom[$key]['border']['L']['dash'] < 0) {
16797									$dom[$key]['border']['L'] = array();
16798								}
16799							}
16800							if (isset($brd_styles[1])) {
16801								$dom[$key]['border']['R']['cap'] = 'square';
16802								$dom[$key]['border']['R']['join'] = 'miter';
16803								$dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
16804								if ($dom[$key]['border']['R']['dash'] < 0) {
16805									$dom[$key]['border']['R'] = array();
16806								}
16807							}
16808							if (isset($brd_styles[0])) {
16809								$dom[$key]['border']['T']['cap'] = 'square';
16810								$dom[$key]['border']['T']['join'] = 'miter';
16811								$dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
16812								if ($dom[$key]['border']['T']['dash'] < 0) {
16813									$dom[$key]['border']['T'] = array();
16814								}
16815							}
16816							if (isset($brd_styles[2])) {
16817								$dom[$key]['border']['B']['cap'] = 'square';
16818								$dom[$key]['border']['B']['join'] = 'miter';
16819								$dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
16820								if ($dom[$key]['border']['B']['dash'] < 0) {
16821									$dom[$key]['border']['B'] = array();
16822								}
16823							}
16824						}
16825						$cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
16826						foreach ($cellside as $bsk => $bsv) {
16827							if (isset($dom[$key]['style']['border-'.$bsv])) {
16828								$borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
16829								if (!empty($borderstyle)) {
16830									$dom[$key]['border'][$bsk] = $borderstyle;
16831								}
16832							}
16833							if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
16834								$dom[$key]['border'][$bsk]['color'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color'], $this->spot_colors);
16835							}
16836							if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
16837								$dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
16838							}
16839							if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
16840								$dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
16841								if ($dom[$key]['border'][$bsk]['dash'] < 0) {
16842									$dom[$key]['border'][$bsk] = array();
16843								}
16844							}
16845						}
16846						// check for CSS padding properties
16847						if (isset($dom[$key]['style']['padding'])) {
16848							$dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
16849						} else {
16850							$dom[$key]['padding'] = $this->cell_padding;
16851						}
16852						foreach ($cellside as $psk => $psv) {
16853							if (isset($dom[$key]['style']['padding-'.$psv])) {
16854								$dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
16855							}
16856						}
16857						// check for CSS margin properties
16858						if (isset($dom[$key]['style']['margin'])) {
16859							$dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
16860						} else {
16861							$dom[$key]['margin'] = $this->cell_margin;
16862						}
16863						foreach ($cellside as $psk => $psv) {
16864							if (isset($dom[$key]['style']['margin-'.$psv])) {
16865								$dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
16866							}
16867						}
16868						// check for CSS border-spacing properties
16869						if (isset($dom[$key]['style']['border-spacing'])) {
16870							$dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
16871						}
16872						// page-break-inside
16873						if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
16874							$dom[$key]['attribute']['nobr'] = 'true';
16875						}
16876						// page-break-before
16877						if (isset($dom[$key]['style']['page-break-before'])) {
16878							if ($dom[$key]['style']['page-break-before'] == 'always') {
16879								$dom[$key]['attribute']['pagebreak'] = 'true';
16880							} elseif ($dom[$key]['style']['page-break-before'] == 'left') {
16881								$dom[$key]['attribute']['pagebreak'] = 'left';
16882							} elseif ($dom[$key]['style']['page-break-before'] == 'right') {
16883								$dom[$key]['attribute']['pagebreak'] = 'right';
16884							}
16885						}
16886						// page-break-after
16887						if (isset($dom[$key]['style']['page-break-after'])) {
16888							if ($dom[$key]['style']['page-break-after'] == 'always') {
16889								$dom[$key]['attribute']['pagebreakafter'] = 'true';
16890							} elseif ($dom[$key]['style']['page-break-after'] == 'left') {
16891								$dom[$key]['attribute']['pagebreakafter'] = 'left';
16892							} elseif ($dom[$key]['style']['page-break-after'] == 'right') {
16893								$dom[$key]['attribute']['pagebreakafter'] = 'right';
16894							}
16895						}
16896					}
16897					if (isset($dom[$key]['attribute']['display'])) {
16898						$dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
16899					}
16900					if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
16901						$borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
16902						if (!empty($borderstyle)) {
16903							$dom[$key]['border']['LTRB'] = $borderstyle;
16904						}
16905					}
16906					// check for font tag
16907					if ($dom[$key]['value'] == 'font') {
16908						// font family
16909						if (isset($dom[$key]['attribute']['face'])) {
16910							$dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
16911						}
16912						// font size
16913						if (isset($dom[$key]['attribute']['size'])) {
16914							if ($key > 0) {
16915								if ($dom[$key]['attribute']['size'][0] == '+') {
16916									$dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
16917								} elseif ($dom[$key]['attribute']['size'][0] == '-') {
16918									$dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
16919								} else {
16920									$dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
16921								}
16922							} else {
16923								$dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
16924							}
16925						}
16926					}
16927					// force natural alignment for lists
16928					if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
16929						AND (!isset($dom[$key]['align']) OR TCPDF_STATIC::empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
16930						if ($this->rtl) {
16931							$dom[$key]['align'] = 'R';
16932						} else {
16933							$dom[$key]['align'] = 'L';
16934						}
16935					}
16936					if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
16937						if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
16938							$dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
16939						}
16940					}
16941					if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
16942						$dom[$key]['fontstyle'] .= 'B';
16943					}
16944					if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
16945						$dom[$key]['fontstyle'] .= 'I';
16946					}
16947					if ($dom[$key]['value'] == 'u') {
16948						$dom[$key]['fontstyle'] .= 'U';
16949					}
16950					if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
16951						$dom[$key]['fontstyle'] .= 'D';
16952					}
16953					if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
16954						$dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
16955					}
16956					if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
16957						$dom[$key]['fontname'] = $this->default_monospaced_font;
16958					}
16959					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)) {
16960						// headings h1, h2, h3, h4, h5, h6
16961						if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
16962							$headsize = (4 - intval($dom[$key]['value'][1])) * 2;
16963							$dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
16964						}
16965						if (!isset($dom[$key]['style']['font-weight'])) {
16966							$dom[$key]['fontstyle'] .= 'B';
16967						}
16968					}
16969					if (($dom[$key]['value'] == 'table')) {
16970						$dom[$key]['rows'] = 0; // number of rows
16971						$dom[$key]['trids'] = array(); // IDs of TR elements
16972						$dom[$key]['thead'] = ''; // table header rows
16973					}
16974					if (($dom[$key]['value'] == 'tr')) {
16975						$dom[$key]['cols'] = 0;
16976						if ($thead) {
16977							$dom[$key]['thead'] = true;
16978							// rows on thead block are printed as a separate table
16979						} else {
16980							$dom[$key]['thead'] = false;
16981							// store the number of rows on table element
16982							++$dom[($dom[$key]['parent'])]['rows'];
16983							// store the TR elements IDs on table element
16984							array_push($dom[($dom[$key]['parent'])]['trids'], $key);
16985						}
16986					}
16987					if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
16988						if (isset($dom[$key]['attribute']['colspan'])) {
16989							$colspan = intval($dom[$key]['attribute']['colspan']);
16990						} else {
16991							$colspan = 1;
16992						}
16993						$dom[$key]['attribute']['colspan'] = $colspan;
16994						$dom[($dom[$key]['parent'])]['cols'] += $colspan;
16995					}
16996					// text direction
16997					if (isset($dom[$key]['attribute']['dir'])) {
16998						$dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
16999					}
17000					// set foreground color attribute
17001					if (isset($dom[$key]['attribute']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['color']))) {
17002						$dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['color'], $this->spot_colors);
17003					} elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
17004						$dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
17005					}
17006					// set background color attribute
17007					if (isset($dom[$key]['attribute']['bgcolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['bgcolor']))) {
17008						$dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['bgcolor'], $this->spot_colors);
17009					}
17010					// set stroke color attribute
17011					if (isset($dom[$key]['attribute']['strokecolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['strokecolor']))) {
17012						$dom[$key]['strokecolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['strokecolor'], $this->spot_colors);
17013					}
17014					// check for width attribute
17015					if (isset($dom[$key]['attribute']['width'])) {
17016						$dom[$key]['width'] = $dom[$key]['attribute']['width'];
17017					}
17018					// check for height attribute
17019					if (isset($dom[$key]['attribute']['height'])) {
17020						$dom[$key]['height'] = $dom[$key]['attribute']['height'];
17021					}
17022					// check for text alignment
17023					if (isset($dom[$key]['attribute']['align']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
17024						$dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align'][0]);
17025					}
17026					// check for text rendering mode (the following attributes do not exist in HTML)
17027					if (isset($dom[$key]['attribute']['stroke'])) {
17028						// font stroke width
17029						$dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
17030					}
17031					if (isset($dom[$key]['attribute']['fill'])) {
17032						// font fill
17033						if ($dom[$key]['attribute']['fill'] == 'true') {
17034							$dom[$key]['fill'] = true;
17035						} else {
17036							$dom[$key]['fill'] = false;
17037						}
17038					}
17039					if (isset($dom[$key]['attribute']['clip'])) {
17040						// clipping mode
17041						if ($dom[$key]['attribute']['clip'] == 'true') {
17042							$dom[$key]['clip'] = true;
17043						} else {
17044							$dom[$key]['clip'] = false;
17045						}
17046					}
17047				} // end opening tag
17048			} else {
17049				// text
17050				$dom[$key]['tag'] = false;
17051				$dom[$key]['block'] = false;
17052				$dom[$key]['parent'] = end($level);
17053				$dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
17054				if (!empty($dom[$dom[$key]['parent']]['text-transform'])) {
17055					// text-transform for unicode requires mb_convert_case (Multibyte String Functions)
17056					if (function_exists('mb_convert_case')) {
17057						$ttm = array('capitalize' => MB_CASE_TITLE, 'uppercase' => MB_CASE_UPPER, 'lowercase' => MB_CASE_LOWER);
17058						if (isset($ttm[$dom[$dom[$key]['parent']]['text-transform']])) {
17059							$element = mb_convert_case($element, $ttm[$dom[$dom[$key]['parent']]['text-transform']], $this->encoding);
17060						}
17061					} elseif (!$this->isunicode) {
17062						switch ($dom[$dom[$key]['parent']]['text-transform']) {
17063							case 'capitalize': {
17064								$element = ucwords(strtolower($element));
17065								break;
17066							}
17067							case 'uppercase': {
17068								$element = strtoupper($element);
17069								break;
17070							}
17071							case 'lowercase': {
17072								$element = strtolower($element);
17073								break;
17074							}
17075						}
17076					}
17077				}
17078				$dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
17079			}
17080			++$elkey;
17081			++$key;
17082		}
17083		return $dom;
17084	}
17085
17086	/**
17087	 * Returns the string used to find spaces
17088	 * @return string
17089	 * @protected
17090	 * @author Nicola Asuni
17091	 * @since 4.8.024 (2010-01-15)
17092	 */
17093	protected function getSpaceString() {
17094		$spacestr = chr(32);
17095		if ($this->isUnicodeFont()) {
17096			$spacestr = chr(0).chr(32);
17097		}
17098		return $spacestr;
17099	}
17100
17101	/**
17102	 * Return an hash code used to ensure that the serialized data has been generated by this TCPDF instance.
17103	 * @param $data (string) serialized data
17104	 * @return string
17105	 * @public static
17106	 */
17107	protected function getHashForTCPDFtagParams($data) {
17108		return md5(strlen($data).$this->file_id.$data);
17109	}
17110
17111	/**
17112	 * Serialize an array of parameters to be used with TCPDF tag in HTML code.
17113	 * @param $data (array) parameters array
17114	 * @return string containing serialized data
17115	 * @public static
17116	 */
17117	public function serializeTCPDFtagParameters($data) {
17118		$encoded = urlencode(json_encode($data));
17119		return $this->getHashForTCPDFtagParams($encoded).$encoded;
17120	}
17121
17122	/**
17123	 * Unserialize parameters to be used with TCPDF tag in HTML code.
17124	 * @param $data (string) serialized data
17125	 * @return array containing unserialized data
17126	 * @protected static
17127	 */
17128	protected function unserializeTCPDFtagParameters($data) {
17129		$hash = substr($data, 0, 32);
17130		$encoded = substr($data, 32);
17131		if ($hash != $this->getHashForTCPDFtagParams($encoded)) {
17132			$this->Error('Invalid parameters');
17133		}
17134		return json_decode(urldecode($encoded), true);
17135	}
17136
17137	/**
17138	 * Prints a cell (rectangular area) with optional borders, background color and html text string.
17139	 * 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 />
17140	 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
17141	 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
17142	 * 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
17143	 * NOTE: all the HTML attributes must be enclosed in double-quote.
17144	 * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
17145	 * @param $h (float) Cell minimum height. The cell extends automatically if needed.
17146	 * @param $x (float) upper-left corner X coordinate
17147	 * @param $y (float) upper-left corner Y coordinate
17148	 * @param $html (string) html text to print. Default value: empty string.
17149	 * @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)))
17150	 * @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>
17151Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
17152	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
17153	 * @param $reseth (boolean) if true reset the last cell height (default true).
17154	 * @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>
17155	 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
17156	 * @see Multicell(), writeHTML()
17157	 * @public
17158	 */
17159	public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
17160		return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
17161	}
17162
17163	/**
17164	 * Allows to preserve some HTML formatting (limited support).<br />
17165	 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
17166	 * 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
17167	 * NOTE: all the HTML attributes must be enclosed in double-quote.
17168	 * @param $html (string) text to display
17169	 * @param $ln (boolean) if true add a new line after text (default = true)
17170	 * @param $fill (boolean) Indicates if the background must be painted (true) or transparent (false).
17171	 * @param $reseth (boolean) if true reset the last cell height (default false).
17172	 * @param $cell (boolean) if true add the current left (or right for RTL) padding to each Write (default false).
17173	 * @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>
17174	 * @public
17175	 */
17176	public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
17177		$gvars = $this->getGraphicVars();
17178		// store current values
17179		$prev_cell_margin = $this->cell_margin;
17180		$prev_cell_padding = $this->cell_padding;
17181		$prevPage = $this->page;
17182		$prevlMargin = $this->lMargin;
17183		$prevrMargin = $this->rMargin;
17184		$curfontname = $this->FontFamily;
17185		$curfontstyle = $this->FontStyle;
17186		$curfontsize = $this->FontSizePt;
17187		$curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
17188		$curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
17189		$curfontstretcing = $this->font_stretching;
17190		$curfonttracking = $this->font_spacing;
17191		$this->newline = true;
17192		$newline = true;
17193		$startlinepage = $this->page;
17194		$minstartliney = $this->y;
17195		$maxbottomliney = 0;
17196		$startlinex = $this->x;
17197		$startliney = $this->y;
17198		$yshift = 0;
17199		$loop = 0;
17200		$curpos = 0;
17201		$this_method_vars = array();
17202		$undo = false;
17203		$fontaligned = false;
17204		$reverse_dir = false; // true when the text direction is reversed
17205		$this->premode = false;
17206		if ($this->inxobj) {
17207			// we are inside an XObject template
17208			$pask = count($this->xobjects[$this->xobjid]['annotations']);
17209		} elseif (isset($this->PageAnnots[$this->page])) {
17210			$pask = count($this->PageAnnots[$this->page]);
17211		} else {
17212			$pask = 0;
17213		}
17214		if ($this->inxobj) {
17215			// we are inside an XObject template
17216			$startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
17217		} elseif (!$this->InFooter) {
17218			if (isset($this->footerlen[$this->page])) {
17219				$this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
17220			} else {
17221				$this->footerpos[$this->page] = $this->pagelen[$this->page];
17222			}
17223			$startlinepos = $this->footerpos[$this->page];
17224		} else {
17225			// we are inside the footer
17226			$startlinepos = $this->pagelen[$this->page];
17227		}
17228		$lalign = $align;
17229		$plalign = $align;
17230		if ($this->rtl) {
17231			$w = $this->x - $this->lMargin;
17232		} else {
17233			$w = $this->w - $this->rMargin - $this->x;
17234		}
17235		$w -= ($this->cell_padding['L'] + $this->cell_padding['R']);
17236		if ($cell) {
17237			if ($this->rtl) {
17238				$this->x -= $this->cell_padding['R'];
17239				$this->lMargin += $this->cell_padding['L'];
17240			} else {
17241				$this->x += $this->cell_padding['L'];
17242				$this->rMargin += $this->cell_padding['R'];
17243			}
17244		}
17245		if ($this->customlistindent >= 0) {
17246			$this->listindent = $this->customlistindent;
17247		} else {
17248			$this->listindent = $this->GetStringWidth('000000');
17249		}
17250		$this->listindentlevel = 0;
17251		// save previous states
17252		$prev_cell_height_ratio = $this->cell_height_ratio;
17253		$prev_listnum = $this->listnum;
17254		$prev_listordered = $this->listordered;
17255		$prev_listcount = $this->listcount;
17256		$prev_lispacer = $this->lispacer;
17257		$this->listnum = 0;
17258		$this->listordered = array();
17259		$this->listcount = array();
17260		$this->lispacer = '';
17261		if ((TCPDF_STATIC::empty_string($this->lasth)) OR ($reseth)) {
17262			// reset row height
17263			$this->resetLastH();
17264		}
17265		$dom = $this->getHtmlDomArray($html);
17266		$maxel = count($dom);
17267		$key = 0;
17268		while ($key < $maxel) {
17269			if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND $dom[$key]['hide']) {
17270				// store the node key
17271				$hidden_node_key = $key;
17272				if ($dom[$key]['self']) {
17273					// skip just this self-closing tag
17274					++$key;
17275				} else {
17276					// skip this and all children tags
17277					while (($key < $maxel) AND (!$dom[$key]['tag'] OR $dom[$key]['opening'] OR ($dom[$key]['parent'] != $hidden_node_key))) {
17278						// skip hidden objects
17279						++$key;
17280					}
17281					++$key;
17282				}
17283			}
17284			if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
17285				// check for pagebreak
17286				if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
17287					// add a page (or trig AcceptPageBreak() for multicolumn mode)
17288					$this->checkPageBreak($this->PageBreakTrigger + 1);
17289					$this->htmlvspace = ($this->PageBreakTrigger + 1);
17290				}
17291				if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
17292					OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
17293					// add a page (or trig AcceptPageBreak() for multicolumn mode)
17294					$this->checkPageBreak($this->PageBreakTrigger + 1);
17295					$this->htmlvspace = ($this->PageBreakTrigger + 1);
17296				}
17297			}
17298			if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
17299				if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
17300					$dom[$key]['attribute']['nobr'] = false;
17301				} else {
17302					// store current object
17303					$this->startTransaction();
17304					// save this method vars
17305					$this_method_vars['html'] = $html;
17306					$this_method_vars['ln'] = $ln;
17307					$this_method_vars['fill'] = $fill;
17308					$this_method_vars['reseth'] = $reseth;
17309					$this_method_vars['cell'] = $cell;
17310					$this_method_vars['align'] = $align;
17311					$this_method_vars['gvars'] = $gvars;
17312					$this_method_vars['prevPage'] = $prevPage;
17313					$this_method_vars['prev_cell_margin'] = $prev_cell_margin;
17314					$this_method_vars['prev_cell_padding'] = $prev_cell_padding;
17315					$this_method_vars['prevlMargin'] = $prevlMargin;
17316					$this_method_vars['prevrMargin'] = $prevrMargin;
17317					$this_method_vars['curfontname'] = $curfontname;
17318					$this_method_vars['curfontstyle'] = $curfontstyle;
17319					$this_method_vars['curfontsize'] = $curfontsize;
17320					$this_method_vars['curfontascent'] = $curfontascent;
17321					$this_method_vars['curfontdescent'] = $curfontdescent;
17322					$this_method_vars['curfontstretcing'] = $curfontstretcing;
17323					$this_method_vars['curfonttracking'] = $curfonttracking;
17324					$this_method_vars['minstartliney'] = $minstartliney;
17325					$this_method_vars['maxbottomliney'] = $maxbottomliney;
17326					$this_method_vars['yshift'] = $yshift;
17327					$this_method_vars['startlinepage'] = $startlinepage;
17328					$this_method_vars['startlinepos'] = $startlinepos;
17329					$this_method_vars['startlinex'] = $startlinex;
17330					$this_method_vars['startliney'] = $startliney;
17331					$this_method_vars['newline'] = $newline;
17332					$this_method_vars['loop'] = $loop;
17333					$this_method_vars['curpos'] = $curpos;
17334					$this_method_vars['pask'] = $pask;
17335					$this_method_vars['lalign'] = $lalign;
17336					$this_method_vars['plalign'] = $plalign;
17337					$this_method_vars['w'] = $w;
17338					$this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
17339					$this_method_vars['prev_listnum'] = $prev_listnum;
17340					$this_method_vars['prev_listordered'] = $prev_listordered;
17341					$this_method_vars['prev_listcount'] = $prev_listcount;
17342					$this_method_vars['prev_lispacer'] = $prev_lispacer;
17343					$this_method_vars['fontaligned'] = $fontaligned;
17344					$this_method_vars['key'] = $key;
17345					$this_method_vars['dom'] = $dom;
17346				}
17347			}
17348			// print THEAD block
17349			if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
17350				if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !TCPDF_STATIC::empty_string($dom[$dom[$key]['parent']]['thead'])) {
17351					$this->inthead = true;
17352					// print table header (thead)
17353					$this->writeHTML($this->thead, false, false, false, false, '');
17354					// check if we are on a new page or on a new column
17355					if (($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) {
17356						// we are on a new page or on a new column and the total object height is less than the available vertical space.
17357						// restore previous object
17358						$this->rollbackTransaction(true);
17359						// restore previous values
17360						foreach ($this_method_vars as $vkey => $vval) {
17361							$$vkey = $vval;
17362						}
17363						// disable table header
17364						$tmp_thead = $this->thead;
17365						$this->thead = '';
17366						// add a page (or trig AcceptPageBreak() for multicolumn mode)
17367						$pre_y = $this->y;
17368						if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
17369							// fix for multicolumn mode
17370							$startliney = $this->y;
17371						}
17372						$this->start_transaction_page = $this->page;
17373						$this->start_transaction_y = $this->y;
17374						// restore table header
17375						$this->thead = $tmp_thead;
17376						// fix table border properties
17377						if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
17378							$tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
17379						} elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
17380							$tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
17381						} else {
17382							$tmp_cellspacing = 0;
17383						}
17384						$dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page;
17385						$dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column;
17386						$dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing;
17387						$xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']);
17388						$dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset;
17389						$dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset;
17390						// print table header (thead)
17391						$this->writeHTML($this->thead, false, false, false, false, '');
17392					}
17393				}
17394				// move $key index forward to skip THEAD block
17395				while ( ($key < $maxel) AND (!(
17396					($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
17397					OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
17398					++$key;
17399				}
17400			}
17401			if ($dom[$key]['tag'] OR ($key == 0)) {
17402				if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
17403					$dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
17404				}
17405				// vertically align image in line
17406				if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
17407					// get image height
17408					$imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], ($dom[$key]['fontsize'] / $this->k), 'px');
17409					$autolinebreak = false;
17410					if (!empty($dom[$key]['width'])) {
17411						$imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], ($dom[$key]['fontsize'] / $this->k), 'px', false);
17412						if (($imgw <= ($this->w - $this->lMargin - $this->rMargin - $this->cell_padding['L'] - $this->cell_padding['R']))
17413							AND ((($this->rtl) AND (($this->x - $imgw) < ($this->lMargin + $this->cell_padding['L'])))
17414							OR ((!$this->rtl) AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cell_padding['R']))))) {
17415							// add automatic line break
17416							$autolinebreak = true;
17417							$this->Ln('', $cell);
17418							if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
17419								// go back to evaluate this line break
17420								--$key;
17421							}
17422						}
17423					}
17424					if (!$autolinebreak) {
17425						if ($this->inPageBody()) {
17426							$pre_y = $this->y;
17427							// check for page break
17428							if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) {
17429								// fix for multicolumn mode
17430								$startliney = $this->y;
17431							}
17432						}
17433						if ($this->page > $startlinepage) {
17434							// fix line splitted over two pages
17435							if (isset($this->footerlen[$startlinepage])) {
17436								$curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17437							}
17438							// line to be moved one page forward
17439							$pagebuff = $this->getPageBuffer($startlinepage);
17440							$linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
17441							$tstart = substr($pagebuff, 0, $startlinepos);
17442							$tend = substr($this->getPageBuffer($startlinepage), $curpos);
17443							// remove line from previous page
17444							$this->setPageBuffer($startlinepage, $tstart.''.$tend);
17445							$pagebuff = $this->getPageBuffer($this->page);
17446							$tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
17447							$tend = substr($pagebuff, $this->cntmrk[$this->page]);
17448							// add line start to current page
17449							$yshift = ($minstartliney - $this->y);
17450							if ($fontaligned) {
17451								$yshift += ($curfontsize / $this->k);
17452							}
17453							$try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
17454							$this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
17455							// shift the annotations and links
17456							if (isset($this->PageAnnots[$this->page])) {
17457								$next_pask = count($this->PageAnnots[$this->page]);
17458							} else {
17459								$next_pask = 0;
17460							}
17461							if (isset($this->PageAnnots[$startlinepage])) {
17462								foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
17463									if ($pak >= $pask) {
17464										$this->PageAnnots[$this->page][] = $pac;
17465										unset($this->PageAnnots[$startlinepage][$pak]);
17466										$npak = count($this->PageAnnots[$this->page]) - 1;
17467										$this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
17468									}
17469								}
17470							}
17471							$pask = $next_pask;
17472							$startlinepos = $this->cntmrk[$this->page];
17473							$startlinepage = $this->page;
17474							$startliney = $this->y;
17475							$this->newline = false;
17476						}
17477						$this->y += ($this->getCellHeight($curfontsize / $this->k) - ($curfontdescent * $this->cell_height_ratio) - $imgh);
17478						$minstartliney = min($this->y, $minstartliney);
17479						$maxbottomliney = ($startliney + $this->getCellHeight($curfontsize / $this->k));
17480					}
17481				} elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
17482					// account for different font size
17483					$pfontname = $curfontname;
17484					$pfontstyle = $curfontstyle;
17485					$pfontsize = $curfontsize;
17486					$fontname = (isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname);
17487					$fontstyle = (isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle);
17488					$fontsize = (isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize);
17489					$fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
17490					$fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
17491					if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
17492						OR ($this->cell_height_ratio != $dom[$key]['line-height'])
17493						OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
17494						if (($key < ($maxel - 1)) AND (
17495								($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
17496								OR ($this->cell_height_ratio != $dom[$key]['line-height'])
17497								OR (!$this->newline AND is_numeric($fontsize) AND is_numeric($curfontsize)
17498								AND ($fontsize >= 0) AND ($curfontsize >= 0)
17499								AND (($fontsize != $curfontsize) OR ($fontstyle != $curfontstyle) OR ($fontname != $curfontname)))
17500							)) {
17501							if ($this->page > $startlinepage) {
17502								// fix lines splitted over two pages
17503								if (isset($this->footerlen[$startlinepage])) {
17504									$curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17505								}
17506								// line to be moved one page forward
17507								$pagebuff = $this->getPageBuffer($startlinepage);
17508								$linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
17509								$tstart = substr($pagebuff, 0, $startlinepos);
17510								$tend = substr($this->getPageBuffer($startlinepage), $curpos);
17511								// remove line start from previous page
17512								$this->setPageBuffer($startlinepage, $tstart.''.$tend);
17513								$pagebuff = $this->getPageBuffer($this->page);
17514								$tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
17515								$tend = substr($pagebuff, $this->cntmrk[$this->page]);
17516								// add line start to current page
17517								$yshift = ($minstartliney - $this->y);
17518								$try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
17519								$this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
17520								// shift the annotations and links
17521								if (isset($this->PageAnnots[$this->page])) {
17522									$next_pask = count($this->PageAnnots[$this->page]);
17523								} else {
17524									$next_pask = 0;
17525								}
17526								if (isset($this->PageAnnots[$startlinepage])) {
17527									foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
17528										if ($pak >= $pask) {
17529											$this->PageAnnots[$this->page][] = $pac;
17530											unset($this->PageAnnots[$startlinepage][$pak]);
17531											$npak = count($this->PageAnnots[$this->page]) - 1;
17532											$this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
17533										}
17534									}
17535								}
17536								$pask = $next_pask;
17537								$startlinepos = $this->cntmrk[$this->page];
17538								$startlinepage = $this->page;
17539								$startliney = $this->y;
17540							}
17541							if (!isset($dom[$key]['line-height'])) {
17542								$dom[$key]['line-height'] = $this->cell_height_ratio;
17543							}
17544							if (!$dom[$key]['block']) {
17545								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']))) {
17546									$this->y += (((($curfontsize * $this->cell_height_ratio) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2;
17547								}
17548								if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
17549									$current_line_align_data = array($key, $minstartliney, $maxbottomliney);
17550									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)))) {
17551										$minstartliney = min($this->y, $line_align_data[1]);
17552										$maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $line_align_data[2]);
17553									} else {
17554										$minstartliney = min($this->y, $minstartliney);
17555										$maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $maxbottomliney);
17556									}
17557									$line_align_data = $current_line_align_data;
17558								}
17559							}
17560							$this->cell_height_ratio = $dom[$key]['line-height'];
17561							$fontaligned = true;
17562						}
17563						$this->SetFont($fontname, $fontstyle, $fontsize);
17564						// reset row height
17565						$this->resetLastH();
17566						$curfontname = $fontname;
17567						$curfontstyle = $fontstyle;
17568						$curfontsize = $fontsize;
17569						$curfontascent = $fontascent;
17570						$curfontdescent = $fontdescent;
17571					}
17572				}
17573				// set text rendering mode
17574				$textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth;
17575				$textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0);
17576				$textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3);
17577				$this->setTextRenderingMode($textstroke, $textfill, $textclip);
17578				if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
17579					$this->setFontStretching($dom[$key]['font-stretch']);
17580				}
17581				if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
17582					$this->setFontSpacing($dom[$key]['letter-spacing']);
17583				}
17584				if (($plalign == 'J') AND $dom[$key]['block']) {
17585					$plalign = '';
17586				}
17587				// get current position on page buffer
17588				$curpos = $this->pagelen[$startlinepage];
17589				if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
17590					$this->SetFillColorArray($dom[$key]['bgcolor']);
17591					$wfill = true;
17592				} else {
17593					$wfill = $fill | false;
17594				}
17595				if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
17596					$this->SetTextColorArray($dom[$key]['fgcolor']);
17597				}
17598				if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
17599					$this->SetDrawColorArray($dom[$key]['strokecolor']);
17600				}
17601				if (isset($dom[$key]['align'])) {
17602					$lalign = $dom[$key]['align'];
17603				}
17604				if (TCPDF_STATIC::empty_string($lalign)) {
17605					$lalign = $align;
17606				}
17607			}
17608			// align lines
17609			if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
17610				$newline = true;
17611				$fontaligned = false;
17612				// we are at the beginning of a new line
17613				if (isset($startlinex)) {
17614					$yshift = ($minstartliney - $startliney);
17615					if (($yshift > 0) OR ($this->page > $startlinepage)) {
17616						$yshift = 0;
17617					}
17618					$t_x = 0;
17619					// the last line must be shifted to be aligned as requested
17620					$linew = abs($this->endlinex - $startlinex);
17621					if ($this->inxobj) {
17622						// we are inside an XObject template
17623						$pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
17624						if (isset($opentagpos)) {
17625							$midpos = $opentagpos;
17626						} else {
17627							$midpos = 0;
17628						}
17629						if ($midpos > 0) {
17630							$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
17631							$pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
17632						} else {
17633							$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
17634							$pend = '';
17635						}
17636					} else {
17637						$pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
17638						if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
17639							$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17640							$midpos = min($opentagpos, $this->footerpos[$startlinepage]);
17641						} elseif (isset($opentagpos)) {
17642							$midpos = $opentagpos;
17643						} elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
17644							$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17645							$midpos = $this->footerpos[$startlinepage];
17646						} else {
17647							$midpos = 0;
17648						}
17649						if ($midpos > 0) {
17650							$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
17651							$pend = substr($this->getPageBuffer($startlinepage), $midpos);
17652						} else {
17653							$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
17654							$pend = '';
17655						}
17656					}
17657					if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
17658						// calculate shifting amount
17659						$tw = $w;
17660						if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) {
17661							$tw += $this->cell_padding['R'];
17662						}
17663						if ($this->lMargin != $prevlMargin) {
17664							$tw += ($prevlMargin - $this->lMargin);
17665						}
17666						if ($this->rMargin != $prevrMargin) {
17667							$tw += ($prevrMargin - $this->rMargin);
17668						}
17669						$one_space_width = $this->GetStringWidth(chr(32));
17670						$no = 0; // number of spaces on a line contained on a single block
17671						if ($this->isRTLTextDir()) { // RTL
17672							// remove left space if exist
17673							$pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
17674							if ($pos1 > 0) {
17675								$pos1 = intval($pos1);
17676								if ($this->isUnicodeFont()) {
17677									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
17678									$spacelen = 2;
17679								} else {
17680									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
17681									$spacelen = 1;
17682								}
17683								if ($pos1 == $pos2) {
17684									$pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
17685									if (substr($pmid, $pos1, 4) == '[()]') {
17686										$linew -= $one_space_width;
17687									} elseif ($pos1 == strpos($pmid, '[(')) {
17688										$no = 1;
17689									}
17690								}
17691							}
17692						} else { // LTR
17693							// remove right space if exist
17694							$pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
17695							if ($pos1 > 0) {
17696								$pos1 = intval($pos1);
17697								if ($this->isUnicodeFont()) {
17698									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
17699									$spacelen = 2;
17700								} else {
17701									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
17702									$spacelen = 1;
17703								}
17704								if ($pos1 == $pos2) {
17705									$pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
17706									$linew -= $one_space_width;
17707								}
17708							}
17709						}
17710						$mdiff = ($tw - $linew);
17711						if ($plalign == 'C') {
17712							if ($this->rtl) {
17713								$t_x = -($mdiff / 2);
17714							} else {
17715								$t_x = ($mdiff / 2);
17716							}
17717						} elseif ($plalign == 'R') {
17718							// right alignment on LTR document
17719							$t_x = $mdiff;
17720						} elseif ($plalign == 'L') {
17721							// left alignment on RTL document
17722							$t_x = -$mdiff;
17723						} elseif (($plalign == 'J') AND ($plalign == $lalign)) {
17724							// Justification
17725							if ($this->isRTLTextDir()) {
17726								// align text on the left
17727								$t_x = -$mdiff;
17728							}
17729							$ns = 0; // number of spaces
17730							$pmidtemp = $pmid;
17731							// escape special characters
17732							$pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
17733							$pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
17734							// search spaces
17735							if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
17736								$spacestr = $this->getSpaceString();
17737								$maxkk = count($lnstring[1]) - 1;
17738								for ($kk=0; $kk <= $maxkk; ++$kk) {
17739									// restore special characters
17740									$lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
17741									$lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
17742									// store number of spaces on the strings
17743									$lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
17744									// count total spaces on line
17745									$ns += $lnstring[2][$kk];
17746									$lnstring[3][$kk] = $ns;
17747								}
17748								if ($ns == 0) {
17749									$ns = 1;
17750								}
17751								// calculate additional space to add to each existing space
17752								$spacewidth = ($mdiff / ($ns - $no)) * $this->k;
17753								if ($this->FontSize <= 0) {
17754									$this->FontSize = 1;
17755								}
17756								$spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize;
17757								if ($this->font_spacing != 0) {
17758									// fixed spacing mode
17759									$osw = -1000 * $this->font_spacing / $this->FontSize;
17760									$spacewidthu += $osw;
17761								}
17762								$nsmax = $ns;
17763								$ns = 0;
17764								reset($lnstring);
17765								$offset = 0;
17766								$strcount = 0;
17767								$prev_epsposbeg = 0;
17768								$textpos = 0;
17769								if ($this->isRTLTextDir()) {
17770									$textpos = $this->wPt;
17771								}
17772								while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
17773									// check if we are inside a string section '[( ... )]'
17774									$stroffset = strpos($pmid, '[(', $offset);
17775									if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
17776										// set offset to the end of string section
17777										$offset = strpos($pmid, ')]', $stroffset);
17778										while (($offset !== false) AND ($pmid[($offset - 1)] == '\\')) {
17779											$offset = strpos($pmid, ')]', ($offset + 1));
17780										}
17781										if ($offset === false) {
17782											$this->Error('HTML Justification: malformed PDF code.');
17783										}
17784										continue;
17785									}
17786									if ($this->isRTLTextDir()) {
17787										$spacew = ($spacewidth * ($nsmax - $ns));
17788									} else {
17789										$spacew = ($spacewidth * $ns);
17790									}
17791									$offset = $strpiece[2][1] + strlen($strpiece[2][0]);
17792									$epsposend = strpos($pmid, $this->epsmarker.'Q', $offset);
17793									if ($epsposend !== null) {
17794										$epsposend += strlen($this->epsmarker.'Q');
17795										$epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
17796										if ($epsposbeg === null) {
17797											$epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
17798											$prev_epsposbeg = $epsposbeg;
17799										}
17800										if (($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend)) {
17801											// shift EPS images
17802											$trx = sprintf('1 0 0 1 %F 0 cm', $spacew);
17803											$pmid_b = substr($pmid, 0, $epsposbeg);
17804											$pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
17805											$pmid_e = substr($pmid, $epsposend);
17806											$pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
17807											$offset = $epsposend;
17808											continue;
17809										}
17810									}
17811									$currentxpos = 0;
17812									// shift blocks of code
17813									switch ($strpiece[2][0]) {
17814										case 'Td':
17815										case 'cm':
17816										case 'm':
17817										case 'l': {
17818											// get current X position
17819											preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
17820											if (!isset($xmatches[1])) {
17821												break;
17822											}
17823											$currentxpos = $xmatches[1];
17824											$textpos = $currentxpos;
17825											if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
17826												$ns = $lnstring[3][$strcount];
17827												if ($this->isRTLTextDir()) {
17828													$spacew = ($spacewidth * ($nsmax - $ns));
17829												}
17830												++$strcount;
17831											}
17832											// justify block
17833											if (preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $pmatch) == 1) {
17834												$newpmid = sprintf('%F',(floatval($pmatch[1]) + $spacew)).' '.$pmatch[2].' x*#!#*x'.$pmatch[3].$pmatch[4];
17835												$pmid = str_replace($pmatch[0], $newpmid, $pmid);
17836												unset($pmatch, $newpmid);
17837											}
17838											break;
17839										}
17840										case 're': {
17841											// justify block
17842											if (!TCPDF_STATIC::empty_string($this->lispacer)) {
17843												$this->lispacer = '';
17844												break;
17845											}
17846											preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
17847											if (!isset($xmatches[1])) {
17848												break;
17849											}
17850											$currentxpos = $xmatches[1];
17851											$x_diff = 0;
17852											$w_diff = 0;
17853											if ($this->isRTLTextDir()) { // RTL
17854												if ($currentxpos < $textpos) {
17855													$x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
17856													$w_diff = ($spacewidth * $lnstring[2][$strcount]);
17857												} else {
17858													if ($strcount > 0) {
17859														$x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
17860														$w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
17861													}
17862												}
17863											} else { // LTR
17864												if ($currentxpos > $textpos) {
17865													if ($strcount > 0) {
17866														$x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
17867													}
17868													$w_diff = ($spacewidth * $lnstring[2][$strcount]);
17869												} else {
17870													if ($strcount > 1) {
17871														$x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
17872													}
17873													if ($strcount > 0) {
17874														$w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
17875													}
17876												}
17877											}
17878											if (preg_match('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $pmatch) == 1) {
17879												$newx = sprintf('%F',(floatval($pmatch[1]) + $x_diff));
17880												$neww = sprintf('%F',(floatval($pmatch[3]) + $w_diff));
17881												$newpmid = $newx.' '.$pmatch[2].' '.$neww.' '.$pmatch[4].' x*#!#*x'.$pmatch[5].$pmatch[6];
17882												$pmid = str_replace($pmatch[0], $newpmid, $pmid);
17883												unset($pmatch, $newpmid, $newx, $neww);
17884											}
17885											break;
17886										}
17887										case 'c': {
17888											// get current X position
17889											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);
17890											if (!isset($xmatches[1])) {
17891												break;
17892											}
17893											$currentxpos = $xmatches[1];
17894											// justify block
17895											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) {
17896												$newx1 = sprintf('%F',(floatval($pmatch[1]) + $spacew));
17897												$newx2 = sprintf('%F',(floatval($pmatch[3]) + $spacew));
17898												$newx3 = sprintf('%F',(floatval($pmatch[5]) + $spacew));
17899												$newpmid = $newx1.' '.$pmatch[2].' '.$newx2.' '.$pmatch[4].' '.$newx3.' '.$pmatch[6].' x*#!#*x'.$pmatch[7].$pmatch[8];
17900												$pmid = str_replace($pmatch[0], $newpmid, $pmid);
17901												unset($pmatch, $newpmid, $newx1, $newx2, $newx3);
17902											}
17903											break;
17904										}
17905									}
17906									// shift the annotations and links
17907									$cxpos = ($currentxpos / $this->k);
17908									$lmpos = ($this->lMargin + $this->cell_padding['L'] + $this->feps);
17909									if ($this->inxobj) {
17910										// we are inside an XObject template
17911										foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
17912											if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
17913												if ($cxpos > $lmpos) {
17914													$this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += ($spacew / $this->k);
17915													$this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17916												} else {
17917													$this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17918												}
17919												break;
17920											}
17921										}
17922									} elseif (isset($this->PageAnnots[$this->page])) {
17923										foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
17924											if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
17925												if ($cxpos > $lmpos) {
17926													$this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
17927													$this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17928												} else {
17929													$this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17930												}
17931												break;
17932											}
17933										}
17934									}
17935								} // end of while
17936								// remove markers
17937								$pmid = str_replace('x*#!#*x', '', $pmid);
17938								if ($this->isUnicodeFont()) {
17939									// multibyte characters
17940									$spacew = $spacewidthu;
17941									if ($this->font_stretching != 100) {
17942										// word spacing is affected by stretching
17943										$spacew /= ($this->font_stretching / 100);
17944									}
17945									// escape special characters
17946									$pos = 0;
17947									$pmid = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmid);
17948									$pmid = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmid);
17949									if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmid, $pamatch) > 0) {
17950										foreach($pamatch[0] as $pk => $pmatch) {
17951											$replace = $pamatch[1][$pk];
17952											$replace = str_replace('#!#OP#!#', '(', $replace);
17953											$replace = str_replace('#!#CP#!#', ')', $replace);
17954											$newpmid = '[('.str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacew).' (', $replace).')]';
17955											$pos = strpos($pmid, $pmatch, $pos);
17956											if ($pos !== FALSE) {
17957												$pmid = substr_replace($pmid, $newpmid, $pos, strlen($pmatch));
17958											}
17959											++$pos;
17960										}
17961										unset($pamatch);
17962									}
17963									if ($this->inxobj) {
17964										// we are inside an XObject template
17965										$this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\n".$pend;
17966									} else {
17967										$this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
17968									}
17969									$endlinepos = strlen($pstart."\n".$pmid."\n");
17970								} else {
17971									// non-unicode (single-byte characters)
17972									if ($this->font_stretching != 100) {
17973										// word spacing (Tw) is affected by stretching
17974										$spacewidth /= ($this->font_stretching / 100);
17975									}
17976									$rs = sprintf('%F Tw', $spacewidth);
17977									$pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
17978									if ($this->inxobj) {
17979										// we are inside an XObject template
17980										$this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
17981									} else {
17982										$this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
17983									}
17984									$endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
17985								}
17986							}
17987						} // end of J
17988					} // end if $startlinex
17989					if (($t_x != 0) OR ($yshift < 0)) {
17990						// shift the line
17991						$trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
17992						$pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
17993						$endlinepos = strlen($pstart);
17994						if ($this->inxobj) {
17995							// we are inside an XObject template
17996							$this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
17997							foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
17998								if ($pak >= $pask) {
17999									$this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
18000									$this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
18001								}
18002							}
18003						} else {
18004							$this->setPageBuffer($startlinepage, $pstart.$pend);
18005							// shift the annotations and links
18006							if (isset($this->PageAnnots[$this->page])) {
18007								foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
18008									if ($pak >= $pask) {
18009										$this->PageAnnots[$this->page][$pak]['x'] += $t_x;
18010										$this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
18011									}
18012								}
18013							}
18014						}
18015						$this->y -= $yshift;
18016					}
18017				}
18018				$pbrk = $this->checkPageBreak($this->lasth);
18019				$this->newline = false;
18020				$startlinex = $this->x;
18021				$startliney = $this->y;
18022				if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
18023					$startliney -= ((0.3 * $this->FontSizePt) / $this->k);
18024				} elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
18025					$startliney -= (($this->FontSizePt / 0.7) / $this->k);
18026				} else {
18027					$minstartliney = $startliney;
18028					$maxbottomliney = ($this->y + $this->getCellHeight($fontsize / $this->k));
18029				}
18030				$startlinepage = $this->page;
18031				if (isset($endlinepos) AND (!$pbrk)) {
18032					$startlinepos = $endlinepos;
18033				} else {
18034					if ($this->inxobj) {
18035						// we are inside an XObject template
18036						$startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
18037					} elseif (!$this->InFooter) {
18038						if (isset($this->footerlen[$this->page])) {
18039							$this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
18040						} else {
18041							$this->footerpos[$this->page] = $this->pagelen[$this->page];
18042						}
18043						$startlinepos = $this->footerpos[$this->page];
18044					} else {
18045						$startlinepos = $this->pagelen[$this->page];
18046					}
18047				}
18048				unset($endlinepos);
18049				$plalign = $lalign;
18050				if (isset($this->PageAnnots[$this->page])) {
18051					$pask = count($this->PageAnnots[$this->page]);
18052				} else {
18053					$pask = 0;
18054				}
18055				if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
18056					AND (isset($this->emptypagemrk[$this->page]))
18057					AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) {
18058					$this->SetFont($fontname, $fontstyle, $fontsize);
18059					if ($wfill) {
18060						$this->SetFillColorArray($this->bgcolor);
18061					}
18062				}
18063			} // end newline
18064			if (isset($opentagpos)) {
18065				unset($opentagpos);
18066			}
18067			if ($dom[$key]['tag']) {
18068				if ($dom[$key]['opening']) {
18069					// get text indentation (if any)
18070					if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
18071						$this->textindent = $dom[$key]['text-indent'];
18072						$this->newline = true;
18073					}
18074					// table
18075					if (($dom[$key]['value'] == 'table') AND isset($dom[$key]['cols']) AND ($dom[$key]['cols'] > 0)) {
18076						// available page width
18077						if ($this->rtl) {
18078							$wtmp = $this->x - $this->lMargin;
18079						} else {
18080							$wtmp = $this->w - $this->rMargin - $this->x;
18081						}
18082						// get cell spacing
18083						if (isset($dom[$key]['attribute']['cellspacing'])) {
18084							$clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
18085							$cellspacing = array('H' => $clsp, 'V' => $clsp);
18086						} elseif (isset($dom[$key]['border-spacing'])) {
18087							$cellspacing = $dom[$key]['border-spacing'];
18088						} else {
18089							$cellspacing = array('H' => 0, 'V' => 0);
18090						}
18091						// table width
18092						if (isset($dom[$key]['width'])) {
18093							$table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
18094						} else {
18095							$table_width = $wtmp;
18096						}
18097						$table_width -= (2 * $cellspacing['H']);
18098						if (!$this->inthead) {
18099							$this->y += $cellspacing['V'];
18100						}
18101						if ($this->rtl) {
18102							$cellspacingx = -$cellspacing['H'];
18103						} else {
18104							$cellspacingx = $cellspacing['H'];
18105						}
18106						// total table width without cellspaces
18107						$table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
18108						// minimum column width
18109						$table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
18110						// array of custom column widths
18111						$table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
18112					}
18113					// table row
18114					if ($dom[$key]['value'] == 'tr') {
18115						// reset column counter
18116						$colid = 0;
18117					}
18118					// table cell
18119					if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
18120						$trid = $dom[$key]['parent'];
18121						$table_el = $dom[$trid]['parent'];
18122						if (!isset($dom[$table_el]['cols'])) {
18123							$dom[$table_el]['cols'] = $dom[$trid]['cols'];
18124						}
18125						// store border info
18126						$tdborder = 0;
18127						if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
18128							$tdborder = $dom[$key]['border'];
18129						}
18130						$colspan = intval($dom[$key]['attribute']['colspan']);
18131						if ($colspan <= 0) {
18132							$colspan = 1;
18133						}
18134						$old_cell_padding = $this->cell_padding;
18135						if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
18136							$crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
18137							$current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
18138						} elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
18139							$current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
18140						} else {
18141							$current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
18142						}
18143						$this->cell_padding = $current_cell_padding;
18144						if (isset($dom[$key]['height'])) {
18145							// minimum cell height
18146							$cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
18147						} else {
18148							$cellh = 0;
18149						}
18150						if (isset($dom[$key]['content'])) {
18151							$cell_content = $dom[$key]['content'];
18152						} else {
18153							$cell_content = '&nbsp;';
18154						}
18155						$tagtype = $dom[$key]['value'];
18156						$parentid = $key;
18157						while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
18158							// move $key index forward
18159							++$key;
18160						}
18161						if (!isset($dom[$trid]['startpage'])) {
18162							$dom[$trid]['startpage'] = $this->page;
18163						} else {
18164							$this->setPage($dom[$trid]['startpage']);
18165						}
18166						if (!isset($dom[$trid]['startcolumn'])) {
18167							$dom[$trid]['startcolumn'] = $this->current_column;
18168						} elseif ($this->current_column != $dom[$trid]['startcolumn']) {
18169							$tmpx = $this->x;
18170							$this->selectColumn($dom[$trid]['startcolumn']);
18171							$this->x = $tmpx;
18172						}
18173						if (!isset($dom[$trid]['starty'])) {
18174							$dom[$trid]['starty'] = $this->y;
18175						} else {
18176							$this->y = $dom[$trid]['starty'];
18177						}
18178						if (!isset($dom[$trid]['startx'])) {
18179							$dom[$trid]['startx'] = $this->x;
18180							$this->x += $cellspacingx;
18181						} else {
18182							$this->x += ($cellspacingx / 2);
18183						}
18184						if (isset($dom[$parentid]['attribute']['rowspan'])) {
18185							$rowspan = intval($dom[$parentid]['attribute']['rowspan']);
18186						} else {
18187							$rowspan = 1;
18188						}
18189						// skip row-spanned cells started on the previous rows
18190						if (isset($dom[$table_el]['rowspans'])) {
18191							$rsk = 0;
18192							$rskmax = count($dom[$table_el]['rowspans']);
18193							while ($rsk < $rskmax) {
18194								$trwsp = $dom[$table_el]['rowspans'][$rsk];
18195								$rsstartx = $trwsp['startx'];
18196								$rsendx = $trwsp['endx'];
18197								// account for margin changes
18198								if ($trwsp['startpage'] < $this->page) {
18199									if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
18200										$dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
18201										$rsstartx -= $dl;
18202										$rsendx -= $dl;
18203									} elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
18204										$dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
18205										$rsstartx += $dl;
18206										$rsendx += $dl;
18207									}
18208								}
18209								if (($trwsp['rowspan'] > 0)
18210									AND ($rsstartx > ($this->x - $cellspacing['H'] - $current_cell_padding['L'] - $this->feps))
18211									AND ($rsstartx < ($this->x + $cellspacing['H'] + $current_cell_padding['R'] + $this->feps))
18212									AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) {
18213									// set the starting X position of the current cell
18214									$this->x = $rsendx + $cellspacingx;
18215									// increment column indicator
18216									$colid += $trwsp['colspan'];
18217									if (($trwsp['rowspan'] == 1)
18218										AND (isset($dom[$trid]['endy']))
18219										AND (isset($dom[$trid]['endpage']))
18220										AND (isset($dom[$trid]['endcolumn']))
18221										AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
18222										AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
18223										// set ending Y position for row
18224										$dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
18225										$dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
18226									}
18227									$rsk = 0;
18228								} else {
18229									++$rsk;
18230								}
18231							}
18232						}
18233						if (isset($dom[$parentid]['width'])) {
18234							// user specified width
18235							$cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
18236							$tmpcw = ($cellw / $colspan);
18237							for ($i = 0; $i < $colspan; ++$i) {
18238								$table_colwidths[($colid + $i)] = $tmpcw;
18239							}
18240						} else {
18241							// inherit column width
18242							$cellw = 0;
18243							for ($i = 0; $i < $colspan; ++$i) {
18244								$cellw += (isset($table_colwidths[($colid + $i)]) ? $table_colwidths[($colid + $i)] : 0);
18245							}
18246						}
18247						$cellw += (($colspan - 1) * $cellspacing['H']);
18248						// increment column indicator
18249						$colid += $colspan;
18250						// add rowspan information to table element
18251						if ($rowspan > 1) {
18252							$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));
18253						}
18254						$cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
18255						if ($rowspan > 1) {
18256							$dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
18257						}
18258						// push background colors
18259						if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
18260							$dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
18261						}
18262						// store border info
18263						if (isset($tdborder) AND !empty($tdborder)) {
18264							$dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
18265						}
18266						$prevLastH = $this->lasth;
18267						// store some info for multicolumn mode
18268						if ($this->rtl) {
18269							$this->colxshift['x'] = $this->w - $this->x - $this->rMargin;
18270						} else {
18271							$this->colxshift['x'] = $this->x - $this->lMargin;
18272						}
18273						$this->colxshift['s'] = $cellspacing;
18274						$this->colxshift['p'] = $current_cell_padding;
18275						// ****** write the cell content ******
18276						$this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
18277						// restore some values
18278						$this->colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
18279						$this->lasth = $prevLastH;
18280						$this->cell_padding = $old_cell_padding;
18281						$dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
18282						// update the end of row position
18283						if ($rowspan <= 1) {
18284							if (isset($dom[$trid]['endy'])) {
18285								if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) {
18286									$dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
18287								} elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) {
18288									$dom[$trid]['endy'] = $this->y;
18289								}
18290							} else {
18291								$dom[$trid]['endy'] = $this->y;
18292							}
18293							if (isset($dom[$trid]['endpage'])) {
18294								$dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
18295							} else {
18296								$dom[$trid]['endpage'] = $this->page;
18297							}
18298							if (isset($dom[$trid]['endcolumn'])) {
18299								$dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']);
18300							} else {
18301								$dom[$trid]['endcolumn'] = $this->current_column;
18302							}
18303						} else {
18304							// account for row-spanned cells
18305							$dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
18306							$dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
18307							$dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
18308							$dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column;
18309						}
18310						if (isset($dom[$table_el]['rowspans'])) {
18311							// update endy and endpage on rowspanned cells
18312							foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
18313								if ($trwsp['rowspan'] > 0) {
18314									if (isset($dom[$trid]['endpage'])) {
18315										if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
18316											$dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
18317										} elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
18318											$dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
18319											$dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
18320											$dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
18321										} else {
18322											$dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
18323										}
18324									}
18325								}
18326							}
18327						}
18328						$this->x += ($cellspacingx / 2);
18329					} else {
18330						// opening tag (or self-closing tag)
18331						if (!isset($opentagpos)) {
18332							if ($this->inxobj) {
18333								// we are inside an XObject template
18334								$opentagpos = strlen($this->xobjects[$this->xobjid]['outdata']);
18335							} elseif (!$this->InFooter) {
18336								if (isset($this->footerlen[$this->page])) {
18337									$this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
18338								} else {
18339									$this->footerpos[$this->page] = $this->pagelen[$this->page];
18340								}
18341								$opentagpos = $this->footerpos[$this->page];
18342							}
18343						}
18344						$dom = $this->openHTMLTagHandler($dom, $key, $cell);
18345					}
18346				} else { // closing tag
18347					$prev_numpages = $this->numpages;
18348					$old_bordermrk = $this->bordermrk[$this->page];
18349					$dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
18350					if ($this->bordermrk[$this->page] > $old_bordermrk) {
18351						$startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk);
18352					}
18353					if ($prev_numpages > $this->numpages) {
18354						$startlinepage = $this->page;
18355					}
18356				}
18357			} elseif (strlen($dom[$key]['value']) > 0) {
18358				// print list-item
18359				if (!TCPDF_STATIC::empty_string($this->lispacer) AND ($this->lispacer != '^')) {
18360					$this->SetFont($pfontname, $pfontstyle, $pfontsize);
18361					$this->resetLastH();
18362					$minstartliney = $this->y;
18363					$maxbottomliney = ($startliney + $this->getCellHeight($this->FontSize));
18364					if (is_numeric($pfontsize) AND ($pfontsize > 0)) {
18365						$this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
18366					}
18367					$this->SetFont($curfontname, $curfontstyle, $curfontsize);
18368					$this->resetLastH();
18369					if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
18370						$pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
18371						$pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
18372						$this->y += ($this->getCellHeight(($pfontsize - $curfontsize) / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2;
18373						$minstartliney = min($this->y, $minstartliney);
18374						$maxbottomliney = max(($this->y + $this->getCellHeight($pfontsize / $this->k)), $maxbottomliney);
18375					}
18376				}
18377				// text
18378				$this->htmlvspace = 0;
18379				$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']);
18380				if ((!$this->premode) AND $this->isRTLTextDir() AND !$isRTLString) {
18381					// reverse spaces order
18382					$lsp = ''; // left spaces
18383					$rsp = ''; // right spaces
18384					if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
18385						$lsp = $matches[1];
18386					}
18387					if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
18388						$rsp = $matches[1];
18389					}
18390					$dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
18391				}
18392				if ($newline) {
18393					if (!$this->premode) {
18394						$prelen = strlen($dom[$key]['value']);
18395						if ($this->isRTLTextDir() AND !$isRTLString) {
18396							// right trim except non-breaking space
18397							$dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
18398						} else {
18399							// left trim except non-breaking space
18400							$dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
18401						}
18402						$postlen = strlen($dom[$key]['value']);
18403						if (($postlen == 0) AND ($prelen > 0)) {
18404							$dom[$key]['trimmed_space'] = true;
18405						}
18406					}
18407					$newline = false;
18408					$firstblock = true;
18409				} else {
18410					$firstblock = false;
18411					// replace empty multiple spaces string with a single space
18412					$dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']);
18413				}
18414				$strrest = '';
18415				if ($this->rtl) {
18416					$this->x -= $this->textindent;
18417				} else {
18418					$this->x += $this->textindent;
18419				}
18420				if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
18421					$strlinelen = $this->GetStringWidth($dom[$key]['value']);
18422					if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
18423						// HTML <a> Link
18424						$hrefcolor = '';
18425						if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
18426							$hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
18427						}
18428						$hrefstyle = -1;
18429						if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
18430							$hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
18431						}
18432						$strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
18433					} else {
18434						$wadj = 0; // space to leave for block continuity
18435						if ($this->rtl) {
18436							$cwa = ($this->x - $this->lMargin);
18437						} else {
18438							$cwa = ($this->w - $this->rMargin - $this->x);
18439						}
18440						if (($strlinelen < $cwa) AND (isset($dom[($key + 1)])) AND ($dom[($key + 1)]['tag']) AND (!$dom[($key + 1)]['block'])) {
18441							// check the next text blocks for continuity
18442							$nkey = ($key + 1);
18443							$write_block = true;
18444							$same_textdir = true;
18445							$tmp_fontname = $this->FontFamily;
18446							$tmp_fontstyle = $this->FontStyle;
18447							$tmp_fontsize = $this->FontSizePt;
18448							while ($write_block AND isset($dom[$nkey])) {
18449								if ($dom[$nkey]['tag']) {
18450									if ($dom[$nkey]['block']) {
18451										// end of block
18452										$write_block = false;
18453									}
18454									$tmp_fontname = isset($dom[$nkey]['fontname']) ? $dom[$nkey]['fontname'] : $this->FontFamily;
18455									$tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ? $dom[$nkey]['fontstyle'] : $this->FontStyle;
18456									$tmp_fontsize = isset($dom[$nkey]['fontsize']) ? $dom[$nkey]['fontsize'] : $this->FontSizePt;
18457									$same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
18458								} else {
18459									$nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'+/', $this->re_space['m'], $dom[$nkey]['value']);
18460									if (isset($nextstr[0]) AND $same_textdir) {
18461										$wadj += $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
18462										if (isset($nextstr[1])) {
18463											$write_block = false;
18464										}
18465									}
18466								}
18467								++$nkey;
18468							}
18469						}
18470						if (($wadj > 0) AND (($strlinelen + $wadj) >= $cwa)) {
18471							$wadj = 0;
18472							$nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $dom[$key]['value']);
18473							$numblks = count($nextstr);
18474							if ($numblks > 1) {
18475								// try to split on blank spaces
18476								$wadj = ($cwa - $strlinelen + $this->GetStringWidth($nextstr[($numblks - 1)]));
18477							} else {
18478								// set the entire block on new line
18479								$wadj = $this->GetStringWidth($nextstr[0]);
18480							}
18481						}
18482						// check for reversed text direction
18483						if (($wadj > 0) AND (($this->rtl AND ($this->tmprtl === 'L')) OR (!$this->rtl AND ($this->tmprtl === 'R')))) {
18484							// LTR text on RTL direction or RTL text on LTR direction
18485							$reverse_dir = true;
18486							$this->rtl = !$this->rtl;
18487							$revshift = ($strlinelen + $wadj + 0.000001); // add little quantity for rounding problems
18488							if ($this->rtl) {
18489								$this->x += $revshift;
18490							} else {
18491								$this->x -= $revshift;
18492							}
18493							$xws = $this->x;
18494						}
18495						// ****** write only until the end of the line and get the rest ******
18496						$strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
18497						// restore default direction
18498						if ($reverse_dir AND ($wadj == 0)) {
18499							$this->x = $xws;
18500							$this->rtl = !$this->rtl;
18501							$reverse_dir = false;
18502						}
18503					}
18504				}
18505				$this->textindent = 0;
18506				if (strlen($strrest) > 0) {
18507					// store the remaining string on the previous $key position
18508					$this->newline = true;
18509					if ($strrest == $dom[$key]['value']) {
18510						// used to avoid infinite loop
18511						++$loop;
18512					} else {
18513						$loop = 0;
18514					}
18515					$dom[$key]['value'] = $strrest;
18516					if ($cell) {
18517						if ($this->rtl) {
18518							$this->x -= $this->cell_padding['R'];
18519						} else {
18520							$this->x += $this->cell_padding['L'];
18521						}
18522					}
18523					if ($loop < 3) {
18524						--$key;
18525					}
18526				} else {
18527					$loop = 0;
18528					// add the positive font spacing of the last character (if any)
18529					 if ($this->font_spacing > 0) {
18530					 	if ($this->rtl) {
18531							$this->x -= $this->font_spacing;
18532						} else {
18533							$this->x += $this->font_spacing;
18534						}
18535					}
18536				}
18537			}
18538			++$key;
18539			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')) {
18540				// check if we are on a new page or on a new column
18541				if ((!$undo) AND (($this->y < $this->start_transaction_y) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y)))) {
18542					// we are on a new page or on a new column and the total object height is less than the available vertical space.
18543					// restore previous object
18544					$this->rollbackTransaction(true);
18545					// restore previous values
18546					foreach ($this_method_vars as $vkey => $vval) {
18547						$$vkey = $vval;
18548					}
18549					if (!empty($dom[$key]['thead'])) {
18550						$this->inthead = true;
18551					}
18552					// add a page (or trig AcceptPageBreak() for multicolumn mode)
18553					$pre_y = $this->y;
18554					if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
18555						$startliney = $this->y;
18556					}
18557					$undo = true; // avoid infinite loop
18558				} else {
18559					$undo = false;
18560				}
18561			}
18562		} // end for each $key
18563		// align the last line
18564		if (isset($startlinex)) {
18565			$yshift = ($minstartliney - $startliney);
18566			if (($yshift > 0) OR ($this->page > $startlinepage)) {
18567				$yshift = 0;
18568			}
18569			$t_x = 0;
18570			// the last line must be shifted to be aligned as requested
18571			$linew = abs($this->endlinex - $startlinex);
18572			if ($this->inxobj) {
18573				// we are inside an XObject template
18574				$pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
18575				if (isset($opentagpos)) {
18576					$midpos = $opentagpos;
18577				} else {
18578					$midpos = 0;
18579				}
18580				if ($midpos > 0) {
18581					$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
18582					$pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
18583				} else {
18584					$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
18585					$pend = '';
18586				}
18587			} else {
18588				$pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
18589				if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
18590					$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
18591					$midpos = min($opentagpos, $this->footerpos[$startlinepage]);
18592				} elseif (isset($opentagpos)) {
18593					$midpos = $opentagpos;
18594				} elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
18595					$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
18596					$midpos = $this->footerpos[$startlinepage];
18597				} else {
18598					$midpos = 0;
18599				}
18600				if ($midpos > 0) {
18601					$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
18602					$pend = substr($this->getPageBuffer($startlinepage), $midpos);
18603				} else {
18604					$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
18605					$pend = '';
18606				}
18607			}
18608			if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
18609				// calculate shifting amount
18610				$tw = $w;
18611				if ($this->lMargin != $prevlMargin) {
18612					$tw += ($prevlMargin - $this->lMargin);
18613				}
18614				if ($this->rMargin != $prevrMargin) {
18615					$tw += ($prevrMargin - $this->rMargin);
18616				}
18617				$one_space_width = $this->GetStringWidth(chr(32));
18618				$no = 0; // number of spaces on a line contained on a single block
18619				if ($this->isRTLTextDir()) { // RTL
18620					// remove left space if exist
18621					$pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
18622					if ($pos1 > 0) {
18623						$pos1 = intval($pos1);
18624						if ($this->isUnicodeFont()) {
18625							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
18626							$spacelen = 2;
18627						} else {
18628							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
18629							$spacelen = 1;
18630						}
18631						if ($pos1 == $pos2) {
18632							$pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
18633							if (substr($pmid, $pos1, 4) == '[()]') {
18634								$linew -= $one_space_width;
18635							} elseif ($pos1 == strpos($pmid, '[(')) {
18636								$no = 1;
18637							}
18638						}
18639					}
18640				} else { // LTR
18641					// remove right space if exist
18642					$pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
18643					if ($pos1 > 0) {
18644						$pos1 = intval($pos1);
18645						if ($this->isUnicodeFont()) {
18646							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
18647							$spacelen = 2;
18648						} else {
18649							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
18650							$spacelen = 1;
18651						}
18652						if ($pos1 == $pos2) {
18653							$pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
18654							$linew -= $one_space_width;
18655						}
18656					}
18657				}
18658				$mdiff = ($tw - $linew);
18659				if ($plalign == 'C') {
18660					if ($this->rtl) {
18661						$t_x = -($mdiff / 2);
18662					} else {
18663						$t_x = ($mdiff / 2);
18664					}
18665				} elseif ($plalign == 'R') {
18666					// right alignment on LTR document
18667					$t_x = $mdiff;
18668				} elseif ($plalign == 'L') {
18669					// left alignment on RTL document
18670					$t_x = -$mdiff;
18671				}
18672			} // end if startlinex
18673			if (($t_x != 0) OR ($yshift < 0)) {
18674				// shift the line
18675				$trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
18676				$pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
18677				$endlinepos = strlen($pstart);
18678				if ($this->inxobj) {
18679					// we are inside an XObject template
18680					$this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
18681					foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
18682						if ($pak >= $pask) {
18683							$this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
18684							$this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
18685						}
18686					}
18687				} else {
18688					$this->setPageBuffer($startlinepage, $pstart.$pend);
18689					// shift the annotations and links
18690					if (isset($this->PageAnnots[$this->page])) {
18691						foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
18692							if ($pak >= $pask) {
18693								$this->PageAnnots[$this->page][$pak]['x'] += $t_x;
18694								$this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
18695							}
18696						}
18697					}
18698				}
18699				$this->y -= $yshift;
18700				$yshift = 0;
18701			}
18702		}
18703		// restore previous values
18704		$this->setGraphicVars($gvars);
18705		if ($this->num_columns > 1) {
18706			$this->selectColumn();
18707		} elseif ($this->page > $prevPage) {
18708			$this->lMargin = $this->pagedim[$this->page]['olm'];
18709			$this->rMargin = $this->pagedim[$this->page]['orm'];
18710		}
18711		// restore previous list state
18712		$this->cell_height_ratio = $prev_cell_height_ratio;
18713		$this->listnum = $prev_listnum;
18714		$this->listordered = $prev_listordered;
18715		$this->listcount = $prev_listcount;
18716		$this->lispacer = $prev_lispacer;
18717		if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
18718			$this->Ln($this->lasth);
18719			if (($this->y < $maxbottomliney) AND ($startlinepage == $this->page)) {
18720				$this->y = $maxbottomliney;
18721			}
18722		}
18723		unset($dom);
18724	}
18725
18726	/**
18727	 * Process opening tags.
18728	 * @param $dom (array) html dom array
18729	 * @param $key (int) current element id
18730	 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
18731	 * @return $dom array
18732	 * @protected
18733	 */
18734	protected function openHTMLTagHandler($dom, $key, $cell) {
18735		$tag = $dom[$key];
18736		$parent = $dom[($dom[$key]['parent'])];
18737		$firsttag = ($key == 1);
18738		// check for text direction attribute
18739		if (isset($tag['dir'])) {
18740			$this->setTempRTL($tag['dir']);
18741		} else {
18742			$this->tmprtl = false;
18743		}
18744		if ($tag['block']) {
18745			$hbz = 0; // distance from y to line bottom
18746			$hb = 0; // vertical space between block tags
18747			// calculate vertical space for block tags
18748			if (isset($this->tagvspaces[$tag['value']][0]['h']) && !empty($this->tagvspaces[$tag['value']][0]['h']) && ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) {
18749				$cur_h = $this->tagvspaces[$tag['value']][0]['h'];
18750			} elseif (isset($tag['fontsize'])) {
18751				$cur_h = $this->getCellHeight($tag['fontsize'] / $this->k);
18752			} else {
18753				$cur_h = $this->getCellHeight($this->FontSize);
18754			}
18755			if (isset($this->tagvspaces[$tag['value']][0]['n'])) {
18756				$on = $this->tagvspaces[$tag['value']][0]['n'];
18757			} elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
18758				$on = 0.6;
18759			} else {
18760				$on = 1;
18761			}
18762			if ((!isset($this->tagvspaces[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br', 'hr')))) {
18763				$hb = 0;
18764			} else {
18765				$hb = ($on * $cur_h);
18766			}
18767			if (($this->htmlvspace <= 0) AND ($on > 0)) {
18768				if (isset($parent['fontsize'])) {
18769					$hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
18770				} else {
18771					$hbz = $this->getCellHeight($this->FontSize);
18772				}
18773			}
18774			if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == 'table')) {
18775				// fix vertical space after table
18776				$hbz = 0;
18777			}
18778			// closing vertical space
18779			$hbc = 0;
18780			if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
18781				$pre_h = $this->tagvspaces[$tag['value']][1]['h'];
18782			} elseif (isset($parent['fontsize'])) {
18783				$pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
18784			} else {
18785				$pre_h = $this->getCellHeight($this->FontSize);
18786			}
18787			if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
18788				$cn = $this->tagvspaces[$tag['value']][1]['n'];
18789			} elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
18790				$cn = 0.6;
18791			} else {
18792				$cn = 1;
18793			}
18794			if (isset($this->tagvspaces[$tag['value']][1])) {
18795				$hbc = ($cn * $pre_h);
18796			}
18797		}
18798		// Opening tag
18799		switch($tag['value']) {
18800			case 'table': {
18801				$cp = 0;
18802				$cs = 0;
18803				$dom[$key]['rowspans'] = array();
18804				if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
18805					$this->htmlvspace = 0;
18806					// set table header
18807					if (!TCPDF_STATIC::empty_string($dom[$key]['thead'])) {
18808						// set table header
18809						$this->thead = $dom[$key]['thead'];
18810						if (!isset($this->theadMargins) OR (empty($this->theadMargins))) {
18811							$this->theadMargins = array();
18812							$this->theadMargins['cell_padding'] = $this->cell_padding;
18813							$this->theadMargins['lmargin'] = $this->lMargin;
18814							$this->theadMargins['rmargin'] = $this->rMargin;
18815							$this->theadMargins['page'] = $this->page;
18816							$this->theadMargins['cell'] = $cell;
18817							$this->theadMargins['gvars'] = $this->getGraphicVars();
18818						}
18819					}
18820				}
18821				// store current margins and page
18822				$dom[$key]['old_cell_padding'] = $this->cell_padding;
18823				if (isset($tag['attribute']['cellpadding'])) {
18824					$pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
18825					$this->SetCellPadding($pad);
18826				} elseif (isset($tag['padding'])) {
18827					$this->cell_padding = $tag['padding'];
18828				}
18829				if (isset($tag['attribute']['cellspacing'])) {
18830					$cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
18831				} elseif (isset($tag['border-spacing'])) {
18832					$cs = $tag['border-spacing']['V'];
18833				}
18834				$prev_y = $this->y;
18835				if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) {
18836					$this->inthead = true;
18837					// add a page (or trig AcceptPageBreak() for multicolumn mode)
18838					$this->checkPageBreak($this->PageBreakTrigger + 1);
18839				}
18840				break;
18841			}
18842			case 'tr': {
18843				// array of columns positions
18844				$dom[$key]['cellpos'] = array();
18845				break;
18846			}
18847			case 'hr': {
18848				if ((isset($tag['height'])) AND ($tag['height'] != '')) {
18849					$hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
18850				} else {
18851					$hrHeight = $this->GetLineWidth();
18852				}
18853				$this->addHTMLVertSpace($hbz, max($hb, ($hrHeight / 2)), $cell, $firsttag);
18854				$x = $this->GetX();
18855				$y = $this->GetY();
18856				$wtmp = $this->w - $this->lMargin - $this->rMargin;
18857				if ($cell) {
18858					$wtmp -= ($this->cell_padding['L'] + $this->cell_padding['R']);
18859				}
18860				if ((isset($tag['width'])) AND ($tag['width'] != '')) {
18861					$hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
18862				} else {
18863					$hrWidth = $wtmp;
18864				}
18865				$prevlinewidth = $this->GetLineWidth();
18866				$this->SetLineWidth($hrHeight);
18867				$this->Line($x, $y, $x + $hrWidth, $y);
18868				$this->SetLineWidth($prevlinewidth);
18869				$this->addHTMLVertSpace(max($hbc, ($hrHeight / 2)), 0, $cell, !isset($dom[($key + 1)]));
18870				break;
18871			}
18872			case 'a': {
18873				if (array_key_exists('href', $tag['attribute'])) {
18874					$this->HREF['url'] = $tag['attribute']['href'];
18875				}
18876				break;
18877			}
18878			case 'img': {
18879				if (empty($tag['attribute']['src'])) {
18880					break;
18881				}
18882				$imgsrc = $tag['attribute']['src'];
18883				if ($imgsrc[0] === '@') {
18884					// data stream
18885					$imgsrc = '@'.base64_decode(substr($imgsrc, 1));
18886					$type = '';
18887				} else {
18888					if (($imgsrc[0] === '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
18889						// fix image path
18890						$findroot = strpos($imgsrc, $_SERVER['DOCUMENT_ROOT']);
18891						if (($findroot === false) OR ($findroot > 1)) {
18892							if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
18893								$imgsrc = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$imgsrc;
18894							} else {
18895								$imgsrc = $_SERVER['DOCUMENT_ROOT'].$imgsrc;
18896							}
18897						}
18898						$imgsrc = urldecode($imgsrc);
18899						$testscrtype = @parse_url($imgsrc);
18900						if (empty($testscrtype['query'])) {
18901							// convert URL to server path
18902							$imgsrc = str_replace(K_PATH_URL, K_PATH_MAIN, $imgsrc);
18903						} elseif (preg_match('|^https?://|', $imgsrc) !== 1) {
18904							// convert URL to server path
18905							$imgsrc = str_replace(K_PATH_MAIN, K_PATH_URL, $imgsrc);
18906						}
18907					}
18908					// get image type
18909					$type = TCPDF_IMAGES::getImageFileType($imgsrc);
18910				}
18911				if (!isset($tag['width'])) {
18912					$tag['width'] = 0;
18913				}
18914				if (!isset($tag['height'])) {
18915					$tag['height'] = 0;
18916				}
18917				//if (!isset($tag['attribute']['align'])) {
18918					// the only alignment supported is "bottom"
18919					// further development is required for other modes.
18920					$tag['attribute']['align'] = 'bottom';
18921				//}
18922				switch($tag['attribute']['align']) {
18923					case 'top': {
18924						$align = 'T';
18925						break;
18926					}
18927					case 'middle': {
18928						$align = 'M';
18929						break;
18930					}
18931					case 'bottom': {
18932						$align = 'B';
18933						break;
18934					}
18935					default: {
18936						$align = 'B';
18937						break;
18938					}
18939				}
18940				$prevy = $this->y;
18941				$xpos = $this->x;
18942				$imglink = '';
18943				if (isset($this->HREF['url']) AND !TCPDF_STATIC::empty_string($this->HREF['url'])) {
18944					$imglink = $this->HREF['url'];
18945					if ($imglink[0] == '#') {
18946						// convert url to internal link
18947						$lnkdata = explode(',', $imglink);
18948						if (isset($lnkdata[0])) {
18949							$page = intval(substr($lnkdata[0], 1));
18950							if (empty($page) OR ($page <= 0)) {
18951								$page = $this->page;
18952							}
18953							if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
18954								$lnky = floatval($lnkdata[1]);
18955							} else {
18956								$lnky = 0;
18957							}
18958							$imglink = $this->AddLink();
18959							$this->SetLink($imglink, $lnky, $page);
18960						}
18961					}
18962				}
18963				$border = 0;
18964				if (isset($tag['border']) AND !empty($tag['border'])) {
18965					// currently only support 1 (frame) or a combination of 'LTRB'
18966					$border = $tag['border'];
18967				}
18968				$iw = '';
18969				if (isset($tag['width'])) {
18970					$iw = $this->getHTMLUnitToUnits($tag['width'], ($tag['fontsize'] / $this->k), 'px', false);
18971				}
18972				$ih = '';
18973				if (isset($tag['height'])) {
18974					$ih = $this->getHTMLUnitToUnits($tag['height'], ($tag['fontsize'] / $this->k), 'px', false);
18975				}
18976				if (($type == 'eps') OR ($type == 'ai')) {
18977					$this->ImageEps($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true);
18978				} elseif ($type == 'svg') {
18979					$this->ImageSVG($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true);
18980				} else {
18981					$this->Image($imgsrc, $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
18982				}
18983				switch($align) {
18984					case 'T': {
18985						$this->y = $prevy;
18986						break;
18987					}
18988					case 'M': {
18989						$this->y = (($this->img_rb_y + $prevy - ($this->getCellHeight($tag['fontsize'] / $this->k))) / 2);
18990						break;
18991					}
18992					case 'B': {
18993						$this->y = $this->img_rb_y - ($this->getCellHeight($tag['fontsize'] / $this->k) - ($this->getFontDescent($tag['fontname'], $tag['fontstyle'], $tag['fontsize']) * $this->cell_height_ratio));
18994						break;
18995					}
18996				}
18997				break;
18998			}
18999			case 'dl': {
19000				++$this->listnum;
19001				if ($this->listnum == 1) {
19002					$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19003				} else {
19004					$this->addHTMLVertSpace(0, 0, $cell, $firsttag);
19005				}
19006				break;
19007			}
19008			case 'dt': {
19009				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19010				break;
19011			}
19012			case 'dd': {
19013				if ($this->rtl) {
19014					$this->rMargin += $this->listindent;
19015				} else {
19016					$this->lMargin += $this->listindent;
19017				}
19018				++$this->listindentlevel;
19019				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19020				break;
19021			}
19022			case 'ul':
19023			case 'ol': {
19024				++$this->listnum;
19025				if ($tag['value'] == 'ol') {
19026					$this->listordered[$this->listnum] = true;
19027				} else {
19028					$this->listordered[$this->listnum] = false;
19029				}
19030				if (isset($tag['attribute']['start'])) {
19031					$this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
19032				} else {
19033					$this->listcount[$this->listnum] = 0;
19034				}
19035				if ($this->rtl) {
19036					$this->rMargin += $this->listindent;
19037					$this->x -= $this->listindent;
19038				} else {
19039					$this->lMargin += $this->listindent;
19040					$this->x += $this->listindent;
19041				}
19042				++$this->listindentlevel;
19043				if ($this->listnum == 1) {
19044					if ($key > 1) {
19045						$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19046					}
19047				} else {
19048					$this->addHTMLVertSpace(0, 0, $cell, $firsttag);
19049				}
19050				break;
19051			}
19052			case 'li': {
19053				if ($key > 2) {
19054					$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19055				}
19056				if ($this->listordered[$this->listnum]) {
19057					// ordered item
19058					if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
19059						$this->lispacer = $parent['attribute']['type'];
19060					} elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
19061						$this->lispacer = $parent['listtype'];
19062					} elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
19063						$this->lispacer = $this->lisymbol;
19064					} else {
19065						$this->lispacer = '#';
19066					}
19067					++$this->listcount[$this->listnum];
19068					if (isset($tag['attribute']['value'])) {
19069						$this->listcount[$this->listnum] = intval($tag['attribute']['value']);
19070					}
19071				} else {
19072					// unordered item
19073					if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
19074						$this->lispacer = $parent['attribute']['type'];
19075					} elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
19076						$this->lispacer = $parent['listtype'];
19077					} elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
19078						$this->lispacer = $this->lisymbol;
19079					} else {
19080						$this->lispacer = '!';
19081					}
19082				}
19083				break;
19084			}
19085			case 'blockquote': {
19086				if ($this->rtl) {
19087					$this->rMargin += $this->listindent;
19088				} else {
19089					$this->lMargin += $this->listindent;
19090				}
19091				++$this->listindentlevel;
19092				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19093				break;
19094			}
19095			case 'br': {
19096				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19097				break;
19098			}
19099			case 'div': {
19100				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19101				break;
19102			}
19103			case 'p': {
19104				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19105				break;
19106			}
19107			case 'pre': {
19108				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19109				$this->premode = true;
19110				break;
19111			}
19112			case 'sup': {
19113				$this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
19114				break;
19115			}
19116			case 'sub': {
19117				$this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
19118				break;
19119			}
19120			case 'h1':
19121			case 'h2':
19122			case 'h3':
19123			case 'h4':
19124			case 'h5':
19125			case 'h6': {
19126				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19127				break;
19128			}
19129			// Form fields (since 4.8.000 - 2009-09-07)
19130			case 'form': {
19131				if (isset($tag['attribute']['action'])) {
19132					$this->form_action = $tag['attribute']['action'];
19133				} else {
19134					$this->Error('Please explicitly set action attribute path!');
19135				}
19136				if (isset($tag['attribute']['enctype'])) {
19137					$this->form_enctype = $tag['attribute']['enctype'];
19138				} else {
19139					$this->form_enctype = 'application/x-www-form-urlencoded';
19140				}
19141				if (isset($tag['attribute']['method'])) {
19142					$this->form_mode = $tag['attribute']['method'];
19143				} else {
19144					$this->form_mode = 'post';
19145				}
19146				break;
19147			}
19148			case 'input': {
19149				if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
19150					$name = $tag['attribute']['name'];
19151				} else {
19152					break;
19153				}
19154				$prop = array();
19155				$opt = array();
19156				if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
19157					$prop['readonly'] = true;
19158				}
19159				if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
19160					$value = $tag['attribute']['value'];
19161				}
19162				if (isset($tag['attribute']['maxlength']) AND !TCPDF_STATIC::empty_string($tag['attribute']['maxlength'])) {
19163					$opt['maxlen'] = intval($tag['attribute']['maxlength']);
19164				}
19165				$h = $this->getCellHeight($this->FontSize);
19166				if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
19167					$w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
19168				} else {
19169					$w = $h;
19170				}
19171				if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
19172					$checked = true;
19173				} else {
19174					$checked = false;
19175				}
19176				if (isset($tag['align'])) {
19177					switch ($tag['align']) {
19178						case 'C': {
19179							$opt['q'] = 1;
19180							break;
19181						}
19182						case 'R': {
19183							$opt['q'] = 2;
19184							break;
19185						}
19186						case 'L':
19187						default: {
19188							break;
19189						}
19190					}
19191				}
19192				switch ($tag['attribute']['type']) {
19193					case 'text': {
19194						if (isset($value)) {
19195							$opt['v'] = $value;
19196						}
19197						$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19198						break;
19199					}
19200					case 'password': {
19201						if (isset($value)) {
19202							$opt['v'] = $value;
19203						}
19204						$prop['password'] = 'true';
19205						$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19206						break;
19207					}
19208					case 'checkbox': {
19209						if (!isset($value)) {
19210							break;
19211						}
19212						$this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
19213						break;
19214					}
19215					case 'radio': {
19216						if (!isset($value)) {
19217							break;
19218						}
19219						$this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
19220						break;
19221					}
19222					case 'submit': {
19223						if (!isset($value)) {
19224							$value = 'submit';
19225						}
19226						$w = $this->GetStringWidth($value) * 1.5;
19227						$h *= 1.6;
19228						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19229						$action = array();
19230						$action['S'] = 'SubmitForm';
19231						$action['F'] = $this->form_action;
19232						if ($this->form_enctype != 'FDF') {
19233							$action['Flags'] = array('ExportFormat');
19234						}
19235						if ($this->form_mode == 'get') {
19236							$action['Flags'] = array('GetMethod');
19237						}
19238						$this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
19239						break;
19240					}
19241					case 'reset': {
19242						if (!isset($value)) {
19243							$value = 'reset';
19244						}
19245						$w = $this->GetStringWidth($value) * 1.5;
19246						$h *= 1.6;
19247						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19248						$this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
19249						break;
19250					}
19251					case 'file': {
19252						$prop['fileSelect'] = 'true';
19253						$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19254						if (!isset($value)) {
19255							$value = '*';
19256						}
19257						$w = $this->GetStringWidth($value) * 2;
19258						$h *= 1.2;
19259						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19260						$jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
19261						$this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19262						break;
19263					}
19264					case 'hidden': {
19265						if (isset($value)) {
19266							$opt['v'] = $value;
19267						}
19268						$opt['f'] = array('invisible', 'hidden');
19269						$this->TextField($name, 0, 0, $prop, $opt, '', '', false);
19270						break;
19271					}
19272					case 'image': {
19273						// THIS TYPE MUST BE FIXED
19274						if (isset($tag['attribute']['src']) AND !TCPDF_STATIC::empty_string($tag['attribute']['src'])) {
19275							$img = $tag['attribute']['src'];
19276						} else {
19277							break;
19278						}
19279						$value = 'img';
19280						//$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
19281						if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
19282							$jsaction = $tag['attribute']['onclick'];
19283						} else {
19284							$jsaction = '';
19285						}
19286						$this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19287						break;
19288					}
19289					case 'button': {
19290						if (!isset($value)) {
19291							$value = ' ';
19292						}
19293						$w = $this->GetStringWidth($value) * 1.5;
19294						$h *= 1.6;
19295						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19296						if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
19297							$jsaction = $tag['attribute']['onclick'];
19298						} else {
19299							$jsaction = '';
19300						}
19301						$this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19302						break;
19303					}
19304				}
19305				break;
19306			}
19307			case 'textarea': {
19308				$prop = array();
19309				$opt = array();
19310				if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
19311					$prop['readonly'] = true;
19312				}
19313				if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
19314					$name = $tag['attribute']['name'];
19315				} else {
19316					break;
19317				}
19318				if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
19319					$opt['v'] = $tag['attribute']['value'];
19320				}
19321				if (isset($tag['attribute']['cols']) AND !TCPDF_STATIC::empty_string($tag['attribute']['cols'])) {
19322					$w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
19323				} else {
19324					$w = 40;
19325				}
19326				if (isset($tag['attribute']['rows']) AND !TCPDF_STATIC::empty_string($tag['attribute']['rows'])) {
19327					$h = intval($tag['attribute']['rows']) * $this->getCellHeight($this->FontSize);
19328				} else {
19329					$h = 10;
19330				}
19331				$prop['multiline'] = 'true';
19332				$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19333				break;
19334			}
19335			case 'select': {
19336				$h = $this->getCellHeight($this->FontSize);
19337				if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
19338					$h *= ($tag['attribute']['size'] + 1);
19339				}
19340				$prop = array();
19341				$opt = array();
19342				if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
19343					$name = $tag['attribute']['name'];
19344				} else {
19345					break;
19346				}
19347				$w = 0;
19348				if (isset($tag['attribute']['opt']) AND !TCPDF_STATIC::empty_string($tag['attribute']['opt'])) {
19349					$options = explode('#!NwL!#', $tag['attribute']['opt']);
19350					$values = array();
19351					foreach ($options as $val) {
19352						if (strpos($val, '#!TaB!#') !== false) {
19353							$opts = explode('#!TaB!#', $val);
19354							$values[] = $opts;
19355							$w = max($w, $this->GetStringWidth($opts[1]));
19356						} else {
19357							$values[] = $val;
19358							$w = max($w, $this->GetStringWidth($val));
19359						}
19360					}
19361				} else {
19362					break;
19363				}
19364				$w *= 2;
19365				if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
19366					$prop['multipleSelection'] = 'true';
19367					$this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
19368				} else {
19369					$this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
19370				}
19371				break;
19372			}
19373			case 'tcpdf': {
19374				if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
19375					// Special tag used to call TCPDF methods
19376					if (isset($tag['attribute']['method'])) {
19377						$tcpdf_method = $tag['attribute']['method'];
19378						if (method_exists($this, $tcpdf_method)) {
19379							if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
19380								$params = $this->unserializeTCPDFtagParameters($tag['attribute']['params']);
19381								call_user_func_array(array($this, $tcpdf_method), $params);
19382							} else {
19383								$this->$tcpdf_method();
19384							}
19385							$this->newline = true;
19386						}
19387					}
19388				}
19389				break;
19390			}
19391			default: {
19392				break;
19393			}
19394		}
19395		// define tags that support borders and background colors
19396		$bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
19397		if (in_array($tag['value'], $bordertags)) {
19398			// set border
19399			$dom[$key]['borderposition'] = $this->getBorderStartPosition();
19400		}
19401		if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
19402			$pba = $dom[$key]['attribute']['pagebreakafter'];
19403			// check for pagebreak
19404			if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
19405				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19406				$this->checkPageBreak($this->PageBreakTrigger + 1);
19407			}
19408			if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
19409				OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
19410				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19411				$this->checkPageBreak($this->PageBreakTrigger + 1);
19412			}
19413		}
19414		return $dom;
19415	}
19416
19417	/**
19418	 * Process closing tags.
19419	 * @param $dom (array) html dom array
19420	 * @param $key (int) current element id
19421	 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
19422	 * @param $maxbottomliney (int) maximum y value of current line
19423	 * @return $dom array
19424	 * @protected
19425	 */
19426	protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
19427		$tag = $dom[$key];
19428		$parent = $dom[($dom[$key]['parent'])];
19429		$lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
19430		$in_table_head = false;
19431		// maximum x position (used to draw borders)
19432		if ($this->rtl) {
19433			$xmax = $this->w;
19434		} else {
19435			$xmax = 0;
19436		}
19437		if ($tag['block']) {
19438			$hbz = 0; // distance from y to line bottom
19439			$hb = 0; // vertical space between block tags
19440			// calculate vertical space for block tags
19441			if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
19442				$pre_h = $this->tagvspaces[$tag['value']][1]['h'];
19443			} elseif (isset($parent['fontsize'])) {
19444				$pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
19445			} else {
19446				$pre_h = $this->getCellHeight($this->FontSize);
19447			}
19448			if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
19449				$cn = $this->tagvspaces[$tag['value']][1]['n'];
19450			} elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
19451				$cn = 0.6;
19452			} else {
19453				$cn = 1;
19454			}
19455			if ((!isset($this->tagvspaces[$tag['value']])) AND ($tag['value'] == 'div')) {
19456				$hb = 0;
19457			} else {
19458				$hb = ($cn * $pre_h);
19459			}
19460			if ($maxbottomliney > $this->PageBreakTrigger) {
19461				$hbz = $this->getCellHeight($this->FontSize);
19462			} elseif ($this->y < $maxbottomliney) {
19463				$hbz = ($maxbottomliney - $this->y);
19464			}
19465		}
19466		// Closing tag
19467		switch($tag['value']) {
19468			case 'tr': {
19469				$table_el = $dom[($dom[$key]['parent'])]['parent'];
19470				if (!isset($parent['endy'])) {
19471					$dom[($dom[$key]['parent'])]['endy'] = $this->y;
19472					$parent['endy'] = $this->y;
19473				}
19474				if (!isset($parent['endpage'])) {
19475					$dom[($dom[$key]['parent'])]['endpage'] = $this->page;
19476					$parent['endpage'] = $this->page;
19477				}
19478				if (!isset($parent['endcolumn'])) {
19479					$dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column;
19480					$parent['endcolumn'] = $this->current_column;
19481				}
19482				// update row-spanned cells
19483				if (isset($dom[$table_el]['rowspans'])) {
19484					foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19485						$dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
19486						if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19487							if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
19488								$dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
19489							} elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
19490								$dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
19491								$dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
19492								$dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
19493							}
19494						}
19495					}
19496					// report new endy and endpage to the rowspanned cells
19497					foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19498						if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19499							$dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
19500							$dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
19501							$dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
19502							$dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
19503							$dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
19504							$dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
19505						}
19506					}
19507					// update remaining rowspanned cells
19508					foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19509						if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19510							$dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
19511							$dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
19512							$dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
19513						}
19514					}
19515				}
19516				$prev_page = $this->page;
19517				$this->setPage($dom[($dom[$key]['parent'])]['endpage']);
19518				if ($this->num_columns > 1) {
19519					if (($prev_page < $this->page)
19520						AND ((($this->current_column == 0) AND ($dom[($dom[$key]['parent'])]['endcolumn'] == ($this->num_columns - 1)))
19521							OR ($this->current_column == $dom[($dom[$key]['parent'])]['endcolumn']))) {
19522						// page jump
19523						$this->selectColumn(0);
19524						$dom[($dom[$key]['parent'])]['endcolumn'] = 0;
19525						$dom[($dom[$key]['parent'])]['endy'] = $this->y;
19526					} else {
19527						$this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
19528						$this->y = $dom[($dom[$key]['parent'])]['endy'];
19529					}
19530				} else {
19531					$this->y = $dom[($dom[$key]['parent'])]['endy'];
19532				}
19533				if (isset($dom[$table_el]['attribute']['cellspacing'])) {
19534					$this->y += $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
19535				} elseif (isset($dom[$table_el]['border-spacing'])) {
19536					$this->y += $dom[$table_el]['border-spacing']['V'];
19537				}
19538				$this->Ln(0, $cell);
19539				if ($this->current_column == $parent['startcolumn']) {
19540					$this->x = $parent['startx'];
19541				}
19542				// account for booklet mode
19543				if ($this->page > $parent['startpage']) {
19544					if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
19545						$this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
19546					} elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
19547						$this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
19548					}
19549				}
19550				break;
19551			}
19552			case 'tablehead':
19553				// closing tag used for the thead part
19554				$in_table_head = true;
19555				$this->inthead = false;
19556			case 'table': {
19557				$table_el = $parent;
19558				// set default border
19559				if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
19560					// set default border
19561					$border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
19562				} else {
19563					$border = 0;
19564				}
19565				$default_border = $border;
19566				// fix bottom line alignment of last line before page break
19567				foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
19568					// update row-spanned cells
19569					if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
19570						foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
19571							if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] > 0)) {
19572								$dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
19573							}
19574							if ($dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] == $trkey) {
19575								$dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
19576							}
19577						}
19578					}
19579					if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
19580						$pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
19581						$dom[$prevtrkey]['endy'] = $pgendy;
19582						// update row-spanned cells
19583						if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
19584							foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
19585								if (($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
19586									$dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
19587									$dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
19588								}
19589							}
19590						}
19591					}
19592					$prevtrkey = $trkey;
19593					$table_el = $dom[($dom[$key]['parent'])];
19594				}
19595				// for each row
19596				if (count($table_el['trids']) > 0) {
19597					unset($xmax);
19598				}
19599				foreach ($table_el['trids'] as $j => $trkey) {
19600					$parent = $dom[$trkey];
19601					if (!isset($xmax)) {
19602						$xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
19603					}
19604					// for each cell on the row
19605					foreach ($parent['cellpos'] as $k => $cellpos) {
19606						if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
19607							$cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
19608							$cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
19609							$endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
19610							$startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
19611							$endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
19612							$startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
19613							$endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
19614						} else {
19615							$endy = $parent['endy'];
19616							$startpage = $parent['startpage'];
19617							$endpage = $parent['endpage'];
19618							$startcolumn = $parent['startcolumn'];
19619							$endcolumn = $parent['endcolumn'];
19620						}
19621						if ($this->num_columns == 0) {
19622							$this->num_columns = 1;
19623						}
19624						if (isset($cellpos['border'])) {
19625							$border = $cellpos['border'];
19626						}
19627						if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
19628							$this->SetFillColorArray($cellpos['bgcolor']);
19629							$fill = true;
19630						} else {
19631							$fill = false;
19632						}
19633						$x = $cellpos['startx'];
19634						$y = $parent['starty'];
19635						$starty = $y;
19636						$w = abs($cellpos['endx'] - $cellpos['startx']);
19637						// get border modes
19638						$border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
19639						$border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
19640						$border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
19641						// design borders around HTML cells.
19642						for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
19643							$ccode = '';
19644							$this->setPage($page);
19645							if ($this->num_columns < 2) {
19646								// single-column mode
19647								$this->x = $x;
19648								$this->y = $this->tMargin;
19649							}
19650							// account for margin changes
19651							if ($page > $startpage) {
19652								if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
19653									$this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
19654								} elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
19655									$this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
19656								}
19657							}
19658							if ($startpage == $endpage) { // single page
19659								$deltacol = 0;
19660								$deltath = 0;
19661								for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
19662									$this->selectColumn($column);
19663									if ($startcolumn == $endcolumn) { // single column
19664										$cborder = $border;
19665										$h = $endy - $parent['starty'];
19666										$this->y = $y;
19667										$this->x = $x;
19668									} elseif ($column == $startcolumn) { // first column
19669										$cborder = $border_start;
19670										$this->y = $starty;
19671										$this->x = $x;
19672										$h = $this->h - $this->y - $this->bMargin;
19673										if ($this->rtl) {
19674											$deltacol = $this->x + $this->rMargin - $this->w;
19675										} else {
19676											$deltacol = $this->x - $this->lMargin;
19677										}
19678									} elseif ($column == $endcolumn) { // end column
19679										$cborder = $border_end;
19680										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19681											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19682										}
19683										$this->x += $deltacol;
19684										$h = $endy - $this->y;
19685									} else { // middle column
19686										$cborder = $border_middle;
19687										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19688											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19689										}
19690										$this->x += $deltacol;
19691										$h = $this->h - $this->y - $this->bMargin;
19692									}
19693									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19694								} // end for each column
19695							} elseif ($page == $startpage) { // first page
19696								$deltacol = 0;
19697								$deltath = 0;
19698								for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
19699									$this->selectColumn($column);
19700									if ($column == $startcolumn) { // first column
19701										$cborder = $border_start;
19702										$this->y = $starty;
19703										$this->x = $x;
19704										$h = $this->h - $this->y - $this->bMargin;
19705										if ($this->rtl) {
19706											$deltacol = $this->x + $this->rMargin - $this->w;
19707										} else {
19708											$deltacol = $this->x - $this->lMargin;
19709										}
19710									} else { // middle column
19711										$cborder = $border_middle;
19712										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19713											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19714										}
19715										$this->x += $deltacol;
19716										$h = $this->h - $this->y - $this->bMargin;
19717									}
19718									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19719								} // end for each column
19720							} elseif ($page == $endpage) { // last page
19721								$deltacol = 0;
19722								$deltath = 0;
19723								for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
19724									$this->selectColumn($column);
19725									if ($column == $endcolumn) { // end column
19726										$cborder = $border_end;
19727										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19728											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19729										}
19730										$this->x += $deltacol;
19731										$h = $endy - $this->y;
19732									} else { // middle column
19733										$cborder = $border_middle;
19734										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19735											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19736										}
19737										$this->x += $deltacol;
19738										$h = $this->h - $this->y - $this->bMargin;
19739									}
19740									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19741								} // end for each column
19742							} else { // middle page
19743								$deltacol = 0;
19744								$deltath = 0;
19745								for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
19746									$this->selectColumn($column);
19747									$cborder = $border_middle;
19748									if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19749										$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19750									}
19751									$this->x += $deltacol;
19752									$h = $this->h - $this->y - $this->bMargin;
19753									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19754								} // end for each column
19755							}
19756							if (!empty($cborder) OR !empty($fill)) {
19757								$offsetlen = strlen($ccode);
19758								// draw border and fill
19759								if ($this->inxobj) {
19760									// we are inside an XObject template
19761									if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
19762										$pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
19763										$pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
19764										$this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
19765									} else {
19766										$pagemark = $this->xobjects[$this->xobjid]['intmrk'];
19767										$this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
19768									}
19769									$pagebuff = $this->xobjects[$this->xobjid]['outdata'];
19770									$pstart = substr($pagebuff, 0, $pagemark);
19771									$pend = substr($pagebuff, $pagemark);
19772									$this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
19773								} else {
19774									// draw border and fill
19775									if (end($this->transfmrk[$this->page]) !== false) {
19776										$pagemarkkey = key($this->transfmrk[$this->page]);
19777										$pagemark = $this->transfmrk[$this->page][$pagemarkkey];
19778									} elseif ($this->InFooter) {
19779										$pagemark = $this->footerpos[$this->page];
19780									} else {
19781										$pagemark = $this->intmrk[$this->page];
19782									}
19783									$pagebuff = $this->getPageBuffer($this->page);
19784									$pstart = substr($pagebuff, 0, $pagemark);
19785									$pend = substr($pagebuff, $pagemark);
19786									$this->setPageBuffer($this->page, $pstart.$ccode.$pend);
19787								}
19788							}
19789						} // end for each page
19790						// restore default border
19791						$border = $default_border;
19792					} // end for each cell on the row
19793					if (isset($table_el['attribute']['cellspacing'])) {
19794						$this->y += $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
19795					} elseif (isset($table_el['border-spacing'])) {
19796						$this->y += $table_el['border-spacing']['V'];
19797					}
19798					$this->Ln(0, $cell);
19799					$this->x = $parent['startx'];
19800					if ($endpage > $startpage) {
19801						if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
19802							$this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
19803						} elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
19804							$this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
19805						}
19806					}
19807				}
19808				if (!$in_table_head) { // we are not inside a thead section
19809					$this->cell_padding = $table_el['old_cell_padding'];
19810					// reset row height
19811					$this->resetLastH();
19812					if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages])) {
19813						$plendiff = ($this->pagelen[$this->numpages] - $this->emptypagemrk[$this->numpages]);
19814						if (($plendiff > 0) AND ($plendiff < 60)) {
19815							$pagediff = substr($this->getPageBuffer($this->numpages), $this->emptypagemrk[$this->numpages], $plendiff);
19816							if (substr($pagediff, 0, 5) == 'BT /F') {
19817								// the difference is only a font setting
19818								$plendiff = 0;
19819							}
19820						}
19821						if ($plendiff == 0) {
19822							// remove last blank page
19823							$this->deletePage($this->numpages);
19824						}
19825					}
19826					if (isset($this->theadMargins['top'])) {
19827						// restore top margin
19828						$this->tMargin = $this->theadMargins['top'];
19829					}
19830					if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
19831						// reset main table header
19832						$this->thead = '';
19833						$this->theadMargins = array();
19834						$this->pagedim[$this->page]['tm'] = $this->tMargin;
19835					}
19836				}
19837				$parent = $table_el;
19838				break;
19839			}
19840			case 'a': {
19841				$this->HREF = array();
19842				break;
19843			}
19844			case 'sup': {
19845				$this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
19846				break;
19847			}
19848			case 'sub': {
19849				$this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize']) / $this->k));
19850				break;
19851			}
19852			case 'div': {
19853				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19854				break;
19855			}
19856			case 'blockquote': {
19857				if ($this->rtl) {
19858					$this->rMargin -= $this->listindent;
19859				} else {
19860					$this->lMargin -= $this->listindent;
19861				}
19862				--$this->listindentlevel;
19863				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19864				break;
19865			}
19866			case 'p': {
19867				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19868				break;
19869			}
19870			case 'pre': {
19871				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19872				$this->premode = false;
19873				break;
19874			}
19875			case 'dl': {
19876				--$this->listnum;
19877				if ($this->listnum <= 0) {
19878					$this->listnum = 0;
19879					$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19880				} else {
19881					$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19882				}
19883				$this->resetLastH();
19884				break;
19885			}
19886			case 'dt': {
19887				$this->lispacer = '';
19888				$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19889				break;
19890			}
19891			case 'dd': {
19892				$this->lispacer = '';
19893				if ($this->rtl) {
19894					$this->rMargin -= $this->listindent;
19895				} else {
19896					$this->lMargin -= $this->listindent;
19897				}
19898				--$this->listindentlevel;
19899				$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19900				break;
19901			}
19902			case 'ul':
19903			case 'ol': {
19904				--$this->listnum;
19905				$this->lispacer = '';
19906				if ($this->rtl) {
19907					$this->rMargin -= $this->listindent;
19908				} else {
19909					$this->lMargin -= $this->listindent;
19910				}
19911				--$this->listindentlevel;
19912				if ($this->listnum <= 0) {
19913					$this->listnum = 0;
19914					$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19915				} else {
19916					$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19917				}
19918				$this->resetLastH();
19919				break;
19920			}
19921			case 'li': {
19922				$this->lispacer = '';
19923				$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19924				break;
19925			}
19926			case 'h1':
19927			case 'h2':
19928			case 'h3':
19929			case 'h4':
19930			case 'h5':
19931			case 'h6': {
19932				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19933				break;
19934			}
19935			// Form fields (since 4.8.000 - 2009-09-07)
19936			case 'form': {
19937				$this->form_action = '';
19938				$this->form_enctype = 'application/x-www-form-urlencoded';
19939				break;
19940			}
19941			default : {
19942				break;
19943			}
19944		}
19945		// draw border and background (if any)
19946		$this->drawHTMLTagBorder($parent, $xmax);
19947		if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
19948			$pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
19949			// check for pagebreak
19950			if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
19951				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19952				$this->checkPageBreak($this->PageBreakTrigger + 1);
19953			}
19954			if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
19955				OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
19956				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19957				$this->checkPageBreak($this->PageBreakTrigger + 1);
19958			}
19959		}
19960		$this->tmprtl = false;
19961		return $dom;
19962	}
19963
19964	/**
19965	 * Add vertical spaces if needed.
19966	 * @param $hbz (string) Distance between current y and line bottom.
19967	 * @param $hb (string) The height of the break.
19968	 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
19969	 * @param $firsttag (boolean) set to true when the tag is the first.
19970	 * @param $lasttag (boolean) set to true when the tag is the last.
19971	 * @protected
19972	 */
19973	protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
19974		if ($firsttag) {
19975			$this->Ln(0, $cell);
19976			$this->htmlvspace = 0;
19977			return;
19978		}
19979		if ($lasttag) {
19980			$this->Ln($hbz, $cell);
19981			$this->htmlvspace = 0;
19982			return;
19983		}
19984		if ($hb < $this->htmlvspace) {
19985			$hd = 0;
19986		} else {
19987			$hd = $hb - $this->htmlvspace;
19988			$this->htmlvspace = $hb;
19989		}
19990		$this->Ln(($hbz + $hd), $cell);
19991	}
19992
19993	/**
19994	 * Return the starting coordinates to draw an html border
19995	 * @return array containing top-left border coordinates
19996	 * @protected
19997	 * @since 5.7.000 (2010-08-03)
19998	 */
19999	protected function getBorderStartPosition() {
20000		if ($this->rtl) {
20001			$xmax = $this->lMargin;
20002		} else {
20003			$xmax = $this->w - $this->rMargin;
20004		}
20005		return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax);
20006	}
20007
20008	/**
20009	 * Draw an HTML block border and fill
20010	 * @param $tag (array) array of tag properties.
20011	 * @param $xmax (int) end X coordinate for border.
20012	 * @protected
20013	 * @since 5.7.000 (2010-08-03)
20014	 */
20015	protected function drawHTMLTagBorder($tag, $xmax) {
20016		if (!isset($tag['borderposition'])) {
20017			// nothing to draw
20018			return;
20019		}
20020		$prev_x = $this->x;
20021		$prev_y = $this->y;
20022		$prev_lasth = $this->lasth;
20023		$border = 0;
20024		$fill = false;
20025		$this->lasth = 0;
20026		if (isset($tag['border']) AND !empty($tag['border'])) {
20027			// get border style
20028			$border = $tag['border'];
20029			if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
20030				// border for table header
20031				$border = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
20032			}
20033		}
20034		if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
20035			// get background color
20036			$old_bgcolor = $this->bgcolor;
20037			$this->SetFillColorArray($tag['bgcolor']);
20038			$fill = true;
20039		}
20040		if (!$border AND !$fill) {
20041			// nothing to draw
20042			return;
20043		}
20044		if (isset($tag['attribute']['cellspacing'])) {
20045			$clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
20046			$cellspacing = array('H' => $clsp, 'V' => $clsp);
20047		} elseif (isset($tag['border-spacing'])) {
20048			$cellspacing = $tag['border-spacing'];
20049		} else {
20050			$cellspacing = array('H' => 0, 'V' => 0);
20051		}
20052		if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
20053			// draw the border externally respect the sqare edge.
20054			$border['mode'] = 'ext';
20055		}
20056		if ($this->rtl) {
20057			if ($xmax >= $tag['borderposition']['x']) {
20058				$xmax = $tag['borderposition']['xmax'];
20059			}
20060			$w = ($tag['borderposition']['x'] - $xmax);
20061		} else {
20062			if ($xmax <= $tag['borderposition']['x']) {
20063				$xmax = $tag['borderposition']['xmax'];
20064			}
20065			$w = ($xmax - $tag['borderposition']['x']);
20066		}
20067		if ($w <= 0) {
20068			return;
20069		}
20070		$w += $cellspacing['H'];
20071		$startpage = $tag['borderposition']['page'];
20072		$startcolumn = $tag['borderposition']['column'];
20073		$x = $tag['borderposition']['x'];
20074		$y = $tag['borderposition']['y'];
20075		$endpage = $this->page;
20076		$starty = $tag['borderposition']['y'] - $cellspacing['V'];
20077		$currentY = $this->y;
20078		$this->x = $x;
20079		// get latest column
20080		$endcolumn = $this->current_column;
20081		if ($this->num_columns == 0) {
20082			$this->num_columns = 1;
20083		}
20084		// get border modes
20085		$border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
20086		$border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
20087		$border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
20088		// temporary disable page regions
20089		$temp_page_regions = $this->page_regions;
20090		$this->page_regions = array();
20091		// design borders around HTML cells.
20092		for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
20093			$ccode = '';
20094			$this->setPage($page);
20095			if ($this->num_columns < 2) {
20096				// single-column mode
20097				$this->x = $x;
20098				$this->y = $this->tMargin;
20099			}
20100			// account for margin changes
20101			if ($page > $startpage) {
20102				if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
20103					$this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
20104				} elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
20105					$this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
20106				}
20107			}
20108			if ($startpage == $endpage) {
20109				// single page
20110				for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
20111					$this->selectColumn($column);
20112					if ($startcolumn == $endcolumn) { // single column
20113						$cborder = $border;
20114						$h = ($currentY - $y) + $cellspacing['V'];
20115						$this->y = $starty;
20116					} elseif ($column == $startcolumn) { // first column
20117						$cborder = $border_start;
20118						$this->y = $starty;
20119						$h = $this->h - $this->y - $this->bMargin;
20120					} elseif ($column == $endcolumn) { // end column
20121						$cborder = $border_end;
20122						$h = $currentY - $this->y;
20123					} else { // middle column
20124						$cborder = $border_middle;
20125						$h = $this->h - $this->y - $this->bMargin;
20126					}
20127					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20128				} // end for each column
20129			} elseif ($page == $startpage) { // first page
20130				for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
20131					$this->selectColumn($column);
20132					if ($column == $startcolumn) { // first column
20133						$cborder = $border_start;
20134						$this->y = $starty;
20135						$h = $this->h - $this->y - $this->bMargin;
20136					} else { // middle column
20137						$cborder = $border_middle;
20138						$h = $this->h - $this->y - $this->bMargin;
20139					}
20140					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20141				} // end for each column
20142			} elseif ($page == $endpage) { // last page
20143				for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
20144					$this->selectColumn($column);
20145					if ($column == $endcolumn) {
20146						// end column
20147						$cborder = $border_end;
20148						$h = $currentY - $this->y;
20149					} else {
20150						// middle column
20151						$cborder = $border_middle;
20152						$h = $this->h - $this->y - $this->bMargin;
20153					}
20154					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20155				} // end for each column
20156			} else { // middle page
20157				for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
20158					$this->selectColumn($column);
20159					$cborder = $border_middle;
20160					$h = $this->h - $this->y - $this->bMargin;
20161					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20162				} // end for each column
20163			}
20164			if ($cborder OR $fill) {
20165				$offsetlen = strlen($ccode);
20166				// draw border and fill
20167				if ($this->inxobj) {
20168					// we are inside an XObject template
20169					if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
20170						$pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
20171						$pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
20172						$this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
20173					} else {
20174						$pagemark = $this->xobjects[$this->xobjid]['intmrk'];
20175						$this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
20176					}
20177					$pagebuff = $this->xobjects[$this->xobjid]['outdata'];
20178					$pstart = substr($pagebuff, 0, $pagemark);
20179					$pend = substr($pagebuff, $pagemark);
20180					$this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
20181				} else {
20182					if (end($this->transfmrk[$this->page]) !== false) {
20183						$pagemarkkey = key($this->transfmrk[$this->page]);
20184						$pagemark = $this->transfmrk[$this->page][$pagemarkkey];
20185					} elseif ($this->InFooter) {
20186						$pagemark = $this->footerpos[$this->page];
20187					} else {
20188						$pagemark = $this->intmrk[$this->page];
20189					}
20190					$pagebuff = $this->getPageBuffer($this->page);
20191					$pstart = substr($pagebuff, 0, $pagemark);
20192					$pend = substr($pagebuff, $pagemark);
20193					$this->setPageBuffer($this->page, $pstart.$ccode.$pend);
20194					$this->bordermrk[$this->page] += $offsetlen;
20195					$this->cntmrk[$this->page] += $offsetlen;
20196				}
20197			}
20198		} // end for each page
20199		// restore page regions
20200		$this->page_regions = $temp_page_regions;
20201		if (isset($old_bgcolor)) {
20202			// restore background color
20203			$this->SetFillColorArray($old_bgcolor);
20204		}
20205		// restore pointer position
20206		$this->x = $prev_x;
20207		$this->y = $prev_y;
20208		$this->lasth = $prev_lasth;
20209	}
20210
20211	/**
20212	 * Set the default bullet to be used as LI bullet symbol
20213	 * @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')
20214	 * @public
20215	 * @since 4.0.028 (2008-09-26)
20216	 */
20217	public function setLIsymbol($symbol='!') {
20218		// check for custom image symbol
20219		if (substr($symbol, 0, 4) == 'img|') {
20220			$this->lisymbol = $symbol;
20221			return;
20222		}
20223		$symbol = strtolower($symbol);
20224		$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');
20225		if (in_array($symbol, $valid_symbols)) {
20226			$this->lisymbol = $symbol;
20227		} else {
20228			$this->lisymbol = '';
20229		}
20230	}
20231
20232	/**
20233	 * Set the booklet mode for double-sided pages.
20234	 * @param $booklet (boolean) true set the booklet mode on, false otherwise.
20235	 * @param $inner (float) Inner page margin.
20236	 * @param $outer (float) Outer page margin.
20237	 * @public
20238	 * @since 4.2.000 (2008-10-29)
20239	 */
20240	public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
20241		$this->booklet = $booklet;
20242		if ($inner >= 0) {
20243			$this->lMargin = $inner;
20244		}
20245		if ($outer >= 0) {
20246			$this->rMargin = $outer;
20247		}
20248	}
20249
20250	/**
20251	 * Swap the left and right margins.
20252	 * @param $reverse (boolean) if true swap left and right margins.
20253	 * @protected
20254	 * @since 4.2.000 (2008-10-29)
20255	 */
20256	protected function swapMargins($reverse=true) {
20257		if ($reverse) {
20258			// swap left and right margins
20259			$mtemp = $this->original_lMargin;
20260			$this->original_lMargin = $this->original_rMargin;
20261			$this->original_rMargin = $mtemp;
20262			$deltam = $this->original_lMargin - $this->original_rMargin;
20263			$this->lMargin += $deltam;
20264			$this->rMargin -= $deltam;
20265		}
20266	}
20267
20268	/**
20269	 * Set the vertical spaces for HTML tags.
20270	 * The array must have the following structure (example):
20271	 * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
20272	 * The first array level contains the tag names,
20273	 * the second level contains 0 for opening tags or 1 for closing tags,
20274	 * the third level contains the vertical space unit (h) and the number spaces to add (n).
20275	 * If the h parameter is not specified, default values are used.
20276	 * @param $tagvs (array) array of tags and relative vertical spaces.
20277	 * @public
20278	 * @since 4.2.001 (2008-10-30)
20279	 */
20280	public function setHtmlVSpace($tagvs) {
20281		$this->tagvspaces = $tagvs;
20282	}
20283
20284	/**
20285	 * Set custom width for list indentation.
20286	 * @param $width (float) width of the indentation. Use negative value to disable it.
20287	 * @public
20288	 * @since 4.2.007 (2008-11-12)
20289	 */
20290	public function setListIndentWidth($width) {
20291		return $this->customlistindent = floatval($width);
20292	}
20293
20294	/**
20295	 * Set the top/bottom cell sides to be open or closed when the cell cross the page.
20296	 * @param $isopen (boolean) if true keeps the top/bottom border open for the cell sides that cross the page.
20297	 * @public
20298	 * @since 4.2.010 (2008-11-14)
20299	 */
20300	public function setOpenCell($isopen) {
20301		$this->opencell = $isopen;
20302	}
20303
20304	/**
20305	 * Set the color and font style for HTML links.
20306	 * @param $color (array) RGB array of colors
20307	 * @param $fontstyle (string) additional font styles to add
20308	 * @public
20309	 * @since 4.4.003 (2008-12-09)
20310	 */
20311	public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
20312		$this->htmlLinkColorArray = $color;
20313		$this->htmlLinkFontStyle = $fontstyle;
20314	}
20315
20316	/**
20317	 * Convert HTML string containing value and unit of measure to user's units or points.
20318	 * @param $htmlval (string) String containing values and unit.
20319	 * @param $refsize (string) Reference value in points.
20320	 * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
20321	 * @param $points (boolean) If true returns points, otherwise returns value in user's units.
20322	 * @return float value in user's unit or point if $points=true
20323	 * @public
20324	 * @since 4.4.004 (2008-12-10)
20325	 */
20326	public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
20327		$supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
20328		$retval = 0;
20329		$value = 0;
20330		$unit = 'px';
20331		if ($points) {
20332			$k = 1;
20333		} else {
20334			$k = $this->k;
20335		}
20336		if (in_array($defaultunit, $supportedunits)) {
20337			$unit = $defaultunit;
20338		}
20339		if (is_numeric($htmlval)) {
20340			$value = floatval($htmlval);
20341		} elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
20342			$value = floatval($mnum[1]);
20343			if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
20344				if (in_array($munit[1], $supportedunits)) {
20345					$unit = $munit[1];
20346				}
20347			}
20348		}
20349		switch ($unit) {
20350			// percentage
20351			case '%': {
20352				$retval = (($value * $refsize) / 100);
20353				break;
20354			}
20355			// relative-size
20356			case 'em': {
20357				$retval = ($value * $refsize);
20358				break;
20359			}
20360			// height of lower case 'x' (about half the font-size)
20361			case 'ex': {
20362				$retval = ($value * ($refsize / 2));
20363				break;
20364			}
20365			// absolute-size
20366			case 'in': {
20367				$retval = (($value * $this->dpi) / $k);
20368				break;
20369			}
20370			// centimeters
20371			case 'cm': {
20372				$retval = (($value / 2.54 * $this->dpi) / $k);
20373				break;
20374			}
20375			// millimeters
20376			case 'mm': {
20377				$retval = (($value / 25.4 * $this->dpi) / $k);
20378				break;
20379			}
20380			// one pica is 12 points
20381			case 'pc': {
20382				$retval = (($value * 12) / $k);
20383				break;
20384			}
20385			// points
20386			case 'pt': {
20387				$retval = ($value / $k);
20388				break;
20389			}
20390			// pixels
20391			case 'px': {
20392				$retval = $this->pixelsToUnits($value);
20393				if ($points) {
20394					$retval *= $this->k;
20395				}
20396				break;
20397			}
20398		}
20399		return $retval;
20400	}
20401
20402	/**
20403	 * Output an HTML list bullet or ordered item symbol
20404	 * @param $listdepth (int) list nesting level
20405	 * @param $listtype (string) type of list
20406	 * @param $size (float) current font size
20407	 * @protected
20408	 * @since 4.4.004 (2008-12-10)
20409	 */
20410	protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
20411		if ($this->state != 2) {
20412			return;
20413		}
20414		$size /= $this->k;
20415		$fill = '';
20416		$bgcolor = $this->bgcolor;
20417		$color = $this->fgcolor;
20418		$strokecolor = $this->strokecolor;
20419		$width = 0;
20420		$textitem = '';
20421		$tmpx = $this->x;
20422		$lspace = $this->GetStringWidth('  ');
20423		if ($listtype == '^') {
20424			// special symbol used for avoid justification of rect bullet
20425			$this->lispacer = '';
20426			return;
20427		} elseif ($listtype == '!') {
20428			// set default list type for unordered list
20429			$deftypes = array('disc', 'circle', 'square');
20430			$listtype = $deftypes[($listdepth - 1) % 3];
20431		} elseif ($listtype == '#') {
20432			// set default list type for ordered list
20433			$listtype = 'decimal';
20434		} elseif (substr($listtype, 0, 4) == 'img|') {
20435			// custom image type ('img|type|width|height|image.ext')
20436			$img = explode('|', $listtype);
20437			$listtype = 'img';
20438		}
20439		switch ($listtype) {
20440			// unordered types
20441			case 'none': {
20442				break;
20443			}
20444			case 'disc': {
20445				$r = $size / 6;
20446				$lspace += (2 * $r);
20447				if ($this->rtl) {
20448					$this->x += $lspace;
20449				} else {
20450					$this->x -= $lspace;
20451				}
20452				$this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, 'F', array(), $color, 8);
20453				break;
20454			}
20455			case 'circle': {
20456				$r = $size / 6;
20457				$lspace += (2 * $r);
20458				if ($this->rtl) {
20459					$this->x += $lspace;
20460				} else {
20461					$this->x -= $lspace;
20462				}
20463				$prev_line_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor;
20464				$new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
20465				$this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
20466				$this->_out($prev_line_style); // restore line settings
20467				break;
20468			}
20469			case 'square': {
20470				$l = $size / 3;
20471				$lspace += $l;
20472				if ($this->rtl) {;
20473					$this->x += $lspace;
20474				} else {
20475					$this->x -= $lspace;
20476				}
20477				$this->Rect($this->x, ($this->y + (($this->lasth - $l) / 2)), $l, $l, 'F', array(), $color);
20478				break;
20479			}
20480			case 'img': {
20481				// 1=>type, 2=>width, 3=>height, 4=>image.ext
20482				$lspace += $img[2];
20483				if ($this->rtl) {;
20484					$this->x += $lspace;
20485				} else {
20486					$this->x -= $lspace;
20487				}
20488				$imgtype = strtolower($img[1]);
20489				$prev_y = $this->y;
20490				switch ($imgtype) {
20491					case 'svg': {
20492						$this->ImageSVG($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
20493						break;
20494					}
20495					case 'ai':
20496					case 'eps': {
20497						$this->ImageEps($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
20498						break;
20499					}
20500					default: {
20501						$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);
20502						break;
20503					}
20504				}
20505				$this->y = $prev_y;
20506				break;
20507			}
20508			// ordered types
20509			// $this->listcount[$this->listnum];
20510			// $textitem
20511			case '1':
20512			case 'decimal': {
20513				$textitem = $this->listcount[$this->listnum];
20514				break;
20515			}
20516			case 'decimal-leading-zero': {
20517				$textitem = sprintf('%02d', $this->listcount[$this->listnum]);
20518				break;
20519			}
20520			case 'i':
20521			case 'lower-roman': {
20522				$textitem = strtolower(TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]));
20523				break;
20524			}
20525			case 'I':
20526			case 'upper-roman': {
20527				$textitem = TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]);
20528				break;
20529			}
20530			case 'a':
20531			case 'lower-alpha':
20532			case 'lower-latin': {
20533				$textitem = chr(97 + $this->listcount[$this->listnum] - 1);
20534				break;
20535			}
20536			case 'A':
20537			case 'upper-alpha':
20538			case 'upper-latin': {
20539				$textitem = chr(65 + $this->listcount[$this->listnum] - 1);
20540				break;
20541			}
20542			case 'lower-greek': {
20543				$textitem = TCPDF_FONTS::unichr((945 + $this->listcount[$this->listnum] - 1), $this->isunicode);
20544				break;
20545			}
20546			/*
20547			// Types to be implemented (special handling)
20548			case 'hebrew': {
20549				break;
20550			}
20551			case 'armenian': {
20552				break;
20553			}
20554			case 'georgian': {
20555				break;
20556			}
20557			case 'cjk-ideographic': {
20558				break;
20559			}
20560			case 'hiragana': {
20561				break;
20562			}
20563			case 'katakana': {
20564				break;
20565			}
20566			case 'hiragana-iroha': {
20567				break;
20568			}
20569			case 'katakana-iroha': {
20570				break;
20571			}
20572			*/
20573			default: {
20574				$textitem = $this->listcount[$this->listnum];
20575			}
20576		}
20577		if (!TCPDF_STATIC::empty_string($textitem)) {
20578			// Check whether we need a new page or new column
20579			$prev_y = $this->y;
20580			$h = $this->getCellHeight($this->FontSize);
20581			if ($this->checkPageBreak($h) OR ($this->y < $prev_y)) {
20582				$tmpx = $this->x;
20583			}
20584			// print ordered item
20585			if ($this->rtl) {
20586				$textitem = '.'.$textitem;
20587			} else {
20588				$textitem = $textitem.'.';
20589			}
20590			$lspace += $this->GetStringWidth($textitem);
20591			if ($this->rtl) {
20592				$this->x += $lspace;
20593			} else {
20594				$this->x -= $lspace;
20595			}
20596			$this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
20597		}
20598		$this->x = $tmpx;
20599		$this->lispacer = '^';
20600		// restore colors
20601		$this->SetFillColorArray($bgcolor);
20602		$this->SetDrawColorArray($strokecolor);
20603		$this->SettextColorArray($color);
20604	}
20605
20606	/**
20607	 * Returns current graphic variables as array.
20608	 * @return array of graphic variables
20609	 * @protected
20610	 * @since 4.2.010 (2008-11-14)
20611	 */
20612	protected function getGraphicVars() {
20613		$grapvars = array(
20614			'FontFamily' => $this->FontFamily,
20615			'FontStyle' => $this->FontStyle,
20616			'FontSizePt' => $this->FontSizePt,
20617			'rMargin' => $this->rMargin,
20618			'lMargin' => $this->lMargin,
20619			'cell_padding' => $this->cell_padding,
20620			'cell_margin' => $this->cell_margin,
20621			'LineWidth' => $this->LineWidth,
20622			'linestyleWidth' => $this->linestyleWidth,
20623			'linestyleCap' => $this->linestyleCap,
20624			'linestyleJoin' => $this->linestyleJoin,
20625			'linestyleDash' => $this->linestyleDash,
20626			'textrendermode' => $this->textrendermode,
20627			'textstrokewidth' => $this->textstrokewidth,
20628			'DrawColor' => $this->DrawColor,
20629			'FillColor' => $this->FillColor,
20630			'TextColor' => $this->TextColor,
20631			'ColorFlag' => $this->ColorFlag,
20632			'bgcolor' => $this->bgcolor,
20633			'fgcolor' => $this->fgcolor,
20634			'htmlvspace' => $this->htmlvspace,
20635			'listindent' => $this->listindent,
20636			'listindentlevel' => $this->listindentlevel,
20637			'listnum' => $this->listnum,
20638			'listordered' => $this->listordered,
20639			'listcount' => $this->listcount,
20640			'lispacer' => $this->lispacer,
20641			'cell_height_ratio' => $this->cell_height_ratio,
20642			'font_stretching' => $this->font_stretching,
20643			'font_spacing' => $this->font_spacing,
20644			'alpha' => $this->alpha,
20645			// extended
20646			'lasth' => $this->lasth,
20647			'tMargin' => $this->tMargin,
20648			'bMargin' => $this->bMargin,
20649			'AutoPageBreak' => $this->AutoPageBreak,
20650			'PageBreakTrigger' => $this->PageBreakTrigger,
20651			'x' => $this->x,
20652			'y' => $this->y,
20653			'w' => $this->w,
20654			'h' => $this->h,
20655			'wPt' => $this->wPt,
20656			'hPt' => $this->hPt,
20657			'fwPt' => $this->fwPt,
20658			'fhPt' => $this->fhPt,
20659			'page' => $this->page,
20660			'current_column' => $this->current_column,
20661			'num_columns' => $this->num_columns
20662			);
20663		return $grapvars;
20664	}
20665
20666	/**
20667	 * Set graphic variables.
20668	 * @param $gvars (array) array of graphic variablesto restore
20669	 * @param $extended (boolean) if true restore extended graphic variables
20670	 * @protected
20671	 * @since 4.2.010 (2008-11-14)
20672	 */
20673	protected function setGraphicVars($gvars, $extended=false) {
20674		if ($this->state != 2) {
20675			 return;
20676		}
20677		$this->FontFamily = $gvars['FontFamily'];
20678		$this->FontStyle = $gvars['FontStyle'];
20679		$this->FontSizePt = $gvars['FontSizePt'];
20680		$this->rMargin = $gvars['rMargin'];
20681		$this->lMargin = $gvars['lMargin'];
20682		$this->cell_padding = $gvars['cell_padding'];
20683		$this->cell_margin = $gvars['cell_margin'];
20684		$this->LineWidth = $gvars['LineWidth'];
20685		$this->linestyleWidth = $gvars['linestyleWidth'];
20686		$this->linestyleCap = $gvars['linestyleCap'];
20687		$this->linestyleJoin = $gvars['linestyleJoin'];
20688		$this->linestyleDash = $gvars['linestyleDash'];
20689		$this->textrendermode = $gvars['textrendermode'];
20690		$this->textstrokewidth = $gvars['textstrokewidth'];
20691		$this->DrawColor = $gvars['DrawColor'];
20692		$this->FillColor = $gvars['FillColor'];
20693		$this->TextColor = $gvars['TextColor'];
20694		$this->ColorFlag = $gvars['ColorFlag'];
20695		$this->bgcolor = $gvars['bgcolor'];
20696		$this->fgcolor = $gvars['fgcolor'];
20697		$this->htmlvspace = $gvars['htmlvspace'];
20698		$this->listindent = $gvars['listindent'];
20699		$this->listindentlevel = $gvars['listindentlevel'];
20700		$this->listnum = $gvars['listnum'];
20701		$this->listordered = $gvars['listordered'];
20702		$this->listcount = $gvars['listcount'];
20703		$this->lispacer = $gvars['lispacer'];
20704		$this->cell_height_ratio = $gvars['cell_height_ratio'];
20705		$this->font_stretching = $gvars['font_stretching'];
20706		$this->font_spacing = $gvars['font_spacing'];
20707		$this->alpha = $gvars['alpha'];
20708		if ($extended) {
20709			// restore extended values
20710			$this->lasth = $gvars['lasth'];
20711			$this->tMargin = $gvars['tMargin'];
20712			$this->bMargin = $gvars['bMargin'];
20713			$this->AutoPageBreak = $gvars['AutoPageBreak'];
20714			$this->PageBreakTrigger = $gvars['PageBreakTrigger'];
20715			$this->x = $gvars['x'];
20716			$this->y = $gvars['y'];
20717			$this->w = $gvars['w'];
20718			$this->h = $gvars['h'];
20719			$this->wPt = $gvars['wPt'];
20720			$this->hPt = $gvars['hPt'];
20721			$this->fwPt = $gvars['fwPt'];
20722			$this->fhPt = $gvars['fhPt'];
20723			$this->page = $gvars['page'];
20724			$this->current_column = $gvars['current_column'];
20725			$this->num_columns = $gvars['num_columns'];
20726		}
20727		$this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
20728		if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
20729			$this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
20730		}
20731	}
20732
20733	/**
20734	 * Outputs the "save graphics state" operator 'q'
20735	 * @protected
20736	 */
20737	protected function _outSaveGraphicsState() {
20738		$this->_out('q');
20739	}
20740
20741	/**
20742	 * Outputs the "restore graphics state" operator 'Q'
20743	 * @protected
20744	 */
20745	protected function _outRestoreGraphicsState() {
20746		$this->_out('Q');
20747	}
20748
20749	/**
20750	 * Set buffer content (always append data).
20751	 * @param $data (string) data
20752	 * @protected
20753	 * @since 4.5.000 (2009-01-02)
20754	 */
20755	protected function setBuffer($data) {
20756		$this->bufferlen += strlen($data);
20757		$this->buffer .= $data;
20758	}
20759
20760	/**
20761	 * Replace the buffer content
20762	 * @param $data (string) data
20763	 * @protected
20764	 * @since 5.5.000 (2010-06-22)
20765	 */
20766	protected function replaceBuffer($data) {
20767		$this->bufferlen = strlen($data);
20768		$this->buffer = $data;
20769	}
20770
20771	/**
20772	 * Get buffer content.
20773	 * @return string buffer content
20774	 * @protected
20775	 * @since 4.5.000 (2009-01-02)
20776	 */
20777	protected function getBuffer() {
20778		return $this->buffer;
20779	}
20780
20781	/**
20782	 * Set page buffer content.
20783	 * @param $page (int) page number
20784	 * @param $data (string) page data
20785	 * @param $append (boolean) if true append data, false replace.
20786	 * @protected
20787	 * @since 4.5.000 (2008-12-31)
20788	 */
20789	protected function setPageBuffer($page, $data, $append=false) {
20790		if ($append) {
20791			$this->pages[$page] .= $data;
20792		} else {
20793			$this->pages[$page] = $data;
20794		}
20795		if ($append AND isset($this->pagelen[$page])) {
20796			$this->pagelen[$page] += strlen($data);
20797		} else {
20798			$this->pagelen[$page] = strlen($data);
20799		}
20800	}
20801
20802	/**
20803	 * Get page buffer content.
20804	 * @param $page (int) page number
20805	 * @return string page buffer content or false in case of error
20806	 * @protected
20807	 * @since 4.5.000 (2008-12-31)
20808	 */
20809	protected function getPageBuffer($page) {
20810		if (isset($this->pages[$page])) {
20811			return $this->pages[$page];
20812		}
20813		return false;
20814	}
20815
20816	/**
20817	 * Set image buffer content.
20818	 * @param $image (string) image key
20819	 * @param $data (array) image data
20820	 * @return int image index number
20821	 * @protected
20822	 * @since 4.5.000 (2008-12-31)
20823	 */
20824	protected function setImageBuffer($image, $data) {
20825		if (($data['i'] = array_search($image, $this->imagekeys)) === FALSE) {
20826			$this->imagekeys[$this->numimages] = $image;
20827			$data['i'] = $this->numimages;
20828			++$this->numimages;
20829		}
20830		$this->images[$image] = $data;
20831		return $data['i'];
20832	}
20833
20834	/**
20835	 * Set image buffer content for a specified sub-key.
20836	 * @param $image (string) image key
20837	 * @param $key (string) image sub-key
20838	 * @param $data (array) image data
20839	 * @protected
20840	 * @since 4.5.000 (2008-12-31)
20841	 */
20842	protected function setImageSubBuffer($image, $key, $data) {
20843		if (!isset($this->images[$image])) {
20844			$this->setImageBuffer($image, array());
20845		}
20846		$this->images[$image][$key] = $data;
20847	}
20848
20849	/**
20850	 * Get image buffer content.
20851	 * @param $image (string) image key
20852	 * @return string image buffer content or false in case of error
20853	 * @protected
20854	 * @since 4.5.000 (2008-12-31)
20855	 */
20856	protected function getImageBuffer($image) {
20857		if (isset($this->images[$image])) {
20858			return $this->images[$image];
20859		}
20860		return false;
20861	}
20862
20863	/**
20864	 * Set font buffer content.
20865	 * @param $font (string) font key
20866	 * @param $data (array) font data
20867	 * @protected
20868	 * @since 4.5.000 (2009-01-02)
20869	 */
20870	protected function setFontBuffer($font, $data) {
20871		$this->fonts[$font] = $data;
20872		if (!in_array($font, $this->fontkeys)) {
20873			$this->fontkeys[] = $font;
20874			// store object ID for current font
20875			++$this->n;
20876			$this->font_obj_ids[$font] = $this->n;
20877			$this->setFontSubBuffer($font, 'n', $this->n);
20878		}
20879	}
20880
20881	/**
20882	 * Set font buffer content.
20883	 * @param $font (string) font key
20884	 * @param $key (string) font sub-key
20885	 * @param $data (array) font data
20886	 * @protected
20887	 * @since 4.5.000 (2009-01-02)
20888	 */
20889	protected function setFontSubBuffer($font, $key, $data) {
20890		if (!isset($this->fonts[$font])) {
20891			$this->setFontBuffer($font, array());
20892		}
20893		$this->fonts[$font][$key] = $data;
20894	}
20895
20896	/**
20897	 * Get font buffer content.
20898	 * @param $font (string) font key
20899	 * @return string font buffer content or false in case of error
20900	 * @protected
20901	 * @since 4.5.000 (2009-01-02)
20902	 */
20903	protected function getFontBuffer($font) {
20904		if (isset($this->fonts[$font])) {
20905			return $this->fonts[$font];
20906		}
20907		return false;
20908	}
20909
20910	/**
20911	 * Move a page to a previous position.
20912	 * @param $frompage (int) number of the source page
20913	 * @param $topage (int) number of the destination page (must be less than $frompage)
20914	 * @return true in case of success, false in case of error.
20915	 * @public
20916	 * @since 4.5.000 (2009-01-02)
20917	 */
20918	public function movePage($frompage, $topage) {
20919		if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
20920			return false;
20921		}
20922		if ($frompage == $this->page) {
20923			// close the page before moving it
20924			$this->endPage();
20925		}
20926		// move all page-related states
20927		$tmppage = $this->getPageBuffer($frompage);
20928		$tmppagedim = $this->pagedim[$frompage];
20929		$tmppagelen = $this->pagelen[$frompage];
20930		$tmpintmrk = $this->intmrk[$frompage];
20931		$tmpbordermrk = $this->bordermrk[$frompage];
20932		$tmpcntmrk = $this->cntmrk[$frompage];
20933		$tmppageobjects = $this->pageobjects[$frompage];
20934		if (isset($this->footerpos[$frompage])) {
20935			$tmpfooterpos = $this->footerpos[$frompage];
20936		}
20937		if (isset($this->footerlen[$frompage])) {
20938			$tmpfooterlen = $this->footerlen[$frompage];
20939		}
20940		if (isset($this->transfmrk[$frompage])) {
20941			$tmptransfmrk = $this->transfmrk[$frompage];
20942		}
20943		if (isset($this->PageAnnots[$frompage])) {
20944			$tmpannots = $this->PageAnnots[$frompage];
20945		}
20946		if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
20947			for ($i = $frompage; $i > $topage; --$i) {
20948				if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $frompage)) {
20949					--$this->pagegroups[$this->newpagegroup[$i]];
20950					break;
20951				}
20952			}
20953			for ($i = $topage; $i > 0; --$i) {
20954				if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $topage)) {
20955					++$this->pagegroups[$this->newpagegroup[$i]];
20956					break;
20957				}
20958			}
20959		}
20960		for ($i = $frompage; $i > $topage; --$i) {
20961			$j = $i - 1;
20962			// shift pages down
20963			$this->setPageBuffer($i, $this->getPageBuffer($j));
20964			$this->pagedim[$i] = $this->pagedim[$j];
20965			$this->pagelen[$i] = $this->pagelen[$j];
20966			$this->intmrk[$i] = $this->intmrk[$j];
20967			$this->bordermrk[$i] = $this->bordermrk[$j];
20968			$this->cntmrk[$i] = $this->cntmrk[$j];
20969			$this->pageobjects[$i] = $this->pageobjects[$j];
20970			if (isset($this->footerpos[$j])) {
20971				$this->footerpos[$i] = $this->footerpos[$j];
20972			} elseif (isset($this->footerpos[$i])) {
20973				unset($this->footerpos[$i]);
20974			}
20975			if (isset($this->footerlen[$j])) {
20976				$this->footerlen[$i] = $this->footerlen[$j];
20977			} elseif (isset($this->footerlen[$i])) {
20978				unset($this->footerlen[$i]);
20979			}
20980			if (isset($this->transfmrk[$j])) {
20981				$this->transfmrk[$i] = $this->transfmrk[$j];
20982			} elseif (isset($this->transfmrk[$i])) {
20983				unset($this->transfmrk[$i]);
20984			}
20985			if (isset($this->PageAnnots[$j])) {
20986				$this->PageAnnots[$i] = $this->PageAnnots[$j];
20987			} elseif (isset($this->PageAnnots[$i])) {
20988				unset($this->PageAnnots[$i]);
20989			}
20990			if (isset($this->newpagegroup[$j])) {
20991				$this->newpagegroup[$i] = $this->newpagegroup[$j];
20992				unset($this->newpagegroup[$j]);
20993			}
20994			if ($this->currpagegroup == $j) {
20995				$this->currpagegroup = $i;
20996			}
20997		}
20998		$this->setPageBuffer($topage, $tmppage);
20999		$this->pagedim[$topage] = $tmppagedim;
21000		$this->pagelen[$topage] = $tmppagelen;
21001		$this->intmrk[$topage] = $tmpintmrk;
21002		$this->bordermrk[$topage] = $tmpbordermrk;
21003		$this->cntmrk[$topage] = $tmpcntmrk;
21004		$this->pageobjects[$topage] = $tmppageobjects;
21005		if (isset($tmpfooterpos)) {
21006			$this->footerpos[$topage] = $tmpfooterpos;
21007		} elseif (isset($this->footerpos[$topage])) {
21008			unset($this->footerpos[$topage]);
21009		}
21010		if (isset($tmpfooterlen)) {
21011			$this->footerlen[$topage] = $tmpfooterlen;
21012		} elseif (isset($this->footerlen[$topage])) {
21013			unset($this->footerlen[$topage]);
21014		}
21015		if (isset($tmptransfmrk)) {
21016			$this->transfmrk[$topage] = $tmptransfmrk;
21017		} elseif (isset($this->transfmrk[$topage])) {
21018			unset($this->transfmrk[$topage]);
21019		}
21020		if (isset($tmpannots)) {
21021			$this->PageAnnots[$topage] = $tmpannots;
21022		} elseif (isset($this->PageAnnots[$topage])) {
21023			unset($this->PageAnnots[$topage]);
21024		}
21025		// adjust outlines
21026		$tmpoutlines = $this->outlines;
21027		foreach ($tmpoutlines as $key => $outline) {
21028			if (!$outline['f']) {
21029				if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
21030					$this->outlines[$key]['p'] = ($outline['p'] + 1);
21031				} elseif ($outline['p'] == $frompage) {
21032					$this->outlines[$key]['p'] = $topage;
21033				}
21034			}
21035		}
21036		// adjust dests
21037		$tmpdests = $this->dests;
21038		foreach ($tmpdests as $key => $dest) {
21039			if (!$dest['f']) {
21040				if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
21041					$this->dests[$key]['p'] = ($dest['p'] + 1);
21042				} elseif ($dest['p'] == $frompage) {
21043					$this->dests[$key]['p'] = $topage;
21044				}
21045			}
21046		}
21047		// adjust links
21048		$tmplinks = $this->links;
21049		foreach ($tmplinks as $key => $link) {
21050			if (!$link['f']) {
21051				if (($link['p'] >= $topage) AND ($link['p'] < $frompage)) {
21052					$this->links[$key]['p'] = ($link['p'] + 1);
21053				} elseif ($link['p'] == $frompage) {
21054					$this->links[$key]['p'] = $topage;
21055				}
21056			}
21057		}
21058		// adjust javascript
21059		$jfrompage = $frompage;
21060		$jtopage = $topage;
21061		if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
21062			foreach($pamatch[0] as $pk => $pmatch) {
21063				$pagenum = intval($pamatch[3][$pk]) + 1;
21064				if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
21065					$newpage = ($pagenum + 1);
21066				} elseif ($pagenum == $jfrompage) {
21067					$newpage = $jtopage;
21068				} else {
21069					$newpage = $pagenum;
21070				}
21071				--$newpage;
21072				$newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
21073				$this->javascript = str_replace($pmatch, $newjs, $this->javascript);
21074			}
21075			unset($pamatch);
21076		}
21077		// return to last page
21078		$this->lastPage(true);
21079		return true;
21080	}
21081
21082	/**
21083	 * Remove the specified page.
21084	 * @param $page (int) page to remove
21085	 * @return true in case of success, false in case of error.
21086	 * @public
21087	 * @since 4.6.004 (2009-04-23)
21088	 */
21089	public function deletePage($page) {
21090		if (($page < 1) OR ($page > $this->numpages)) {
21091			return false;
21092		}
21093		// delete current page
21094		unset($this->pages[$page]);
21095		unset($this->pagedim[$page]);
21096		unset($this->pagelen[$page]);
21097		unset($this->intmrk[$page]);
21098		unset($this->bordermrk[$page]);
21099		unset($this->cntmrk[$page]);
21100		foreach ($this->pageobjects[$page] as $oid) {
21101			if (isset($this->offsets[$oid])){
21102				unset($this->offsets[$oid]);
21103			}
21104		}
21105		unset($this->pageobjects[$page]);
21106		if (isset($this->footerpos[$page])) {
21107			unset($this->footerpos[$page]);
21108		}
21109		if (isset($this->footerlen[$page])) {
21110			unset($this->footerlen[$page]);
21111		}
21112		if (isset($this->transfmrk[$page])) {
21113			unset($this->transfmrk[$page]);
21114		}
21115		if (isset($this->PageAnnots[$page])) {
21116			unset($this->PageAnnots[$page]);
21117		}
21118		if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
21119			for ($i = $page; $i > 0; --$i) {
21120				if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $page)) {
21121					--$this->pagegroups[$this->newpagegroup[$i]];
21122					break;
21123				}
21124			}
21125		}
21126		if (isset($this->pageopen[$page])) {
21127			unset($this->pageopen[$page]);
21128		}
21129		if ($page < $this->numpages) {
21130			// update remaining pages
21131			for ($i = $page; $i < $this->numpages; ++$i) {
21132				$j = $i + 1;
21133				// shift pages
21134				$this->setPageBuffer($i, $this->getPageBuffer($j));
21135				$this->pagedim[$i] = $this->pagedim[$j];
21136				$this->pagelen[$i] = $this->pagelen[$j];
21137				$this->intmrk[$i] = $this->intmrk[$j];
21138				$this->bordermrk[$i] = $this->bordermrk[$j];
21139				$this->cntmrk[$i] = $this->cntmrk[$j];
21140				$this->pageobjects[$i] = $this->pageobjects[$j];
21141				if (isset($this->footerpos[$j])) {
21142					$this->footerpos[$i] = $this->footerpos[$j];
21143				} elseif (isset($this->footerpos[$i])) {
21144					unset($this->footerpos[$i]);
21145				}
21146				if (isset($this->footerlen[$j])) {
21147					$this->footerlen[$i] = $this->footerlen[$j];
21148				} elseif (isset($this->footerlen[$i])) {
21149					unset($this->footerlen[$i]);
21150				}
21151				if (isset($this->transfmrk[$j])) {
21152					$this->transfmrk[$i] = $this->transfmrk[$j];
21153				} elseif (isset($this->transfmrk[$i])) {
21154					unset($this->transfmrk[$i]);
21155				}
21156				if (isset($this->PageAnnots[$j])) {
21157					$this->PageAnnots[$i] = $this->PageAnnots[$j];
21158				} elseif (isset($this->PageAnnots[$i])) {
21159					unset($this->PageAnnots[$i]);
21160				}
21161				if (isset($this->newpagegroup[$j])) {
21162					$this->newpagegroup[$i] = $this->newpagegroup[$j];
21163					unset($this->newpagegroup[$j]);
21164				}
21165				if ($this->currpagegroup == $j) {
21166					$this->currpagegroup = $i;
21167				}
21168				if (isset($this->pageopen[$j])) {
21169					$this->pageopen[$i] = $this->pageopen[$j];
21170				} elseif (isset($this->pageopen[$i])) {
21171					unset($this->pageopen[$i]);
21172				}
21173			}
21174			// remove last page
21175			unset($this->pages[$this->numpages]);
21176			unset($this->pagedim[$this->numpages]);
21177			unset($this->pagelen[$this->numpages]);
21178			unset($this->intmrk[$this->numpages]);
21179			unset($this->bordermrk[$this->numpages]);
21180			unset($this->cntmrk[$this->numpages]);
21181			foreach ($this->pageobjects[$this->numpages] as $oid) {
21182				if (isset($this->offsets[$oid])){
21183					unset($this->offsets[$oid]);
21184				}
21185			}
21186			unset($this->pageobjects[$this->numpages]);
21187			if (isset($this->footerpos[$this->numpages])) {
21188				unset($this->footerpos[$this->numpages]);
21189			}
21190			if (isset($this->footerlen[$this->numpages])) {
21191				unset($this->footerlen[$this->numpages]);
21192			}
21193			if (isset($this->transfmrk[$this->numpages])) {
21194				unset($this->transfmrk[$this->numpages]);
21195			}
21196			if (isset($this->PageAnnots[$this->numpages])) {
21197				unset($this->PageAnnots[$this->numpages]);
21198			}
21199			if (isset($this->newpagegroup[$this->numpages])) {
21200				unset($this->newpagegroup[$this->numpages]);
21201			}
21202			if ($this->currpagegroup == $this->numpages) {
21203				$this->currpagegroup = ($this->numpages - 1);
21204			}
21205			if (isset($this->pagegroups[$this->numpages])) {
21206				unset($this->pagegroups[$this->numpages]);
21207			}
21208			if (isset($this->pageopen[$this->numpages])) {
21209				unset($this->pageopen[$this->numpages]);
21210			}
21211		}
21212		--$this->numpages;
21213		$this->page = $this->numpages;
21214		// adjust outlines
21215		$tmpoutlines = $this->outlines;
21216		foreach ($tmpoutlines as $key => $outline) {
21217			if (!$outline['f']) {
21218				if ($outline['p'] > $page) {
21219					$this->outlines[$key]['p'] = $outline['p'] - 1;
21220				} elseif ($outline['p'] == $page) {
21221					unset($this->outlines[$key]);
21222				}
21223			}
21224		}
21225		// adjust dests
21226		$tmpdests = $this->dests;
21227		foreach ($tmpdests as $key => $dest) {
21228			if (!$dest['f']) {
21229				if ($dest['p'] > $page) {
21230					$this->dests[$key]['p'] = $dest['p'] - 1;
21231				} elseif ($dest['p'] == $page) {
21232					unset($this->dests[$key]);
21233				}
21234			}
21235		}
21236		// adjust links
21237		$tmplinks = $this->links;
21238		foreach ($tmplinks as $key => $link) {
21239			if (!$link['f']) {
21240				if ($link['p'] > $page) {
21241					$this->links[$key]['p'] = $link['p'] - 1;
21242				} elseif ($link['p'] == $page) {
21243					unset($this->links[$key]);
21244				}
21245			}
21246		}
21247		// adjust javascript
21248		$jpage = $page;
21249		if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
21250			foreach($pamatch[0] as $pk => $pmatch) {
21251				$pagenum = intval($pamatch[3][$pk]) + 1;
21252				if ($pagenum >= $jpage) {
21253					$newpage = ($pagenum - 1);
21254				} elseif ($pagenum == $jpage) {
21255					$newpage = 1;
21256				} else {
21257					$newpage = $pagenum;
21258				}
21259				--$newpage;
21260				$newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
21261				$this->javascript = str_replace($pmatch, $newjs, $this->javascript);
21262			}
21263			unset($pamatch);
21264		}
21265		// return to last page
21266		if ($this->numpages > 0) {
21267			$this->lastPage(true);
21268		}
21269		return true;
21270	}
21271
21272	/**
21273	 * Clone the specified page to a new page.
21274	 * @param $page (int) number of page to copy (0 = current page)
21275	 * @return true in case of success, false in case of error.
21276	 * @public
21277	 * @since 4.9.015 (2010-04-20)
21278	 */
21279	public function copyPage($page=0) {
21280		if ($page == 0) {
21281			// default value
21282			$page = $this->page;
21283		}
21284		if (($page < 1) OR ($page > $this->numpages)) {
21285			return false;
21286		}
21287		// close the last page
21288		$this->endPage();
21289		// copy all page-related states
21290		++$this->numpages;
21291		$this->page = $this->numpages;
21292		$this->setPageBuffer($this->page, $this->getPageBuffer($page));
21293		$this->pagedim[$this->page] = $this->pagedim[$page];
21294		$this->pagelen[$this->page] = $this->pagelen[$page];
21295		$this->intmrk[$this->page] = $this->intmrk[$page];
21296		$this->bordermrk[$this->page] = $this->bordermrk[$page];
21297		$this->cntmrk[$this->page] = $this->cntmrk[$page];
21298		$this->pageobjects[$this->page] = $this->pageobjects[$page];
21299		$this->pageopen[$this->page] = false;
21300		if (isset($this->footerpos[$page])) {
21301			$this->footerpos[$this->page] = $this->footerpos[$page];
21302		}
21303		if (isset($this->footerlen[$page])) {
21304			$this->footerlen[$this->page] = $this->footerlen[$page];
21305		}
21306		if (isset($this->transfmrk[$page])) {
21307			$this->transfmrk[$this->page] = $this->transfmrk[$page];
21308		}
21309		if (isset($this->PageAnnots[$page])) {
21310			$this->PageAnnots[$this->page] = $this->PageAnnots[$page];
21311		}
21312		if (isset($this->newpagegroup[$page])) {
21313			// start a new group
21314			$this->newpagegroup[$this->page] = sizeof($this->newpagegroup) + 1;
21315			$this->currpagegroup = $this->newpagegroup[$this->page];
21316			$this->pagegroups[$this->currpagegroup] = 1;
21317		} elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
21318			++$this->pagegroups[$this->currpagegroup];
21319		}
21320		// copy outlines
21321		$tmpoutlines = $this->outlines;
21322		foreach ($tmpoutlines as $key => $outline) {
21323			if ($outline['p'] == $page) {
21324				$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']);
21325			}
21326		}
21327		// copy links
21328		$tmplinks = $this->links;
21329		foreach ($tmplinks as $key => $link) {
21330			if ($link['p'] == $page) {
21331				$this->links[] = array('p' => $this->page, 'y' => $link['y'], 'f' => $link['f']);
21332			}
21333		}
21334		// return to last page
21335		$this->lastPage(true);
21336		return true;
21337	}
21338
21339	/**
21340	 * Output a Table of Content Index (TOC).
21341	 * This method must be called after all Bookmarks were set.
21342	 * Before calling this method you have to open the page using the addTOCPage() method.
21343	 * After calling this method you have to call endTOCPage() to close the TOC page.
21344	 * You can override this method to achieve different styles.
21345	 * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
21346	 * @param $numbersfont (string) set the font for page numbers (please use monospaced font for better alignment).
21347	 * @param $filler (string) string used to fill the space between text and page number.
21348	 * @param $toc_name (string) name to use for TOC bookmark.
21349	 * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
21350	 * @param $color (array) RGB color array for bookmark title (values from 0 to 255).
21351	 * @public
21352	 * @author Nicola Asuni
21353	 * @since 4.5.000 (2009-01-02)
21354	 * @see addTOCPage(), endTOCPage(), addHTMLTOC()
21355	 */
21356	public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
21357		$fontsize = $this->FontSizePt;
21358		$fontfamily = $this->FontFamily;
21359		$fontstyle = $this->FontStyle;
21360		$w = $this->w - $this->lMargin - $this->rMargin;
21361		$spacer = $this->GetStringWidth(chr(32)) * 4;
21362		$lmargin = $this->lMargin;
21363		$rmargin = $this->rMargin;
21364		$x_start = $this->GetX();
21365		$page_first = $this->page;
21366		$current_page = $this->page;
21367		$page_fill_start = false;
21368		$page_fill_end = false;
21369		$current_column = $this->current_column;
21370		if (TCPDF_STATIC::empty_string($numbersfont)) {
21371			$numbersfont = $this->default_monospaced_font;
21372		}
21373		if (TCPDF_STATIC::empty_string($filler)) {
21374			$filler = ' ';
21375		}
21376		if (TCPDF_STATIC::empty_string($page)) {
21377			$gap = ' ';
21378		} else {
21379			$gap = '';
21380			if ($page < 1) {
21381				$page = 1;
21382			}
21383		}
21384		$this->SetFont($numbersfont, $fontstyle, $fontsize);
21385		$numwidth = $this->GetStringWidth('00000');
21386		$maxpage = 0; //used for pages on attached documents
21387		foreach ($this->outlines as $key => $outline) {
21388			// check for extra pages (used for attachments)
21389			if (($this->page > $page_first) AND ($outline['p'] >= $this->numpages)) {
21390				$outline['p'] += ($this->page - $page_first);
21391			}
21392			if ($this->rtl) {
21393				$aligntext = 'R';
21394				$alignnum = 'L';
21395			} else {
21396				$aligntext = 'L';
21397				$alignnum = 'R';
21398			}
21399			if ($outline['l'] == 0) {
21400				$this->SetFont($fontfamily, $outline['s'].'B', $fontsize);
21401			} else {
21402				$this->SetFont($fontfamily, $outline['s'], $fontsize - $outline['l']);
21403			}
21404			$this->SetTextColorArray($outline['c']);
21405			// check for page break
21406			$this->checkPageBreak(2 * $this->getCellHeight($this->FontSize));
21407			// set margins and X position
21408			if (($this->page == $current_page) AND ($this->current_column == $current_column)) {
21409				$this->lMargin = $lmargin;
21410				$this->rMargin = $rmargin;
21411			} else {
21412				if ($this->current_column != $current_column) {
21413					if ($this->rtl) {
21414						$x_start = $this->w - $this->columns[$this->current_column]['x'];
21415					} else {
21416						$x_start = $this->columns[$this->current_column]['x'];
21417					}
21418				}
21419				$lmargin = $this->lMargin;
21420				$rmargin = $this->rMargin;
21421				$current_page = $this->page;
21422				$current_column = $this->current_column;
21423			}
21424			$this->SetX($x_start);
21425			$indent = ($spacer * $outline['l']);
21426			if ($this->rtl) {
21427				$this->x -= $indent;
21428				$this->rMargin = $this->w - $this->x;
21429			} else {
21430				$this->x += $indent;
21431				$this->lMargin = $this->x;
21432			}
21433			$link = $this->AddLink();
21434			$this->SetLink($link, $outline['y'], $outline['p']);
21435			// write the text
21436			if ($this->rtl) {
21437				$txt = ' '.$outline['t'];
21438			} else {
21439				$txt = $outline['t'].' ';
21440			}
21441			$this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
21442			if ($this->rtl) {
21443				$tw = $this->x - $this->lMargin;
21444			} else {
21445				$tw = $this->w - $this->rMargin - $this->x;
21446			}
21447			$this->SetFont($numbersfont, $fontstyle, $fontsize);
21448			if (TCPDF_STATIC::empty_string($page)) {
21449				$pagenum = $outline['p'];
21450			} else {
21451				// placemark to be replaced with the correct number
21452				$pagenum = '{#'.($outline['p']).'}';
21453				if ($this->isUnicodeFont()) {
21454					$pagenum = '{'.$pagenum.'}';
21455				}
21456				$maxpage = max($maxpage, $outline['p']);
21457			}
21458			$fw = ($tw - $this->GetStringWidth($pagenum.$filler));
21459			$wfiller = $this->GetStringWidth($filler);
21460			if ($wfiller > 0) {
21461				$numfills = floor($fw / $wfiller);
21462			} else {
21463				$numfills = 0;
21464			}
21465			if ($numfills > 0) {
21466				$rowfill = str_repeat($filler, $numfills);
21467			} else {
21468				$rowfill = '';
21469			}
21470			if ($this->rtl) {
21471				$pagenum = $pagenum.$gap.$rowfill;
21472			} else {
21473				$pagenum = $rowfill.$gap.$pagenum;
21474			}
21475			// write the number
21476			$this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
21477		}
21478		$page_last = $this->getPage();
21479		$numpages = ($page_last - $page_first + 1);
21480		// account for booklet mode
21481		if ($this->booklet) {
21482			// check if a blank page is required before TOC
21483			$page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
21484			$page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
21485			if ($page_fill_start) {
21486				// add a page at the end (to be moved before TOC)
21487				$this->addPage();
21488				++$page_last;
21489				++$numpages;
21490			}
21491			if ($page_fill_end) {
21492				// add a page at the end
21493				$this->addPage();
21494				++$page_last;
21495				++$numpages;
21496			}
21497		}
21498		$maxpage = max($maxpage, $page_last);
21499		if (!TCPDF_STATIC::empty_string($page)) {
21500			for ($p = $page_first; $p <= $page_last; ++$p) {
21501				// get page data
21502				$temppage = $this->getPageBuffer($p);
21503				for ($n = 1; $n <= $maxpage; ++$n) {
21504					// update page numbers
21505					$a = '{#'.$n.'}';
21506					// get page number aliases
21507					$pnalias = $this->getInternalPageNumberAliases($a);
21508					// calculate replacement number
21509					if (($n >= $page) AND ($n <= $this->numpages)) {
21510						$np = $n + $numpages;
21511					} else {
21512						$np = $n;
21513					}
21514					$na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
21515					$nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
21516					// replace aliases with numbers
21517					foreach ($pnalias['u'] as $u) {
21518						$sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
21519						if ($this->rtl) {
21520							$nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
21521						} else {
21522							$nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
21523						}
21524						$temppage = str_replace($u, $nr, $temppage);
21525					}
21526					foreach ($pnalias['a'] as $a) {
21527						$sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
21528						if ($this->rtl) {
21529							$nr = $na.' '.$sfill;
21530						} else {
21531							$nr = $sfill.' '.$na;
21532						}
21533						$temppage = str_replace($a, $nr, $temppage);
21534					}
21535				}
21536				// save changes
21537				$this->setPageBuffer($p, $temppage);
21538			}
21539			// move pages
21540			$this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
21541			if ($page_fill_start) {
21542				$this->movePage($page_last, $page_first);
21543			}
21544			for ($i = 0; $i < $numpages; ++$i) {
21545				$this->movePage($page_last, $page);
21546			}
21547		}
21548	}
21549
21550	/**
21551	 * Output a Table Of Content Index (TOC) using HTML templates.
21552	 * This method must be called after all Bookmarks were set.
21553	 * Before calling this method you have to open the page using the addTOCPage() method.
21554	 * After calling this method you have to call endTOCPage() to close the TOC page.
21555	 * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
21556	 * @param $toc_name (string) name to use for TOC bookmark.
21557	 * @param $templates (array) array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
21558	 * @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)
21559	 * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
21560	 * @param $color (array) RGB color array for title (values from 0 to 255).
21561	 * @public
21562	 * @author Nicola Asuni
21563	 * @since 5.0.001 (2010-05-06)
21564	 * @see addTOCPage(), endTOCPage(), addTOC()
21565	 */
21566	public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
21567		$filler = ' ';
21568		$prev_htmlLinkColorArray = $this->htmlLinkColorArray;
21569		$prev_htmlLinkFontStyle = $this->htmlLinkFontStyle;
21570		// set new style for link
21571		$this->htmlLinkColorArray = array();
21572		$this->htmlLinkFontStyle = '';
21573		$page_first = $this->getPage();
21574		$page_fill_start = false;
21575		$page_fill_end = false;
21576		// get the font type used for numbers in each template
21577		$current_font = $this->FontFamily;
21578		foreach ($templates as $level => $html) {
21579			$dom = $this->getHtmlDomArray($html);
21580			foreach ($dom as $key => $value) {
21581				if ($value['value'] == '#TOC_PAGE_NUMBER#') {
21582					$this->SetFont($dom[($key - 1)]['fontname']);
21583					$templates['F'.$level] = $this->isUnicodeFont();
21584				}
21585			}
21586		}
21587		$this->SetFont($current_font);
21588		$maxpage = 0; //used for pages on attached documents
21589		foreach ($this->outlines as $key => $outline) {
21590			// get HTML template
21591			$row = $templates[$outline['l']];
21592			if (TCPDF_STATIC::empty_string($page)) {
21593				$pagenum = $outline['p'];
21594			} else {
21595				// placemark to be replaced with the correct number
21596				$pagenum = '{#'.($outline['p']).'}';
21597				if (isset($templates['F'.$outline['l']]) && $templates['F'.$outline['l']]) {
21598					$pagenum = '{'.$pagenum.'}';
21599				}
21600				$maxpage = max($maxpage, $outline['p']);
21601			}
21602			// replace templates with current values
21603			$row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
21604			$row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
21605			// add link to page
21606			$row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
21607			// write bookmark entry
21608			$this->writeHTML($row, false, false, true, false, '');
21609		}
21610		// restore link styles
21611		$this->htmlLinkColorArray = $prev_htmlLinkColorArray;
21612		$this->htmlLinkFontStyle = $prev_htmlLinkFontStyle;
21613		// move TOC page and replace numbers
21614		$page_last = $this->getPage();
21615		$numpages = ($page_last - $page_first + 1);
21616		// account for booklet mode
21617		if ($this->booklet) {
21618			// check if a blank page is required before TOC
21619			$page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
21620			$page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
21621			if ($page_fill_start) {
21622				// add a page at the end (to be moved before TOC)
21623				$this->addPage();
21624				++$page_last;
21625				++$numpages;
21626			}
21627			if ($page_fill_end) {
21628				// add a page at the end
21629				$this->addPage();
21630				++$page_last;
21631				++$numpages;
21632			}
21633		}
21634		$maxpage = max($maxpage, $page_last);
21635		if (!TCPDF_STATIC::empty_string($page)) {
21636			for ($p = $page_first; $p <= $page_last; ++$p) {
21637				// get page data
21638				$temppage = $this->getPageBuffer($p);
21639				for ($n = 1; $n <= $maxpage; ++$n) {
21640					// update page numbers
21641					$a = '{#'.$n.'}';
21642					// get page number aliases
21643					$pnalias = $this->getInternalPageNumberAliases($a);
21644					// calculate replacement number
21645					if ($n >= $page) {
21646						$np = $n + $numpages;
21647					} else {
21648						$np = $n;
21649					}
21650					$na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
21651					$nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
21652					// replace aliases with numbers
21653					foreach ($pnalias['u'] as $u) {
21654						if ($correct_align) {
21655							$sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
21656							if ($this->rtl) {
21657								$nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
21658							} else {
21659								$nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
21660							}
21661						} else {
21662							$nr = $nu;
21663						}
21664						$temppage = str_replace($u, $nr, $temppage);
21665					}
21666					foreach ($pnalias['a'] as $a) {
21667						if ($correct_align) {
21668							$sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
21669							if ($this->rtl) {
21670								$nr = $na.' '.$sfill;
21671							} else {
21672								$nr = $sfill.' '.$na;
21673							}
21674						} else {
21675							$nr = $na;
21676						}
21677						$temppage = str_replace($a, $nr, $temppage);
21678					}
21679				}
21680				// save changes
21681				$this->setPageBuffer($p, $temppage);
21682			}
21683			// move pages
21684			$this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
21685			if ($page_fill_start) {
21686				$this->movePage($page_last, $page_first);
21687			}
21688			for ($i = 0; $i < $numpages; ++$i) {
21689				$this->movePage($page_last, $page);
21690			}
21691		}
21692	}
21693
21694	/**
21695	 * Stores a copy of the current TCPDF object used for undo operation.
21696	 * @public
21697	 * @since 4.5.029 (2009-03-19)
21698	 */
21699	public function startTransaction() {
21700		if (isset($this->objcopy)) {
21701			// remove previous copy
21702			$this->commitTransaction();
21703		}
21704		// record current page number and Y position
21705		$this->start_transaction_page = $this->page;
21706		$this->start_transaction_y = $this->y;
21707		// clone current object
21708		$this->objcopy = TCPDF_STATIC::objclone($this);
21709	}
21710
21711	/**
21712	 * Delete the copy of the current TCPDF object used for undo operation.
21713	 * @public
21714	 * @since 4.5.029 (2009-03-19)
21715	 */
21716	public function commitTransaction() {
21717		if (isset($this->objcopy)) {
21718			$this->objcopy->_destroy(true, true);
21719			unset($this->objcopy);
21720		}
21721	}
21722
21723	/**
21724	 * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
21725	 * @param $self (boolean) if true restores current class object to previous state without the need of reassignment via the returned value.
21726	 * @return TCPDF object.
21727	 * @public
21728	 * @since 4.5.029 (2009-03-19)
21729	 */
21730	public function rollbackTransaction($self=false) {
21731		if (isset($this->objcopy)) {
21732			$this->_destroy(true, true);
21733			if ($self) {
21734				$objvars = get_object_vars($this->objcopy);
21735				foreach ($objvars as $key => $value) {
21736					$this->$key = $value;
21737				}
21738			}
21739			return $this->objcopy;
21740		}
21741		return $this;
21742	}
21743
21744	// --- MULTI COLUMNS METHODS -----------------------
21745
21746	/**
21747	 * Set multiple columns of the same size
21748	 * @param $numcols (int) number of columns (set to zero to disable columns mode)
21749	 * @param $width (int) column width
21750	 * @param $y (int) column starting Y position (leave empty for current Y position)
21751	 * @public
21752	 * @since 4.9.001 (2010-03-28)
21753	 */
21754	public function setEqualColumns($numcols=0, $width=0, $y='') {
21755		$this->columns = array();
21756		if ($numcols < 2) {
21757			$numcols = 0;
21758			$this->columns = array();
21759		} else {
21760			// maximum column width
21761			$maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols;
21762			if (($width == 0) OR ($width > $maxwidth)) {
21763				$width = $maxwidth;
21764			}
21765			if (TCPDF_STATIC::empty_string($y)) {
21766				$y = $this->y;
21767			}
21768			// space between columns
21769			$space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1));
21770			// fill the columns array (with, space, starting Y position)
21771			for ($i = 0; $i < $numcols; ++$i) {
21772				$this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y);
21773			}
21774		}
21775		$this->num_columns = $numcols;
21776		$this->current_column = 0;
21777		$this->column_start_page = $this->page;
21778		$this->selectColumn(0);
21779	}
21780
21781	/**
21782	 * Remove columns and reset page margins.
21783	 * @public
21784	 * @since 5.9.072 (2011-04-26)
21785	 */
21786	public function resetColumns() {
21787		$this->lMargin = $this->original_lMargin;
21788		$this->rMargin = $this->original_rMargin;
21789		$this->setEqualColumns();
21790	}
21791
21792	/**
21793	 * Set columns array.
21794	 * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
21795	 * @param $columns (array)
21796	 * @public
21797	 * @since 4.9.001 (2010-03-28)
21798	 */
21799	public function setColumnsArray($columns) {
21800		$this->columns = $columns;
21801		$this->num_columns = count($columns);
21802		$this->current_column = 0;
21803		$this->column_start_page = $this->page;
21804		$this->selectColumn(0);
21805	}
21806
21807	/**
21808	 * Set position at a given column
21809	 * @param $col (int) column number (from 0 to getNumberOfColumns()-1); empty string = current column.
21810	 * @public
21811	 * @since 4.9.001 (2010-03-28)
21812	 */
21813	public function selectColumn($col='') {
21814		if (is_string($col)) {
21815			$col = $this->current_column;
21816		} elseif ($col >= $this->num_columns) {
21817			$col = 0;
21818		}
21819		$xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
21820		$enable_thead = false;
21821		if ($this->num_columns > 1) {
21822			if ($col != $this->current_column) {
21823				// move Y pointer at the top of the column
21824				if ($this->column_start_page == $this->page) {
21825					$this->y = $this->columns[$col]['y'];
21826				} else {
21827					$this->y = $this->tMargin;
21828				}
21829				// Avoid to write table headers more than once
21830				if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) {
21831					$enable_thead = true;
21832					$this->maxselcol['page'] = $this->page;
21833					$this->maxselcol['column'] = $col;
21834				}
21835			}
21836			$xshift = $this->colxshift;
21837			// set X position of the current column by case
21838			$listindent = ($this->listindentlevel * $this->listindent);
21839			// calculate column X position
21840			$colpos = 0;
21841			for ($i = 0; $i < $col; ++$i) {
21842				$colpos += ($this->columns[$i]['w'] + $this->columns[$i]['s']);
21843			}
21844			if ($this->rtl) {
21845				$x = $this->w - $this->original_rMargin - $colpos;
21846				$this->rMargin = ($this->w - $x + $listindent);
21847				$this->lMargin = ($x - $this->columns[$col]['w']);
21848				$this->x = $x - $listindent;
21849			} else {
21850				$x = $this->original_lMargin + $colpos;
21851				$this->lMargin = ($x + $listindent);
21852				$this->rMargin = ($this->w - $x - $this->columns[$col]['w']);
21853				$this->x = $x + $listindent;
21854			}
21855			$this->columns[$col]['x'] = $x;
21856		}
21857		$this->current_column = $col;
21858		// fix for HTML mode
21859		$this->newline = true;
21860		// print HTML table header (if any)
21861		if ((!TCPDF_STATIC::empty_string($this->thead)) AND (!$this->inthead)) {
21862			if ($enable_thead) {
21863				// print table header
21864				$this->writeHTML($this->thead, false, false, false, false, '');
21865				$this->y += $xshift['s']['V'];
21866				// store end of header position
21867				if (!isset($this->columns[$col]['th'])) {
21868					$this->columns[$col]['th'] = array();
21869				}
21870				$this->columns[$col]['th']['\''.$this->page.'\''] = $this->y;
21871				$this->lasth = 0;
21872			} elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) {
21873				$this->y = $this->columns[$col]['th']['\''.$this->page.'\''];
21874			}
21875		}
21876		// account for an html table cell over multiple columns
21877		if ($this->rtl) {
21878			$this->rMargin += $xshift['x'];
21879			$this->x -= ($xshift['x'] + $xshift['p']['R']);
21880		} else {
21881			$this->lMargin += $xshift['x'];
21882			$this->x += $xshift['x'] + $xshift['p']['L'];
21883		}
21884	}
21885
21886	/**
21887	 * Return the current column number
21888	 * @return int current column number
21889	 * @public
21890	 * @since 5.5.011 (2010-07-08)
21891	 */
21892	public function getColumn() {
21893		return $this->current_column;
21894	}
21895
21896	/**
21897	 * Return the current number of columns.
21898	 * @return int number of columns
21899	 * @public
21900	 * @since 5.8.018 (2010-08-25)
21901	 */
21902	public function getNumberOfColumns() {
21903		return $this->num_columns;
21904	}
21905
21906	/**
21907	 * Set Text rendering mode.
21908	 * @param $stroke (int) outline size in user units (0 = disable).
21909	 * @param $fill (boolean) if true fills the text (default).
21910	 * @param $clip (boolean) if true activate clipping mode
21911	 * @public
21912	 * @since 4.9.008 (2009-04-02)
21913	 */
21914	public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
21915		// Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
21916		// convert text rendering parameters
21917		if ($stroke < 0) {
21918			$stroke = 0;
21919		}
21920		if ($fill === true) {
21921			if ($stroke > 0) {
21922				if ($clip === true) {
21923					// Fill, then stroke text and add to path for clipping
21924					$textrendermode = 6;
21925				} else {
21926					// Fill, then stroke text
21927					$textrendermode = 2;
21928				}
21929				$textstrokewidth = $stroke;
21930			} else {
21931				if ($clip === true) {
21932					// Fill text and add to path for clipping
21933					$textrendermode = 4;
21934				} else {
21935					// Fill text
21936					$textrendermode = 0;
21937				}
21938			}
21939		} else {
21940			if ($stroke > 0) {
21941				if ($clip === true) {
21942					// Stroke text and add to path for clipping
21943					$textrendermode = 5;
21944				} else {
21945					// Stroke text
21946					$textrendermode = 1;
21947				}
21948				$textstrokewidth = $stroke;
21949			} else {
21950				if ($clip === true) {
21951					// Add text to path for clipping
21952					$textrendermode = 7;
21953				} else {
21954					// Neither fill nor stroke text (invisible)
21955					$textrendermode = 3;
21956				}
21957			}
21958		}
21959		$this->textrendermode = $textrendermode;
21960		$this->textstrokewidth = $stroke;
21961	}
21962
21963	/**
21964	 * Set parameters for drop shadow effect for text.
21965	 * @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.
21966	 * @since 5.9.174 (2012-07-25)
21967	 * @public
21968	*/
21969	public function setTextShadow($params=array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal')) {
21970		if (isset($params['enabled'])) {
21971			$this->txtshadow['enabled'] = $params['enabled']?true:false;
21972		} else {
21973			$this->txtshadow['enabled'] = false;
21974		}
21975		if (isset($params['depth_w'])) {
21976			$this->txtshadow['depth_w'] = floatval($params['depth_w']);
21977		} else {
21978			$this->txtshadow['depth_w'] = 0;
21979		}
21980		if (isset($params['depth_h'])) {
21981			$this->txtshadow['depth_h'] = floatval($params['depth_h']);
21982		} else {
21983			$this->txtshadow['depth_h'] = 0;
21984		}
21985		if (isset($params['color']) AND ($params['color'] !== false) AND is_array($params['color'])) {
21986			$this->txtshadow['color'] = $params['color'];
21987		} else {
21988			$this->txtshadow['color'] = $this->strokecolor;
21989		}
21990		if (isset($params['opacity'])) {
21991			$this->txtshadow['opacity'] = min(1, max(0, floatval($params['opacity'])));
21992		} else {
21993			$this->txtshadow['opacity'] = 1;
21994		}
21995		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'))) {
21996			$this->txtshadow['blend_mode'] = $params['blend_mode'];
21997		} else {
21998			$this->txtshadow['blend_mode'] = 'Normal';
21999		}
22000		if ((($this->txtshadow['depth_w'] == 0) AND ($this->txtshadow['depth_h'] == 0)) OR ($this->txtshadow['opacity'] == 0)) {
22001			$this->txtshadow['enabled'] = false;
22002		}
22003	}
22004
22005	/**
22006	 * Return the text shadow parameters array.
22007	 * @return Array of parameters.
22008	 * @since 5.9.174 (2012-07-25)
22009	 * @public
22010	 */
22011	public function getTextShadow() {
22012		return $this->txtshadow;
22013	}
22014
22015	/**
22016	 * Returns an array of chars containing soft hyphens.
22017	 * @param $word (array) array of chars
22018	 * @param $patterns (array) Array of hypenation patterns.
22019	 * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
22020	 * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
22021	 * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
22022	 * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
22023	 * @param $charmax (int) Maximum length of broken piece of word.
22024	 * @return array text with soft hyphens
22025	 * @author Nicola Asuni
22026	 * @since 4.9.012 (2010-04-12)
22027	 * @protected
22028	 */
22029	protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
22030		$hyphenword = array(); // hyphens positions
22031		$numchars = count($word);
22032		if ($numchars <= $charmin) {
22033			return $word;
22034		}
22035		$word_string = TCPDF_FONTS::UTF8ArrSubString($word, '', '', $this->isunicode);
22036		// some words will be returned as-is
22037		$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})(\]?)$/';
22038		if (preg_match($pattern, $word_string) > 0) {
22039			// email
22040			return $word;
22041		}
22042		$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})(\]?)$/';
22043		if (preg_match($pattern, $word_string) > 0) {
22044			// URL
22045			return $word;
22046		}
22047		if (isset($dictionary[$word_string])) {
22048			return TCPDF_FONTS::UTF8StringToArray($dictionary[$word_string], $this->isunicode, $this->CurrentFont);
22049		}
22050		// surround word with '_' characters
22051		$tmpword = array_merge(array(46), $word, array(46));
22052		$tmpnumchars = $numchars + 2;
22053		$maxpos = $tmpnumchars - 1;
22054		for ($pos = 0; $pos < $maxpos; ++$pos) {
22055			$imax = min(($tmpnumchars - $pos), $charmax);
22056			for ($i = 1; $i <= $imax; ++$i) {
22057				$subword = strtolower(TCPDF_FONTS::UTF8ArrSubString($tmpword, $pos, ($pos + $i), $this->isunicode));
22058				if (isset($patterns[$subword])) {
22059					$pattern = TCPDF_FONTS::UTF8StringToArray($patterns[$subword], $this->isunicode, $this->CurrentFont);
22060					$pattern_length = count($pattern);
22061					$digits = 1;
22062					for ($j = 0; $j < $pattern_length; ++$j) {
22063						// check if $pattern[$j] is a number = hyphenation level (only numbers from 1 to 5 are valid)
22064						if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
22065							if ($j == 0) {
22066								$zero = $pos - 1;
22067							} else {
22068								$zero = $pos + $j - $digits;
22069							}
22070							// get hyphenation level
22071							$level = ($pattern[$j] - 48);
22072							// if two levels from two different patterns match at the same point, the higher one is selected.
22073							if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] < $level)) {
22074								$hyphenword[$zero] = $level;
22075							}
22076							++$digits;
22077						}
22078					}
22079				}
22080			}
22081		}
22082		$inserted = 0;
22083		$maxpos = $numchars - $rightmin;
22084		for ($i = $leftmin; $i <= $maxpos; ++$i) {
22085			// only odd levels indicate allowed hyphenation points
22086			if (isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) {
22087				// 173 = soft hyphen character
22088				array_splice($word, $i + $inserted, 0, 173);
22089				++$inserted;
22090			}
22091		}
22092		return $word;
22093	}
22094
22095	/**
22096	 * Returns text with soft hyphens.
22097	 * @param $text (string) text to process
22098	 * @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/
22099	 * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
22100	 * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
22101	 * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
22102	 * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
22103	 * @param $charmax (int) Maximum length of broken piece of word.
22104	 * @return array text with soft hyphens
22105	 * @author Nicola Asuni
22106	 * @since 4.9.012 (2010-04-12)
22107	 * @public
22108	 */
22109	public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
22110		$text = $this->unhtmlentities($text);
22111		$word = array(); // last word
22112		$txtarr = array(); // text to be returned
22113		$intag = false; // true if we are inside an HTML tag
22114		$skip = false; // true to skip hyphenation
22115		if (!is_array($patterns)) {
22116			$patterns = TCPDF_STATIC::getHyphenPatternsFromTEX($patterns);
22117		}
22118		// get array of characters
22119		$unichars = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
22120		// for each char
22121		foreach ($unichars as $char) {
22122			if ((!$intag) AND (!$skip) AND TCPDF_FONT_DATA::$uni_type[$char] == 'L') {
22123				// letter character
22124				$word[] = $char;
22125			} else {
22126				// other type of character
22127				if (!TCPDF_STATIC::empty_string($word)) {
22128					// hypenate the word
22129					$txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
22130					$word = array();
22131				}
22132				$txtarr[] = $char;
22133				if (chr($char) == '<') {
22134					// we are inside an HTML tag
22135					$intag = true;
22136				} elseif ($intag AND (chr($char) == '>')) {
22137					// end of HTML tag
22138					$intag = false;
22139					// check for style tag
22140					$expected = array(115, 116, 121, 108, 101); // = 'style'
22141					$current = array_slice($txtarr, -6, 5); // last 5 chars
22142					$compare = array_diff($expected, $current);
22143					if (empty($compare)) {
22144						// check if it is a closing tag
22145						$expected = array(47); // = '/'
22146						$current = array_slice($txtarr, -7, 1);
22147						$compare = array_diff($expected, $current);
22148						if (empty($compare)) {
22149							// closing style tag
22150							$skip = false;
22151						} else {
22152							// opening style tag
22153							$skip = true;
22154						}
22155					}
22156				}
22157			}
22158		}
22159		if (!TCPDF_STATIC::empty_string($word)) {
22160			// hypenate the word
22161			$txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
22162		}
22163		// convert char array to string and return
22164		return TCPDF_FONTS::UTF8ArrSubString($txtarr, '', '', $this->isunicode);
22165	}
22166
22167	/**
22168	 * Enable/disable rasterization of vector images using ImageMagick library.
22169	 * @param $mode (boolean) if true enable rasterization, false otherwise.
22170	 * @public
22171	 * @since 5.0.000 (2010-04-27)
22172	 */
22173	public function setRasterizeVectorImages($mode) {
22174		$this->rasterize_vector_images = $mode;
22175	}
22176
22177	/**
22178	 * Enable or disable default option for font subsetting.
22179	 * @param $enable (boolean) if true enable font subsetting by default.
22180	 * @author Nicola Asuni
22181	 * @public
22182	 * @since 5.3.002 (2010-06-07)
22183	 */
22184	public function setFontSubsetting($enable=true) {
22185		if ($this->pdfa_mode) {
22186			$this->font_subsetting = false;
22187		} else {
22188			$this->font_subsetting = $enable ? true : false;
22189		}
22190	}
22191
22192	/**
22193	 * Return the default option for font subsetting.
22194	 * @return boolean default font subsetting state.
22195	 * @author Nicola Asuni
22196	 * @public
22197	 * @since 5.3.002 (2010-06-07)
22198	 */
22199	public function getFontSubsetting() {
22200		return $this->font_subsetting;
22201	}
22202
22203	/**
22204	 * Left trim the input string
22205	 * @param $str (string) string to trim
22206	 * @param $replace (string) string that replace spaces.
22207	 * @return left trimmed string
22208	 * @author Nicola Asuni
22209	 * @public
22210	 * @since 5.8.000 (2010-08-11)
22211	 */
22212	public function stringLeftTrim($str, $replace='') {
22213		return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str);
22214	}
22215
22216	/**
22217	 * Right trim the input string
22218	 * @param $str (string) string to trim
22219	 * @param $replace (string) string that replace spaces.
22220	 * @return right trimmed string
22221	 * @author Nicola Asuni
22222	 * @public
22223	 * @since 5.8.000 (2010-08-11)
22224	 */
22225	public function stringRightTrim($str, $replace='') {
22226		return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str);
22227	}
22228
22229	/**
22230	 * Trim the input string
22231	 * @param $str (string) string to trim
22232	 * @param $replace (string) string that replace spaces.
22233	 * @return trimmed string
22234	 * @author Nicola Asuni
22235	 * @public
22236	 * @since 5.8.000 (2010-08-11)
22237	 */
22238	public function stringTrim($str, $replace='') {
22239		$str = $this->stringLeftTrim($str, $replace);
22240		$str = $this->stringRightTrim($str, $replace);
22241		return $str;
22242	}
22243
22244	/**
22245	 * Return true if the current font is unicode type.
22246	 * @return true for unicode font, false otherwise.
22247	 * @author Nicola Asuni
22248	 * @public
22249	 * @since 5.8.002 (2010-08-14)
22250	 */
22251	public function isUnicodeFont() {
22252		return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0'));
22253	}
22254
22255	/**
22256	 * Return normalized font name
22257	 * @param $fontfamily (string) property string containing font family names
22258	 * @return string normalized font name
22259	 * @author Nicola Asuni
22260	 * @public
22261	 * @since 5.8.004 (2010-08-17)
22262	 */
22263	public function getFontFamilyName($fontfamily) {
22264		// remove spaces and symbols
22265		$fontfamily = preg_replace('/[^a-z0-9_\,]/', '', strtolower($fontfamily));
22266		// extract all font names
22267		$fontslist = preg_split('/[,]/', $fontfamily);
22268		// find first valid font name
22269		foreach ($fontslist as $font) {
22270			// replace font variations
22271			$font = preg_replace('/regular$/', '', $font);
22272			$font = preg_replace('/italic$/', 'I', $font);
22273			$font = preg_replace('/oblique$/', 'I', $font);
22274			$font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
22275			// replace common family names and core fonts
22276			$pattern = array();
22277			$replacement = array();
22278			$pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
22279			$replacement[] = 'times';
22280			$pattern[] = '/^sansserif/';
22281			$replacement[] = 'helvetica';
22282			$pattern[] = '/^monospace/';
22283			$replacement[] = 'courier';
22284			$font = preg_replace($pattern, $replacement, $font);
22285			if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) {
22286				return $font;
22287			}
22288		}
22289		// return current font as default
22290		return $this->CurrentFont['fontkey'];
22291	}
22292
22293	/**
22294	 * Start a new XObject Template.
22295	 * 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).
22296	 * 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.
22297	 * Note: X,Y coordinates will be reset to 0,0.
22298	 * @param $w (int) Template width in user units (empty string or zero = page width less margins).
22299	 * @param $h (int) Template height in user units (empty string or zero = page height less margins).
22300	 * @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).
22301	 * @return int the XObject Template ID in case of success or false in case of error.
22302	 * @author Nicola Asuni
22303	 * @public
22304	 * @since 5.8.017 (2010-08-24)
22305	 * @see endTemplate(), printTemplate()
22306	 */
22307	public function startTemplate($w=0, $h=0, $group=false) {
22308		if ($this->inxobj) {
22309			// we are already inside an XObject template
22310			return false;
22311		}
22312		$this->inxobj = true;
22313		++$this->n;
22314		// XObject ID
22315		$this->xobjid = 'XT'.$this->n;
22316		// object ID
22317		$this->xobjects[$this->xobjid] = array('n' => $this->n);
22318		// store current graphic state
22319		$this->xobjects[$this->xobjid]['gvars'] = $this->getGraphicVars();
22320		// initialize data
22321		$this->xobjects[$this->xobjid]['intmrk'] = 0;
22322		$this->xobjects[$this->xobjid]['transfmrk'] = array();
22323		$this->xobjects[$this->xobjid]['outdata'] = '';
22324		$this->xobjects[$this->xobjid]['xobjects'] = array();
22325		$this->xobjects[$this->xobjid]['images'] = array();
22326		$this->xobjects[$this->xobjid]['fonts'] = array();
22327		$this->xobjects[$this->xobjid]['annotations'] = array();
22328		$this->xobjects[$this->xobjid]['extgstates'] = array();
22329		$this->xobjects[$this->xobjid]['gradients'] = array();
22330		$this->xobjects[$this->xobjid]['spot_colors'] = array();
22331		// set new environment
22332		$this->num_columns = 1;
22333		$this->current_column = 0;
22334		$this->SetAutoPageBreak(false);
22335		if (($w === '') OR ($w <= 0)) {
22336			$w = $this->w - $this->lMargin - $this->rMargin;
22337		}
22338		if (($h === '') OR ($h <= 0)) {
22339			$h = $this->h - $this->tMargin - $this->bMargin;
22340		}
22341		$this->xobjects[$this->xobjid]['x'] = 0;
22342		$this->xobjects[$this->xobjid]['y'] = 0;
22343		$this->xobjects[$this->xobjid]['w'] = $w;
22344		$this->xobjects[$this->xobjid]['h'] = $h;
22345		$this->w = $w;
22346		$this->h = $h;
22347		$this->wPt = $this->w * $this->k;
22348		$this->hPt = $this->h * $this->k;
22349		$this->fwPt = $this->wPt;
22350		$this->fhPt = $this->hPt;
22351		$this->x = 0;
22352		$this->y = 0;
22353		$this->lMargin = 0;
22354		$this->rMargin = 0;
22355		$this->tMargin = 0;
22356		$this->bMargin = 0;
22357		// set group mode
22358		$this->xobjects[$this->xobjid]['group'] = $group;
22359		return $this->xobjid;
22360	}
22361
22362	/**
22363	 * End the current XObject Template started with startTemplate() and restore the previous graphic state.
22364	 * 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).
22365	 * 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.
22366	 * @return int the XObject Template ID in case of success or false in case of error.
22367	 * @author Nicola Asuni
22368	 * @public
22369	 * @since 5.8.017 (2010-08-24)
22370	 * @see startTemplate(), printTemplate()
22371	 */
22372	public function endTemplate() {
22373		if (!$this->inxobj) {
22374			// we are not inside a template
22375			return false;
22376		}
22377		$this->inxobj = false;
22378		// restore previous graphic state
22379		$this->setGraphicVars($this->xobjects[$this->xobjid]['gvars'], true);
22380		return $this->xobjid;
22381	}
22382
22383	/**
22384	 * Print an XObject Template.
22385	 * You can print an XObject Template inside the currently opened Template.
22386	 * 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).
22387	 * 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.
22388	 * @param $id (string) The ID of XObject Template to print.
22389	 * @param $x (int) X position in user units (empty string = current x position)
22390	 * @param $y (int) Y position in user units (empty string = current y position)
22391	 * @param $w (int) Width in user units (zero = remaining page width)
22392	 * @param $h (int) Height in user units (zero = remaining page height)
22393	 * @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>
22394	 * @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>
22395	 * @param $fitonpage (boolean) If true the template is resized to not exceed page dimensions.
22396	 * @author Nicola Asuni
22397	 * @public
22398	 * @since 5.8.017 (2010-08-24)
22399	 * @see startTemplate(), endTemplate()
22400	 */
22401	public function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) {
22402		if ($this->state != 2) {
22403			 return;
22404		}
22405		if (!isset($this->xobjects[$id])) {
22406			$this->Error('The XObject Template \''.$id.'\' doesn\'t exist!');
22407		}
22408		if ($this->inxobj) {
22409			if ($id == $this->xobjid) {
22410				// close current template
22411				$this->endTemplate();
22412			} else {
22413				// use the template as resource for the template currently opened
22414				$this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id];
22415			}
22416		}
22417		// set default values
22418		if ($x === '') {
22419			$x = $this->x;
22420		}
22421		if ($y === '') {
22422			$y = $this->y;
22423		}
22424		// check page for no-write regions and adapt page margins if necessary
22425		list($x, $y) = $this->checkPageRegions($h, $x, $y);
22426		$ow = $this->xobjects[$id]['w'];
22427		if ($ow <= 0) {
22428			$ow = 1;
22429		}
22430		$oh = $this->xobjects[$id]['h'];
22431		if ($oh <= 0) {
22432			$oh = 1;
22433		}
22434		// calculate template width and height on document
22435		if (($w <= 0) AND ($h <= 0)) {
22436			$w = $ow;
22437			$h = $oh;
22438		} elseif ($w <= 0) {
22439			$w = $h * $ow / $oh;
22440		} elseif ($h <= 0) {
22441			$h = $w * $oh / $ow;
22442		}
22443		// fit the template on available space
22444		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
22445		// set page alignment
22446		$rb_y = $y + $h;
22447		// set alignment
22448		if ($this->rtl) {
22449			if ($palign == 'L') {
22450				$xt = $this->lMargin;
22451			} elseif ($palign == 'C') {
22452				$xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22453			} elseif ($palign == 'R') {
22454				$xt = $this->w - $this->rMargin - $w;
22455			} else {
22456				$xt = $x - $w;
22457			}
22458			$rb_x = $xt;
22459		} else {
22460			if ($palign == 'L') {
22461				$xt = $this->lMargin;
22462			} elseif ($palign == 'C') {
22463				$xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22464			} elseif ($palign == 'R') {
22465				$xt = $this->w - $this->rMargin - $w;
22466			} else {
22467				$xt = $x;
22468			}
22469			$rb_x = $xt + $w;
22470		}
22471		// print XObject Template + Transformation matrix
22472		$this->StartTransform();
22473		// translate and scale
22474		$sx = ($w / $ow);
22475		$sy = ($h / $oh);
22476		$tm = array();
22477		$tm[0] = $sx;
22478		$tm[1] = 0;
22479		$tm[2] = 0;
22480		$tm[3] = $sy;
22481		$tm[4] = $xt * $this->k;
22482		$tm[5] = ($this->h - $h - $y) * $this->k;
22483		$this->Transform($tm);
22484		// set object
22485		$this->_out('/'.$id.' Do');
22486		$this->StopTransform();
22487		// add annotations
22488		if (!empty($this->xobjects[$id]['annotations'])) {
22489			foreach ($this->xobjects[$id]['annotations'] as $annot) {
22490				// transform original coordinates
22491				$coordlt = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k)));
22492				$ax = ($coordlt[4] / $this->k);
22493				$ay = ($this->h - $h - ($coordlt[5] / $this->k));
22494				$coordrb = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k)));
22495				$aw = ($coordrb[4] / $this->k) - $ax;
22496				$ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay;
22497				$this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);
22498			}
22499		}
22500		// set pointer to align the next text/objects
22501		switch($align) {
22502			case 'T': {
22503				$this->y = $y;
22504				$this->x = $rb_x;
22505				break;
22506			}
22507			case 'M': {
22508				$this->y = $y + round($h/2);
22509				$this->x = $rb_x;
22510				break;
22511			}
22512			case 'B': {
22513				$this->y = $rb_y;
22514				$this->x = $rb_x;
22515				break;
22516			}
22517			case 'N': {
22518				$this->SetY($rb_y);
22519				break;
22520			}
22521			default:{
22522				break;
22523			}
22524		}
22525	}
22526
22527	/**
22528	 * Set the percentage of character stretching.
22529	 * @param $perc (int) percentage of stretching (100 = no stretching)
22530	 * @author Nicola Asuni
22531	 * @public
22532	 * @since 5.9.000 (2010-09-29)
22533	 */
22534	public function setFontStretching($perc=100) {
22535		$this->font_stretching = $perc;
22536	}
22537
22538	/**
22539	 * Get the percentage of character stretching.
22540	 * @return float stretching value
22541	 * @author Nicola Asuni
22542	 * @public
22543	 * @since 5.9.000 (2010-09-29)
22544	 */
22545	public function getFontStretching() {
22546		return $this->font_stretching;
22547	}
22548
22549	/**
22550	 * Set the amount to increase or decrease the space between characters in a text.
22551	 * @param $spacing (float) amount to increase or decrease the space between characters in a text (0 = default spacing)
22552	 * @author Nicola Asuni
22553	 * @public
22554	 * @since 5.9.000 (2010-09-29)
22555	 */
22556	public function setFontSpacing($spacing=0) {
22557		$this->font_spacing = $spacing;
22558	}
22559
22560	/**
22561	 * Get the amount to increase or decrease the space between characters in a text.
22562	 * @return int font spacing (tracking) value
22563	 * @author Nicola Asuni
22564	 * @public
22565	 * @since 5.9.000 (2010-09-29)
22566	 */
22567	public function getFontSpacing() {
22568		return $this->font_spacing;
22569	}
22570
22571	/**
22572	 * Return an array of no-write page regions
22573	 * @return array of no-write page regions
22574	 * @author Nicola Asuni
22575	 * @public
22576	 * @since 5.9.003 (2010-10-13)
22577	 * @see setPageRegions(), addPageRegion()
22578	 */
22579	public function getPageRegions() {
22580		return $this->page_regions;
22581	}
22582
22583	/**
22584	 * Set no-write regions on page.
22585	 * 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.
22586	 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22587	 * You can set multiple regions for the same page.
22588	 * @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.
22589	 * @author Nicola Asuni
22590	 * @public
22591	 * @since 5.9.003 (2010-10-13)
22592	 * @see addPageRegion(), getPageRegions()
22593	 */
22594	public function setPageRegions($regions=array()) {
22595		// empty current regions array
22596		$this->page_regions = array();
22597		// add regions
22598		foreach ($regions as $data) {
22599			$this->addPageRegion($data);
22600		}
22601	}
22602
22603	/**
22604	 * Add a single no-write region on selected page.
22605	 * 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.
22606	 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22607	 * You can set multiple regions for the same page.
22608	 * @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).
22609	 * @author Nicola Asuni
22610	 * @public
22611	 * @since 5.9.003 (2010-10-13)
22612	 * @see setPageRegions(), getPageRegions()
22613	 */
22614	public function addPageRegion($region) {
22615		if (!isset($region['page']) OR empty($region['page'])) {
22616			$region['page'] = $this->page;
22617		}
22618		if (isset($region['xt']) AND isset($region['xb']) AND ($region['xt'] > 0) AND ($region['xb'] > 0)
22619			AND isset($region['yt'])  AND isset($region['yb']) AND ($region['yt'] >= 0) AND ($region['yt'] < $region['yb'])
22620			AND isset($region['side']) AND (($region['side'] == 'L') OR ($region['side'] == 'R'))) {
22621			$this->page_regions[] = $region;
22622		}
22623	}
22624
22625	/**
22626	 * Remove a single no-write region.
22627	 * @param $key (int) region key
22628	 * @author Nicola Asuni
22629	 * @public
22630	 * @since 5.9.003 (2010-10-13)
22631	 * @see setPageRegions(), getPageRegions()
22632	 */
22633	public function removePageRegion($key) {
22634		if (isset($this->page_regions[$key])) {
22635			unset($this->page_regions[$key]);
22636		}
22637	}
22638
22639	/**
22640	 * Check page for no-write regions and adapt current coordinates and page margins if necessary.
22641	 * 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.
22642	 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22643	 * @param $h (float) height of the text/image/object to print in user units
22644	 * @param $x (float) current X coordinate in user units
22645	 * @param $y (float) current Y coordinate in user units
22646	 * @return array($x, $y)
22647	 * @author Nicola Asuni
22648	 * @protected
22649	 * @since 5.9.003 (2010-10-13)
22650	 */
22651	protected function checkPageRegions($h, $x, $y) {
22652		// set default values
22653		if ($x === '') {
22654			$x = $this->x;
22655		}
22656		if ($y === '') {
22657			$y = $this->y;
22658		}
22659		if (!$this->check_page_regions OR empty($this->page_regions)) {
22660			// no page regions defined
22661			return array($x, $y);
22662		}
22663		if (empty($h)) {
22664			$h = $this->getCellHeight($this->FontSize);
22665		}
22666		// check for page break
22667		if ($this->checkPageBreak($h, $y)) {
22668			// the content will be printed on a new page
22669			$x = $this->x;
22670			$y = $this->y;
22671		}
22672		if ($this->num_columns > 1) {
22673			if ($this->rtl) {
22674				$this->lMargin = ($this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
22675			} else {
22676				$this->rMargin = ($this->w - $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
22677			}
22678		} else {
22679			if ($this->rtl) {
22680				$this->lMargin = max($this->clMargin, $this->original_lMargin);
22681			} else {
22682				$this->rMargin = max($this->crMargin, $this->original_rMargin);
22683			}
22684		}
22685		// adjust coordinates and page margins
22686		foreach ($this->page_regions as $regid => $regdata) {
22687			if ($regdata['page'] == $this->page) {
22688				// check region boundaries
22689				if (($y > ($regdata['yt'] - $h)) AND ($y <= $regdata['yb'])) {
22690					// Y is inside the region
22691					$minv = ($regdata['xb'] - $regdata['xt']) / ($regdata['yb'] - $regdata['yt']); // inverse of angular coefficient
22692					$yt = max($y, $regdata['yt']);
22693					$yb = min(($yt + $h), $regdata['yb']);
22694					$xt = (($yt - $regdata['yt']) * $minv) + $regdata['xt'];
22695					$xb = (($yb - $regdata['yt']) * $minv) + $regdata['xt'];
22696					if ($regdata['side'] == 'L') { // left side
22697						$new_margin = max($xt, $xb);
22698						if ($this->lMargin < $new_margin) {
22699							if ($this->rtl) {
22700								// adjust left page margin
22701								$this->lMargin = max(0, $new_margin);
22702							}
22703							if ($x < $new_margin) {
22704								// adjust x position
22705								$x = $new_margin;
22706								if ($new_margin > ($this->w - $this->rMargin)) {
22707									// adjust y position
22708									$y = $regdata['yb'] - $h;
22709								}
22710							}
22711						}
22712					} elseif ($regdata['side'] == 'R') { // right side
22713						$new_margin = min($xt, $xb);
22714						if (($this->w - $this->rMargin) > $new_margin) {
22715							if (!$this->rtl) {
22716								// adjust right page margin
22717								$this->rMargin = max(0, ($this->w - $new_margin));
22718							}
22719							if ($x > $new_margin) {
22720								// adjust x position
22721								$x = $new_margin;
22722								if ($new_margin > $this->lMargin) {
22723									// adjust y position
22724									$y = $regdata['yb'] - $h;
22725								}
22726							}
22727						}
22728					}
22729				}
22730			}
22731		}
22732		return array($x, $y);
22733	}
22734
22735	// --- SVG METHODS ---------------------------------------------------------
22736
22737	/**
22738	 * Embedd a Scalable Vector Graphics (SVG) image.
22739	 * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
22740	 * @param $file (string) Name of the SVG file or a '@' character followed by the SVG data string.
22741	 * @param $x (float) Abscissa of the upper-left corner.
22742	 * @param $y (float) Ordinate of the upper-left corner.
22743	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
22744	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
22745	 * @param $link (mixed) URL or identifier returned by AddLink().
22746	 * @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.
22747	 * @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>
22748	 * @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)))
22749	 * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
22750	 * @author Nicola Asuni
22751	 * @since 5.0.000 (2010-05-02)
22752	 * @public
22753	 */
22754	public function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {
22755		if ($this->state != 2) {
22756			 return;
22757		}
22758		// reset SVG vars
22759		$this->svggradients = array();
22760		$this->svggradientid = 0;
22761		$this->svgdefsmode = false;
22762		$this->svgdefs = array();
22763		$this->svgclipmode = false;
22764		$this->svgclippaths = array();
22765		$this->svgcliptm = array();
22766		$this->svgclipid = 0;
22767		$this->svgtext = '';
22768		$this->svgtextmode = array();
22769		if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
22770			// convert SVG to raster image using GD or ImageMagick libraries
22771			return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
22772		}
22773		if ($file[0] === '@') { // image from string
22774			$this->svgdir = '';
22775			$svgdata = substr($file, 1);
22776		} else { // SVG file
22777			$this->svgdir = dirname($file);
22778			$svgdata = TCPDF_STATIC::fileGetContents($file);
22779		}
22780		if ($svgdata === FALSE) {
22781			$this->Error('SVG file not found: '.$file);
22782		}
22783		if ($x === '') {
22784			$x = $this->x;
22785		}
22786		if ($y === '') {
22787			$y = $this->y;
22788		}
22789		// check page for no-write regions and adapt page margins if necessary
22790		list($x, $y) = $this->checkPageRegions($h, $x, $y);
22791		$k = $this->k;
22792		$ox = 0;
22793		$oy = 0;
22794		$ow = $w;
22795		$oh = $h;
22796		$aspect_ratio_align = 'xMidYMid';
22797		$aspect_ratio_ms = 'meet';
22798		$regs = array();
22799		// get original image width and height
22800		preg_match('/<svg([^\>]*)>/si', $svgdata, $regs);
22801		if (isset($regs[1]) AND !empty($regs[1])) {
22802			$tmp = array();
22803			if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22804				$ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
22805			}
22806			$tmp = array();
22807			if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22808				$oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
22809			}
22810			$tmp = array();
22811			if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22812				$ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
22813			}
22814			$tmp = array();
22815			if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22816				$oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
22817			}
22818			$tmp = array();
22819			$view_box = array();
22820			if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) {
22821				if (count($tmp) == 5) {
22822					array_shift($tmp);
22823					foreach ($tmp as $key => $val) {
22824						$view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
22825					}
22826					$ox = $view_box[0];
22827					$oy = $view_box[1];
22828				}
22829				// get aspect ratio
22830				$tmp = array();
22831				if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22832					$aspect_ratio = preg_split('/[\s]+/si', $tmp[1]);
22833					switch (count($aspect_ratio)) {
22834						case 3: {
22835							$aspect_ratio_align = $aspect_ratio[1];
22836							$aspect_ratio_ms = $aspect_ratio[2];
22837							break;
22838						}
22839						case 2: {
22840							$aspect_ratio_align = $aspect_ratio[0];
22841							$aspect_ratio_ms = $aspect_ratio[1];
22842							break;
22843						}
22844						case 1: {
22845							$aspect_ratio_align = $aspect_ratio[0];
22846							$aspect_ratio_ms = 'meet';
22847							break;
22848						}
22849					}
22850				}
22851			}
22852		}
22853		if ($ow <= 0) {
22854			$ow = 1;
22855		}
22856		if ($oh <= 0) {
22857			$oh = 1;
22858		}
22859		// calculate image width and height on document
22860		if (($w <= 0) AND ($h <= 0)) {
22861			// convert image size to document unit
22862			$w = $ow;
22863			$h = $oh;
22864		} elseif ($w <= 0) {
22865			$w = $h * $ow / $oh;
22866		} elseif ($h <= 0) {
22867			$h = $w * $oh / $ow;
22868		}
22869		// fit the image on available space
22870		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
22871		if ($this->rasterize_vector_images) {
22872			// convert SVG to raster image using GD or ImageMagick libraries
22873			return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
22874		}
22875		// set alignment
22876		$this->img_rb_y = $y + $h;
22877		// set alignment
22878		if ($this->rtl) {
22879			if ($palign == 'L') {
22880				$ximg = $this->lMargin;
22881			} elseif ($palign == 'C') {
22882				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22883			} elseif ($palign == 'R') {
22884				$ximg = $this->w - $this->rMargin - $w;
22885			} else {
22886				$ximg = $x - $w;
22887			}
22888			$this->img_rb_x = $ximg;
22889		} else {
22890			if ($palign == 'L') {
22891				$ximg = $this->lMargin;
22892			} elseif ($palign == 'C') {
22893				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22894			} elseif ($palign == 'R') {
22895				$ximg = $this->w - $this->rMargin - $w;
22896			} else {
22897				$ximg = $x;
22898			}
22899			$this->img_rb_x = $ximg + $w;
22900		}
22901		// store current graphic vars
22902		$gvars = $this->getGraphicVars();
22903		// store SVG position and scale factors
22904		$svgoffset_x = ($ximg - $ox) * $this->k;
22905		$svgoffset_y = -($y - $oy) * $this->k;
22906		if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {
22907			$ow = $view_box[2];
22908			$oh = $view_box[3];
22909		} else {
22910			if ($ow <= 0) {
22911				$ow = $w;
22912			}
22913			if ($oh <= 0) {
22914				$oh = $h;
22915			}
22916		}
22917		$svgscale_x = $w / $ow;
22918		$svgscale_y = $h / $oh;
22919		// scaling and alignment
22920		if ($aspect_ratio_align != 'none') {
22921			// store current scaling values
22922			$svgscale_old_x = $svgscale_x;
22923			$svgscale_old_y = $svgscale_y;
22924			// force uniform scaling
22925			if ($aspect_ratio_ms == 'slice') {
22926				// the entire viewport is covered by the viewBox
22927				if ($svgscale_x > $svgscale_y) {
22928					$svgscale_y = $svgscale_x;
22929				} elseif ($svgscale_x < $svgscale_y) {
22930					$svgscale_x = $svgscale_y;
22931				}
22932			} else { // meet
22933				// the entire viewBox is visible within the viewport
22934				if ($svgscale_x < $svgscale_y) {
22935					$svgscale_y = $svgscale_x;
22936				} elseif ($svgscale_x > $svgscale_y) {
22937					$svgscale_x = $svgscale_y;
22938				}
22939			}
22940			// correct X alignment
22941			switch (substr($aspect_ratio_align, 1, 3)) {
22942				case 'Min': {
22943					// do nothing
22944					break;
22945				}
22946				case 'Max': {
22947					$svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x));
22948					break;
22949				}
22950				default:
22951				case 'Mid': {
22952					$svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2);
22953					break;
22954				}
22955			}
22956			// correct Y alignment
22957			switch (substr($aspect_ratio_align, 5)) {
22958				case 'Min': {
22959					// do nothing
22960					break;
22961				}
22962				case 'Max': {
22963					$svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y));
22964					break;
22965				}
22966				default:
22967				case 'Mid': {
22968					$svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2);
22969					break;
22970				}
22971			}
22972		}
22973		// store current page break mode
22974		$page_break_mode = $this->AutoPageBreak;
22975		$page_break_margin = $this->getBreakMargin();
22976		$cell_padding = $this->cell_padding;
22977		$this->SetCellPadding(0);
22978		$this->SetAutoPageBreak(false);
22979		// save the current graphic state
22980		$this->_out('q'.$this->epsmarker);
22981		// set initial clipping mask
22982		$this->Rect($ximg, $y, $w, $h, 'CNZ', array(), array());
22983		// scale and translate
22984		$e = $ox * $this->k * (1 - $svgscale_x);
22985		$f = ($this->h - $oy) * $this->k * (1 - $svgscale_y);
22986		$this->_out(sprintf('%F %F %F %F %F %F cm', $svgscale_x, 0, 0, $svgscale_y, ($e + $svgoffset_x), ($f + $svgoffset_y)));
22987		// creates a new XML parser to be used by the other XML functions
22988		$this->parser = xml_parser_create('UTF-8');
22989		// the following function allows to use parser inside object
22990		xml_set_object($this->parser, $this);
22991		// disable case-folding for this XML parser
22992		xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
22993		// sets the element handler functions for the XML parser
22994		xml_set_element_handler($this->parser, 'startSVGElementHandler', 'endSVGElementHandler');
22995		// sets the character data handler function for the XML parser
22996		xml_set_character_data_handler($this->parser, 'segSVGContentHandler');
22997		// start parsing an XML document
22998		if (!xml_parse($this->parser, $svgdata)) {
22999			$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));
23000			$this->Error($error_message);
23001		}
23002		// free this XML parser
23003		xml_parser_free($this->parser);
23004		// restore previous graphic state
23005		$this->_out($this->epsmarker.'Q');
23006		// restore graphic vars
23007		$this->setGraphicVars($gvars);
23008		$this->lasth = $gvars['lasth'];
23009		if (!empty($border)) {
23010			$bx = $this->x;
23011			$by = $this->y;
23012			$this->x = $ximg;
23013			if ($this->rtl) {
23014				$this->x += $w;
23015			}
23016			$this->y = $y;
23017			$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
23018			$this->x = $bx;
23019			$this->y = $by;
23020		}
23021		if ($link) {
23022			$this->Link($ximg, $y, $w, $h, $link, 0);
23023		}
23024		// set pointer to align the next text/objects
23025		switch($align) {
23026			case 'T':{
23027				$this->y = $y;
23028				$this->x = $this->img_rb_x;
23029				break;
23030			}
23031			case 'M':{
23032				$this->y = $y + round($h/2);
23033				$this->x = $this->img_rb_x;
23034				break;
23035			}
23036			case 'B':{
23037				$this->y = $this->img_rb_y;
23038				$this->x = $this->img_rb_x;
23039				break;
23040			}
23041			case 'N':{
23042				$this->SetY($this->img_rb_y);
23043				break;
23044			}
23045			default:{
23046				// restore pointer to starting position
23047				$this->x = $gvars['x'];
23048				$this->y = $gvars['y'];
23049				$this->page = $gvars['page'];
23050				$this->current_column = $gvars['current_column'];
23051				$this->tMargin = $gvars['tMargin'];
23052				$this->bMargin = $gvars['bMargin'];
23053				$this->w = $gvars['w'];
23054				$this->h = $gvars['h'];
23055				$this->wPt = $gvars['wPt'];
23056				$this->hPt = $gvars['hPt'];
23057				$this->fwPt = $gvars['fwPt'];
23058				$this->fhPt = $gvars['fhPt'];
23059				break;
23060			}
23061		}
23062		$this->endlinex = $this->img_rb_x;
23063		// restore page break
23064		$this->SetAutoPageBreak($page_break_mode, $page_break_margin);
23065		$this->cell_padding = $cell_padding;
23066	}
23067
23068	/**
23069	 * Convert SVG transformation matrix to PDF.
23070	 * @param $tm (array) original SVG transformation matrix
23071	 * @return array transformation matrix
23072	 * @protected
23073	 * @since 5.0.000 (2010-05-02)
23074	 */
23075	protected function convertSVGtMatrix($tm) {
23076		$a = $tm[0];
23077		$b = -$tm[1];
23078		$c = -$tm[2];
23079		$d = $tm[3];
23080		$e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit, false) * $this->k;
23081		$f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit, false) * $this->k;
23082		$x = 0;
23083		$y = $this->h * $this->k;
23084		$e = ($x * (1 - $a)) - ($y * $c) + $e;
23085		$f = ($y * (1 - $d)) - ($x * $b) + $f;
23086		return array($a, $b, $c, $d, $e, $f);
23087	}
23088
23089	/**
23090	 * Apply SVG graphic transformation matrix.
23091	 * @param $tm (array) original SVG transformation matrix
23092	 * @protected
23093	 * @since 5.0.000 (2010-05-02)
23094	 */
23095	protected function SVGTransform($tm) {
23096		$this->Transform($this->convertSVGtMatrix($tm));
23097	}
23098
23099	/**
23100	 * Apply the requested SVG styles (*** TO BE COMPLETED ***)
23101	 * @param $svgstyle (array) array of SVG styles to apply
23102	 * @param $prevsvgstyle (array) array of previous SVG style
23103	 * @param $x (int) X origin of the bounding box
23104	 * @param $y (int) Y origin of the bounding box
23105	 * @param $w (int) width of the bounding box
23106	 * @param $h (int) height of the bounding box
23107	 * @param $clip_function (string) clip function
23108	 * @param $clip_params (array) array of parameters for clipping function
23109	 * @return object style
23110	 * @author Nicola Asuni
23111	 * @since 5.0.000 (2010-05-02)
23112	 * @protected
23113	 */
23114	protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {
23115		if ($this->state != 2) {
23116			 return;
23117		}
23118		$objstyle = '';
23119		$minlen = (0.01 / $this->k); // minimum acceptable length
23120		if (!isset($svgstyle['opacity'])) {
23121			return $objstyle;
23122		}
23123		// clip-path
23124		$regs = array();
23125		if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) {
23126			$clip_path = $this->svgclippaths[$regs[1]];
23127			foreach ($clip_path as $cp) {
23128				$this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);
23129			}
23130		}
23131		// opacity
23132		if ($svgstyle['opacity'] != 1) {
23133			$this->setAlpha($svgstyle['opacity'], 'Normal', $svgstyle['opacity'], false);
23134		}
23135		// color
23136		$fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['color'], $this->spot_colors);
23137		$this->SetFillColorArray($fill_color);
23138		// text color
23139		$text_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['text-color'], $this->spot_colors);
23140		$this->SetTextColorArray($text_color);
23141		// clip
23142		if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) {
23143			$top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0);
23144			$right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0);
23145			$bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0);
23146			$left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0);
23147			$cx = $x + $left;
23148			$cy = $y + $top;
23149			$cw = $w - $left - $right;
23150			$ch = $h - $top - $bottom;
23151			if ($svgstyle['clip-rule'] == 'evenodd') {
23152				$clip_rule = 'CNZ';
23153			} else {
23154				$clip_rule = 'CEO';
23155			}
23156			$this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());
23157		}
23158		// fill
23159		$regs = array();
23160		if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) {
23161			// gradient
23162			$gradient = $this->svggradients[$regs[1]];
23163			if (isset($gradient['xref'])) {
23164				// reference to another gradient definition
23165				$newgradient = $this->svggradients[$gradient['xref']];
23166				$newgradient['coords'] = $gradient['coords'];
23167				$newgradient['mode'] = $gradient['mode'];
23168				$newgradient['type'] = $gradient['type'];
23169				$newgradient['gradientUnits'] = $gradient['gradientUnits'];
23170				if (isset($gradient['gradientTransform'])) {
23171					$newgradient['gradientTransform'] = $gradient['gradientTransform'];
23172				}
23173				$gradient = $newgradient;
23174			}
23175			//save current Graphic State
23176			$this->_outSaveGraphicsState();
23177			//set clipping area
23178			if (!empty($clip_function) AND method_exists($this, $clip_function)) {
23179				$bbox = call_user_func_array(array($this, $clip_function), $clip_params);
23180				if ((!isset($gradient['type']) OR ($gradient['type'] != 3)) AND is_array($bbox) AND (count($bbox) == 4)) {
23181					list($x, $y, $w, $h) = $bbox;
23182				}
23183			}
23184			if ($gradient['mode'] == 'measure') {
23185				if (!isset($gradient['coords'][4])) {
23186					$gradient['coords'][4] = 0.5;
23187				}
23188				if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {
23189					$gtm = $gradient['gradientTransform'];
23190					// apply transformation matrix
23191					$xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4];
23192					$ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5];
23193					$xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4];
23194					$yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5];
23195					$r = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2));
23196					$gradient['coords'][0] = $xa;
23197					$gradient['coords'][1] = $ya;
23198					$gradient['coords'][2] = $xb;
23199					$gradient['coords'][3] = $yb;
23200					$gradient['coords'][4] = $r;
23201				}
23202				// convert SVG coordinates to user units
23203				$gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false);
23204				$gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false);
23205				$gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false);
23206				$gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false);
23207				$gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false);
23208				if ($w <= $minlen) {
23209					$w = $minlen;
23210				}
23211				if ($h <= $minlen) {
23212					$h = $minlen;
23213				}
23214				// shift units
23215				if ($gradient['gradientUnits'] == 'objectBoundingBox') {
23216					// convert to SVG coordinate system
23217					$gradient['coords'][0] += $x;
23218					$gradient['coords'][1] += $y;
23219					$gradient['coords'][2] += $x;
23220					$gradient['coords'][3] += $y;
23221				}
23222				// calculate percentages
23223				$gradient['coords'][0] = (($gradient['coords'][0] - $x) / $w);
23224				$gradient['coords'][1] = (($gradient['coords'][1] - $y) / $h);
23225				$gradient['coords'][2] = (($gradient['coords'][2] - $x) / $w);
23226				$gradient['coords'][3] = (($gradient['coords'][3] - $y) / $h);
23227				$gradient['coords'][4] /= $w;
23228			} elseif ($gradient['mode'] == 'percentage') {
23229				foreach($gradient['coords'] as $key => $val) {
23230					$gradient['coords'][$key] = (intval($val) / 100);
23231					if ($val < 0) {
23232						$gradient['coords'][$key] = 0;
23233					} elseif ($val > 1) {
23234						$gradient['coords'][$key] = 1;
23235					}
23236				}
23237			}
23238			if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {
23239				// single color (no shading)
23240				$gradient['coords'][0] = 1;
23241				$gradient['coords'][1] = 0;
23242				$gradient['coords'][2] = 0.999;
23243				$gradient['coords'][3] = 0;
23244			}
23245			// swap Y coordinates
23246			$tmp = $gradient['coords'][1];
23247			$gradient['coords'][1] = $gradient['coords'][3];
23248			$gradient['coords'][3] = $tmp;
23249			// set transformation map for gradient
23250			$cy = ($this->h - $y);
23251			if ($gradient['type'] == 3) {
23252				// circular gradient
23253				$cy -= ($gradient['coords'][1] * ($w + $h));
23254				$h = $w = max($w, $h);
23255			} else {
23256				$cy -= $h;
23257			}
23258			$this->_out(sprintf('%F 0 0 %F %F %F cm', ($w * $this->k), ($h * $this->k), ($x * $this->k), ($cy * $this->k)));
23259			if (count($gradient['stops']) > 1) {
23260				$this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);
23261			}
23262		} elseif ($svgstyle['fill'] != 'none') {
23263			$fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['fill'], $this->spot_colors);
23264			if ($svgstyle['fill-opacity'] != 1) {
23265				$this->setAlpha($this->alpha['CA'], 'Normal', $svgstyle['fill-opacity'], false);
23266			}
23267			$this->SetFillColorArray($fill_color);
23268			if ($svgstyle['fill-rule'] == 'evenodd') {
23269				$objstyle .= 'F*';
23270			} else {
23271				$objstyle .= 'F';
23272			}
23273		}
23274		// stroke
23275		if ($svgstyle['stroke'] != 'none') {
23276			if ($svgstyle['stroke-opacity'] != 1) {
23277				$this->setAlpha($svgstyle['stroke-opacity'], 'Normal', $this->alpha['ca'], false);
23278			} elseif (preg_match('/rgba\(\d+%?,\s*\d+%?,\s*\d+%?,\s*(\d+(?:\.\d+)?)\)/i', $svgstyle['stroke'], $rgba_matches)) {
23279				$this->setAlpha($rgba_matches[1], 'Normal', $this->alpha['ca'], false);
23280			}
23281			$stroke_style = array(
23282				'color' => TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stroke'], $this->spot_colors),
23283				'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false),
23284				'cap' => $svgstyle['stroke-linecap'],
23285				'join' => $svgstyle['stroke-linejoin']
23286				);
23287			if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {
23288				$stroke_style['dash'] = $svgstyle['stroke-dasharray'];
23289			}
23290			$this->SetLineStyle($stroke_style);
23291			$objstyle .= 'D';
23292		}
23293		// font
23294		$regs = array();
23295		if (!empty($svgstyle['font'])) {
23296			if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) {
23297				$font_family = $this->getFontFamilyName($regs[1]);
23298			} else {
23299				$font_family = $svgstyle['font-family'];
23300			}
23301			if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23302				$font_size = trim($regs[1]);
23303			} else {
23304				$font_size = $svgstyle['font-size'];
23305			}
23306			if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23307				$font_style = trim($regs[1]);
23308			} else {
23309				$font_style = $svgstyle['font-style'];
23310			}
23311			if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23312				$font_weight = trim($regs[1]);
23313			} else {
23314				$font_weight = $svgstyle['font-weight'];
23315			}
23316			if (preg_match('/font-stretch[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23317				$font_stretch = trim($regs[1]);
23318			} else {
23319				$font_stretch = $svgstyle['font-stretch'];
23320			}
23321			if (preg_match('/letter-spacing[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23322				$font_spacing = trim($regs[1]);
23323			} else {
23324				$font_spacing = $svgstyle['letter-spacing'];
23325			}
23326		} else {
23327			$font_family = $this->getFontFamilyName($svgstyle['font-family']);
23328			$font_size = $svgstyle['font-size'];
23329			$font_style = $svgstyle['font-style'];
23330			$font_weight = $svgstyle['font-weight'];
23331			$font_stretch = $svgstyle['font-stretch'];
23332			$font_spacing = $svgstyle['letter-spacing'];
23333		}
23334		$font_size = $this->getHTMLFontUnits($font_size, $this->svgstyles[0]['font-size'], $prevsvgstyle['font-size'], $this->svgunit);
23335		$font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);
23336		$font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);
23337		switch ($font_style) {
23338			case 'italic': {
23339				$font_style = 'I';
23340				break;
23341			}
23342			case 'oblique': {
23343				$font_style = 'I';
23344				break;
23345			}
23346			default:
23347			case 'normal': {
23348				$font_style = '';
23349				break;
23350			}
23351		}
23352		switch ($font_weight) {
23353			case 'bold':
23354			case 'bolder': {
23355				$font_style .= 'B';
23356				break;
23357			}
23358			case 'normal': {
23359				if ((substr($font_family, -1) == 'I') AND (substr($font_family, -2, 1) == 'B')) {
23360					$font_family = substr($font_family, 0, -2).'I';
23361				} elseif (substr($font_family, -1) == 'B') {
23362					$font_family = substr($font_family, 0, -1);
23363				}
23364				break;
23365			}
23366		}
23367		switch ($svgstyle['text-decoration']) {
23368			case 'underline': {
23369				$font_style .= 'U';
23370				break;
23371			}
23372			case 'overline': {
23373				$font_style .= 'O';
23374				break;
23375			}
23376			case 'line-through': {
23377				$font_style .= 'D';
23378				break;
23379			}
23380			default:
23381			case 'none': {
23382				break;
23383			}
23384		}
23385		$this->SetFont($font_family, $font_style, $font_size);
23386		$this->setFontStretching($font_stretch);
23387		$this->setFontSpacing($font_spacing);
23388		return $objstyle;
23389	}
23390
23391	/**
23392	 * Draws an SVG path
23393	 * @param $d (string) attribute d of the path SVG element
23394	 * @param $style (string) Style of rendering. Possible values are:
23395	 * <ul>
23396	 *	 <li>D or empty string: Draw (default).</li>
23397	 *	 <li>F: Fill.</li>
23398	 *	 <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
23399	 *	 <li>DF or FD: Draw and fill.</li>
23400	 *	 <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
23401	 *	 <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
23402	 *	 <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
23403	 * </ul>
23404	 * @return array of container box measures (x, y, w, h)
23405	 * @author Nicola Asuni
23406	 * @since 5.0.000 (2010-05-02)
23407	 * @protected
23408	 */
23409	protected function SVGPath($d, $style='') {
23410		if ($this->state != 2) {
23411			return;
23412		}
23413		// set fill/stroke style
23414		$op = TCPDF_STATIC::getPathPaintOperator($style, '');
23415		if (empty($op)) {
23416			return;
23417		}
23418		$paths = array();
23419		$d = preg_replace('/([0-9ACHLMQSTVZ])([\-\+])/si', '\\1 \\2', $d);
23420		preg_match_all('/([ACHLMQSTVZ])[\s]*([^ACHLMQSTVZ\"]*)/si', $d, $paths, PREG_SET_ORDER);
23421		$x = 0;
23422		$y = 0;
23423		$x1 = 0;
23424		$y1 = 0;
23425		$x2 = 0;
23426		$y2 = 0;
23427		$xmin = 2147483647;
23428		$xmax = 0;
23429		$ymin = 2147483647;
23430		$ymax = 0;
23431		$xinitial = 0;
23432		$yinitial = 0;
23433		$relcoord = false;
23434		$minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
23435		$firstcmd = true; // used to print first point
23436		// draw curve pieces
23437		foreach ($paths as $key => $val) {
23438			// get curve type
23439			$cmd = trim($val[1]);
23440			if (strtolower($cmd) == $cmd) {
23441				// use relative coordinated instead of absolute
23442				$relcoord = true;
23443				$xoffset = $x;
23444				$yoffset = $y;
23445			} else {
23446				$relcoord = false;
23447				$xoffset = 0;
23448				$yoffset = 0;
23449			}
23450			$params = array();
23451			if (isset($val[2])) {
23452				// get curve parameters
23453				$rawparams = preg_split('/([\,\s]+)/si', trim($val[2]));
23454				$params = array();
23455				foreach ($rawparams as $ck => $cp) {
23456					$params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit, false);
23457					if (abs($params[$ck]) < $minlen) {
23458						// approximate little values to zero
23459						$params[$ck] = 0;
23460					}
23461				}
23462			}
23463			// store current origin point
23464			$x0 = $x;
23465			$y0 = $y;
23466			switch (strtoupper($cmd)) {
23467				case 'M': { // moveto
23468					foreach ($params as $ck => $cp) {
23469						if (($ck % 2) == 0) {
23470							$x = $cp + $xoffset;
23471						} else {
23472							$y = $cp + $yoffset;
23473							if ($firstcmd OR (abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23474								if ($ck == 1) {
23475									$this->_outPoint($x, $y);
23476									$firstcmd = false;
23477									$xinitial = $x;
23478									$yinitial = $y;
23479								} else {
23480									$this->_outLine($x, $y);
23481								}
23482								$x0 = $x;
23483								$y0 = $y;
23484							}
23485							$xmin = min($xmin, $x);
23486							$ymin = min($ymin, $y);
23487							$xmax = max($xmax, $x);
23488							$ymax = max($ymax, $y);
23489							if ($relcoord) {
23490								$xoffset = $x;
23491								$yoffset = $y;
23492							}
23493						}
23494					}
23495					break;
23496				}
23497				case 'L': { // lineto
23498					foreach ($params as $ck => $cp) {
23499						if (($ck % 2) == 0) {
23500							$x = $cp + $xoffset;
23501						} else {
23502							$y = $cp + $yoffset;
23503							if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23504								$this->_outLine($x, $y);
23505								$x0 = $x;
23506								$y0 = $y;
23507							}
23508							$xmin = min($xmin, $x);
23509							$ymin = min($ymin, $y);
23510							$xmax = max($xmax, $x);
23511							$ymax = max($ymax, $y);
23512							if ($relcoord) {
23513								$xoffset = $x;
23514								$yoffset = $y;
23515							}
23516						}
23517					}
23518					break;
23519				}
23520				case 'H': { // horizontal lineto
23521					foreach ($params as $ck => $cp) {
23522						$x = $cp + $xoffset;
23523						if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23524							$this->_outLine($x, $y);
23525							$x0 = $x;
23526							$y0 = $y;
23527						}
23528						$xmin = min($xmin, $x);
23529						$xmax = max($xmax, $x);
23530						if ($relcoord) {
23531							$xoffset = $x;
23532						}
23533					}
23534					break;
23535				}
23536				case 'V': { // vertical lineto
23537					foreach ($params as $ck => $cp) {
23538						$y = $cp + $yoffset;
23539						if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23540							$this->_outLine($x, $y);
23541							$x0 = $x;
23542							$y0 = $y;
23543						}
23544						$ymin = min($ymin, $y);
23545						$ymax = max($ymax, $y);
23546						if ($relcoord) {
23547							$yoffset = $y;
23548						}
23549					}
23550					break;
23551				}
23552				case 'C': { // curveto
23553					foreach ($params as $ck => $cp) {
23554						$params[$ck] = $cp;
23555						if ((($ck + 1) % 6) == 0) {
23556							$x1 = $params[($ck - 5)] + $xoffset;
23557							$y1 = $params[($ck - 4)] + $yoffset;
23558							$x2 = $params[($ck - 3)] + $xoffset;
23559							$y2 = $params[($ck - 2)] + $yoffset;
23560							$x = $params[($ck - 1)] + $xoffset;
23561							$y = $params[($ck)] + $yoffset;
23562							$this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
23563							$xmin = min($xmin, $x, $x1, $x2);
23564							$ymin = min($ymin, $y, $y1, $y2);
23565							$xmax = max($xmax, $x, $x1, $x2);
23566							$ymax = max($ymax, $y, $y1, $y2);
23567							if ($relcoord) {
23568								$xoffset = $x;
23569								$yoffset = $y;
23570							}
23571						}
23572					}
23573					break;
23574				}
23575				case 'S': { // shorthand/smooth curveto
23576					foreach ($params as $ck => $cp) {
23577						$params[$ck] = $cp;
23578						if ((($ck + 1) % 4) == 0) {
23579							if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) {
23580								$x1 = (2 * $x) - $x2;
23581								$y1 = (2 * $y) - $y2;
23582							} else {
23583								$x1 = $x;
23584								$y1 = $y;
23585							}
23586							$x2 = $params[($ck - 3)] + $xoffset;
23587							$y2 = $params[($ck - 2)] + $yoffset;
23588							$x = $params[($ck - 1)] + $xoffset;
23589							$y = $params[($ck)] + $yoffset;
23590							$this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
23591							$xmin = min($xmin, $x, $x1, $x2);
23592							$ymin = min($ymin, $y, $y1, $y2);
23593							$xmax = max($xmax, $x, $x1, $x2);
23594							$ymax = max($ymax, $y, $y1, $y2);
23595							if ($relcoord) {
23596								$xoffset = $x;
23597								$yoffset = $y;
23598							}
23599						}
23600					}
23601					break;
23602				}
23603				case 'Q': { // quadratic Bezier curveto
23604					foreach ($params as $ck => $cp) {
23605						$params[$ck] = $cp;
23606						if ((($ck + 1) % 4) == 0) {
23607							// convert quadratic points to cubic points
23608							$x1 = $params[($ck - 3)] + $xoffset;
23609							$y1 = $params[($ck - 2)] + $yoffset;
23610							$xa = ($x + (2 * $x1)) / 3;
23611							$ya = ($y + (2 * $y1)) / 3;
23612							$x = $params[($ck - 1)] + $xoffset;
23613							$y = $params[($ck)] + $yoffset;
23614							$xb = ($x + (2 * $x1)) / 3;
23615							$yb = ($y + (2 * $y1)) / 3;
23616							$this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
23617							$xmin = min($xmin, $x, $xa, $xb);
23618							$ymin = min($ymin, $y, $ya, $yb);
23619							$xmax = max($xmax, $x, $xa, $xb);
23620							$ymax = max($ymax, $y, $ya, $yb);
23621							if ($relcoord) {
23622								$xoffset = $x;
23623								$yoffset = $y;
23624							}
23625						}
23626					}
23627					break;
23628				}
23629				case 'T': { // shorthand/smooth quadratic Bezier curveto
23630					foreach ($params as $ck => $cp) {
23631						$params[$ck] = $cp;
23632						if (($ck % 2) != 0) {
23633							if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) {
23634								$x1 = (2 * $x) - $x1;
23635								$y1 = (2 * $y) - $y1;
23636							} else {
23637								$x1 = $x;
23638								$y1 = $y;
23639							}
23640							// convert quadratic points to cubic points
23641							$xa = ($x + (2 * $x1)) / 3;
23642							$ya = ($y + (2 * $y1)) / 3;
23643							$x = $params[($ck - 1)] + $xoffset;
23644							$y = $params[($ck)] + $yoffset;
23645							$xb = ($x + (2 * $x1)) / 3;
23646							$yb = ($y + (2 * $y1)) / 3;
23647							$this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
23648							$xmin = min($xmin, $x, $xa, $xb);
23649							$ymin = min($ymin, $y, $ya, $yb);
23650							$xmax = max($xmax, $x, $xa, $xb);
23651							$ymax = max($ymax, $y, $ya, $yb);
23652							if ($relcoord) {
23653								$xoffset = $x;
23654								$yoffset = $y;
23655							}
23656						}
23657					}
23658					break;
23659				}
23660				case 'A': { // elliptical arc
23661					foreach ($params as $ck => $cp) {
23662						$params[$ck] = $cp;
23663						if ((($ck + 1) % 7) == 0) {
23664							$x0 = $x;
23665							$y0 = $y;
23666							$rx = max(abs($params[($ck - 6)]), .000000001);
23667							$ry = max(abs($params[($ck - 5)]), .000000001);
23668							$ang = -$rawparams[($ck - 4)];
23669							$angle = deg2rad($ang);
23670							$fa = $rawparams[($ck - 3)]; // large-arc-flag
23671							$fs = $rawparams[($ck - 2)]; // sweep-flag
23672							$x = $params[($ck - 1)] + $xoffset;
23673							$y = $params[$ck] + $yoffset;
23674							if ((abs($x0 - $x) < $minlen) AND (abs($y0 - $y) < $minlen)) {
23675								// endpoints are almost identical
23676								$xmin = min($xmin, $x);
23677								$ymin = min($ymin, $y);
23678								$xmax = max($xmax, $x);
23679								$ymax = max($ymax, $y);
23680							} else {
23681								$cos_ang = cos($angle);
23682								$sin_ang = sin($angle);
23683								$a = (($x0 - $x) / 2);
23684								$b = (($y0 - $y) / 2);
23685								$xa = ($a * $cos_ang) - ($b * $sin_ang);
23686								$ya = ($a * $sin_ang) + ($b * $cos_ang);
23687								$rx2 = $rx * $rx;
23688								$ry2 = $ry * $ry;
23689								$xa2 = $xa * $xa;
23690								$ya2 = $ya * $ya;
23691								$delta = ($xa2 / $rx2) + ($ya2 / $ry2);
23692								if ($delta > 1) {
23693									$rx *= sqrt($delta);
23694									$ry *= sqrt($delta);
23695									$rx2 = $rx * $rx;
23696									$ry2 = $ry * $ry;
23697								}
23698								$numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2));
23699								if ($numerator < 0) {
23700									$root = 0;
23701								} else {
23702									$root = sqrt($numerator / (($rx2 * $ya2) + ($ry2 * $xa2)));
23703								}
23704								if ($fa == $fs){
23705									$root *= -1;
23706								}
23707								$cax = $root * (($rx * $ya) / $ry);
23708								$cay = -$root * (($ry * $xa) / $rx);
23709								// coordinates of ellipse center
23710								$cx = ($cax * $cos_ang) - ($cay * $sin_ang) + (($x0 + $x) / 2);
23711								$cy = ($cax * $sin_ang) + ($cay * $cos_ang) + (($y0 + $y) / 2);
23712								// get angles
23713								$angs = TCPDF_STATIC::getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry));
23714								$dang = TCPDF_STATIC::getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry));
23715								if (($fs == 0) AND ($dang > 0)) {
23716									$dang -= (2 * M_PI);
23717								} elseif (($fs == 1) AND ($dang < 0)) {
23718									$dang += (2 * M_PI);
23719								}
23720								$angf = $angs - $dang;
23721								if ((($fs == 0) AND ($angs > $angf)) OR (($fs == 1) AND ($angs < $angf))) {
23722									// reverse angles
23723									$tmp = $angs;
23724									$angs = $angf;
23725									$angf = $tmp;
23726								}
23727								$angs = round(rad2deg($angs), 6);
23728								$angf = round(rad2deg($angf), 6);
23729								// covent angles to positive values
23730								if (($angs < 0) AND ($angf < 0)) {
23731									$angs += 360;
23732									$angf += 360;
23733								}
23734								$pie = false;
23735								if (($key == 0) AND (isset($paths[($key + 1)][1])) AND (trim($paths[($key + 1)][1]) == 'z')) {
23736									$pie = true;
23737								}
23738								list($axmin, $aymin, $axmax, $aymax) = $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2, false, ($fs == 0), true);
23739								$xmin = min($xmin, $x, $axmin);
23740								$ymin = min($ymin, $y, $aymin);
23741								$xmax = max($xmax, $x, $axmax);
23742								$ymax = max($ymax, $y, $aymax);
23743							}
23744							if ($relcoord) {
23745								$xoffset = $x;
23746								$yoffset = $y;
23747							}
23748						}
23749					}
23750					break;
23751				}
23752				case 'Z': {
23753					$this->_out('h');
23754					$x = $x0 = $xinitial;
23755					$y = $y0 = $yinitial;
23756					break;
23757				}
23758			}
23759			$firstcmd = false;
23760		} // end foreach
23761		if (!empty($op)) {
23762			$this->_out($op);
23763		}
23764		return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin));
23765	}
23766
23767	/**
23768	 * Return the tag name without the namespace
23769	 * @param $name (string) Tag name
23770	 * @protected
23771	 */
23772	protected function removeTagNamespace($name) {
23773		if(strpos($name, ':') !== false) {
23774			$parts = explode(':', $name);
23775			return $parts[(sizeof($parts) - 1)];
23776		}
23777		return $name;
23778	}
23779
23780	/**
23781	 * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***)
23782	 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
23783	 * @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.
23784	 * @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.
23785	 * @param $ctm (array) tranformation matrix for clipping mode (starting transformation matrix).
23786	 * @author Nicola Asuni
23787	 * @since 5.0.000 (2010-05-02)
23788	 * @protected
23789	 */
23790	protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) {
23791		$name = $this->removeTagNamespace($name);
23792		// check if we are in clip mode
23793		if ($this->svgclipmode) {
23794			$this->svgclippaths[$this->svgclipid][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm[$this->svgclipid]);
23795			return;
23796		}
23797		if ($this->svgdefsmode AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) {
23798			if (isset($attribs['id'])) {
23799				$attribs['child_elements'] = array();
23800				$this->svgdefs[$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
23801				return;
23802			}
23803			if (end($this->svgdefs) !== FALSE) {
23804				$last_svgdefs_id = key($this->svgdefs);
23805				if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
23806					$attribs['id'] = 'DF_'.(count($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements']) + 1);
23807					$this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
23808					return;
23809				}
23810			}
23811			return;
23812		}
23813		$clipping = false;
23814		if ($parser == 'clip-path') {
23815			// set clipping mode
23816			$clipping = true;
23817		}
23818		// get styling properties
23819		$prev_svgstyle = $this->svgstyles[max(0,(count($this->svgstyles) - 1))]; // previous style
23820		$svgstyle = $this->svgstyles[0]; // set default style
23821		if ($clipping AND !isset($attribs['fill']) AND (!isset($attribs['style']) OR (!preg_match('/[;\"\s]{1}fill[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval)))) {
23822			// default fill attribute for clipping
23823			$attribs['fill'] = 'none';
23824		}
23825		if (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style']) AND ($attribs['style'][0] != ';')) {
23826			// fix style for regular expression
23827			$attribs['style'] = ';'.$attribs['style'];
23828		}
23829		foreach ($prev_svgstyle as $key => $val) {
23830			if (in_array($key, TCPDF_IMAGES::$svginheritprop)) {
23831				// inherit previous value
23832				$svgstyle[$key] = $val;
23833			}
23834			if (isset($attribs[$key]) AND !TCPDF_STATIC::empty_string($attribs[$key])) {
23835				// specific attribute settings
23836				if ($attribs[$key] == 'inherit') {
23837					$svgstyle[$key] = $val;
23838				} else {
23839					$svgstyle[$key] = $attribs[$key];
23840				}
23841			} elseif (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style'])) {
23842				// CSS style syntax
23843				$attrval = array();
23844				if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) {
23845					if ($attrval[1] == 'inherit') {
23846						$svgstyle[$key] = $val;
23847					} else {
23848						$svgstyle[$key] = $attrval[1];
23849					}
23850				}
23851			}
23852		}
23853		// transformation matrix
23854		if (!empty($ctm)) {
23855			$tm = $ctm;
23856		} else {
23857			$tm = array(1,0,0,1,0,0);
23858		}
23859		if (isset($attribs['transform']) AND !empty($attribs['transform'])) {
23860			$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, TCPDF_STATIC::getSVGTransformMatrix($attribs['transform']));
23861		}
23862		$svgstyle['transfmatrix'] = $tm;
23863		$invisible = false;
23864		if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) {
23865			// the current graphics element is invisible (nothing is painted)
23866			$invisible = true;
23867		}
23868		// process tag
23869		switch($name) {
23870			case 'defs': {
23871				$this->svgdefsmode = true;
23872				break;
23873			}
23874			// clipPath
23875			case 'clipPath': {
23876				if ($invisible) {
23877					break;
23878				}
23879				$this->svgclipmode = true;
23880				if (!isset($attribs['id'])) {
23881					$attribs['id'] = 'CP_'.(count($this->svgcliptm) + 1);
23882				}
23883				$this->svgclipid = $attribs['id'];
23884				$this->svgclippaths[$this->svgclipid] = array();
23885				$this->svgcliptm[$this->svgclipid] = $tm;
23886				break;
23887			}
23888			case 'svg': {
23889				// start of SVG object
23890				if(++$this->svg_tag_depth <= 1) {
23891					break;
23892				}
23893				// inner SVG
23894				array_push($this->svgstyles, $svgstyle);
23895				$this->StartTransform();
23896				$svgX = (isset($attribs['x'])?$attribs['x']:0);
23897				$svgY = (isset($attribs['y'])?$attribs['y']:0);
23898				$svgW = (isset($attribs['width'])?$attribs['width']:0);
23899				$svgH = (isset($attribs['height'])?$attribs['height']:0);
23900				// set x, y position using transform matrix
23901				$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array( 1, 0, 0, 1, $svgX, $svgY));
23902				$this->SVGTransform($tm);
23903				// set clipping for width and height
23904				$x = 0;
23905				$y = 0;
23906				$w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):$this->w);
23907				$h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):$this->h);
23908				// draw clipping rect
23909				$this->Rect($x, $y, $w, $h, 'CNZ', array(), array());
23910				// parse viewbox, calculate extra transformation matrix
23911				if (isset($attribs['viewBox'])) {
23912					$tmp = array();
23913					preg_match_all("/[0-9]+/", $attribs['viewBox'], $tmp);
23914					$tmp = $tmp[0];
23915					if (sizeof($tmp) == 4) {
23916						$vx = $tmp[0];
23917						$vy = $tmp[1];
23918						$vw = $tmp[2];
23919						$vh = $tmp[3];
23920						// get aspect ratio
23921						$tmp = array();
23922						$aspectX = 'xMid';
23923						$aspectY = 'YMid';
23924						$fit = 'meet';
23925						if (isset($attribs['preserveAspectRatio'])) {
23926							if($attribs['preserveAspectRatio'] == 'none') {
23927								$fit = 'none';
23928							} else {
23929								preg_match_all('/[a-zA-Z]+/', $attribs['preserveAspectRatio'], $tmp);
23930								$tmp = $tmp[0];
23931								if ((sizeof($tmp) == 2) AND (strlen($tmp[0]) == 8) AND (in_array($tmp[1], array('meet', 'slice', 'none')))) {
23932									$aspectX = substr($tmp[0], 0, 4);
23933									$aspectY = substr($tmp[0], 4, 4);
23934									$fit = $tmp[1];
23935								}
23936							}
23937						}
23938						$wr = ($svgW / $vw);
23939						$hr = ($svgH / $vh);
23940						$ax = $ay = 0;
23941						if ((($fit == 'meet') AND ($hr < $wr)) OR (($fit == 'slice') AND ($hr > $wr))) {
23942							if ($aspectX == 'xMax') {
23943								$ax = (($vw * ($wr / $hr)) - $vw);
23944							}
23945							if ($aspectX == 'xMid') {
23946								$ax = ((($vw * ($wr / $hr)) - $vw) / 2);
23947							}
23948							$wr = $hr;
23949						} elseif ((($fit == 'meet') AND ($hr > $wr)) OR (($fit == 'slice') AND ($hr < $wr))) {
23950							if ($aspectY == 'YMax') {
23951								$ay = (($vh * ($hr / $wr)) - $vh);
23952							}
23953							if ($aspectY == 'YMid') {
23954								$ay = ((($vh * ($hr / $wr)) - $vh) / 2);
23955							}
23956							$hr = $wr;
23957						}
23958						$newtm = array($wr, 0, 0, $hr, (($wr * ($ax - $vx)) - $svgX), (($hr * ($ay - $vy)) - $svgY));
23959						$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, $newtm);
23960						$this->SVGTransform($tm);
23961					}
23962				}
23963				$this->setSVGStyles($svgstyle, $prev_svgstyle);
23964				break;
23965			}
23966			case 'g': {
23967				// group together related graphics elements
23968				array_push($this->svgstyles, $svgstyle);
23969				$this->StartTransform();
23970				$x = (isset($attribs['x'])?$attribs['x']:0);
23971				$y = (isset($attribs['y'])?$attribs['y']:0);
23972				$w = 1;//(isset($attribs['width'])?$attribs['width']:1);
23973				$h = 1;//(isset($attribs['height'])?$attribs['height']:1);
23974				$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
23975				$this->SVGTransform($tm);
23976				$this->setSVGStyles($svgstyle, $prev_svgstyle);
23977				break;
23978			}
23979			case 'linearGradient': {
23980				if ($this->pdfa_mode) {
23981					break;
23982				}
23983				if (!isset($attribs['id'])) {
23984					$attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
23985				}
23986				$this->svggradientid = $attribs['id'];
23987				$this->svggradients[$this->svggradientid] = array();
23988				$this->svggradients[$this->svggradientid]['type'] = 2;
23989				$this->svggradients[$this->svggradientid]['stops'] = array();
23990				if (isset($attribs['gradientUnits'])) {
23991					$this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
23992				} else {
23993					$this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
23994				}
23995				//$attribs['spreadMethod']
23996				if (((!isset($attribs['x1'])) AND (!isset($attribs['y1'])) AND (!isset($attribs['x2'])) AND (!isset($attribs['y2'])))
23997					OR ((isset($attribs['x1']) AND (substr($attribs['x1'], -1) == '%'))
23998						OR (isset($attribs['y1']) AND (substr($attribs['y1'], -1) == '%'))
23999						OR (isset($attribs['x2']) AND (substr($attribs['x2'], -1) == '%'))
24000						OR (isset($attribs['y2']) AND (substr($attribs['y2'], -1) == '%')))) {
24001					$this->svggradients[$this->svggradientid]['mode'] = 'percentage';
24002				} else {
24003					$this->svggradients[$this->svggradientid]['mode'] = 'measure';
24004				}
24005				$x1 = (isset($attribs['x1'])?$attribs['x1']:'0');
24006				$y1 = (isset($attribs['y1'])?$attribs['y1']:'0');
24007				$x2 = (isset($attribs['x2'])?$attribs['x2']:'100');
24008				$y2 = (isset($attribs['y2'])?$attribs['y2']:'0');
24009				if (isset($attribs['gradientTransform'])) {
24010					$this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
24011				}
24012				$this->svggradients[$this->svggradientid]['coords'] = array($x1, $y1, $x2, $y2);
24013				if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24014					// gradient is defined on another place
24015					$this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
24016				}
24017				break;
24018			}
24019			case 'radialGradient': {
24020				if ($this->pdfa_mode) {
24021					break;
24022				}
24023				if (!isset($attribs['id'])) {
24024					$attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
24025				}
24026				$this->svggradientid = $attribs['id'];
24027				$this->svggradients[$this->svggradientid] = array();
24028				$this->svggradients[$this->svggradientid]['type'] = 3;
24029				$this->svggradients[$this->svggradientid]['stops'] = array();
24030				if (isset($attribs['gradientUnits'])) {
24031					$this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
24032				} else {
24033					$this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
24034				}
24035				//$attribs['spreadMethod']
24036				if (((!isset($attribs['cx'])) AND (!isset($attribs['cy'])))
24037					OR ((isset($attribs['cx']) AND (substr($attribs['cx'], -1) == '%'))
24038					OR (isset($attribs['cy']) AND (substr($attribs['cy'], -1) == '%')))) {
24039					$this->svggradients[$this->svggradientid]['mode'] = 'percentage';
24040				} elseif (isset($attribs['r']) AND is_numeric($attribs['r']) AND ($attribs['r']) <= 1) {
24041					$this->svggradients[$this->svggradientid]['mode'] = 'ratio';
24042				} else {
24043					$this->svggradients[$this->svggradientid]['mode'] = 'measure';
24044				}
24045				$cx = (isset($attribs['cx']) ? $attribs['cx'] : 0.5);
24046				$cy = (isset($attribs['cy']) ? $attribs['cy'] : 0.5);
24047				$fx = (isset($attribs['fx']) ? $attribs['fx'] : $cx);
24048				$fy = (isset($attribs['fy']) ? $attribs['fy'] : $cy);
24049				$r = (isset($attribs['r']) ? $attribs['r'] : 0.5);
24050				if (isset($attribs['gradientTransform'])) {
24051					$this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
24052				}
24053				$this->svggradients[$this->svggradientid]['coords'] = array($cx, $cy, $fx, $fy, $r);
24054				if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24055					// gradient is defined on another place
24056					$this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
24057				}
24058				break;
24059			}
24060			case 'stop': {
24061				// gradient stops
24062				if (substr($attribs['offset'], -1) == '%') {
24063					$offset = floatval(substr($attribs['offset'], 0, -1)) / 100;
24064				} else {
24065					$offset = floatval($attribs['offset']);
24066					if ($offset > 1) {
24067						$offset /= 100;
24068					}
24069				}
24070				$stop_color = isset($svgstyle['stop-color'])?TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stop-color'], $this->spot_colors):'black';
24071				$opacity = isset($svgstyle['stop-opacity'])?$svgstyle['stop-opacity']:1;
24072				$this->svggradients[$this->svggradientid]['stops'][] = array('offset' => $offset, 'color' => $stop_color, 'opacity' => $opacity);
24073				break;
24074			}
24075			// paths
24076			case 'path': {
24077				if ($invisible) {
24078					break;
24079				}
24080				if (isset($attribs['d'])) {
24081					$d = trim($attribs['d']);
24082					if (!empty($d)) {
24083						$x = (isset($attribs['x'])?$attribs['x']:0);
24084						$y = (isset($attribs['y'])?$attribs['y']:0);
24085						$w = (isset($attribs['width'])?$attribs['width']:1);
24086						$h = (isset($attribs['height'])?$attribs['height']:1);
24087						$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
24088						if ($clipping) {
24089							$this->SVGTransform($tm);
24090							$this->SVGPath($d, 'CNZ');
24091						} else {
24092							$this->StartTransform();
24093							$this->SVGTransform($tm);
24094							$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'SVGPath', array($d, 'CNZ'));
24095							if (!empty($obstyle)) {
24096								$this->SVGPath($d, $obstyle);
24097							}
24098							$this->StopTransform();
24099						}
24100					}
24101				}
24102				break;
24103			}
24104			// shapes
24105			case 'rect': {
24106				if ($invisible) {
24107					break;
24108				}
24109				$x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
24110				$y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
24111				$w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
24112				$h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
24113				$rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
24114				$ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):$rx);
24115				if ($clipping) {
24116					$this->SVGTransform($tm);
24117					$this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ', array(), array());
24118				} else {
24119					$this->StartTransform();
24120					$this->SVGTransform($tm);
24121					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'RoundedRectXY', array($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ'));
24122					if (!empty($obstyle)) {
24123						$this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', $obstyle, array(), array());
24124					}
24125					$this->StopTransform();
24126				}
24127				break;
24128			}
24129			case 'circle': {
24130				if ($invisible) {
24131					break;
24132				}
24133				$r = (isset($attribs['r']) ? $this->getHTMLUnitToUnits($attribs['r'], 0, $this->svgunit, false) : 0);
24134				$cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
24135				$cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
24136				$x = ($cx - $r);
24137				$y = ($cy - $r);
24138				$w = (2 * $r);
24139				$h = $w;
24140				if ($clipping) {
24141					$this->SVGTransform($tm);
24142					$this->Circle($cx, $cy, $r, 0, 360, 'CNZ', array(), array(), 8);
24143				} else {
24144					$this->StartTransform();
24145					$this->SVGTransform($tm);
24146					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Circle', array($cx, $cy, $r, 0, 360, 'CNZ'));
24147					if (!empty($obstyle)) {
24148						$this->Circle($cx, $cy, $r, 0, 360, $obstyle, array(), array(), 8);
24149					}
24150					$this->StopTransform();
24151				}
24152				break;
24153			}
24154			case 'ellipse': {
24155				if ($invisible) {
24156					break;
24157				}
24158				$rx = (isset($attribs['rx']) ? $this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false) : 0);
24159				$ry = (isset($attribs['ry']) ? $this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false) : 0);
24160				$cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
24161				$cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
24162				$x = ($cx - $rx);
24163				$y = ($cy - $ry);
24164				$w = (2 * $rx);
24165				$h = (2 * $ry);
24166				if ($clipping) {
24167					$this->SVGTransform($tm);
24168					$this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ', array(), array(), 8);
24169				} else {
24170					$this->StartTransform();
24171					$this->SVGTransform($tm);
24172					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Ellipse', array($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ'));
24173					if (!empty($obstyle)) {
24174						$this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, $obstyle, array(), array(), 8);
24175					}
24176					$this->StopTransform();
24177				}
24178				break;
24179			}
24180			case 'line': {
24181				if ($invisible) {
24182					break;
24183				}
24184				$x1 = (isset($attribs['x1'])?$this->getHTMLUnitToUnits($attribs['x1'], 0, $this->svgunit, false):0);
24185				$y1 = (isset($attribs['y1'])?$this->getHTMLUnitToUnits($attribs['y1'], 0, $this->svgunit, false):0);
24186				$x2 = (isset($attribs['x2'])?$this->getHTMLUnitToUnits($attribs['x2'], 0, $this->svgunit, false):0);
24187				$y2 = (isset($attribs['y2'])?$this->getHTMLUnitToUnits($attribs['y2'], 0, $this->svgunit, false):0);
24188				$x = $x1;
24189				$y = $y1;
24190				$w = abs($x2 - $x1);
24191				$h = abs($y2 - $y1);
24192				if (!$clipping) {
24193					$this->StartTransform();
24194					$this->SVGTransform($tm);
24195					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Line', array($x1, $y1, $x2, $y2));
24196					$this->Line($x1, $y1, $x2, $y2);
24197					$this->StopTransform();
24198				}
24199				break;
24200			}
24201			case 'polyline':
24202			case 'polygon': {
24203				if ($invisible) {
24204					break;
24205				}
24206				$points = (isset($attribs['points'])?$attribs['points']:'0 0');
24207				$points = trim($points);
24208				// note that point may use a complex syntax not covered here
24209				$points = preg_split('/[\,\s]+/si', $points);
24210				if (count($points) < 4) {
24211					break;
24212				}
24213				$p = array();
24214				$xmin = 2147483647;
24215				$xmax = 0;
24216				$ymin = 2147483647;
24217				$ymax = 0;
24218				foreach ($points as $key => $val) {
24219					$p[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
24220					if (($key % 2) == 0) {
24221						// X coordinate
24222						$xmin = min($xmin, $p[$key]);
24223						$xmax = max($xmax, $p[$key]);
24224					} else {
24225						// Y coordinate
24226						$ymin = min($ymin, $p[$key]);
24227						$ymax = max($ymax, $p[$key]);
24228					}
24229				}
24230				$x = $xmin;
24231				$y = $ymin;
24232				$w = ($xmax - $xmin);
24233				$h = ($ymax - $ymin);
24234				if ($name == 'polyline') {
24235					$this->StartTransform();
24236					$this->SVGTransform($tm);
24237					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'PolyLine', array($p, 'CNZ'));
24238					if (!empty($obstyle)) {
24239						$this->PolyLine($p, $obstyle, array(), array());
24240					}
24241					$this->StopTransform();
24242				} else { // polygon
24243					if ($clipping) {
24244						$this->SVGTransform($tm);
24245						$this->Polygon($p, 'CNZ', array(), array(), true);
24246					} else {
24247						$this->StartTransform();
24248						$this->SVGTransform($tm);
24249						$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Polygon', array($p, 'CNZ'));
24250						if (!empty($obstyle)) {
24251							$this->Polygon($p, $obstyle, array(), array(), true);
24252						}
24253						$this->StopTransform();
24254					}
24255				}
24256				break;
24257			}
24258			// image
24259			case 'image': {
24260				if ($invisible) {
24261					break;
24262				}
24263				if (!isset($attribs['xlink:href']) OR empty($attribs['xlink:href'])) {
24264					break;
24265				}
24266				$x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
24267				$y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
24268				$w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
24269				$h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
24270				$img = $attribs['xlink:href'];
24271				if (!$clipping) {
24272					$this->StartTransform();
24273					$this->SVGTransform($tm);
24274					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h);
24275					if (preg_match('/^data:image\/[^;]+;base64,/', $img, $m) > 0) {
24276						// embedded image encoded as base64
24277						$img = '@'.base64_decode(substr($img, strlen($m[0])));
24278					} else {
24279						// fix image path
24280						if (!TCPDF_STATIC::empty_string($this->svgdir) AND (($img[0] == '.') OR (basename($img) == $img))) {
24281							// replace relative path with full server path
24282							$img = $this->svgdir.'/'.$img;
24283						}
24284						if (($img[0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
24285							$findroot = strpos($img, $_SERVER['DOCUMENT_ROOT']);
24286							if (($findroot === false) OR ($findroot > 1)) {
24287								if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
24288									$img = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$img;
24289								} else {
24290									$img = $_SERVER['DOCUMENT_ROOT'].$img;
24291								}
24292							}
24293						}
24294						$img = urldecode($img);
24295						$testscrtype = @parse_url($img);
24296						if (empty($testscrtype['query'])) {
24297							// convert URL to server path
24298							$img = str_replace(K_PATH_URL, K_PATH_MAIN, $img);
24299						} elseif (preg_match('|^https?://|', $img) !== 1) {
24300							// convert server path to URL
24301							$img = str_replace(K_PATH_MAIN, K_PATH_URL, $img);
24302						}
24303					}
24304					// get image type
24305					$imgtype = TCPDF_IMAGES::getImageFileType($img);
24306					if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
24307						$this->ImageEps($img, $x, $y, $w, $h);
24308					} elseif ($imgtype == 'svg') {
24309						// store SVG vars
24310						$svggradients = $this->svggradients;
24311						$svggradientid = $this->svggradientid;
24312						$svgdefsmode = $this->svgdefsmode;
24313						$svgdefs = $this->svgdefs;
24314						$svgclipmode = $this->svgclipmode;
24315						$svgclippaths = $this->svgclippaths;
24316						$svgcliptm = $this->svgcliptm;
24317						$svgclipid = $this->svgclipid;
24318						$svgtext = $this->svgtext;
24319						$svgtextmode = $this->svgtextmode;
24320						$this->ImageSVG($img, $x, $y, $w, $h);
24321						// restore SVG vars
24322						$this->svggradients = $svggradients;
24323						$this->svggradientid = $svggradientid;
24324						$this->svgdefsmode = $svgdefsmode;
24325						$this->svgdefs = $svgdefs;
24326						$this->svgclipmode = $svgclipmode;
24327						$this->svgclippaths = $svgclippaths;
24328						$this->svgcliptm = $svgcliptm;
24329						$this->svgclipid = $svgclipid;
24330						$this->svgtext = $svgtext;
24331						$this->svgtextmode = $svgtextmode;
24332					} else {
24333						$this->Image($img, $x, $y, $w, $h);
24334					}
24335					$this->StopTransform();
24336				}
24337				break;
24338			}
24339			// text
24340			case 'text':
24341			case 'tspan': {
24342				if (isset($this->svgtextmode['text-anchor']) AND !empty($this->svgtext)) {
24343					// @TODO: unsupported feature
24344				}
24345				// only basic support - advanced features must be implemented
24346				$this->svgtextmode['invisible'] = $invisible;
24347				if ($invisible) {
24348					break;
24349				}
24350				array_push($this->svgstyles, $svgstyle);
24351				if (isset($attribs['x'])) {
24352					$x = $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false);
24353				} elseif ($name == 'tspan') {
24354					$x = $this->x;
24355				} else {
24356					$x = 0;
24357				}
24358				if (isset($attribs['dx'])) {
24359					$x += $this->getHTMLUnitToUnits($attribs['dx'], 0, $this->svgunit, false);
24360				}
24361				if (isset($attribs['y'])) {
24362					$y = $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false);
24363				} elseif ($name == 'tspan') {
24364					$y = $this->y;
24365				} else {
24366					$y = 0;
24367				}
24368				if (isset($attribs['dy'])) {
24369					$y += $this->getHTMLUnitToUnits($attribs['dy'], 0, $this->svgunit, false);
24370				}
24371				$svgstyle['text-color'] = $svgstyle['fill'];
24372				$this->svgtext = '';
24373				if (isset($svgstyle['text-anchor'])) {
24374					$this->svgtextmode['text-anchor'] = $svgstyle['text-anchor'];
24375				} else {
24376					$this->svgtextmode['text-anchor'] = 'start';
24377				}
24378				if (isset($svgstyle['direction'])) {
24379					if ($svgstyle['direction'] == 'rtl') {
24380						$this->svgtextmode['rtl'] = true;
24381					} else {
24382						$this->svgtextmode['rtl'] = false;
24383					}
24384				} else {
24385					$this->svgtextmode['rtl'] = false;
24386				}
24387				if (isset($svgstyle['stroke']) AND ($svgstyle['stroke'] != 'none') AND isset($svgstyle['stroke-width']) AND ($svgstyle['stroke-width'] > 0)) {
24388					$this->svgtextmode['stroke'] = $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false);
24389				} else {
24390					$this->svgtextmode['stroke'] = false;
24391				}
24392				$this->StartTransform();
24393				$this->SVGTransform($tm);
24394				$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, 1, 1);
24395				$this->x = $x;
24396				$this->y = $y;
24397				break;
24398			}
24399			// use
24400			case 'use': {
24401				if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24402					$svgdefid = substr($attribs['xlink:href'], 1);
24403					if (isset($this->svgdefs[$svgdefid])) {
24404						$use = $this->svgdefs[$svgdefid];
24405						if (isset($attribs['xlink:href'])) {
24406							unset($attribs['xlink:href']);
24407						}
24408						if (isset($attribs['id'])) {
24409							unset($attribs['id']);
24410						}
24411						if (isset($use['attribs']['x']) AND isset($attribs['x'])) {
24412							$attribs['x'] += $use['attribs']['x'];
24413						}
24414						if (isset($use['attribs']['y']) AND isset($attribs['y'])) {
24415							$attribs['y'] += $use['attribs']['y'];
24416						}
24417						if (empty($attribs['style'])) {
24418							$attribs['style'] = '';
24419						}
24420						if (!empty($use['attribs']['style'])) {
24421							// merge styles
24422							$attribs['style'] = str_replace(';;',';',';'.$use['attribs']['style'].$attribs['style']);
24423						}
24424						$attribs = array_merge($use['attribs'], $attribs);
24425						$this->startSVGElementHandler($parser, $use['name'], $attribs);
24426						return;
24427					}
24428				}
24429				break;
24430			}
24431			default: {
24432				break;
24433			}
24434		} // end of switch
24435		// process child elements
24436		if (!empty($attribs['child_elements'])) {
24437			$child_elements = $attribs['child_elements'];
24438			unset($attribs['child_elements']);
24439			foreach($child_elements as $child_element) {
24440				if (empty($child_element['attribs']['closing_tag'])) {
24441					$this->startSVGElementHandler('child-tag', $child_element['name'], $child_element['attribs']);
24442				} else {
24443					if (isset($child_element['attribs']['content'])) {
24444						$this->svgtext = $child_element['attribs']['content'];
24445					}
24446					$this->endSVGElementHandler('child-tag', $child_element['name']);
24447				}
24448			}
24449		}
24450	}
24451
24452	/**
24453	 * Sets the closing SVG element handler function for the XML parser.
24454	 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
24455	 * @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.
24456	 * @author Nicola Asuni
24457	 * @since 5.0.000 (2010-05-02)
24458	 * @protected
24459	 */
24460	protected function endSVGElementHandler($parser, $name) {
24461		$name = $this->removeTagNamespace($name);
24462		if ($this->svgdefsmode AND !in_array($name, array('defs', 'clipPath', 'linearGradient', 'radialGradient', 'stop'))) {;
24463			if (end($this->svgdefs) !== FALSE) {
24464				$last_svgdefs_id = key($this->svgdefs);
24465				if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
24466					foreach($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'] as $child_element) {
24467						if (isset($child_element['attribs']['id']) AND ($child_element['name'] == $name)) {
24468							$this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$child_element['attribs']['id'].'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
24469							return;
24470						}
24471					}
24472					if ($this->svgdefs[$last_svgdefs_id]['name'] == $name) {
24473						$this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$last_svgdefs_id.'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
24474						return;
24475					}
24476				}
24477			}
24478			return;
24479		}
24480		switch($name) {
24481			case 'defs': {
24482				$this->svgdefsmode = false;
24483				break;
24484			}
24485			// clipPath
24486			case 'clipPath': {
24487				$this->svgclipmode = false;
24488				break;
24489			}
24490			case 'svg': {
24491				if (--$this->svg_tag_depth <= 0) {
24492					break;
24493				}
24494			}
24495			case 'g': {
24496				// ungroup: remove last style from array
24497				array_pop($this->svgstyles);
24498				$this->StopTransform();
24499				break;
24500			}
24501			case 'text':
24502			case 'tspan': {
24503				if ($this->svgtextmode['invisible']) {
24504					// This implementation must be fixed to following the rule:
24505					// 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.
24506					break;
24507				}
24508				// print text
24509				$text = $this->svgtext;
24510				//$text = $this->stringTrim($text);
24511				$textlen = $this->GetStringWidth($text);
24512				if ($this->svgtextmode['text-anchor'] != 'start') {
24513					// check if string is RTL text
24514					if ($this->svgtextmode['text-anchor'] == 'end') {
24515						if ($this->svgtextmode['rtl']) {
24516							$this->x += $textlen;
24517						} else {
24518							$this->x -= $textlen;
24519						}
24520					} elseif ($this->svgtextmode['text-anchor'] == 'middle') {
24521						if ($this->svgtextmode['rtl']) {
24522							$this->x += ($textlen / 2);
24523						} else {
24524							$this->x -= ($textlen / 2);
24525						}
24526					}
24527				}
24528				$textrendermode = $this->textrendermode;
24529				$textstrokewidth = $this->textstrokewidth;
24530				$this->setTextRenderingMode($this->svgtextmode['stroke'], true, false);
24531				if ($name == 'text') {
24532					// store current coordinates
24533					$tmpx = $this->x;
24534					$tmpy = $this->y;
24535				}
24536				// print the text
24537				$this->Cell($textlen, 0, $text, 0, 0, '', false, '', 0, false, 'L', 'T');
24538				if ($name == 'text') {
24539					// restore coordinates
24540					$this->x = $tmpx;
24541					$this->y = $tmpy;
24542				}
24543				// restore previous rendering mode
24544				$this->textrendermode = $textrendermode;
24545				$this->textstrokewidth = $textstrokewidth;
24546				$this->svgtext = '';
24547				$this->StopTransform();
24548				if (!$this->svgdefsmode) {
24549					array_pop($this->svgstyles);
24550				}
24551				break;
24552			}
24553			default: {
24554				break;
24555			}
24556		}
24557	}
24558
24559	/**
24560	 * Sets the character data handler function for the XML parser.
24561	 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
24562	 * @param $data (string) The second parameter, data, contains the character data as a string.
24563	 * @author Nicola Asuni
24564	 * @since 5.0.000 (2010-05-02)
24565	 * @protected
24566	 */
24567	protected function segSVGContentHandler($parser, $data) {
24568		$this->svgtext .= $data;
24569	}
24570
24571	// --- END SVG METHODS -----------------------------------------------------
24572
24573} // END OF TCPDF CLASS
24574
24575//============================================================+
24576// END OF FILE
24577//============================================================+
24578